MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
K-Means Clustering & The Elbow Method0%
Study MaterialsCheatsheet
Advanced Analytics & Machine LearningProgress 0%
1.1Downcasting Dtypes & Category Encoding for 10x Memory Savings1.2Method Chaining (pipe, assign) for Clean Production Pipelines1.3Window Functions & Moving Averages in Pandas1.4Modern Pandas 2.x/3.0: PyArrow Backend & Copy-on-Write
5.1K-Means Clustering & The Elbow Method5.2RFM (Recency, Frequency, Monetary) Customer Segmentation
HomeTutorialsAdvanced Analytics & Machine LearningK-Means Clustering & The Elbow Method
RFM (Recency, Frequency, Monetary) Customer Segmentation

K-Means Clustering & The Elbow Method

Advanced7 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

In modern commerce, treating all customers identically leads to suboptimal marketing returns and high churn. K-Means Clustering is the preeminent unsupervised machine learning algorithm used to partition unlabeled datasets into $K$ distinct, non-overlapping behavioral clusters based on geometric feature proximity.


1. How K-Means Works: The Lloyd-Forgy Algorithm

  1. 1
    Initialization: Select $K$ initial centroid coordinates at random (or via K-Means++).
  2. 2
    Assignment Step: Assign each data point to its nearest centroid using Euclidean distance:

$$d(x, c_j) = \sqrt{\sum_{i=1}^{p} (x_i - c_{ji})^2}$$

  1. 1
    Update Step: Recalculate each centroid as the geometric mean of all data points assigned to it.
  2. 2
    Convergence: Repeat steps 2 and 3 until centroids stabilize (inertia stops decreasing).

2. Choosing Optimal $K$: The Elbow Method & Inertia

Because K-Means is unsupervised, there are no ground-truth labels. Analysts use Inertia (Within-Cluster Sum of Squares - WCSS):

$$WCSS = \sum_{k=1}^{K} \sum_{x \in C_k} ||x - \mu_k||^2$$

As $K$ increases, WCSS naturally drops towards zero (if $K=N$, WCSS=0). The Elbow Method finds the point of diminishing marginal returns:

1import matplotlib.pyplot as plt
2from sklearn.cluster import KMeans
3from sklearn.preprocessing import StandardScaler
4 
5# Step 1: ALWAYS scale features before K-Means!
6scaler = StandardScaler()
7X_scaled = scaler.fit_transform(df[['recency', 'frequency', 'monetary']])
8 
9# Step 2: Compute WCSS for K = 1 to 10
10wcss = []
11k_range = range(1, 11)
12for k in k_range:
13 kmeans = KMeans(n_clusters=k, init='k-means++', random_state=42, n_init=10)
14 kmeans.fit(X_scaled)
15 wcss.append(kmeans.inertia_)
16 
17# Step 3: Plot Elbow Curve
18plt.figure(figsize=(8, 5))
19plt.plot(k_range, wcss, marker='o', linestyle='--', color='b')
20plt.title('The Elbow Method for Optimal K')
21plt.xlabel('Number of Clusters (K)')
22plt.ylabel('WCSS (Inertia)')
23plt.grid(True)
24plt.show()

3. Validating with Silhouette Score

When the elbow curve is ambiguous, calculate the Silhouette Score (ranges from -1 to +1):

  • Near +1: Clusters are dense and cleanly separated.
  • Near 0: Clusters overlap significantly.
  • Negative: Points are assigned to the wrong cluster.
1from sklearn.metrics import silhouette_score
2 
3for k in range(2, 7):
4 km = KMeans(n_clusters=k, random_state=42, n_init=10)
5 labels = km.fit_predict(X_scaled)
6 sil = silhouette_score(X_scaled, labels)
7 print(f"K = {k} | Silhouette Score: {sil:.3f}")

4. Profiling Clusters for Business Strategy

After assigning cluster labels, profile each cluster by calculating unscaled feature means:

1df['cluster'] = kmeans.fit_predict(X_scaled)
2cluster_profiles = df.groupby('cluster')[['recency', 'frequency', 'monetary']].mean()
3print(cluster_profiles)

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
Why is feature scaling mandatory before running K-Means clustering?
Question 2
What does the "Elbow Point" represent in an Elbow plot of K-Means clustering?
Question 3
What does a Silhouette Score close to +1.0 indicate?
Question 4
What is the main advantage of the init='k-means++' initialization algorithm over pure random initialization?
Question 5
If $K$ is set equal to the total number of observations ($N$) in the dataset, what is the value of Inertia (WCSS)?

Next Lesson

RFM (Recency, Frequency, Monetary) Customer Segmentation

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Decision Trees & Feature Importance InterpretationRFM (Recency, Frequency, Monetary) Customer Segmentation

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

12-Month Data Analysis Mastery Program

Master Full-Stack Data Analytics (Excel, SQL, Python, Power BI & Tableau)

Combine 15 complete courses, 150 chapters, 541 topics, live SQL/Power BI/Tableau dashboards, and Scikit-Learn capstones at MSK Institute Shikohabad or Live Online.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext