Despite the similar names, K-Nearest Neighbors and K-Means solve fundamentally different problems.
KNN is supervised: given labeled training points, classify a new point by majority vote among its nearest neighbors.
K-Means is unsupervised: given unlabeled points, partition them into clusters by minimizing within-cluster variance,
The only thing they share is the letter and a reliance on distance metrics. Everything else — the problem being solved, whether labels are needed, what “” even means — is different.
Choosing
For KNN, small overfits (sensitive to noise), large underfits (oversmooths decision boundaries) — typically chosen via cross-validation.
For K-Means, is chosen before clustering even starts, often via the elbow method: plot within-cluster sum of squares against and look for the point of diminishing returns.
from sklearn.cluster import KMeans
inertias = []
for k in range(1, 11):
km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X)
inertias.append(km.inertia_)
Two algorithms, two totally different notions of what “” is even for.