Machine Learning, FoundationsLesson 63 of 92

Module 7 · Learning without labels, and learning a representation

k-means, and what it assumes about your data

In this lesson

  • 9 min read
  • 6 reading sections
  • Knowledge check
  • Lesson 1 of 10 in this chapter

This chapter’s goalCluster a dataset and defend the number of clusters with more than an elbow plot, reduce dimensionality with PCA and state how much information the reduction discarded, explain what an embedding is as a geometric object, and build a working nearest-neighbour search over pretrained embeddings without a GPU.

This chapter’s media

The film explains chapter ideas. The audiobook narrates the complete teaching text.

FormatEnglishहिंदी
Chapter filmWatch1:55Not available
Full audiobookNot availableNot available

A little at a time

Explore an idea, try it, then check what stays.

Step 1 of 8Free · no account needed
Lesson steps

The algorithm in four lines

  1. Pick k random points as initial centres.
  2. Assign every row to its nearest centre.
  3. Move each centre to the mean of the rows assigned to it.
  4. Repeat 2 and 3 until nothing moves.

That is the whole of k-means. It converges quickly, it is easy to implement, and it is the most used clustering algorithm by a wide margin.

Python
from sklearn.cluster import KMeans
km = KMeans(n_clusters=5, n_init=10, random_state=0).fit(X_scaled)
km.labels_, km.cluster_centers_, km.inertia_

inertia_ is the sum of squared distances from each point to its assigned centre. It is what the algorithm minimises, and it will feature in the next lesson.

Your place and first choices stay on this browser. Classroom credit is recorded separately.

Every lesson here is open. Your progress is recorded once you pass the How a Language Model Actually Works exam.

Stuck on something?Ask Funke, your AI tutor

How to cite: Addaly (2026) ‘k-means, and what it assumes about your data’, in Machine Learning, Foundations. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/machine-learning-foundations/clustering-with-k-means (Accessed: 29 November 2026).