Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 39

K-Means Clustering

Group unlabelled points into k clusters by assigning each point to the nearest center and moving the centers. One example is on this page.

Intermediate12 min
K-Means Clustering MahiDev

What You Will Learn

  • Idea
  • Example
  • When to use it

Idea

K-means starts with k centers. Each point joins the closest center. Each center then moves to the mean of its points. Those two steps repeat until the centers stop moving. You choose k. The algorithm does not see labels.

Example

python
import numpy as np
from sklearn.cluster import KMeans

X = np.array([[1, 2], [1.5, 1.8], [5, 8], [8, 8], [1, 0.6], [9, 11]], dtype=float)
labels = KMeans(n_clusters=2, n_init=10, random_state=0).fit_predict(X)
print(labels.tolist())

Output:

text
[1, 1, 0, 0, 1, 0]

When to use it

  • Use it when clusters are round and similar in size.
  • Scale the columns first, or the widest column decides the groups.
  • Run it more than once, or set n_init, because the start positions matter.

Loading playground…