+91 99301 12627
Machine Learning

K-Means Clustering Explained: How It Works, With a Python Example

By Mehul Prajapati

Cluster of stars in the night sky representing K-means clustering
On this page

Short answer: K-means is an unsupervised learning algorithm that groups data into K clusters of similar points. It (1) picks K starting centres (centroids), (2) assigns every point to its nearest centroid, (3) moves each centroid to the average of its assigned points, and (4) repeats until assignments stop changing. You choose K using the elbow method or silhouette score, and you should scale features first. It’s widely used for customer segmentation and grouping similar items.

Key takeaways

  • K-means finds groups without labels.
  • You must choose K; use the elbow method, silhouette score and business sense.
  • Scale features first, because K-means uses distances.
  • It works best for roughly round, similarly sized clusters.

How K-means works, step by step

  1. Choose K, the number of clusters
  2. Initialise K centroids (scikit-learn uses the smarter “k-means++” method by default)
  3. Assign each point to its nearest centroid
  4. Update each centroid to the mean of the points assigned to it
  5. Repeat steps 3–4 until centroids barely move

The algorithm minimises inertia: the sum of squared distances from each point to its cluster centre.

Python example: customer segmentation

import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans

df = pd.read_csv('customers.csv')    # annual_spend, visits, avg_order_value
X = StandardScaler().fit_transform(df[['annual_spend', 'visits', 'avg_order_value']])

kmeans = KMeans(n_clusters=4, n_init=10, random_state=42)
df['segment'] = kmeans.fit_predict(X)

print(df.groupby('segment').mean(numeric_only=True))

Then name the segments from their averages, for example “frequent low spenders” or “occasional big spenders”, and design actions for each.

How to choose K

Elbow method

inertias = []
for k in range(1, 11):
    inertias.append(KMeans(n_clusters=k, n_init=10, random_state=42).fit(X).inertia_)
# plot k vs inertia and look for the 'elbow'

Silhouette score

from sklearn.metrics import silhouette_score
for k in range(2, 11):
    labels = KMeans(n_clusters=k, n_init=10, random_state=42).fit_predict(X)
    print(k, round(silhouette_score(X, labels), 3))

Silhouette ranges from −1 to 1; higher means better-separated clusters. Combine these with business usefulness: four clear, actionable segments beat nine confusing ones.

Real-world uses

  • Customer segmentation for marketing
  • Grouping products or stores with similar sales patterns
  • Document or ticket grouping using embeddings
  • Image colour quantisation (reducing colours)
  • Creating features (cluster ID) for other models; see feature engineering

Limitations and alternatives

Limitation Alternative
Must choose K in advance Hierarchical clustering (dendrograms)
Struggles with odd shapes and noise DBSCAN / HDBSCAN
Assumes similar-sized, round clusters Gaussian Mixture Models
Only numeric features K-prototypes for mixed data, or encode categories
Sensitive to outliers and scale Scale features; remove or cap outliers

Common mistakes

  • Not scaling features (e.g. income dominates age)
  • Treating clusters as “truth” without checking they make business sense
  • Choosing K only from the elbow plot
  • Using one random initialisation (keep n_init above 1)

Frequently asked questions

Is K-means supervised or unsupervised?

Unsupervised. There are no target labels; it discovers structure in the data.

What’s the difference between K-means and KNN?

K-means clusters unlabelled data into K groups. KNN (k-nearest neighbours) is a supervised method that classifies or predicts using the K closest labelled examples.

How do I evaluate clusters?

Use silhouette score and inertia, then validate with domain experts: are segments distinct, stable and actionable?

Conclusion

With K-means clustering explained, the recipe is simple: scale features, choose K with the elbow and silhouette methods, fit, and interpret clusters in business terms. It’s one of the most practical unsupervised algorithms to add to your machine learning roadmap.

Build a customer segmentation project in our Machine Learning course.

Learn with Mehul Prajapati in Borivali West

At Mehul Prajapati’s institute, you get 100% practical, hands-on training by industry experts with a minimum of 5+ years of experience, plus job-oriented programmes with placement support. Weekday and weekend batches are available, with multiple 2-hour slots between 8 am and 6 pm.

Address: 12th Floor, 1214, Gold Crest Business Centre, LT Rd, Above Westside Showroom, Borivali West, Mumbai, Maharashtra 400092
Call: +91 99301 12627 / +91 96645 45072

Visit the centre or call us to choose the right course and batch and to know the current fee structure.