Notice
Recent Posts
Recent Comments
Link
«   2026/02   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
Tags
more
Archives
Today
Total
관리 메뉴

Silver bullet

K-Nearest Neighbor Algorithm 본문

AI/AI

K-Nearest Neighbor Algorithm

밀크쌀과자 2024. 7. 11. 13:53

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()