🎓 A1Learner
🔍
0 of 50 lessons completed

Python ML K-Means Clustering

K-Means splits data into k groups called clusters. Each cluster has a centre, and every row joins its nearest centre.

Three clusters on Wine

K-Means with k equal to 3 splits the 178 wines into three groups. Inertia measures how tight those groups are.

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)
model = KMeans(n_clusters=3, random_state=42, n_init=10)
model.fit(X)
print("Inertia:", round(float(model.inertia_), 1))
print("Sizes:", [int((model.labels_ == k).sum()) for k in range(3)])

Inertia falls as k grows

More clusters always means tighter groups. The fall is steep at first and then slows down.

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)
for k in [1, 2, 3]:
    model = KMeans(n_clusters=k, random_state=42, n_init=10)
    model.fit(X)
    print("k =", k, "inertia:", round(float(model.inertia_), 1))

The centres are the cluster middles

Each centroid is one row of numbers. The first three values of the first centroid are shown here.

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)
model = KMeans(n_clusters=3, random_state=42, n_init=10)
model.fit(X)
print([round(float(v), 2) for v in model.cluster_centers_[0][:3]])

Example

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)

# The elbow method: inertia for k from 1 to 6.
for k in range(1, 7):
    model = KMeans(n_clusters=k, random_state=42, n_init=10)
    model.fit(X)
    print("k =", k, "inertia:", round(float(model.inertia_), 1))

Key points

  • K-Means: a method that splits data into k groups
  • Centroid: the centre point of a cluster
  • Inertia: the total squared distance from each row to its own centre
  • Use inertia values for k from 1 upward, and watch where the fall slows down
  • Elbow method: a way to pick k by finding the bend in the inertia curve
  • K-Means needs scaling first, because distance decides the groups
  • The Wine data has 178 rows and 13 measurements, with no labels used here

In this example, the Wine data is scaled first, because K-Means measures distance and the 13 columns use different units. K-Means runs once for each k from 1 to 6, and each run prints its inertia. Inertia falls fast at first, from 2314.0 down to 1277.9 at k equal to 3. After that the fall slows, so the bend sits near k equal to 3. That bend is the elbow, and it is the usual pick for this data.

Note

K-Means starts from random centres, so set random_state to keep the result steady.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does the elbow method look for?