Machine Learning
Label analysis
Analyze cluster labels.
Segment profiles
Clusters are only valuable once interpreted. The means of each segment in original units are computed and the segments are named:
for k in range(3):
uye = X[km.labels_ == k]
print(k, len(uye), uye.mean(axis=0).round(0))
# e.g. low spending + few visits -> "occasional"
# high spending + few visits -> "big basket"
# medium spending + many visits -> "loyal frequent"
Means in original units are reported rather than scaled centres; the marketing team talks TL, not z-scores.
Tying segment names to code
Because cluster numbers may change on every run, names aren't hard-coded to numbers; they are derived from the centres' properties. For example, the cluster with the highest mean visits is picked as "loyal":
ort = np.array([X[km.labels_ == k].mean(axis=0) for k in range(3)])
sadik = ort[:, 1].argmax() # highest visits
buyuk = ort[:, 2].argmax() # biggest basket
print(sadik, buyuk)
This approach prevents names from drifting to the wrong cluster when the model is retrained.
Exercise Extract the profiles
Collect each segment's means in original units in the array ort and print it with np.round(ort, 0). Then print the numbers of the segments with the most visits and the biggest basket on one line.
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
Xs = StandardScaler().fit_transform(X)
from sklearn.cluster import KMeans
km = KMeans(n_clusters=3, n_init=10, random_state=0).fit(Xs)
ort = np.array([X[km.labels_ == k].mean(axis=0) for k in range(3)])
print(np.round(ort, 0))
print(ort[:, 1].argmax(), ort[:, 2].argmax())
Test yourself
-
What is the problem with reporting the centres in scaled data?
- The values can't be read in TL or visits
- They are wrong
- They can't be computed
- There is no problem
Show answer
The values can't be read in TL or visits — z-scores describe relative position; business language needs the original units.
-
Find the segment with the highest mean visits.
sadik = ort[:, 1].____()
Show answer
sadik = ort[:, 1].argmax()
-
Match the profiles with the names.
- Low spend, few visits
- Occasional
- High spend, few visits
- Big basket
- Medium spend, many visits
- Loyal frequent
- ort[:, 1].argmax()
- Tying the name
Next lesson: Printing results