k Nearest Neighber
- 새로운 데이터가 있을때, 기존 데이터의 그룹 중 어떤 그룹에 속하는지를 분류하는 문제
- k는 몇 번째 가까운 데이터까지 볼 것인가를 정하는 수치
![](https://velog.velcdn.com/images/tim0902/post/8022e531-0d98-4fff-938f-e6d8db80d18b/image.png)
![](https://velog.velcdn.com/images/tim0902/post/aa48decf-6ac2-4679-9e42-67e473085061/image.png)
k=5로 설정하면 5번째까지 가까운 데이터
![](https://velog.velcdn.com/images/tim0902/post/64226def-c0f7-4712-b2b8-b033af533285/image.png)
k값에 따라 결과값이 바뀔수 있다
![](https://velog.velcdn.com/images/tim0902/post/5a58b46c-6801-4927-9ad5-6f634ece0901/image.png)
거리를 계산 - 유클리드 기하
![](https://velog.velcdn.com/images/tim0902/post/35ab7a4c-3e05-4af5-ad66-3b0a9714d0b0/image.png)
단위에 따라 바뀔 수도 있다 - 표준화 필요
![](https://velog.velcdn.com/images/tim0902/post/17408482-5be9-4614-b7b1-cb22c853c1f2/image.png)
장단점
- 실시간 예측을 위한 학습이 필요치 않다.
- 결국 속도가 빨라진다.
- 고차원 데이터에는 적합하지 않다.
Iris data
from sklearn.datasets import load_iris
iris = load_iris()
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=13, stratify=iris.target)
kNN 학습
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier()
knn.fit(X_train, y_train)
![](https://velog.velcdn.com/images/tim0902/post/bf1726ea-3cd4-4cf8-bdb8-9d34684946ff/image.png)
accuracy
from sklearn.metrics import accuracy_score
pred = knn.predict(X_test)
print(accuracy_score(y_test, pred))
![](https://velog.velcdn.com/images/tim0902/post/62b3ca17-8ee2-4033-8706-6672743b07a2/image.png)
결과
from sklearn.metrics import classification_report, confusion_matrix
confusion_matrix(y_test, pred)
![](https://velog.velcdn.com/images/tim0902/post/b93f7297-6cf1-44ec-a8c0-b1a7f7e7dc21/image.png)
print(classification_report(y_test, pred))
![](https://velog.velcdn.com/images/tim0902/post/8a9d4c6f-db37-4602-9f27-a7860688da8d/image.png)