Skip to main content

05 - KNN and Clustering: K-Means, DBSCAN and Where They Fail

Run KNN by hand, choose K without touching the test set, and see where K-Means, Ward, single linkage and DBSCAN agree or fail on data with a known answer.

What do you think about this article?

At a Glance

Run KNN by hand, choose K without touching the test set, and see where K-Means, Ward, single linkage and DBSCAN agree or fail on data with a known answer.

Two algorithms that use distance, and that must not be confused

K-Nearest Neighbors (KNN) and K-Means share only the letter K. KNN is supervised: to classify a new point it looks at the K nearest labeled examples and takes the majority class. K-Means is unsupervised: it has no labels and groups the points into K groups around centers. Both rest on an idea to be checked in every project, that near means similar, and therefore on a choice that is almost always made out of habit: how you measure the distance and on what scale the variables are. In the sections that follow you will see KNN with the choice of K, then K-Means, DBSCAN and hierarchical clustering put to the test on data where the right answer is known. If you want the picture of the paradigms first, reread the introduction; for the comparison with another classifier close to the data, the SVMs.

KNN: no training, all the work at prediction time

KNN is a lazy learner: fit merely memorizes the data, and each prediction computes the distance from the new point to all the examples. This makes it simple to understand, and expensive at prediction time when the data grow. The scikit-learn guide describes the brute-force approach, which compares the point with all the others and costs O(D·N²) on the comparison of all pairs, and the tree structures (kd_tree, ball_tree) that reduce it: with algorithm='auto' the library chooses by itself. The most used distance is the Euclidean, the straight line; the Manhattan sums the absolute differences, like walking along the avenues of a grid; the Minkowski includes both with an exponent p (1 is Manhattan, 2 is Euclidean).

The listing makes the prediction by hand on nine fruits described by weight and diameter. The values are invented; I added an unusually large "apple" (196 g) among the oranges, to represent a noisy example. The vicini function computes the Minkowski distance with a p of your choice, sorts the points and the loop votes with the first k. The result is compared with KNeighborsClassifier.

Python - KNN by hand and the weight of K
import numpy as np
from collections import Counter
from sklearn.neighbors import KNeighborsClassifier

# Fruits: weight (g) and diameter (cm). Classes: 0 = apple, 1 = orange (values invented for the example)
X = np.array([[150, 7.0], [160, 7.3], [170, 7.5], [140, 6.8], [190, 8.0], [200, 8.2], [210, 8.5], [180, 7.9],
              [196, 8.1]])                       # an unusually large apple, among the oranges
y = np.array([0, 0, 0, 0, 1, 1, 1, 1, 0])
nuovo = np.array([194, 8.1])

def vicini(X, nuovo, p):
    d = (np.abs(X - nuovo) ** p).sum(axis=1) ** (1 / p)       # Minkowski distance: p=1 Manhattan, p=2 Euclidean
    return np.argsort(d), d

ordine, d = vicini(X, nuovo, 2)
print("Euclidean distances in order:", d[ordine].round(2), "classes:", y[ordine])
for k in (1, 3, 5):
    voto = Counter(y[ordine[:k]]).most_common(1)[0][0]
    print(f"k={k}: manual vote = {voto}   sklearn = {KNeighborsClassifier(n_neighbors=k).fit(X, y).predict([nuovo])[0]}")

# Output:
# Euclidean distances in order: [ 2.    4.    6.   14.   16.   24.01 34.01 44.01 54.02] classes: [0 1 1 1 1 0 0 0 0]
# k=1: manual vote = 0   sklearn = 0
# k=3: manual vote = 1   sklearn = 1
# k=5: manual vote = 1   sklearn = 1

The distances in order are 2, 4, 6, 14, 16 and then over 24, with the corresponding classes 0, 1, 1, 1, 1: the point nearest to 194 g is precisely the anomalous apple at 196 g. With k = 1 the vote is therefore 0 (apple), with k = 3 and k = 5 the majority moves to 1 (orange). The hand-written code and the scikit-learn one agree every time. This is the lesson on the parameter: a small k follows the noise (high variance, overfitting), a large k flattens toward the dominant class (high bias, underfitting), and it is chosen on the data. If k is even, ties can arise in a two-class problem: an odd value is better.

Scaling and choosing K with cross-validation

KNN suffers from unscaled data more than any other: in the fruit example, one gram of weight difference counts as much as one centimeter of diameter difference, and the diameter does not matter. The listing measures it on the Wine dataset (178 wines, 13 chemical measurements, very different scales): first it compares k = 5 with and without StandardScaler, then it chooses k from 1 to 30 with a five-fold cross-validation that sees only the training set, and finally it measures the test set once.

Python - Scaling and choice of K without touching the test set
import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

grezzo = KNeighborsClassifier(n_neighbors=5).fit(X_train, y_train)
scalato = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5)).fit(X_train, y_train)
print(f"k=5 without scaling: test {grezzo.score(X_test, y_test):.3f}   with scaling: test {scalato.score(X_test, y_test):.3f}")

risultati = {}
for k in range(1, 31):
    modello = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=k))
    risultati[k] = cross_val_score(modello, X_train, y_train, cv=5).mean()
for k in (1, 3, 5, 9, 15, 29):
    print(f"k={k:2d}: cross-validation {risultati[k]:.3f}")
best_k = max(risultati, key=risultati.get)
finale = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=best_k)).fit(X_train, y_train)
print(f"chosen k: {best_k} (cv {risultati[best_k]:.3f}), test {finale.score(X_test, y_test):.3f}")

# Output:
# k=5 without scaling: test 0.722   with scaling: test 0.944
# k= 1: cross-validation 0.950
# k= 3: cross-validation 0.951
# k= 5: cross-validation 0.958
# k= 9: cross-validation 0.944
# k=15: cross-validation 0.958
# k=29: cross-validation 0.958
# chosen k: 21 (cv 0.965), test 0.944

The first result is the most important of the article: without scaling the test gives 0.722, with scaling 0.944. That is 22 points lost because the proline variable, in the order of hundreds, crushes the others. Then the table of k: the cross-validation, for the six values printed, stays between 0.944 and 0.958, and the best choice (k = 21 with 0.965) is separated from k = 5 (0.958) by a difference of less than one point, which on a training set of 142 samples equals one or two examples. Take that choice as a good compromise, not as the "optimal" value. The final test, 0.944, is in line with the cross-validation, and this consistency is what says the method worked. One last note: KNN also suffers with many irrelevant variables, because the distance counts them all in the same way: the scikit-learn guide traces this back to the "curse of dimensionality".

K-Means: centers, inertia and how to choose K

K-Means alternates two steps: it assigns each point to the nearest center, then moves each center to the mean of the assigned points. The criterion it minimizes is the inertia, the sum of the squared distances from the centers; the scikit-learn guide warns that inertia presupposes convex and isotropic clusters, that is roundish and of similar size. K must be fixed beforehand, and the elbow method and the quality indexes serve to choose it. The listing generates three groups of customers with two variables (purchase frequency and average basket), standardizes them and tries them with K from 2 to 7, printing four measures. Inertia always falls as K increases, so alone it is not enough: you look for the "elbow" where the decline slows. The silhouette (from -1 to 1, higher is better) and the Calinski-Harabasz index (higher is better) reward compact and separated groups; the Davies-Bouldin index reads the other way round (lower is better).

Python - Choosing K with inertia, silhouette and two other indexes
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import calinski_harabasz_score, davies_bouldin_score, silhouette_score
from sklearn.preprocessing import StandardScaler

# Three customer groups: coordinates (purchase frequency, average basket), with a fixed seed
rng = np.random.default_rng(42)
X = np.vstack([
    rng.normal([2, 2], 0.5, (100, 2)),
    rng.normal([7, 7], 0.8, (100, 2)),
    rng.normal([2, 8], 0.6, (100, 2)),
])
Z = StandardScaler().fit_transform(X)

print(" k   inertia  silhouette  davies-bouldin  calinski-harabasz")
for k in range(2, 8):
    km = KMeans(n_clusters=k, random_state=0, n_init=10).fit(Z)
    print(f"{k:2d}  {km.inertia_:8.1f}  {silhouette_score(Z, km.labels_):10.3f}  {davies_bouldin_score(Z, km.labels_):14.3f}  {calinski_harabasz_score(Z, km.labels_):17.1f}")

# Initialization matters: a single random start at a time, k=3
inerzie = [KMeans(n_clusters=3, init="random", n_init=1, random_state=s).fit(Z).inertia_ for s in range(10)]
print("inertia with a single random start, 10 seeds:", sorted({round(float(i), 1) for i in inerzie}))

# Output:
#  k   inertia  silhouette  davies-bouldin  calinski-harabasz
#  2     255.4       0.606           0.570              402.1
#  3      36.8       0.795           0.295             2275.4
#  4      29.7       0.651           0.713             1896.7
#  5      25.1       0.662           0.654             1690.2
#  6      20.5       0.527           0.836             1660.3
#  7      18.2       0.365           0.977             1560.7
# inertia with a single random start, 10 seeds: [36.8, 253.1]

With K = 2 the inertia is 255.4, with K = 3 it collapses to 36.8 and from there it falls slowly (29.7, 25.1, 20.5, 18.2): the elbow is at 3. The three indexes agree without coordinating with each other: the silhouette has its maximum (0.795) at K = 3, Davies-Bouldin its minimum (0.295), Calinski-Harabasz its maximum (2275.4). Here the answer is clear because I built the groups myself; on real data the three indexes can point to different values, and the decision remains a domain choice. The choice of initialization matters too: the last line repeats K = 3 with a single random start, for ten seeds, and obtains two solutions, inertia 36.8 (the right one) or 253.1, a local optimum with one group split and two merged. It is the reason for the n_init parameter: launch several starts and keep the best. With the default k-means++ initialization the start is already chosen with care, but n_init remains a cheap insurance policy.

DBSCAN and hierarchical clustering, where K-Means fails

DBSCAN defines groups by density. Two parameters: eps, the radius within which two points are neighbors, and min_samples, how many neighbors are needed to consider a point a "core" (in a dense zone). A cluster is a chain of core points close to each other plus the border points attached to them; everything that is not reachable is noise and gets the label -1. It does not require K and finds arbitrary shapes, but eps becomes the delicate parameter. Agglomerative hierarchical clustering merges the two closest groups at each step, and depends on the linkage criterion: Ward minimizes the increase in variance and gives regular groups, single linkage measures the distance between the two closest points of the groups and can follow non-globular shapes.

The listing uses two interleaved half-moons (300 points, noise 0.1), whose true partition we know, so we can measure the agreement with the Adjusted Rand Index (ARI: 1 means identical, 0 means chance). In a real situation you would not have these labels, and it is precisely the case in which the silhouette is the only tool available. That is why the listing prints both measures. Then it varies eps to show the sensitivity.

Python - K-Means, Ward, single linkage and DBSCAN on the half-moons
import numpy as np
from sklearn.cluster import DBSCAN, AgglomerativeClustering, KMeans
from sklearn.datasets import make_moons
from sklearn.metrics import adjusted_rand_score, silhouette_score
from sklearn.preprocessing import StandardScaler

X, vere = make_moons(n_samples=300, noise=0.1, random_state=42)
Z = StandardScaler().fit_transform(X)

def riga(nome, etichette):
    punti = etichette != -1
    sil = silhouette_score(Z[punti], etichette[punti]) if len(set(etichette[punti])) > 1 else float("nan")
    print(f"{nome:22s} silhouette {sil:6.3f}  ARI against the true labels {adjusted_rand_score(vere, etichette):6.3f}")

riga("K-Means (k=2)", KMeans(2, n_init=10, random_state=0).fit_predict(Z))
riga("Ward (k=2)", AgglomerativeClustering(2, linkage="ward").fit_predict(Z))
riga("single linkage (k=2)", AgglomerativeClustering(2, linkage="single").fit_predict(Z))
riga("DBSCAN eps=0.3", DBSCAN(eps=0.3, min_samples=10).fit_predict(Z))

