k-NN
k-Nearest Neighbors
An algorithm that classifies by the k nearest neighbors. A simple but effective non-parametric machine learning technique.
k-Nearest Neighbors
An algorithm that classifies by the k nearest neighbors. A simple but effective non-parametric machine learning technique.
k-NN (k-Nearest Neighbors) is an algorithm that, when classifying or predicting a new data point, makes its decision by referring to the k closest training data points. In classification problems, the class is determined by majority vote among the k neighbors, and in regression problems, the average of the k neighbors' values is used as the predicted value.
k-NN is one of the oldest Machine Learning algorithms, proposed in 1951 by Evelyn Fix and Joseph Hodges. It is called a "lazy learning" algorithm because it does not build a model during the training phase, but simply stores the data and performs the computation at prediction time. This leads to the characteristic of fast training but slow prediction.
The core of k-NN lies in the distance metric and the choice of the k value. Euclidean distance is generally used, but Manhattan distance, Minkowski distance, cosine similarity, and others are also used. If k is too small, the model becomes sensitive to noise (overfitting), and if it is too large, the decision boundary becomes blurred (underfitting). The optimal k is usually found through cross-validation.
In practice, k-NN is often used as a baseline for recommendation systems, anomaly detection, and image classification. It is also the foundation of ANN (Approximate Nearest Neighbor), which is used for similar document search in vector databases (Pinecone, Milvus, etc.). However, performance can degrade on high-dimensional data due to the "curse of dimensionality," so it is advisable to use it together with dimensionality reduction.
# k-NN 완전 가이드: 분류, 회귀, 최적화
import numpy as np
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
from sklearn.model_selection import cross_val_score, GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_iris, load_diabetes
from sklearn.pipeline import Pipeline
import matplotlib.pyplot as plt
# 1. 기본 k-NN 분류
def basic_knn_classification():
"""기본 k-NN 분류 예제"""
# 데이터 로드
iris = load_iris()
X, y = iris.data, iris.target
# 스케일링 + k-NN 파이프라인
pipeline = Pipeline([
('scaler', StandardScaler()), # k-NN은 스케일에 민감!
('knn', KNeighborsClassifier(n_neighbors=5))
])
# 교차 검증으로 성능 평가
scores = cross_val_score(pipeline, X, y, cv=5)
print(f"평균 정확도: {scores.mean():.3f} (+/- {scores.std()*2:.3f})")
# 학습 및 예측
pipeline.fit(X, y)
new_sample = [[5.1, 3.5, 1.4, 0.2]]
prediction = pipeline.predict(new_sample)
probabilities = pipeline.predict_proba(new_sample)
print(f"예측 클래스: {iris.target_names[prediction[0]]}")
print(f"클래스별 확률: {dict(zip(iris.target_names, probabilities[0]))}")
return pipeline
# 2. 최적 k 값 찾기
def find_optimal_k():
"""교차 검증으로 최적의 k 찾기"""
iris = load_iris()
X, y = iris.data, iris.target
k_range = range(1, 31)
scores = []
for k in k_range:
knn = KNeighborsClassifier(n_neighbors=k)
score = cross_val_score(
knn, X, y,
cv=10,
scoring='accuracy'
).mean()
scores.append(score)
optimal_k = k_range[np.argmax(scores)]
print(f"최적 k: {optimal_k}, 정확도: {max(scores):.3f}")
# 시각화
plt.figure(figsize=(10, 6))
plt.plot(k_range, scores, 'bo-')
plt.axvline(x=optimal_k, color='r', linestyle='--', label=f'최적 k={optimal_k}')
plt.xlabel('k (이웃 수)')
plt.ylabel('교차 검증 정확도')
plt.title('k 값에 따른 정확도 변화')
plt.legend()
plt.grid(True)
plt.savefig('knn_k_selection.png')
plt.close()
return optimal_k
# 3. 하이퍼파라미터 그리드 서치
def optimize_knn_hyperparameters():
"""GridSearchCV로 하이퍼파라미터 최적화"""
iris = load_iris()
X, y = iris.data, iris.target
pipeline = Pipeline([
('scaler', StandardScaler()),
('knn', KNeighborsClassifier())
])
param_grid = {
'knn__n_neighbors': [3, 5, 7, 9, 11],
'knn__weights': ['uniform', 'distance'], # 거리 가중치
'knn__metric': ['euclidean', 'manhattan', 'minkowski']
}
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_:.3f}")
return grid_search.best_estimator_
# 4. k-NN 회귀
def knn_regression():
"""k-NN 회귀 예제"""
diabetes = load_diabetes()
X, y = diabetes.data, diabetes.target
pipeline = Pipeline([
('scaler', StandardScaler()),
('knn', KNeighborsRegressor(n_neighbors=5, weights='distance'))
])
scores = cross_val_score(
pipeline, X, y,
cv=5,
scoring='neg_mean_squared_error'
)
rmse = np.sqrt(-scores.mean())
print(f"RMSE: {rmse:.2f}")
return pipeline.fit(X, y)
# 5. 벡터 검색에서의 k-NN (RAG 시스템)
def knn_for_vector_search():
"""RAG 시스템에서 유사 문서 검색"""
from sklearn.neighbors import NearestNeighbors
# 가상의 문서 임베딩 (실제로는 OpenAI/Sentence-Transformers 사용)
documents = [
"파이썬은 배우기 쉬운 프로그래밍 언어입니다.",
"자바스크립트는 웹 개발에 필수적입니다.",
"머신러닝은 인공지능의 한 분야입니다.",
"딥러닝은 신경망을 활용합니다.",
"k-NN은 분류 알고리즘입니다."
]
# 간단한 TF-IDF 임베딩 (실제로는 dense embedding 사용)
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer()
embeddings = vectorizer.fit_transform(documents).toarray()
# k-NN 모델 (코사인 유사도)
nn_model = NearestNeighbors(
n_neighbors=3,
metric='cosine',
algorithm='brute' # 작은 데이터셋에서는 brute force
)
nn_model.fit(embeddings)
# 쿼리 검색
query = "AI와 기계학습에 대해 알려주세요"
query_embedding = vectorizer.transform([query]).toarray()
distances, indices = nn_model.kneighbors(query_embedding)
print("유사 문서 검색 결과:")
for i, (dist, idx) in enumerate(zip(distances[0], indices[0])):
similarity = 1 - dist # 코사인 거리를 유사도로 변환
print(f" {i+1}. [{similarity:.3f}] {documents[idx]}")
return nn_model
# 6. 대용량 데이터를 위한 Approximate NN
def approximate_nn():
"""대용량 데이터를 위한 근사 최근접 이웃 (FAISS)"""
try:
import faiss
# 100만 개의 128차원 벡터 (예시)
d = 128 # 차원
nb = 100000 # 데이터베이스 크기
nq = 10 # 쿼리 수
np.random.seed(1234)
xb = np.random.random((nb, d)).astype('float32')
xq = np.random.random((nq, d)).astype('float32')
# IVF 인덱스 (클러스터 기반 근사 검색)
nlist = 100 # 클러스터 수
quantizer = faiss.IndexFlatL2(d)
index = faiss.IndexIVFFlat(quantizer, d, nlist)
index.train(xb) # 클러스터 중심 학습
index.add(xb) # 벡터 추가
# 검색 (k=4 이웃)
k = 4
index.nprobe = 10 # 검색할 클러스터 수
distances, indices = index.search(xq, k)
print(f"첫 번째 쿼리의 4개 이웃 인덱스: {indices[0]}")
print(f"거리: {distances[0]}")
except ImportError:
print("FAISS가 설치되지 않았습니다: pip install faiss-cpu")
# 실행
if __name__ == "__main__":
# 기본 분류
print("=== 기본 k-NN 분류 ===")
basic_knn_classification()
# 최적 k 찾기
print("\n=== 최적 k 찾기 ===")
find_optimal_k()
# 하이퍼파라미터 최적화
print("\n=== 하이퍼파라미터 최적화 ===")
optimize_knn_hyperparameters()
# 벡터 검색
print("\n=== 벡터 검색 ===")
knn_for_vector_search()
"We need a baseline for the recommendation system." - "Why not start with k-NN? We find the k users with similar tastes based on the similarity between user embeddings, and recommend the items they liked. It's simple to implement and the results are easy to interpret, so it's good for business validation. Once the performance is confirmed, we can upgrade to matrix factorization or deep learning."
"Please explain the pros and cons of k-NN and how to choose the value of k." - "The advantages are that it's simple to implement, easy to interpret, and easy to add new classes. The disadvantages are that it's slow because it compares all the data at prediction time, and it has the 'curse of dimensionality' problem, where performance drops in high dimensions. We find k through cross-validation, and we usually choose an odd number to avoid ties. A small k tends to overfit and a large k tends to underfit, so you need to find the right balance."
"Is vector search in RAG also k-NN?" - "Yes, more precisely, it uses ANN (Approximate Nearest Neighbor). Exact k-NN over millions of documents would be too slow, so approximate algorithms like FAISS or HNSW are used. By sacrificing a little accuracy, you can increase search speed hundreds of times. These algorithms also run inside vector DBs like Pinecone and Milvus."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Because k-NN is distance-based, it is sensitive to the scale of features. When units differ, such as age (0–100) and annual salary (0–100 million), salary dominates the distance calculation. Be sure to apply StandardScaler or MinMaxScaler.
As dimensionality increases, the "curse of dimensionality" occurs, in which the distances between all points become similar. For data with hundreds of dimensions or more, reduce the dimensionality with PCA, t-SNE, etc., or use cosine similarity, which is robust in high dimensions.
Combine scaling and k-NN in a pipeline. Find k through cross-validation, and you can give closer neighbors more weight with the weights='distance' option. For large datasets, consider ANN libraries such as FAISS or Annoy.