Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
⚙️ Week 8 – Advanced ML  ·  दिन 46

दिन 46: K-Means Clustering: Customer Segments

⏱ 2 hours📶 Intermediate🎯 100% self-study
दिन 46 / 60

✅ आज आप सीखेंगे

  • Clustering: labels के बिना groups
  • K-Means step by step
  • पहले scale, फिर k चुनें (elbow, silhouette)
  • Clusters को marketing personas में बदलना
  • DBSCAN या hierarchical clustering कब

🏢 असली दुनिया में

Pune के एक mall के 200 loyalty-card members का age, income और spending score है। Marketing सबको एक ही SMS भेजना बंद करना चाहती है। किसी ने customers के “प्रकार” label नहीं किए – clustering उन्हें ढूँढती है, और हर group को अपना offer मिलता है।

पहले data देखें

Python
import pandas as pd
import matplotlib.pyplot as plt
m = pd.read_csv("mall_customers.csv")
print(m.head()); print(m.describe().round(1).loc[["mean", "min", "max"]])
plt.figure(figsize=(7.5, 4.5))
plt.scatter(m["annual_income_lakh"], m["spending_score"], s=22, color="#64748b")
plt.xlabel("annual income (₹ lakh)"); plt.ylabel("spending score (1–100)")
plt.title("Can you see the groups?"); plt.show()
customer_id gender age annual_income_lakh spending_score 0 M301 Female 56 4.6 52 1 M302 Male 35 6.6 43 2 M303 Male 28 8.5 91 3 M304 Male 58 2.5 20 4 M305 Male 53 2.4 12 age annual_income_lakh spending_score mean 38.2 5.7 48.2 min 18.0 1.0 1.0 max 64.0 10.2 96.0
Mall customers की income vs spending score का scatter
आपकी आँख लगभग पाँच groups देख रही है – K-Means उन्हें गणित से ढूँढेगा।

K-Means कैसे काम करता है

  1. 1k random centres चुनें
  2. 2हर customer को सबसे क़रीबी centre में डालें
  3. 3हर centre को उसके customers के औसत पर ले जाएँ
  4. 4Centres रुकने तक दोहराएँ
Assign → update → repeat
Python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
m = pd.read_csv("mall_customers.csv")
X = m[["annual_income_lakh", "spending_score"]].to_numpy()
Xs = (X - X.mean(0)) / X.std(0)
rng = np.random.default_rng(3)
centres = Xs[rng.choice(len(Xs), 5, replace=False)]
fig, ax = plt.subplots(1, 4, figsize=(14, 3.4), sharey=True)
for it in range(4):
    lab = np.argmin(((Xs[:, None, :] - centres[None]) ** 2).sum(-1), axis=1)
    ax[it].scatter(Xs[:, 0], Xs[:, 1], c=lab, cmap="tab10", s=10)
    ax[it].scatter(centres[:, 0], centres[:, 1], c="black", marker="X", s=120)
    ax[it].set_title(f"iteration {it + 1}")
    centres = np.array([Xs[lab == k].mean(0) for k in range(5)])
plt.tight_layout(); plt.show()
चार K-Means iterations जिनमें centres clusters के बीच जाते हैं
काले cross = centres। कुछ rounds में वे हर group के बीच में बैठ जाते हैं।

scikit-learn से K-Means

Python
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
m = pd.read_csv("mall_customers.csv")
X = StandardScaler().fit_transform(m[["annual_income_lakh", "spending_score"]])
km = KMeans(n_clusters=5, n_init=10, random_state=0).fit(X)
m["cluster"] = km.labels_
print(m["cluster"].value_counts().sort_index().to_dict())
print("inertia (within-cluster spread):", round(km.inertia_, 1))
{0: 26, 1: 60, 2: 40, 3: 35, 4: 39} inertia (within-cluster spread): 27.3
⚠️ हमेशा scale करें

K-Means दूरियाँ इस्तेमाल करता है। Income (2–10 lakh) और score (1–100) अलग scales पर हैं – scaling के बिना अकेला spending score clusters तय कर देगा।

k चुनना

Python
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
m = pd.read_csv("mall_customers.csv")
X = StandardScaler().fit_transform(m[["annual_income_lakh", "spending_score"]])
ks = range(2, 11); inertia, sil = [], []
for k in ks:
    km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X)
    inertia.append(km.inertia_); sil.append(silhouette_score(X, km.labels_))
