Repository navigation
Expand file tree
/
Copy pathsegmentation.py
More file actions
78 lines (68 loc) · 2.94 KB
/
Copy pathsegmentation.py
File metadata and controls
78 lines (68 loc) · 2.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
from pathlib import Path
import numpy as np
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
rfm = pd.read_csv("rfm_table.csv")
# 1) log pour écraser la traîne 2) scaler pour que R, F, M pèsent pareil
X_log = np.log1p(rfm[["Recency", "Frequency", "Monetary"]])
X = StandardScaler().fit_transform(X_log)
#chosir K (coude+silhouette)
ks = range(2, 9)
inerties, silhouettes = [], []
for k in ks:
km = KMeans(n_clusters=k, random_state=42, n_init=10)
labels = km.fit_predict(X)
inerties.append(km.inertia_)
silhouettes.append(silhouette_score(X, labels))
fig, (a1, a2) = plt.subplots(1, 2, figsize=(12, 4))
a1.plot(list(ks), inerties, "o-", color="#1f3a5f")
a1.set_title("Méthode du coude"); a1.set_xlabel("k"); a1.set_ylabel("Inertie")
a1.grid(alpha=0.25)
a2.plot(list(ks), silhouettes, "o-", color="#c8a24b")
a2.set_title("Score de silhouette"); a2.set_xlabel("k"); a2.set_ylabel("Silhouette (↑ mieux)")
a2.grid(alpha=0.25)
fig.tight_layout(); fig.savefig("choix_k.png", dpi=130)
print("Silhouettes :", dict(zip(ks, np.round(silhouettes, 3))))
#clustering final + profil des segments
K = 4 # choisi d'après choix_k.png
km = KMeans(n_clusters=K, random_state=42, n_init=10)
rfm["Cluster"] = km.fit_predict(X)
profil = rfm.groupby("Cluster").agg(
Recency=("Recency", "mean"),
Frequency=("Frequency", "mean"),
Monetary=("Monetary", "mean"),
Taille=("Cluster", "size"),
).round(1)
print(profil)
noms = {
0: "Champions",
1: "Perdus / à réactiver", # R=396 j, 1 achat → lapsed, pas fidèle
2: "En sommeil",
3: "Fidèles", # R=28 j, revient → actif, pas perdu
}
rfm["Segment"] = rfm["Cluster"].map(noms)
#graphe qui vend : % clients vs % CA
seg = rfm.groupby("Segment").agg(
Clients=("Customer ID", "size"),
CA=("Monetary", "sum"),
)
seg["% clients"] = 100 * seg["Clients"] / seg["Clients"].sum()
seg["% CA"] = 100 * seg["CA"] / seg["CA"].sum()
seg = seg.sort_values("% CA", ascending=False)
print(seg.round(1))
x, w = np.arange(len(seg)), 0.38
fig, ax = plt.subplots(figsize=(9, 5))
ax.bar(x - w/2, seg["% clients"], w, label="% des clients", color="#9aa7b5")
ax.bar(x + w/2, seg["% CA"], w, label="% du chiffre d'affaires", color="#1f3a5f")
for i, (c, r) in enumerate(zip(seg["% clients"], seg["% CA"])):
ax.text(i - w/2, c + 0.6, f"{c:.0f}%", ha="center", fontsize=9)
ax.text(i + w/2, r + 0.6, f"{r:.0f}%", ha="center", fontsize=9, weight="bold")
ax.set_xticks(x); ax.set_xticklabels(seg.index)
ax.set_ylabel("%"); ax.set_ylim(0, max(seg["% CA"].max(), seg["% clients"].max()) + 8)
ax.set_title("Qui fait le chiffre d'affaires ? — part de clients vs part de CA", weight="bold")
ax.legend(); ax.grid(axis="y", alpha=0.25)
fig.tight_layout(); fig.savefig("rfm_segments.png", dpi=130)
print("Figure sauvée : rfm_segments.png")