SciPy K-Means Clustering
Clustering groups similar items together without being told the groups in advance: customers with similar buying habits, pixels of similar colour, sensors behaving alike. It's a form of unsupervised learning. SciPy's scipy.cluster package offers the two classic approaches: k-means (scipy.cluster.vq, this lesson) and hierarchical clustering (scipy.cluster.hierarchy, the next lesson).
How k-means works
K-means splits the data into k groups, each represented by its centroid (the mean of its points):
- Pick
kstarting centroids. - Assign every point to its nearest centroid.
- Move each centroid to the mean of its assigned points.
- Repeat steps 2–3 until nothing changes.
The result minimises the total squared distance from points to their centroids (the distortion or inertia).
A first example
Let's create three groups of customers described by two features — visits per month and average spend — and let kmeans2 find them:
import numpy as np
from scipy.cluster.vq import kmeans2
rng = np.random.default_rng(0)
groups = [rng.normal([2, 20], [0.5, 4], size=(30, 2)), # rare, cheap
rng.normal([8, 25], [1.0, 5], size=(30, 2)), # frequent, cheap
rng.normal([5, 80], [1.0, 8], size=(30, 2))] # medium, big spenders
data = np.vstack(groups)
centroids, labels = kmeans2(data, 3, minit="++", seed=1)
order = np.argsort(centroids[:, 1]) # sort by spend for display
for new_id, k in enumerate(order):
c = centroids[k]
print(f"cluster {new_id}: {np.sum(labels == k):2d} customers, "
f"visits {c[0]:.2f}, spend {c[1]:.2f}")cluster 0: 60 customers, visits 5.03, spend 23.19
cluster 1: 6 customers, visits 4.71, spend 68.54
cluster 2: 24 customers, visits 4.91, spend 82.80
kmeans2 returns the centroids and a label for every point. minit="++" uses the k-means++ initialisation, which spreads the starting centroids out and usually gives better results than purely random starts.
But look at the result: it is wrong! We created three groups of 30, yet k-means merged the two cheap groups into one cluster of 60 and split the big spenders in two. The algorithm did its job; the problem is the data, as the next section explains.
Scaling the features first
Spend ranges over tens of units, visits over just a few. K-means uses plain Euclidean distance, so a difference of 6 visits counts no more than a difference of 6 in spend, which is tiny. The feature with the larger spread dominates. whiten() divides each feature by its standard deviation so both count equally:
import numpy as np
from scipy.cluster.vq import kmeans2, whiten
rng = np.random.default_rng(0)
data = np.vstack([rng.normal([2, 20], [0.5, 4], size=(30, 2)),
rng.normal([8, 25], [1.0, 5], size=(30, 2)),
rng.normal([5, 80], [1.0, 8], size=(30, 2))])
truth = np.repeat([0, 1, 2], 30)
def agreement(labels):
# share of points whose cluster matches the majority cluster of their true group
hits = sum(np.bincount(labels[truth == g]).max() for g in range(3))
return hits / len(labels)
_, raw_labels = kmeans2(data, 3, minit="++", seed=3)
scaled = whiten(data)
print("std before:", np.round(data.std(axis=0), 2), " after:", np.round(scaled.std(axis=0), 2))
_, scaled_labels = kmeans2(scaled, 3, minit="++", seed=3)
print(f"agreement with true groups, raw : {agreement(raw_labels):.0%}")
print(f"agreement with true groups, whiten : {agreement(scaled_labels):.0%}")std before: [ 2.66 27.38] after: [1. 1.]
agreement with true groups, raw : 80%
agreement with true groups, whiten : 100%
Tip: Always scale features that are measured in different units before clustering. After clustering scaled data, multiply the centroids by the original standard deviations to read them in the original units.
Choosing k: the elbow method
K-means needs k in advance. A common heuristic: run it for several values and plot the distortion. It always drops as k grows, but the drop slows sharply after the "right" number — the elbow:
import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.vq import kmeans, whiten
rng = np.random.default_rng(0)
data = whiten(np.vstack([rng.normal([2, 20], [0.5, 4], size=(30, 2)),
rng.normal([8, 25], [1.0, 5], size=(30, 2)),
rng.normal([5, 80], [1.0, 8], size=(30, 2))]))
ks = range(1, 7)
distortions = [kmeans(data, k, seed=0)[1] for k in ks]
plt.plot(list(ks), distortions, "o-")
plt.xlabel("k (number of clusters)")
plt.ylabel("mean distance to centroid")
plt.title("Elbow method")
plt.show()
for k, d in zip(ks, distortions):
print(f"k={k}: distortion {d:.3f}")k=1: distortion 1.388
k=2: distortion 0.876
k=3: distortion 0.322
k=4: distortion 0.281
k=5: distortion 0.252
k=6: distortion 0.230
kmeans() (without the 2) returns the centroids and the mean distance of points to their nearest centroid; it runs several random starts and keeps the best.
Vector quantisation
Once you have centroids, vq() assigns new points to the nearest one — that's how k-means is used for classification or compression (the "vq" stands for vector quantisation):
import numpy as np
from scipy.cluster.vq import vq
centroids = np.array([[2.0, 20.0], [8.0, 25.0], [5.0, 80.0]])
names = ["occasional", "regular", "big spender"]
new_customers = np.array([[1.5, 18.0], [9.0, 30.0], [4.0, 70.0], [6.0, 50.0]])
codes, dists = vq(new_customers, centroids)
for point, code, d in zip(new_customers, codes, dists):
print(f"{point} -> {names[code]:11} (distance {d:.2f})")[ 1.5 18. ] -> occasional (distance 2.06)
[ 9. 30.] -> regular (distance 5.10)
[ 4. 70.] -> big spender (distance 10.05)
[ 6. 50.] -> regular (distance 25.08)
Note: K-means assumes roughly round, similarly sized clusters. For elongated or nested shapes, or when you don't know
k, hierarchical clustering (next lesson) or density-based methods may work better.
Test yourself
What does k-means minimise?
- The number of clusters
- The total squared distance between points and their cluster centroids
- The distance between centroids
- The number of iterations
Why call whiten() before k-means?
- To remove outliers
- To give each feature unit variance so no feature dominates the distance
- To sort the data
- To choose k
How does the elbow method suggest a value of k?
- The k with zero distortion
- The k where adding more clusters stops reducing the distortion much
- Always k = 3
- The largest k tried