fig, ax = plt.subplots(1, 2, figsize=(11, 3.6))
ax[0].plot(ks, inertia, marker="o", color="#4f46e5"); ax[0].set_title("Elbow: inertia drops slowly after the bend"); ax[0].set_xlabel("k")
ax[1].plot(ks, sil, marker="o", color="#16a34a"); ax[1].set_title("Silhouette: higher is better"); ax[1].set_xlabel("k")
best = list(ks)[sil.index(max(sil))]; ax[1].axvline(best, color="#dc2626", ls="--")
plt.tight_layout(); plt.show()
print("best k by silhouette:", best, "| scores:", [round(s, 3) for s in sil])
best k by silhouette: 5 | scores: [0.4, 0.5, 0.606, 0.681, 0.592, 0.532, 0.46, 0.454, 0.459]
k = 2 से 10 के लिए elbow curve और silhouette scores
दोनों तरीके k = 5 की ओर इशारा करते हैं।
🧠 एक line में silhouette

हर customer के लिए: अपने cluster के कितने क़रीब vs अगले सबसे क़रीबी cluster के, −1 (ग़लत group) से +1 (perfect) तक। औसत बताता है clusters कितने अलग हैं।

Clusters से personas तक

Python
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
m = pd.read_csv("mall_customers.csv")
X = StandardScaler().fit_transform(m[["annual_income_lakh", "spending_score"]])
m["cluster"] = KMeans(n_clusters=5, n_init=10, random_state=0).fit_predict(X)
prof = m.groupby("cluster")[["age", "annual_income_lakh", "spending_score"]].mean().round(1)
prof["customers"] = m["cluster"].value_counts().sort_index()
def name(r):
    hi_inc, hi_sp = r.annual_income_lakh > 6.5, r.spending_score > 60
    lo_inc, lo_sp = r.annual_income_lakh < 4, r.spending_score < 40
    if hi_inc and hi_sp: return "Premium spenders"
    if hi_inc and lo_sp: return "Careful earners"
    if lo_inc and hi_sp: return "Young trend-seekers"
    if lo_inc and lo_sp: return "Budget shoppers"
    return "Average regulars"
prof["persona"] = prof.apply(name, axis=1)
print(prof.to_string())
m["persona"] = m["cluster"].map(prof["persona"])
plt.figure(figsize=(8, 4.8))
for p, g in m.groupby("persona"):
    plt.scatter(g["annual_income_lakh"], g["spending_score"], s=22, label=p)
plt.xlabel("annual income (₹ lakh)"); plt.ylabel("spending score"); plt.legend(fontsize=8)
plt.title("Five customer personas"); plt.show()
age annual_income_lakh spending_score customers persona cluster 0 21.7 2.7 77.7 26 Young trend-seekers 1 40.2 5.5 48.7 60 Average regulars 2 48.2 2.5 19.3 40 Budget shoppers 3 43.0 8.4 18.5 35 Careful earners 4 31.4 9.0 83.8 39 Premium spenders
पाँच नामित personas के हिसाब से रंगे mall customers
Clusters को इंसानी नाम दें – marketing “cluster 3” पर नहीं, personas पर काम करती है।
💎
Premium spendersज़्यादा income, ज़्यादा ख़र्च → early access, premium brands, loyalty tier।
🧐
Careful earnersज़्यादा income, कम ख़र्च → quality और value वाला संदेश, personal shopper।
✨
Young trend-seekersकम income, ज़्यादा ख़र्च → EMI, student offers, Instagram campaigns।
🛒
Budget shoppersकम income, कम ख़र्च → combo deals और weekday discounts।
हर segment का अपना संदेश

दूसरे clustering तरीके

Python
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import DBSCAN, AgglomerativeClustering
from sklearn.metrics import silhouette_score
m = pd.read_csv("mall_customers.csv")
X = StandardScaler().fit_transform(m[["annual_income_lakh", "spending_score"]])
db = DBSCAN(eps=0.35, min_samples=5).fit(X)
print("DBSCAN clusters:", len(set(db.labels_)) - (1 if -1 in db.labels_ else 0), "| noise points:", (db.labels_ == -1).sum())
ag = AgglomerativeClustering(n_clusters=5, linkage="ward").fit(X)
print("Hierarchical (ward) silhouette:", round(silhouette_score(X, ag.labels_), 3))
DBSCAN clusters: 4 | noise points: 5 Hierarchical (ward) silhouette: 0.679
Methodताक़तकमज़ोरी
K-Meansतेज़, सरल, लाखों तकk चाहिए; गोल, बराबर size के clusters मानता है
DBSCANकोई भी आकार, outliers (noise) पकड़ता हैeps पर निर्भर; अलग density में मुश्किल
HierarchicalDendrogram nested groups दिखाता हैबड़े data पर धीमा

