경고 메시지 출력 표기 생략

from IPython.display import Image
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings

warnings.filterwarnings('ignore')

# unicode 에러
plt.rcParams['axes.unicode_minus'] = False

분류 (Classification)

K Nearest Neighbors (k-최근접 이웃 분류 알고리즘)

가장 중요한 hyperparameter인 K값은 근처에 참고(reference)할 이웃의 숫자

  • k-최근접 이웃 분류 알고리즘
  • 가장 고전적이고 직관적인 머신러닝 분류 알고리즘
  • 기하학적 거리 분류기
  • 가장 가깝게 위치하는 멤버로 분류하는 방식
Image(url='https://miro.medium.com/max/405/0*QyWp7J6eSz0tayc0.png', width=500)

mnist (손글씨) 데이터셋을 활용한 분류

mnist (손글씨) 데이터셋을 활용하여 0~9까지 분류하는 분류기를 만듭니다.

sklearn.datasets 보다 고해상도 이미지이기 때문에 tensorflow.keras.datasets을 활용합니다.

# !pip install tensorflow
from tensorflow.keras.datasets import mnist

(x_digit, y_digit), (_, _15) = mnist.load_data()
x_digit, y_digit = x_digit[:5000], y_digit[:5000]
x_digit = x_digit.reshape(-1, 28*28)
x_digit.shape

mnist (손글씨) 데이터 시각화

w, h = 2, 5
fig, axes = plt.subplots(w, h)
fig.set_size_inches(12, 6)
for i in range(w*h):
    axes[i//h, i%h].imshow(x_digit[i].reshape(-1, 28), cmap='gray')
    axes[i//h, i%h].set_title(y_digit[i], fontsize=20)
    axes[i//h, i%h].axis('off')
plt.tight_layout()
plt.show()

데이터 셋 분할

학습용(train) 데이터셋과 검증 (혹은 테스트)용 데이터 셋을 분할 합니다.

from sklearn.model_selection import train_test_split

SEED = 123
  • random_state에 SEED(123) 적용
  • test_size는 0.1 로 설정
  • stratify 옵션 지정
# 코드를 입력해 주세요
x_train, x_test, y_train, y_test = 
# 코드를 입력해 주세요
x_train.shape, x_test.shape

[출력 결과]

((4500, 784), (500, 784))

모델 정의

KNeighborsClassifier를 정의 하고 핵심 hyperparameter 인 n_neighbors를 지정합니다.

임의로 5개의 이웃을 보도록 n_neighbors=5로 지정하겠습니다.

# 코드를 입력해 주세요
knn = 

학습 (fit)

# 코드를 입력해 주세요

[출력 결과]

KNeighborsClassifier()

예측 (predict)

# 코드를 입력해 주세요
prediction = 

검증 (evaluation)

정확도 (Accuracy) 산출

# 코드를 입력해 주세요

[출력 결과]

0.938

최적의 n_neighbors 찾기

  • k=1 ~ k=10까지의 정확도를 출력
# 코드를 입력해 주세요


[출력 결과]

k: 1, accuracy: 94.40
k: 2, accuracy: 93.20
k: 3, accuracy: 94.20
k: 4, accuracy: 93.80
k: 5, accuracy: 93.80
k: 6, accuracy: 93.40
k: 7, accuracy: 93.80
k: 8, accuracy: 93.60
k: 9, accuracy: 94.00
k: 10, accuracy: 92.80

Iris 붓꽃 데이터셋을 활용한 실습

필요한 데이터셋 불러오기 (load_iris)

from sklearn.datasets import load_iris
# 코드를 입력해 주세요
iris = 

데이터프레임 (DataFrame) 만들기

df 변수에 데이터 프레임 생성합니다.

# 코드를 입력해 주세요
df =

df.head()

[출력 결과]

sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) target
0 5.1 3.5 1.4 0.2 0
1 4.9 3.0 1.4 0.2 0
2 4.7 3.2 1.3 0.2 0
3 4.6 3.1 1.5 0.2 0
4 5.0 3.6 1.4 0.2 0

데이터 셋 분할

학습용(train) 데이터셋과 검증 (혹은 테스트)용 데이터 셋을 분할 합니다.

SEED = 123
  • test_size=0.2
  • random_state=SEED(123) 로 설정합니다.
  • stratify 옵션을 지정합니다.
# 코드를 입력해 주세요
x_train, x_test, y_train, y_test = 

잘 로드가 되었는지 shape를 확인하도록 합니다.

x_train, y_train shape 출력

# 코드를 입력해 주세요

[출력 결과]

((120, 4), (120,))

x_test, y_test shape 확인

# 코드를 입력해 주세요

[출력 결과]

((30, 4), (30,))

모델 정의

# 코드를 입력해 주세요

학습 (fit)

# 코드를 입력해 주세요

[출력 결과]

KNeighborsClassifier()

예측(predict)

예측한 결과를 prediction 변수에 대입합니다.

# 코드를 입력해 주세요
prediction = 

검증 (evaluation)

예측한 결과에 대한 정확도를 출력합니다.

# 코드를 입력해 주세요

[출력 결과]

0.9333333333333333

최적의 k 값 찾기

k=1 ~ 10까지 중 최적의 k 값 찾기

# 코드를 입력해 주세요


[출력 결과]

k: 1, accuracy: 93.33
k: 2, accuracy: 93.33
k: 3, accuracy: 93.33
k: 4, accuracy: 93.33
k: 5, accuracy: 93.33
k: 6, accuracy: 90.00
k: 7, accuracy: 90.00
k: 8, accuracy: 93.33
k: 9, accuracy: 93.33
k: 10, accuracy: 93.33