본문 바로가기
머신러닝/혼공머신

[혼공머신] chapter 2. k-최근접 이웃 알고리즘 - 실습

by 다이노소어 2022. 11. 24.
혼자 공부하는 머신러닝 + 딥러닝의 Chapter 2를 공부하면서 정리한 내용을 기반으로 작성하였다.
이번 장에서는 책 순서와 달리, 개념과 실습을 구분해서 정리하였다.

 

fish_length = [25.4, 26.3, 26.5, 29.0, 29.0, 29.7, 29.7, 30.0, 30.0, 30.7, 31.0, 31.0, 
                31.5, 32.0, 32.0, 32.0, 33.0, 33.0, 33.5, 33.5, 34.0, 34.0, 34.5, 35.0, 
                35.0, 35.0, 35.0, 36.0, 36.0, 37.0, 38.5, 38.5, 39.5, 41.0, 41.0, 9.8, 
                10.5, 10.6, 11.0, 11.2, 11.3, 11.8, 11.8, 12.0, 12.2, 12.4, 13.0, 14.3, 15.0]
fish_weight = [242.0, 290.0, 340.0, 363.0, 430.0, 450.0, 500.0, 390.0, 450.0, 500.0, 475.0, 500.0, 
                500.0, 340.0, 600.0, 600.0, 700.0, 700.0, 610.0, 650.0, 575.0, 685.0, 620.0, 680.0, 
                700.0, 725.0, 720.0, 714.0, 850.0, 1000.0, 920.0, 955.0, 925.0, 975.0, 950.0, 6.7, 
                7.5, 7.0, 9.7, 9.8, 8.7, 10.0, 9.9, 9.8, 12.2, 13.4, 12.2, 19.7, 19.9]
#넘파이
import numpy as np

#사이킷런
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier

#데이터 시각화
import matplotlib.pyplot as plt​

 

 

fish_target 준비


#m1
fish_target = [1]*35 + [0]*14

#m2
fish_target = np.concatenate((np.ones(35), np.zeros(14)))

 

 

 

fish_data 준비


 

1. 2차원 리스트로 합치기

#m1.
fish_data = [[l, w] for l, w in zip(fish_length, fish_weight)]

#m2.
fish_data = np.column_stack((fish_length, fish_weight))

 

 

2. 훈련세트 테스트세트 나누기

#m1.

#넘파이 배열로
input_arr = np.array(fish_data)
target_arr = np.array(fish_target)
#랜덤시드(일정한 값을 원함)
np.random.seed(42)
#인덱스
index = np.arange(49)
#랜덤하게 섞음
np.random.shuffle(index)
#훈련세트
train_input = input_arr[index[:35]]
train_target = target_arr[index[:35]]
#평가세트
test_input = input_arr[index[35:]]
test_target = target_arr[index[35:]]

#m2.
train_input, test_input, train_target, test_target = train_test_split(
    fish_data, fish_target, stratify=fish_target, random_state=42)

 

3. 표준 점수

mean = np.mean(train_input, axis=0)
std = np.std(train_input, axis=0)

train_scaled = (train_input - mean) / std
test_scaled = (test_input - mean) / std

 

 

모델 객체


 

kn.score(test_scaled, test_target)

kn.fit(train_scaled, train_target)

print(kn.predict([new]))