Python ML K-Means from Scratch
K-Means from scratch is the same two-step loop in plain NumPy. Assign each row to its nearest centre, then move each centre to its group middle.
Distance to each centre
One point sits nearer the first centre than the second. The nearest centre wins the point.
import numpy as np
point = np.array([1.0, 2.0])
centres = np.array([[0.0, 0.0], [3.0, 4.0]])
dists = np.sqrt(((centres - point) ** 2).sum(axis=1))
print([round(float(d), 2) for d in dists])
print("Nearest centre:", int(dists.argmin()))Assign rows to the nearest centre
Each row gets the number of its nearest centre. The first two rows join centre 0, and the last two join centre 1.
import numpy as np
X = np.array([[0.0, 0.0], [0.0, 1.0], [9.0, 9.0], [10.0, 9.0]])
centres = np.array([[0.0, 0.0], [10.0, 10.0]])
dists = np.sqrt(((X[:, None, :] - centres[None, :, :]) ** 2).sum(axis=2))
print([int(v) for v in dists.argmin(axis=1)])Move a centre to its group middle
The new centre is the mean of its rows. Three rows average to 0.67 on each side.
import numpy as np
group = np.array([[0.0, 0.0], [0.0, 2.0], [2.0, 0.0]])
print([round(float(v), 2) for v in group.mean(axis=0)])Example
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import load_wine
from sklearn.preprocessing import StandardScaler
wine = load_wine()
X = StandardScaler().fit_transform(wine.data)
start = X[:3].copy()
# From scratch: assign, then move, ten times.
centres = start.copy()
for step in range(10):
dists = np.sqrt(((X[:, None, :] - centres[None, :, :]) ** 2).sum(axis=2))
labels = dists.argmin(axis=1)
new_centres = np.array([X[labels == j].mean(axis=0) for j in range(3)])
shift = np.abs(new_centres - centres).max()
centres = new_centres
print("Step", step + 1, "max centre shift:", round(float(shift), 4))
scratch_inertia = float(((X - centres[labels]) ** 2).sum())
# sklearn, started from the same three centres.
model = KMeans(n_clusters=3, init=start, n_init=1, random_state=42)
sk_labels = model.fit_predict(X)
print("Scratch inertia:", round(scratch_inertia, 1))
print("sklearn inertia:", round(float(model.inertia_), 1))
print("Centre difference:", round(float(np.abs(centres - model.cluster_centers_).max()), 6))
print("Label agreement:", round(float((labels == sk_labels).mean()), 4))Key points
- Assign step: give each row to its nearest centre
- Move step: move each centre to the middle of its rows
- Use a loop to repeat assign and move until the centres stop moving
- Centroid: the centre point of a cluster
- The NumPy version and the sklearn version must agree on the same data
In this example, scaling comes first, and the first three rows become the starting centres. The loop runs ten times. Each pass assigns every row to its nearest centre, then moves each centre to the mean of its rows. The printed shift falls to 0.0 by step 9, so the centres stop moving. Then sklearn runs from the same three starting centres. Both versions land on the same centres and the same labels, so the agreement check prints 1.0 and the centre difference prints 0.0.
Note
Start both versions from the same centres, or the groups may get different numbers.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What are the two steps of one K-Means pass?