🏅 आज के Job Skills

✔ K-Means चलाना और समझाना✔ Elbow और silhouette से k चुनना✔ Clusters को actionable personas में बदलना✔ DBSCAN या hierarchical कब आज़माएँ, जानना

Practice tasks

🏋️ Practice – ख़ुद करें

Task 1: Mall customers को तीनों features (age, income, score) पर cluster करें। क्या k = 5 अब भी सबसे अच्छा है?
Solution देखें
Python
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
m = pd.read_csv("mall_customers.csv")
X = StandardScaler().fit_transform(m[["age", "annual_income_lakh", "spending_score"]])
print({k: round(silhouette_score(X, KMeans(k, n_init=10, random_state=0).fit_predict(X)), 3) for k in range(2, 9)})
{2: 0.367, 3: 0.397, 4: 0.429, 5: 0.478, 6: 0.461, 7: 0.474, 8: 0.482}
Task 2: BazaarKart के 11 शहरों को revenue, AOV और prepaid share से 3 clusters में बाँटें।
Solution देखें
Python
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
s = pd.read_csv("sales_data.csv"); s["rev"] = s["quantity"] * s["unit_price"] * (1 - s["discount"])
c = s.groupby("city").agg(revenue=("rev", "sum"), aov=("rev", "mean"), prepaid=("payment_mode", lambda p: (p != "Cash on Delivery").mean()))
c["cluster"] = KMeans(3, n_init=10, random_state=0).fit_predict(StandardScaler().fit_transform(c))
print(c.round(2).sort_values("cluster"))
revenue aov prepaid cluster city Ahmedabad 450611.90 3633.97 0.80 0 Hyderabad 572190.15 2860.95 0.78 0 Lucknow 394912.00 3014.60 0.79 0 Patna 459941.15 3650.33 0.79 0 Jaipur 260155.35 2454.30 0.83 1 Chennai 545479.20 3519.22 0.85 1 Pune 403765.60 2823.54 0.85 1 Bengaluru 964019.65 3224.15 0.81 2 Kolkata 839885.10 4351.74 0.82 2 Delhi 945592.45 3489.27 0.79 2 Mumbai 1043230.20 4139.80 0.78 2
Task 3: पाँचों personas के लिए एक-एक SMS offer लिखें।

Quick quiz

🧠 Quick Quiz – ख़ुद को जाँचें

1. Clustering है…
कोई labels इस्तेमाल नहीं होते।
2. K-Means में points assign करने के बाद centres कहाँ जाते हैं?
इसीलिए “means”।
3. k बढ़ने पर inertia हमेशा घटता है। इसलिए हम…
Fit और सरलता का संतुलन।
4. Silhouette 1 के क़रीब मतलब…
Points अपने cluster के क़रीब।
5. कौन सा method outliers को noise label करता है?
Label −1।

Interview corner

💼 Interview Corner

Clusters की संख्या कैसे चुनते हैं?

Inertia curve का elbow, silhouette scores, और – सबसे ज़रूरी – business उपयोगिता: segments अलग, काफ़ी बड़े और actionable हों। अलग seeds से स्थिरता जाँचें।

K-Means की सीमाएँ?

k पहले से चाहिए, scaling और outliers से प्रभावित, गोल बराबर size के clusters मानता है, और local minima में फँस सकता है (n_init > 1 लें)। Categorical data के लिए दूसरे तरीके (k-modes) या encoding चाहिए।

सारांश

  • K-Means: सबसे क़रीबी centre में डालें, centres खिसकाएँ, दोहराएँ।
  • Features scale करें; elbow + silhouette + business समझ से k चुनें।
  • Clusters को personas और actions में बदलें।
  • अजीब आकार/outliers के लिए DBSCAN, nested groups के लिए hierarchical।
➡️ आगे

Day 47: PCA – कई columns को कुछ ताक़तवर components में समेटें और high-dimensional data देखें।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

क्या clustering results supervised model में इस्तेमाल कर सकते हैं?
हाँ – cluster id (या हर centre से दूरी) काम का engineered feature है, जैसे churn या response models के लिए।
नए customer को cluster में कैसे डालें?
उसी scaler से scale करें, फिर km.predict(new_row) – दोनों को Pipeline में रखें।
← Data Science (60 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topicदिन 47: PCA और Dimensionality Reduction आपकी प्रगति: 46 / 60 (77%) · Lesson 47 / 60 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें