Skip to content

MLDay 17 of 50Supervised and Unsupervised Learning

Group Unlabeled Data with k-Means

8 min read

A bike-share has 17,379 hours of rental records, and none of them is labelled "rush hour" or "lazy Sunday". The operations team still asks: what kinds of hours do we have? k-means finds the groups for you.

The idea

Unsupervised learning means learning from data that has no labels: no right answer to copy, only structure to find. A cluster is a group of points that sit closer to each other than to the rest.

k-means finds kk clusters, where you choose kk. Each cluster has a centroid (its centre): the mean of its points. Start with kk centres anywhere, then repeat two steps:

  1. Assign. Each point joins its nearest centre, measured by straight-line distance as in D15.
  2. Update. Each centre moves to the mean of its points.

When an Assign step moves no point, the loop has converged and stops. Neither step can raise the total squared distance from points to their centres, so the loop always ends. Where it ends depends on the start.

A tiny example

Six riders take 1, 2, 3, 10, 11 and 12 trips a week. Use k=2k = 2 and a deliberately bad start: centres at 1 and 4.

Round Centres Cluster A Cluster B JJ after Assign
1 1 and 4 1, 2 3, 10, 11, 12 151
2 1.5 and 9 1, 2, 3 10, 11, 12 16.75
3 2 and 11 1, 2, 3 10, 11, 12 4

In round 1, the rider with 3 trips is 1 away from centre 4 but 2 away from centre 1, so they join B. Update moves B's centre to (3+10+11+12)/4=9(3 + 10 + 11 + 12) / 4 = 9. Now the 3-trip rider is closer to 1.5, so they switch to A. In round 3 nobody moves, so k-means stops: casual riders around 2 trips, regulars around 11.

The formula

Inertia JJ adds up each point's squared distance to its own centre. Smaller means tighter clusters.

J=∑j=1k∑x∈Cj∥x−μj∥2J = \sum_{j=1}^{k} \sum_{x \in C_j} \lVert x - \mu_j \rVert^2
Symbol Meaning
JJ the inertia: the total squared distance from points to their centres
CjC_j the points in cluster jj
μj\mu_j the centroid of cluster jj (the mean of its points)
∥x−μj∥\lVert x - \mu_j \rVert the straight-line distance from point xx to that centroid

Worked, round 3: cluster A gives (1−2)2+(2−2)2+(3−2)2=1+0+1=2(1 - 2)^2 + (2 - 2)^2 + (3 - 2)^2 = 1 + 0 + 1 = 2. Cluster B also gives 2, so J=4J = 4.

JJ can't choose kk for you: more clusters can always lower it, down to 0 when every point has its own. Look for the elbow instead, the kk after which JJ stops dropping much. A second check is the silhouette, which asks whether each point is nearer its own cluster than the next one.

s=b−amax⁡(a,b)s = \frac{b - a}{\max(a, b)}
Symbol Meaning
ss one point's silhouette, from −1 to 1
aa the point's average distance to the other points in its own cluster
bb its average distance to the points of the nearest other cluster

Worked, the 2-trip rider: a=(1+1)/2=1a = (1 + 1) / 2 = 1 and b=(8+9+10)/3=9b = (8 + 9 + 10) / 3 = 9, so s=(9−1)/9≈0.89s = (9 - 1) / 9 \approx 0.89. Near 1 means deep inside its cluster; near 0, on a border; below 0, probably in the wrong cluster. The silhouette score is the average ss over all points, and a good kk makes it high.

Try it

Find the rider groups

Assign: each point joins its nearest centre (the crosses). Update: each centre moves to the middle of its points. Repeat until nothing changes.

2468100510Weekday rides a monthWeekend rides a month(1, 1.5), not assigned yet(2, 1), not assigned yet(1.5, 2.5), not assigned yet(2.5, 2), not assigned yet(2, 3), not assigned yet(3, 1.5), not assigned yet(8, 1), not assigned yet(9, 2), not assigned yet(8.5, 0.5), not assigned yet(9.5, 1.5), not assigned yet(7.5, 2), not assigned yet(8.5, 2.5), not assigned yet(1, 8), not assigned yet(2, 9), not assigned yet(1.5, 7), not assigned yet(2.5, 8.5), not assigned yet(3, 7.5), not assigned yet(1, 9.5), not assigned yetcluster 1 centre (7.5, 2)cluster 2 centre (8.5, 0.5)

inertia J press Assignsteps 0

Inertia J = Σ‖x − μ‖², the squared distance from each point to its centre, summed; neither step can raise it.

Press Assign, then Update, until the note says it has converged. With k=2k = 2, two corners share a centre and JJ stops at about 138.5. Set k=3k = 3 and step again: one centre walks across to the empty corner, and JJ falls to about 18.1. k=4k = 4 only gets to about 14.6, so 3 is the elbow.

