36. K-Means Clustering — Python मध्ये
36.4 India Customer / City काल्पनिक Example
का गरजेचे आहे. पूर्ण छोटे India example जोडा: Maharashtra cities मधील काल्पनिक grocery customers.
हे काय आहे. KMeans(n_clusters=3) fit करा, cluster ids जोडा, आणि प्रत्येक cluster चे means सारांश करा.
कसे करायचे.
Customer गट copy-run
- Numeric X तयार करा.
- n_init सेट करून KMeans fit करा (warning noise टाळते).
- Cluster column जोडा.
- गटांना नाव देण्यासाठी groupby mean.
import pandas as pd
from sklearn.cluster import KMeans
df = pd.DataFrame({
"customer": ["Ruhi", "Raja", "Rani", "Asha", "Vijay", "Meera", "Om", "Neha"],
"city": ["Pune", "Kolhapur", "Nashik", "Pune", "Mumbai", "Nagpur", "Pune", "Nashik"],
"orders_per_month": [2, 1, 9, 3, 11, 2, 10, 8],
"avg_basket_inr": [240, 190, 910, 310, 1250, 220, 980, 870],
})
X = df[["orders_per_month", "avg_basket_inr"]]
km = KMeans(n_clusters=3, n_init=10, random_state=42)
df["cluster"] = km.fit_predict(X)
print(df[["customer", "city", "cluster"]])
print(df.groupby("cluster")[["orders_per_month", "avg_basket_inr"]].mean().round(1))
तुम्हाला काय दिसायला हवे. तीन buckets — उदा. light shoppers vs heavy baskets. City रंगांसाठी दाखवले आहे; इथे feature म्हणून वापरले नाही जेणेकरून distance numeric आणि सोपा राहील.
काल्पनिक data
नावे आणि baskets फक्त classroom साठी काल्पनिक आहेत.