MLDay 17 of 50Supervised and Unsupervised Learning
Group Unlabeled Data with k-Means
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 clusters, where you choose . Each cluster has a centroid (its centre): the mean of its points. Start with centres anywhere, then repeat two steps:
- Assign. Each point joins its nearest centre, measured by straight-line distance as in D15.
- 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 and a deliberately bad start: centres at 1 and 4.
| Round | Centres | Cluster A | Cluster B | 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 . 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 adds up each point's squared distance to its own centre. Smaller means tighter clusters.
| Symbol | Meaning |
|---|---|
| the inertia: the total squared distance from points to their centres | |
| the points in cluster | |
| the centroid of cluster (the mean of its points) | |
| the straight-line distance from point to that centroid |
Worked, round 3: cluster A gives . Cluster B also gives 2, so .
can't choose for you: more clusters can always lower it, down to 0 when every point has its own. Look for the elbow instead, the after which stops dropping much. A second check is the silhouette, which asks whether each point is nearer its own cluster than the next one.
| Symbol | Meaning |
|---|---|
| one point's silhouette, from −1 to 1 | |
| the point's average distance to the other points in its own cluster | |
| its average distance to the points of the nearest other cluster |
Worked, the 2-trip rider: and , so . 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 over all points, and a good 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.
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 , two corners share a centre and stops at about 138.5. Set and step again: one centre walks across to the empty corner, and falls to about 18.1. only gets to about 14.6, so 3 is the elbow.
In code
scikit-learn's KMeans runs the loop; inertia_ is and labels_ holds each point's cluster. These are
the six riders, with 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 , then barely moves: that's the elbow. The silhouette agrees, at its highest for . 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 , and 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.