In code

scikit-learn's KMeans runs the loop; inertia_ is JJ and labels_ holds each point's cluster. These are the six riders, with kk from 1 to 4.

# script_id: day_017_k_means_clustering/tiny_riders
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

trips = np.array([[1], [2], [3], [10], [11], [12]])   # trips a week, one rider per row

for k in [1, 2, 3, 4]:
    km = KMeans(n_clusters=k, random_state=42).fit(trips)
    line = f"k={k}  inertia={km.inertia_:6.2f}"
    if k > 1:                                      # the silhouette needs at least 2 clusters
        line += f"  silhouette={silhouette_score(trips, km.labels_):.2f}"
    print(line)

km = KMeans(n_clusters=2, random_state=42).fit(trips)
print("centres:", km.cluster_centers_.ravel())
print("labels: ", km.labels_)
print("a 9-trip rider joins cluster", km.predict([[9]])[0])
k=1  inertia=125.50
k=2  inertia=  4.00  silhouette=0.85
k=3  inertia=  2.50  silhouette=0.50
k=4  inertia=  1.00  silhouette=0.17
centres: [ 2. 11.]
labels:  [0 0 0 1 1 1]
a 9-trip rider joins cluster 1

Inertia drops from 125.5 to 4 at k=2k = 2, then barely moves: that's the elbow. The silhouette agrees, at its highest for k=2k = 2. The labels 0 and 1 are just names; k-means doesn't know which group is "casual".

Now the real hours, described by two features: rentals (cnt) and the casual share, the fraction of riders without a membership. Earlier days dropped casual because it gives away cnt, but nothing is predicted here. Both features are standardized first, because k-means measures distance (D09).

# script_id: day_017_k_means_clustering/bike_hours
import os
from pathlib import Path

import pandas as pd
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler

DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "bike_sharing" / "hour.csv", parse_dates=["dteday"])
df = df.assign(casual_share=df["casual"] / df["cnt"])    # share of riders without a membership
X = StandardScaler().fit_transform(df[["cnt", "casual_share"]])

for k in range(2, 7):
    km = KMeans(n_clusters=k, random_state=42).fit(X)
    print(f"k={k}  inertia={km.inertia_:6.0f}  silhouette={silhouette_score(X, km.labels_):.3f}")

df["cluster"] = KMeans(n_clusters=3, random_state=42).fit_predict(X)   # fit, then label each hour
profile = df.groupby("cluster").agg(hours=("cnt", "size"), rentals=("cnt", "mean"),
                                    casual_share=("casual_share", "mean"),
                                    workday=("workingday", "mean"), top_hour=("hr", lambda h: h.mode()[0]))
print(profile.sort_values("rentals").round(2))

raw = KMeans(n_clusters=3, random_state=42).fit_predict(df[["cnt", "casual_share"]])
print("unscaled, casual share by cluster:", df.groupby(raw)["casual_share"].mean().round(2).tolist())
k=2  inertia= 22037  silhouette=0.388
k=3  inertia= 13805  silhouette=0.425
k=4  inertia= 10867  silhouette=0.411
k=5  inertia=  8684  silhouette=0.398
k=6  inertia=  6837  silhouette=0.409
         hours  rentals  casual_share  workday  top_hour
cluster                                                 
0         8924    95.82          0.09     0.75         5
1         5420   173.96          0.32     0.51        11
2         3035   492.48          0.15     0.80        17
unscaled, casual share by cluster: [0.2, 0.15, 0.19]

The silhouette peaks at k=3k = 3, and JJ drops most from 2 to 3. Real data has no sharp elbow, so the final test is whether the groups make sense. These do: quiet hours (96 rentals, most often 5 a.m.), leisure hours (32% casual riders, half on days off), and commute peaks (492 rentals, most often 5 p.m.).

Quick check

Quick check

1. A cluster holds the points 2, 4 and 9. Where does the Update step move its centre?

2. Inertia keeps falling as k goes from 2 to 10. Why not just pick k = 10?

3. You cluster hours by rentals (up to 977) and temperature in °C (up to 41), without scaling. What happens?

Next

k-means puts every point in exactly one round cluster; Day 18: Gaussian Mixtures and EM makes the clusters soft, giving each point a probability of belonging to each one.

Data: Bike Sharing Dataset (UCI Machine Learning Repository, dataset 275), CC BY 4.0; cite Fanaee-T, H. and Gama, J. (2013), "Event labeling combining ensemble detectors and background knowledge", Progress in Artificial Intelligence, doi:10.1007/s13748-013-0040-3.

Next · Day 18 · 7 minGaussian Mixtures and EM← Previous: Day 16 · Support Vector Machines
Not tapped yet