K-Means Clustering: Customer Segmentation

Lesson 24 of 26

Ab tak ke models me sahi jawab (label) diya hota tha. Clustering me koi label nahi hota — model khud milte-julte data points ke groups dhoondhta hai. Business me iska sabse bada use hai customer segmentation: kaunse customers ek jaise hain, taaki har group ke liye alag marketing ho sake.

K-Means kaise kaam karta hai?

  1. K random points ko cluster centers (centroids) maano.
  2. Har data point ko uske sabse paas wale center ke group me daalo.
  3. Har group ka naya center = us group ke points ka average.
  4. Step 2-3 tab tak repeat karo jab tak centers hilna band na kar dein.

Data: mall ke customers

Example

Python
import numpy as np
import pandas as pd

rng = np.random.default_rng(0)
groups = [(25, 20), (25, 80), (55, 50), (85, 20), (85, 80)]   # (income, spending)

rows = []
for income, spending in groups:
    rows.append(np.column_stack([
        rng.normal(income, 6, 40).clip(10, None),
        rng.normal(spending, 7, 40).clip(1, 100),
    ]))
customers = pd.DataFrame(np.vstack(rows).round(1),
                         columns=["annual_income_k", "spending_score"])
print(customers.shape)
print(customers.describe().round(1))

Output

Plain Text
(200, 2)
       annual_income_k  spending_score
count            200.0           200.0
mean              55.0            49.5
std               27.7            27.3
min               11.0             1.0
25%               26.4            23.2
50%               54.4            46.7
75%               82.9            76.4
max              101.5            94.0

annual_income_k hazaaron me saalana income hai, aur spending_score (1-100) batata hai ki customer kitna kharch karta hai. (Practice ke liye data humne generate kiya hai.)

Scaling zaroori hai

K-Means doori (distance) pe chalta hai, isliye features ko same scale pe laana zaroori hai:

Example

Python
from sklearn.preprocessing import StandardScaler

scaled = StandardScaler().fit_transform(customers)

K kitna ho? Elbow method

K-Means ko K pehle se batana padta hai. Alag-alag K ke liye inertia (points ki apne center se doori ka jod) dekhte hain. Jaha curve 'kohni' (elbow) ki tarah mudta hai, wahi accha K hai:

Example

Python
from sklearn.cluster import KMeans

for k in range(1, 9):
    km = KMeans(n_clusters=k, n_init=10, random_state=42).fit(scaled)
    print(f"K={k}: inertia={km.inertia_:.1f}")

Output

Plain Text
K=1: inertia=400.0
K=2: inertia=233.0
K=3: inertia=140.1
K=4: inertia=62.2
K=5: inertia=21.8
K=6: inertia=19.2
K=7: inertia=17.0
K=8: inertia=15.2

Inertia K=5 tak tezi se girta hai, uske baad girna dheema ho jaata hai — to K = 5 accha choice hai.

Silhouette score

Doosra tareeka: silhouette score (−1 se 1) — kitne achhe se clusters alag hain. Jitna zyada utna accha:

Example

Python
from sklearn.metrics import silhouette_score

for k in [3, 4, 5, 6]:
    labels = KMeans(n_clusters=k, n_init=10, random_state=42).fit_predict(scaled)
    print(f"K={k}: silhouette={silhouette_score(scaled, labels):.3f}")

Output

Plain Text
K=3: silhouette=0.507
K=4: silhouette=0.630
K=5: silhouette=0.715
K=6: silhouette=0.643

Final model aur chart

Example

Python
import matplotlib.pyplot as plt

kmeans = KMeans(n_clusters=5, n_init=10, random_state=42)
customers["cluster"] = kmeans.fit_predict(scaled)

plt.scatter(customers["annual_income_k"], customers["spending_score"],
            c=customers["cluster"], cmap="tab10", alpha=0.8)
plt.xlabel("Annual income (Rs '000)")
plt.ylabel("Spending score")
plt.title("Customer segments (K-Means, K=5)")
plt.show()

K-Means se bane 5 customer segments ka scatter plot

Cluster profiling — har group ko naam dena

Example

Python
profile = customers.groupby("cluster").agg(
    customers=("spending_score", "size"),
    avg_income=("annual_income_k", "mean"),
    avg_spending=("spending_score", "mean"),
).round(1).sort_values("avg_income")
print(profile)

Output

Plain Text
         customers  avg_income  avg_spending
cluster
2               40        24.6          22.1
0               40        25.0          78.8
1               40        55.0          48.5
3               40        85.2          79.5
4               40        85.3          18.5

Ab har cluster ko business ki bhasha me naam dete hain:

Income

Spending

Segment

Strategy

Kam

Kam

Careful spenders

Discounts, value packs

Kam

Zyada

Young trend-followers

Trendy products, EMI offers

Medium

Medium

Average customers

Loyalty programs

Zyada

Kam

Rich but cautious

Premium quality pe focus, trust building

Zyada

Zyada

VIP customers

Exclusive offers, personal attention

Cluster ke number (0, 1, 2...) ka koi matlab nahi — wo bas label hain. Har baar ya har version me numbering alag ho sakti hai, isliye hamesha profile dekh ke naam dijiye.