Module 15 · K means clustering · Lesson 55 of 66

Find groups without labels

Unsupervised learning: let K means discover clusters in unlabeled data.

In this lesson · about 15 minutes

  • Explain how K means assigns points and moves centers
  • Cluster data with scikit-learn's KMeans
  • Choose K with the elbow method

So far every data set came with the answer column. Clustering is unsupervised: there are no labels, and the goal is to find groups of similar rows, such as customer segments or similar documents.

K means finds K groups like this:

  1. Pick K starting centers at random.
  2. Assign every point to its nearest center.
  3. Move each center to the average of its points.
  4. Repeat steps 2 and 3 until nothing changes.

Because the start is random, scikit-learn runs it several times (n_init) and keeps the tightest result.

Some made-up data

make_blobs creates points around 4 centers. It also returns which center each point came from, so we can check K means afterwards.

Exercise

Cluster the blobs

Create KMeans(n_clusters=4, n_init=10, random_state=101) called kmeans and fit it to the points, data[0]. End with kmeans.cluster_centers_.

Code that runs before yours
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
data = make_blobs(n_samples=200, n_features=2, centers=4, cluster_std=1.8, random_state=101)

K means against the truth

Side by side, the clusters match the real groups closely. The colors don't line up, because K means numbers its clusters in its own order.

Choosing K

In real data you don't know K. Try several and plot each model's inertia_, the total squared distance from points to their centers. It always falls as K grows; look for the elbow where it stops falling fast.

Exercises solved: 0 of 1

Tip: solve each exercise first. Press Check to test your code.

Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.