print("DBSCAN sensitivity to eps (min_samples=10):")
for eps in (0.1, 0.2, 0.3, 0.5, 1.0):
    e = DBSCAN(eps=eps, min_samples=10).fit_predict(Z)
    print(f"  eps={eps}: clusters {len(set(e) - {-1})}, noise points {int(np.sum(e == -1))}")

# Output:
# K-Means (k=2)          silhouette  0.491  ARI against the true labels  0.479
# Ward (k=2)             silhouette  0.448  ARI against the true labels  0.716
# single linkage (k=2)   silhouette  0.375  ARI against the true labels  1.000
# DBSCAN eps=0.3         silhouette  0.384  ARI against the true labels  0.960
# DBSCAN sensitivity to eps (min_samples=10):
#   eps=0.1: clusters 0, noise points 300
#   eps=0.2: clusters 8, noise points 172
#   eps=0.3: clusters 2, noise points 6
#   eps=0.5: clusters 1, noise points 0
#   eps=1.0: clusters 1, noise points 0

Look at the two columns together. K-Means has the highest silhouette (0.491) and at the same time the lowest ARI (0.479): it cuts the half-moons in half with a line, obtains compact groups and judges them excellent, while the truth is another. DBSCAN with eps=0.3 has a lower silhouette (0.384, computed excluding the 6 noise points) but reconstructs the partition almost perfectly (ARI 0.960). Single linkage reconstructs it exactly (ARI 1.000), Ward does not (0.716). The silhouette rewards roundish groups, so it is not a neutral measure: choosing the algorithm that maximizes it means choosing the algorithm that finds circles. For irregular shapes you need judgment on the data, or an indirect check, for example whether the groups found make a downstream supervised model more accurate.

The last lines show the fragility of DBSCAN: with eps=0.1 no point has enough neighbors and all 300 are noise, with 0.2 eight fragmented clusters appear and 172 noise points, with 0.3 the two right groups, with 0.5 and 1.0 everything merges into one. A window of useful values exists but it is narrow, and it must be found by looking at the data, for example with the plot of the distances from the k-th neighbor. Since eps is a distance, here too scaling the variables is mandatory.

Which one to choose

KNN to classify with labels when the data are few or medium and the boundary is local, after scaling; K-Means to segment when the groups are round and of similar size and you know how many to look for; DBSCAN when the groups have an irregular shape, there are outliers to isolate or you do not know how many groups to expect; hierarchical when you care about the tree structure of the groupings. All depend on the scale of the variables: the systematic approach is in the article on Feature Engineering and Data Preprocessing.

What you can do now

You can classify with KNN, you know that without scaling the result can collapse by over twenty points, and you can choose K with cross-validation without using the test set. You can segment with K-Means and read inertia, silhouette and the other indexes together, knowing that initialization matters. You know that the silhouette favors round groups and that DBSCAN depends on eps. The next step is the foundation of all this: preparing the data, in Feature Engineering and Data Preprocessing.

The same distances and similarities return in recommendation systems, where nearby users and films are searched for.

Frequently asked questions

How do you choose K in KNN?

With cross-validation on the training set only, trying values over a range (for example 1-30) and preferring odd values in two-class problems. Differences of less than one point between nearby values of K are often noise.

What is the difference between K-Means and KNN?

KNN is supervised: it classifies a point based on the labels of its K neighbors. K-Means is unsupervised: it groups points without labels around K centers.

When is DBSCAN better than K-Means?

When the groups have an irregular shape, you do not know the number of groups or you want to isolate anomalous points as noise. DBSCAN however requires choosing eps with care.

How I checked the listings: I ran each one on its own on 2026-11-21 with Python 3.14.4, NumPy 2.3.5 and scikit-learn 1.8.0, and the decimal figures quoted in the text match the ones produced. With other library versions the last digits may change.

Sources

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects