Machine Learning
Printing results
Print clustering results.
The results report
The report includes, for each segment, a name, its size and a profile in original units. An example showing which segment new customers fall into makes the use of the system concrete:
yeni = np.array([[1400, 3, 1400 / 3]])
segment = km.predict(sc.transform(yeni))[0]
print(f"Yeni müşteri: {adlar[segment]}")
The new customer must be transformed with the same scaler used in training.
Limitations
An honest report also states limitations: the segments rely only on the three features used; there is no seasonal behaviour, age or channel information. KMeans assumes round clusters; the real customer distribution may differ. Segments drift over time; the model should be retrained periodically.
# monitoring suggestion: record segment sizes every month
# a big change = behaviour drift -> recluster
Clustering is an exploration tool; its results need validating with the first campaigns.
Exercise Write the report
Derive the segment names from the profiles: the segment with the most visits is "sadık", the one with the biggest basket "büyük sepetçi", the remaining one "ara sıra". Print the line f"{ad}: {boyut} müşteri" for each segment in segment-number order. Then print the segment name of the customer [[1400, 3, 1400 / 3]].
Show example solution
import numpy as np
rng = np.random.default_rng(5)
n = 400
grup = rng.integers(0, 3, n)
harcama = np.array([300, 1500, 800])[grup] + rng.normal(0, 120, n)
ziyaret = np.array([2, 4, 12])[grup] + rng.normal(0, 1.2, n)
sepet = harcama / np.maximum(ziyaret, 1)
X = np.column_stack([harcama, ziyaret, sepet])
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
sc = StandardScaler().fit(X)
km = KMeans(n_clusters=3, n_init=10, random_state=0).fit(sc.transform(X))
ort = np.array([X[km.labels_ == k].mean(axis=0) for k in range(3)])
adlar = ["ara sıra"] * 3
adlar[ort[:, 1].argmax()] = "sadık"
adlar[ort[:, 2].argmax()] = "büyük sepetçi"
for k, boyut in enumerate(np.bincount(km.labels_)):
print(f"{adlar[k]}: {boyut} müşteri")
print(adlar[km.predict(sc.transform([[1400, 3, 1400 / 3]]))[0]])
Test yourself
-
What happens if you give a new customer to <code>km.predict</code> without scaling?
- It works correctly
- It errors
- A new cluster is opened
- It is assigned to the wrong segment
Show answer
It is assigned to the wrong segment — The centres are in the scaled space; raw values are a very distant point in that space.
-
Transform the new customer with the training scaler.
segment = km.predict(sc.____(yeni))[0]
Show answer
segment = km.predict(sc.transform(yeni))[0]
-
Match the report parts.
- segment name
- Derived from the profile
- dimension
- bincount
- new customer
- sc.transform + predict
- limitation
- Missing features, drift
Next lesson: What is PCA?