Skip to main content

Beginner-Friendly Topic

Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!

Lesson 1 of 9

K-Means & K-Means++ Clustering: Centroid Initialization, Inertia & Silhouette Scores

K-Means partitions N unlabeled observations into K spherical clusters by minimizing Within-Cluster Sum of Squares (Inertia): J = sum(||x_i - mu_k||²). Standard random centroid initialization suffers from high sensitivity to local minima. K-Means++ solves this by initializing centroids with probability proportional to their squared distance to the nearest existing centroid: P(x) = D(x)² / sum(D(x)²). Selecting optimal K requires evaluating the Elbow curve and Silhouette analysis.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

K-Means++ Mechanics & Silhouette Optimization

K-Means++ Mechanics & Silhouette Optimization
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from sklearn.metrics import silhouette_score, calinski_harabasz_score
from sklearn.preprocessing import StandardScaler

# Generate synthetic multi-cluster dataset (4 true clusters in 4 dimensions)
np.random.seed(42)
X_raw, _ = make_blobs(n_samples=600, centers=4, n_features=4, cluster_std=1.2, random_state=42)

# Standardize features (MANDATORY: K-Means relies on Euclidean distance)
scaler = StandardScaler()
X = scaler.fit_transform(X_raw)

# Search optimal K from 2 to 7 using Inertia & Silhouette Score
evaluation_results = []

for k in range(2, 8):
    # n_init='auto' in modern scikit-learn uses K-Means++ with smart restarts
    kmeans = KMeans(n_clusters=k, init='k-means++', n_init=10, random_state=42)
    cluster_labels = kmeans.fit_predict(X)
    
    inertia = kmeans.inertia_
    sil_score = silhouette_score(X, cluster_labels)
    ch_score = calinski_harabasz_score(X, cluster_labels)
    
    evaluation_results.append({
        'K (Clusters)': k,
        'Inertia (WCSS)': f"{inertia:.1f}",
        'Silhouette Score': f"{sil_score:.4f}",
        'Calinski-Harabasz': f"{ch_score:.1f}"
    })

print("=== K-MEANS CLUSTERING QUALITY EVALUATION ===")
print(pd.DataFrame(evaluation_results).to_string(index=False))

# Identify optimal K
best_k_idx = np.argmax([float(r['Silhouette Score']) for r in evaluation_results])
optimal_k = evaluation_results[best_k_idx]['K (Clusters)']
print(f"\nOptimal Cluster Count (Max Silhouette): K = {optimal_k}")

Pro Tip: What Silhouette Values Mean

The Silhouette coefficient s(i) = (b(i) - a(i)) / max(a(i), b(i)) measures how well sample i belongs to its own cluster compared to neighboring clusters. A score near +1.0 indicates sample i is far from other clusters. A score near 0.0 indicates sample i lies on the decision boundary between two clusters. Negative scores indicate misclassification.

Diagram
Loading diagram…

MlKMeansClustering Visual Representation

Hands-On Challenge: Mini-Batch K-Means for Massive Datasets

Compare `sklearn.cluster.MiniBatchKMeans` against standard `KMeans` on a 500,000-sample dataset. Measure training runtime and verify that MiniBatch achieves 98%+ of the inertia reduction in 1/10th of the time.

Quick Quiz & Key Concept Checks

Common Pitfall: Forgetting to Scale Features in K-Means

If one feature has values between 1,000 and 100,000 (annual income) and another between 1 and 5 (household size), Euclidean distance is entirely dominated by the income feature. K-Means will cluster purely on income and ignore household size. Always scale features first.

Finished this lesson?

0 of 9 in Module 9
Sign in to save progress

Topics in This Module

0/9 done