Techbrad

Python을 활용한 KNN 실습 (iris데이터) 본문

AI & BigData/Basic

Python을 활용한 KNN 실습 (iris데이터)

brad.min 2020. 12. 27. 12:44
반응형

지난번 R를 활용한 KNN 실습을 해보았고 이번에는 Python 언어를 활용하여 KNN 실습을 하였다.

 

R를 활용한 KNN 실습 (iris 데이터)

KNN 인접 기법 (k-nearest neighbor) KNN는 머신러닝 기법 중의 한가지로 값을 분류하는 알고리즘이다. 분류와 군집은 비슷해 보이지만 목표값을 알고 분석하는 것은 분류(지도학습), 목표값을 모르고

techbrad.tistory.com

실습 과정은 데이터의 분포를 먼저 살펴보고 적절한 K를 찾아 KNN 알고리즘을 활용하여 모델을 만들어 보고자 한다.

 

 

Python 코드

 

사용한 라이브러리 및 기본 데이터 셋팅

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import datasets
from sklearn.decomposition import PCA
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split, cross_val_score

# load Iris datasets
iris = datasets.load_iris()

# X는 data 배열의 2열까지 출력
X = iris.data[:, :2]
y = iris.target

 

2차원 그래프로 데이터 살펴보기

#x축 y축 범위 설정
x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5

plt.figure(figsize=(8,6))
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Set1, edgecolor='k')
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.show()

Sepal length와 width의 변화에 따라 target이 달라진다. 이를 3D로도 살펴보았다.

 

3차원 그래프로 데이터 살펴보기

fig = plt.figure(figsize=(8,6))
ax = Axes3D(fig, elev=-150, azim=100)
X_reduced = PCA(n_components=3).fit_transform(iris.data)
ax.scatter(X_reduced[:,0], X_reduced[:,1], X_reduced[:,2], c=y, cmap=plt.cm.Set1, edgecolor='k', s=40)
ax.set_title("My First three PDA directions")
ax.set_xlabel("1st eigenvector")
ax.w_xaxis.set_ticklabels([])
ax.set_ylabel("2nd eigenvector")
ax.w_yaxis.set_ticklabels([])
ax.set_zlabel("3rd eigenvector")
ax.w_zaxis.set_ticklabels([])

plt.show()

3D로 보면 명확하게 구분되어 있는 것을 확인할 수 있다.

 

적절한 K 값 찾기

train_acc = []
test_acc = []

for n in range(1,15):
    clf = KNeighborsClassifier(n_jobs=-1, n_neighbors=n)
    clf.fit(x_train, y_train)
    prediction = clf.predict(x_test)
    train_acc.append(clf.score(x_train, y_train))
    test_acc.append((prediction==y_test).mean())

plt.figure(figsize=(12, 9))
plt.plot(range(1, 15), train_acc, label='TRAIN set')
plt.plot(range(1, 15), test_acc, label='TEST set')
plt.xlabel("n_neighbors")
plt.ylabel("accuracy")
plt.xticks(np.arange(0, 16, step=1))
plt.legend()
plt.show()

그래프에서 보면 Train과 Test 결과가 가장 높은 11번으로 K값을 지정하는 것이 가장 좋다고 나온다. 즉, 한 데이터가 입력되었을 때 주변 11개의 데이터를 보고 판단하는 것이 가장 분류 결과가 잘 나온다는 뜻이다.

 

K값을 적용 후 정확도 산정

clf = KNeighborsClassifier(n_neighbors=11)
clf.fit(x_train, y_train)
print("clf.score             : {0:.3f}".format(clf.score(x_train, y_train)))

prediction = clf.predict(x_test)
print("(pred == y_test) score: {0:.3f}".format((prediction==y_test).mean()))
print("cross_val_score       : {0:.3f}".format(cross_val_score(clf, x_train, y_train, cv=10).mean()))

결과 값
clf.score             : 0.830
(pred == y_test) score: 0.789
cross_val_score       : 0.750

학습으로는 정확도가 0.830으로 나왔고 test 데이터를 입력하였을 떄는 0.789의 정확도가 나왔다.

반응형