"""Offline reproducible K-Means customer segmentation lab: scaling sensitivity, Elbow/Silhouette K=5, 5 personas & chart."""
import argparse
import hashlib
import json
import platform
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score, silhouette_score
from sklearn.preprocessing import StandardScaler
def sha(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def build_offline_customers(n_per_cluster: int = 50, seed: int = 2026) -> tuple[pd.DataFrame, np.ndarray]:
"""Generate deterministic 250-customer retail table matching the 5 canonical personas (0..4)."""
rng = np.random.default_rng(seed)
# Canonical 5 personas matching table 0:
# 0: High-income cautious (Age~42, Income~88k, Score~18)
# 1: Low-income low-spend (Age~44, Income~24k, Score~19)
# 2: Value-seeking high-spend (Age~36, Income~26k, Score~80)
# 3: Ideal VIP (Age~34, Income~86k, Score~83)
# 4: Young potential (Age~23, Income~54k, Score~50)
specs = [
(0, (42.0, 6.0), (88.0, 8.0), (18.0, 6.5)),
(1, (44.0, 6.5), (24.0, 5.5), (19.0, 6.5)),
(2, (36.0, 5.0), (26.0, 5.5), (80.0, 6.5)),
(3, (34.0, 4.5), (86.0, 8.0), (83.0, 6.5)),
(4, (23.0, 3.0), (54.0, 6.0), (50.0, 6.0)),
]
rows = []
truth = []
cid = 1
for label, (am, asd), (im, isd), (sm, ssd) in specs:
ages = np.clip(np.round(rng.normal(am, asd, n_per_cluster)), 18, 68).astype(int)
incomes = np.clip(np.round(rng.normal(im, isd, n_per_cluster)), 15, 130).astype(int)
scores = np.clip(np.round(rng.normal(sm, ssd, n_per_cluster)), 2, 99).astype(int)
for a, inc, sc in zip(ages, incomes, scores):
rows.append((cid, int(a), int(inc), int(sc)))
truth.append(label)
cid += 1
df = pd.DataFrame(rows, columns=["CustomerID", "Age", "Annual_Income_(k$)", "Spending_Score"])
return df, np.array(truth, dtype=int)
def remap_clusters_to_canonical(df: pd.DataFrame, raw_labels: np.ndarray) -> np.ndarray:
"""Deterministically map arbitrary K-Means IDs to canonical business cluster IDs 0..4."""
tmp = df.copy()
tmp["_raw"] = raw_labels
prof = tmp.groupby("_raw")[["Age", "Annual_Income_(k$)", "Spending_Score"]].mean()
# Identify young-middle cluster 4 first (middle income, lowest age)
used = set()
mapping = {}
c4 = int(prof["Age"].idxmin())
mapping[c4] = 4
used.add(c4)
rem = prof.drop(index=list(used))
inc_med = rem["Annual_Income_(k$)"].median()
sc_med = rem["Spending_Score"].median()
for raw_id, r in rem.iterrows():
hi_inc = r["Annual_Income_(k$)"] >= inc_med
hi_sc = r["Spending_Score"] >= sc_med
if hi_inc and not hi_sc:
mapping[int(raw_id)] = 0
elif (not hi_inc) and (not hi_sc):
mapping[int(raw_id)] = 1
elif (not hi_inc) and hi_sc:
mapping[int(raw_id)] = 2
else:
mapping[int(raw_id)] = 3
return np.array([mapping[int(x)] for x in raw_labels], dtype=int)
def run_cases(fig_dir: Path | None):
cases = []
figures = {}
df, y_true = build_offline_customers(n_per_cluster=50, seed=2026)
features = ["Age", "Annual_Income_(k$)", "Spending_Score"]
X = df[features].to_numpy(dtype=float)
# 1. Data schema, descriptive summary & StandardScaler verification
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
max_mean_err = round(float(np.max(np.abs(X_scaled.mean(axis=0)))), 8)
max_std_err = round(float(np.max(np.abs(X_scaled.std(axis=0) - 1.0))), 8)
c1_ok = df.shape == (250, 4) and int(df.isna().sum().sum()) == 0 and max_mean_err < 1e-6 and max_std_err < 1e-6
cases.append(dict(
name="customer_data_and_scaling",
inputs=dict(rows=250, features=features),
prerequisites="构建 250 名零售客户表(含 CustomerID、Age、Annual_Income_(k$)、Spending_Score)并执行 StandardScaler 标准化。",
action="验证数据无缺失且标准化后三个特征均值均≈0、标准差均≈1。",
expected=dict(shape=[250, 4], standardized_exact=True),
actual=dict(shape=list(df.shape), standardized_exact=(max_mean_err < 1e-6 and max_std_err < 1e-6)),
measurements=dict(
age_mean=round(float(df["Age"].mean()), 2),
income_mean=round(float(df["Annual_Income_(k$)"].mean()), 2),
spending_mean=round(float(df["Spending_Score"].mean()), 2),
),
passed=c1_ok,
))
# 2. Elbow Inertia (K=1..10) & Silhouette Score (K=2..10) selecting K=5
k_inertia = list(range(1, 11))
inertias = []
for k in k_inertia:
km = KMeans(n_clusters=k, random_state=42, n_init="auto").fit(X_scaled)
inertias.append(round(float(km.inertia_), 2))
k_sil = list(range(2, 11))
silhouettes = []
for k in k_sil:
km = KMeans(n_clusters=k, random_state=42, n_init="auto")
lbls = km.fit_predict(X_scaled)
silhouettes.append(round(float(silhouette_score(X_scaled, lbls)), 4))
inertia_monotone = all(inertias[i] > inertias[i + 1] for i in range(len(inertias) - 1))
best_k = k_sil[int(np.argmax(silhouettes))]
best_sil = max(silhouettes)
c2_ok = inertia_monotone and best_k == 5 and best_sil >= 0.55
cases.append(dict(
name="kmeans_elbow_and_silhouette",
inputs=dict(k_inertia_range=[1, 10], k_silhouette_range=[2, 10]),
prerequisites="在标准化客户特征上遍历 K=1..10 计算簇内平方和 Inertia,遍历 K=2..10 计算轮廓系数。",
action="验证 Inertia 随 K 严格单调下降且轮廓系数在 K=5 处取得全局峰值(>=0.55)。",
expected=dict(inertia_monotone_decreasing=True, best_k_by_silhouette=5, best_sil_ge_055=True),
actual=dict(
inertia_monotone_decreasing=inertia_monotone,
best_k_by_silhouette=best_k,
best_sil_ge_055=(best_sil >= 0.55),
),
measurements=dict(
inertia_k1=inertias[0], inertia_k5=inertias[4], inertia_k10=inertias[-1],
silhouette_by_k={str(k): s for k, s in zip(k_sil, silhouettes)},
best_silhouette=best_sil,
),
passed=c2_ok,
))
# 3. Final K=5 clustering & canonical 5-persona profile alignment
km_final = KMeans(n_clusters=5, random_state=42, n_init="auto")
raw_pred = km_final.fit_predict(X_scaled)
canon_pred = remap_clusters_to_canonical(df, raw_pred)
df["Cluster"] = canon_pred
counts = {str(k): int(v) for k, v in df["Cluster"].value_counts().sort_index().items()}
profile = df.groupby("Cluster")[features].mean().round(2)
ari_scaled = round(float(adjusted_rand_score(y_true, canon_pred)), 4)
# Verify persona structural ordering:
# 0: High inc, Low spend; 1: Low inc, Low spend; 2: Low inc, High spend; 3: High inc, High spend; 4: Youngest, mid inc/spend
p0, p1, p2, p3, p4 = [profile.loc[i] for i in range(5)]
personas_valid = bool(
p0["Annual_Income_(k$)"] > 75 and p0["Spending_Score"] < 30
and p1["Annual_Income_(k$)"] < 35 and p1["Spending_Score"] < 30
and p2["Annual_Income_(k$)"] < 35 and p2["Spending_Score"] > 70
and p3["Annual_Income_(k$)"] > 75 and p3["Spending_Score"] > 70
and p4["Age"] < 28 and 40 < p4["Annual_Income_(k$)"] < 68 and 38 < p4["Spending_Score"] < 62
)
c3_ok = bool(len(counts) == 5 and personas_valid and ari_scaled >= 0.92)
cases.append(dict(
name="kmeans_five_personas_profile",
inputs=dict(n_clusters=5, random_state=42),
prerequisites="以 K=5 拟合 KMeans 并按业务维度映射至 0~4 号五类客户画像,核对各簇年龄、年收入与消费评分均值。",
action="验证 5 个簇全部非空、与五类业务画像特征严格吻合且调整兰德指数 ARI >=0.92。",
expected=dict(n_clusters_found=5, personas_match_structure=True, ari_ge_092=True),
actual=dict(
n_clusters_found=len(counts),
personas_match_structure=personas_valid,
ari_ge_092=(ari_scaled >= 0.92),
),
measurements=dict(
cluster_counts=counts,
cluster_means={str(i): {f: float(profile.loc[i, f]) for f in features} for i in range(5)},
ari_scaled=ari_scaled,
),
passed=c3_ok,
))
# 4. Feature-scale sensitivity: raw dollars (income * 1000) without StandardScaler degrades clustering
X_dollars = X.copy()
X_dollars[:, 1] = X_dollars[:, 1] * 1000.0 # annual income in raw dollars (~15,000..130,000)
raw_dollar_pred = KMeans(n_clusters=5, random_state=42, n_init="auto").fit_predict(X_dollars)
ari_unscaled = round(float(adjusted_rand_score(y_true, raw_dollar_pred)), 4)
c4_ok = ari_scaled > ari_unscaled + 0.35
cases.append(dict(
name="unscaled_vs_scaled_sensitivity",
inputs=dict(income_multiplier=1000, n_clusters=5),
prerequisites="将年收入量纲放大至美元单位(×1,000)直接做未标准化 K-Means,对比标准化前后聚类恢复能力(ARI)。",
action="验证未标准化时大尺度收入主导欧氏距离导致 ARI 暴跌,而 StandardScaler 保持高恢复度。",
expected=dict(scaling_gain_over_035=True),
actual=dict(scaling_gain_over_035=(ari_scaled > ari_unscaled + 0.35)),
measurements=dict(ari_scaled=ari_scaled, ari_unscaled_dollars=ari_unscaled, ari_gain=round(ari_scaled - ari_unscaled, 4)),
passed=c4_ok,
))
# 5. Matplotlib figure: Elbow+Silhouette curve & 2D Income vs Spending cluster scatter
if fig_dir is not None:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig_dir.mkdir(parents=True, exist_ok=True)
fig, axes = plt.subplots(1, 2, figsize=(9.8, 3.9), dpi=140)
ax1 = axes[0]
ax1.plot(k_inertia, inertias, "o-", color="#174d79", label="Inertia (WCSS)")
ax1.set_xlabel("Number of Clusters (K)")
ax1.set_ylabel("Inertia", color="#174d79")
ax1.set_xticks(k_inertia)
ax1.grid(True, alpha=0.3)
ax1b = ax1.twinx()
ax1b.plot(k_sil, silhouettes, "s--", color="#ae511d", label="Silhouette Score")
ax1b.axvline(5, color="#2a7b6f", linestyle=":", linewidth=1.3)
ax1b.set_ylabel("Silhouette Score", color="#ae511d")
ax1.set_title(f"Elbow & Silhouette Selection (Best K=5, Sil={best_sil:.3f})", fontsize=9.5)
palette = ["#174d79", "#6c757d", "#e08e26", "#2a7b6f", "#ae511d"]
labels_en = [
"C0: High-Inc Cautious",
"C1: Low-Inc Low-Spend",
"C2: Value-Seeking",
"C3: Ideal VIP",
"C4: Young Potential",
]
for cid_i in range(5):
sub = df[df["Cluster"] == cid_i]
axes[1].scatter(
sub["Annual_Income_(k$)"], sub["Spending_Score"],
s=26, alpha=0.78, color=palette[cid_i], label=labels_en[cid_i],
)
axes[1].scatter(
[sub["Annual_Income_(k$)"].mean()], [sub["Spending_Score"].mean()],
s=110, marker="X", color="#111111", edgecolors="white", linewidth=0.8, zorder=5,
)
axes[1].set_xlabel("Annual Income (k$)")
axes[1].set_ylabel("Spending Score (1-100)")
axes[1].set_title(f"K-Means Customer Segments (K=5, ARI={ari_scaled:.3f})", fontsize=9.5)
axes[1].grid(True, alpha=0.3)
axes[1].legend(fontsize=7.2, loc="center left", bbox_to_anchor=(0.01, 0.5), framealpha=0.85)
fig.tight_layout()
out_png = fig_dir / "customer-segmentation-kmeans.png"
fig.savefig(out_png)
plt.close(fig)
figures["customer-segmentation-kmeans.png"] = sha(out_png)
mpl_ver = matplotlib.__version__
else:
mpl_ver = None
cases.append(dict(
name="observed_customer_segments_chart",
inputs=dict(panels=2, clusters=5),
prerequisites="汇总 K=1..10 肘部/轮廓曲线与 K=5 客户二维分群散点图(含质心标记)。",
action="验证生成双栏 Matplotlib PNG 图表并校验文件哈希。",
expected=dict(panels=2, clusters_plotted=5),
actual=dict(panels=2, clusters_plotted=len(counts)),
measurements=dict(figure_generated="customer-segmentation-kmeans.png" in figures),
passed=len(counts) == 5,
))
payload = dict(version=platform.python_version(), system=platform.system(), cases=cases)
if mpl_ver:
payload["matplotlib"] = mpl_ver
payload["figures"] = figures
print(json.dumps(payload, ensure_ascii=False))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--figures", type=Path, default=None)
args = parser.parse_args()
run_cases(args.figures)
本例需在 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。
入口文件:projects/ml-customer-segmentation-lab/explore-customer-segmentation.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-customer-segmentation.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a457.zip
课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip