lesson
50 min

Clustering With K-Means

Group similar rows when there is no answer column, and see how k-means works step by step.

Objective

By the end of this lesson, you can explain unsupervised learning, run k-means by hand and with scikit-learn, and describe what a cluster does and does not mean.

Supervised versus unsupervised

Supervised learning trains on examples that have answers (labels), like emails marked spam or not spam. You will do this in Modules 10 and 11.

Unsupervised learning has no answer column. The model looks for structure on its own. The most common job is clustering: putting similar rows into groups.

How k-means works

K-means splits data into k groups. You choose k. Then it repeats two steps:

  1. Assign: put each point in the group with the nearest center.
  2. Update: move each center to the average of its group.

It stops when the groups stop changing.

Run it. Six made-up points start with two centers. Watch the centers move to the middle of each group. Then add the point (5, 5) and run again. Which group does it join?
Python 3
Ctrl+Enter to run | Tab to indent | Python runs in your browser via Pyodide

With scikit-learn

scikit-learn is the standard free Python library for machine learning. Run this in Google Colab with a public dataset. The Iris dataset from the UC Irvine Machine Learning Repository (CC BY 4.0 license) is built into scikit-learn.

from sklearn.datasets import load_iris
from sklearn.cluster import KMeans

X = load_iris().data            # flower measurements, no labels used
model = KMeans(n_clusters=3, n_init=10, random_state=0)
groups = model.fit_predict(X)
print(groups[:10])
print(model.cluster_centers_)

Choosing k

There is no single right k. A common check is the elbow method: try k from 1 to 10, plot how tight the groups are (model.inertia_), and look for the bend where adding groups stops helping much. Then ask whether the groups make sense to a person who knows the topic.

A national example

Judgment check

A cluster is a group of rows that look similar on the columns you chose. It is not a type of person. Never give clusters of people labels like "high-risk" or "low-value." Those labels stick, and they can steer resources away from people who need them.

Reflection

Private. Saved only in this browser. No one else can see it.

Ask. Answer. Build together.