k-means
scikit-learn
clustering
inertia
machine learning

How to get the inertia of each k-means cluster in scikit-learn

Codemia Knowledge Hub ·

Inertia is the sum of the squared distances between each data point and the centroid of its assigned cluster. Lower inertia means more compact clusters. K-means itself works by assigning each point to one of k clusters by distance to the centroids, then recalculating the centroids iteratively to minimize this within-cluster sum of squares.

The inertia formula

Inertia is also known as the within-cluster sum of squares (WCSS):

Inertia=∑_i=1k∑_x∈C_i∣x−μ_i∣2\text{Inertia} = \sum\_{i=1}^{k} \sum\_{x \in C\_i} |x - \mu\_i|^2

Where: • kk is the total number of clusters. • CiC_i represents the iith cluster. • xx is a data point in cluster CiC_i. • μi\mu_i is the centroid of cluster CiC_i. • ∥⋅∥2\|\cdot\|^2 denotes the squared Euclidean distance.

The per-cluster value is the inner sum for a single cluster CiC_i.

Computing inertia with scikit-learn

scikit-learn provides a simple interface for K-Means clustering.

Installation

If you have not installed scikit-learn yet, you can do so with pip:

bash
pip install scikit-learn

Total and per-cluster inertia

After fitting, KMeans stores the total inertia in inertia_. There is no attribute for each cluster's share, but you can compute it from labels_ and cluster_centers_:

python
1import numpy as np
2from sklearn.cluster import KMeans
3
4X = np.array([[1, 2], [1, 4], [1, 0],
5              [10, 2], [10, 4], [10, 0]])
6
7kmeans = KMeans(n_clusters=2, n_init=10, random_state=0).fit(X)
8
9# Total inertia across all clusters
10print(kmeans.inertia_)  # 16.0
11
12# Inertia of each cluster: squared distances to its own centroid
13labels = kmeans.labels_
14centers = kmeans.cluster_centers_
15per_cluster = [
16    float(((X[labels == i] - centers[i]) ** 2).sum())
17    for i in range(kmeans.n_clusters)
18]
19print(per_cluster)  # [8.0, 8.0]

The per-cluster values add up to inertia_.

Choosing k

• Elbow Method: plot the inertia against various values of k and look for an "elbow" point where the rate of decrease sharply changes. • Silhouette Score: measures how similar a point is to its cluster compared to other clusters.

Where K-Means is used

• Market Segmentation: grouping customers based on buying habits. • Image Compression: reducing the number of colors. • Anomaly Detection: identifying unusual patterns.

Limitations of K-Means

• Sensitivity to Initialization: random initialization can lead to different results. • Non-linear Boundaries: K-Means assumes clusters are convex and isotropic. • Scaling: features should be standardized or normalized.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design