KNN
K-Nearest Neighbors
A classification/regression algorithm based on K nearest neighbors. Simple but effective.
K-Nearest Neighbors
A classification/regression algorithm based on K nearest neighbors. Simple but effective.
KNN (K-Nearest Neighbors) is a supervised learning algorithm that performs classification or regression based on the K nearest neighbor data points. When new data comes in, it finds the K closest points among the existing data and predicts by majority vote (classification) or average (regression).
Proposed by Evelyn Fix and Joseph Hodges in 1951, KNN is called a "lazy learning" algorithm. This is because it has no training phase, stores all the data, and performs computation only at prediction time. It is easy to understand and simple to implement, so it is often used in introductory ML education.
Euclidean distance, Manhattan distance, Minkowski distance, and others are used for distance calculation. In high-dimensional data, performance degrades due to the "curse of dimensionality," so dimensionality reduction such as PCA is needed.
In practice, KNN is used as a baseline for recommendation systems, anomaly detection, and image classification. The K value is usually set to an odd number (3, 5, 7), and the optimal value is found through cross-validation. For large datasets, search speed is improved with Ball Tree or KD Tree.
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import cross_val_score, GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_iris
from sklearn.pipeline import Pipeline
import numpy as np
# 데이터 로드
X, y = load_iris(return_X_y=True)
# 파이프라인 구성 (정규화 + KNN)
# KNN은 거리 기반이므로 정규화 필수!
pipeline = Pipeline([
('scaler', StandardScaler()),
('knn', KNeighborsClassifier())
])
# 최적 K값 찾기 (GridSearchCV)
param_grid = {
'knn__n_neighbors': [1, 3, 5, 7, 9, 11],
'knn__weights': ['uniform', 'distance'], # uniform: 동일 가중, distance: 거리 반비례
'knn__metric': ['euclidean', 'manhattan']
}
grid_search = GridSearchCV(
pipeline, param_grid, cv=5, scoring='accuracy', n_jobs=-1
)
grid_search.fit(X, y)
print(f"최적 파라미터: {grid_search.best_params_}")
print(f"최고 정확도: {grid_search.best_score_:.4f}")
# 최적 모델로 예측
best_model = grid_search.best_estimator_
new_sample = [[5.1, 3.5, 1.4, 0.2]] # 새로운 꽃 데이터
prediction = best_model.predict(new_sample)
proba = best_model.predict_proba(new_sample)
print(f"\n새 샘플 예측 클래스: {prediction[0]}")
print(f"클래스별 확률: {proba[0]}")
# K값에 따른 정확도 시각화
k_values = range(1, 21)
accuracies = []
for k in k_values:
knn = Pipeline([
('scaler', StandardScaler()),
('knn', KNeighborsClassifier(n_neighbors=k))
])
scores = cross_val_score(knn, X, y, cv=5)
accuracies.append(scores.mean())
print(f"\n최적 K: {k_values[np.argmax(accuracies)]} (정확도: {max(accuracies):.4f})")
"I ran KNN first as a baseline and got 89% accuracy. I set K=5 with distance weighting. Before introducing a more complex model, this figure will serve as the point of comparison."
"KNN is lazy learning, so it has no training phase and stores all the data. At prediction time it incurs O(n*d) time complexity, so for large datasets, Ball Tree or KD Tree is used to implement O(log n) search."
"In high dimensions, because of the curse of dimensionality, all points end up at similar distances. You should consider reducing dimensions with PCA, or approximate nearest neighbor algorithms such as Locality-Sensitive Hashing."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Features with large scales dominate the distance calculation. Be sure to normalize with StandardScaler or MinMaxScaler.
Ties can occur in majority voting. Use an odd number such as 3, 5, or 7.
Setting weights='distance' gives higher weight to closer neighbors, which improves accuracy.