Silver bullet
K-Nearest Neighbor Algorithm 본문
K-Nearest Neighbor Algorithm (KNN, K-최근접 이웃 알고리즘)
- 기존이 가까운 이웃 데이터를 살펴 새로운 데이터를 분류하는 알고리즘
- K값이 작을수록 Overfitting이 심하게 난다.
* 성능 측면에서는 Gradient Boosting Classifier나 SVM Classifier보다 좋지 않음
KNN - 붓꽃 데이터 분류 문제
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import neighbors, datasets
import warnings
warnings.filterwarnings("ignore") # 불필요한 Warning 메시지를 꺼줍니다.
iris = datasets.load_iris()
pd.DataFrame(iris['target']).value_counts()
# prepare data
x = iris.data[:, :2] # 모든 행, 앞에서 두번째 열까지
y = iris.target
model = neighbors.KNeighborsClassifier(n_neighbors=6) # K-Neighbors & 클러스터 분류 (Classifier)
model.fit(x, y)
model.predict([[9, 2.5], [3.5, 11]]) # class 2, class 0
# 실제 데이터 살펴보기
plt.figure(figsize=(10,5))
plt.scatter(x[:, 0], x[:, 1])
plt.title("Data points")
plt.show()