Grouping with machine learning
45 features from the sales mix, k-means and Ward, choosing the number of clusters without looking at the answer key, and reading the five clusters. Plus the trace the assortment leaves on sales, and a turn we took in the choice rule.
Store Grouping · 4 / 6
In the first article Pars gave the computer only 45 numbers and asked it to bring together the stores whose mixes resemble each other. The result was five clustersA group of stores with similar sales mixes. The plan and the initial allocation treat the stores in a cluster as one unit.. In this article we open up that step: where do the 45 numbers come from, how are they put on the same footing, which method finds the clusters, and what decides on the number five?
As in the last article, the code comes from the working code under
cases/store-clustering/ and the numbers from the case’s report. Let me also
say one thing up front: none of the choices in this article uses the answer
key as an input. We measure the clusters against that key only afterwards.
But I cannot say we made every choice without seeing any result from the key;
where we did see one, I will say so in its place.
One store, 45 numbers
The features are built from the sales of the last 104 completed weeks before the decision day; roughly two years. The week of the decision day is not read, because it has not finished yet. Sales are counted in gross units: returns are not taken off, and identical rows are counted once. DuckDB does the summing:
# store_clustering/features.py (_Reader._build; inside the slice loop)
clean = (f"(select distinct * from sales where date >= ? and date < ? "
f"and store_id::varchar in (select m from {_PREFIX}m))")
self.con.execute(f"""
insert into {_PREFIX}su
select store_id::varchar, product_id::varchar, month(date), sum(units)::bigint
from {clean} where units > 0 group by all""", [d0, d1])
The query sums gross units for every store, every product and every month; only these totals come across to the Python side.
The sales mixHow a store's sales are spread across subcategories, price segments and fits. It describes not how much a store sells but what it sells. is built separately in two line groups: Collection, and Basic with NOS together. The Outlet line is left out; that stock belongs to the outlet stores. Each group has three attributes: subcategory, price segment and fit. The Product hierarchy article explains subcategory and fit.
# store_clustering/features.py
LINE_GROUPS: dict[str, tuple[str, ...]] = {"Collection": ("Collection",), "Basic+NOS": ("Basic", "NOS")}
ATTRIBUTES = ("subcategory", "price_segment", "fit")
FAMILIES: dict[str, tuple[str, ...]] = {
"S1": ("mix",), # sales mix
"S2": ("mix", "size", "season"), # + size curve + seasonality
"S4": ("mix_in_stock", "size_in_stock", "season_in_stock"), # S2, adjusted for assortment
"S5": ("mix", "size", "season", "scale"), # S2 + scale (ablation)
}
The function that builds the mix block:
# store_clustering/features.py
def _mix(o: _Reader, in_stock: bool) -> tuple[pd.DataFrame, int, dict]:
block = "mix_in_stock" if in_stock else "mix"
s = o.sales_attribute()
g = o.days_attribute() if in_stock else None
parts, n, dropped = [], 0, {}
for group in LINE_GROUPS:
for a in ATTRIBUTES:
name = f"{block}/{group}/{a}"
units = _pivot(s[s["group"] == group], a, "units", o.ids, kind=a)
if in_stock:
R, dropped[name] = _rate(units, _pivot(g[g["group"] == group], a, "days", o.ids, kind=a), a)
R, k = _neutral_fill(R, name)
n += k
else:
R = units
parts.append(_name(_to_shares(R, name), block, group, a))
return pd.concat(parts, axis=1), n, dropped
Each (group, attribute) pair is a sub-block: two groups times three
attributes, six sub-blocks. Within each sub-block the shares add up to one;
how much of a store’s Collection sales are dresses, how much shirts, how much
trousers. Put the six sub-blocks’ columns side by side and you get 45
columns. Collection’s share of the store’s total sales is not a separate
feature; we look only at the spread within each group. We will come back to
the in_stock branch in the section on the assortment.
Next to the mix we built two more blocks. The size curve: the sales shares of size orders 1 to 5, within each size set; the sets are equally weighted, so that a store’s mix between women’s and men’s, or between alpha and numeric sizes, does not shift the curve. Seasonality: units per selling day in each of the twelve months, turned into shares. A rate per day, so that a store’s opening or a refit does not distort a month’s share.
These blocks make four feature families:
| Family | Blocks | Columns |
|---|---|---|
| S1 | sales mix | 45 |
| S2 | mix, size curve, seasonality | 62 |
| S4 | S2, adjusted for assortment | 62 |
| S5 | S2 and scale | 65 |
Two families compete for the recommended clustering: S1 and S2. S4 and S5, and the mix-and-scale family we used in the last article, are there only for ablations. I will say at the end of the article why there is no S3 among the names.
Putting them on the same footing
Clustering methods look at the distance between stores. And distance is sensitive to the scale of the columns: a share that moves over a wide range drowns a share that moves over a narrow one. So first, standardising:
# store_clustering/features.py (standardise; check lines left out)
for b in blocks:
Z = X.loc[:, (block_name == b)].astype("float64")
sd = Z.std(axis=0, ddof=0)
Z = Z.loc[:, sd > 1e-12]
Z = (Z - Z.mean(axis=0)) / sd[Z.columns]
if weighting == "column":
divisor = pd.Series(np.sqrt(Z.shape[1]), index=Z.columns)
else:
sub = pd.Series([sub_block(c) for c in Z.columns], index=Z.columns)
divisor = np.sqrt(sub.map(sub.value_counts()) * sub.nunique())
parts.append(Z / divisor)
return pd.concat(parts, axis=1)
Each column is first turned into a z-score: its mean is taken off and it is divided by its standard deviation. A column that is the same in every store carries no information, so it drops. Then comes the weighting, in two layers. The blocks are equal: each block’s total variance is 1, so the mix’s 45 columns do not drown the season’s 12. Within a block the sub-blocks are equal too: in the mix each of the six sub-blocks takes 1/6 of the block’s variance. The subcategory has far more columns than the price segment; without this weighting the subcategory would run the whole mix.
This weighting was not chosen by the answer key’s result. Even so, we had seen one result from the key: while exploring, we measured an option that gave all the weight to the subcategory against the key, and saw that the clusters fitted the key very well. We fixed equal sub-block weights anyway, on principle: the mix has three dimensions, and all three get an equal say. We also ran the other weighting, which keeps the columns within a block equal, as an ablation. With five clusters S1’s agreement with the answer key is 1.000 under both weightings. S2’s falls from 0.137 to 0.091.
Two methods
# store_clustering/learn.py (cluster; check lines left out)
def cluster(X_std: pd.DataFrame, method: Method, k: int, seed: int = constants.SEED) -> pd.Series:
"""Store → canonical cluster number (0..k−1), in `X_std` row order."""
X = _sorted(X_std)
if method == "kmeans":
model = KMeans(n_clusters=k, n_init=constants.KMEANS_N_INIT, random_state=seed)
elif method == "ward":
model = AgglomerativeClustering(n_clusters=k, linkage="ward")
with threadpool_limits(limits=1): # fast on a small table; independent of the thread count
label = canonical(pd.Series(model.fit(X.to_numpy()).labels_, index=X.index))
return label.reindex(pd.Index(X_std.index.astype(str), name="store_id"))
k-means first picks k centres and ties each store to its nearest centre. Then it moves each centre to the mean of its own stores and redoes the tying; until the centres stop moving. Because the result depends on the starting points, it runs with 50 different starts and keeps the result with the smallest within-cluster sum of squares.
Ward starts from the other end: every store is its own cluster. At each step the two clusters whose merger raises the within-cluster variance least are merged; until k clusters are left. There is no chance in Ward; on the same data it always gives the same result.
The cluster numbers are not a name but an order: cluster 0 is the cluster holding the smallest store id. That way two runs giving the same split get the same numbers.
How many clusters
“Who chose five clusters?” says Pelin. “Did you tell the computer five?”
“I didn’t,” says Pars. “I tried every number from three to ten. Which one is better was decided by a measure: the silhouette.”
The silhouette looks at two distances for each store: its average distance to the stores in its own cluster, and its average distance to the nearest other cluster. The more the second exceeds the first, the better the store fits its cluster. The closer the average over the stores gets to 1, the more cleanly the clusters separate; the closer to 0, the more they overlap.
# store_clustering/learn.py
def k_rule(table: pd.DataFrame, smallest: int = constants.SMALLEST_CLUSTER) -> int | None:
"""The k choice rule (module note): the k chosen from a table with `k`, `silhouette`, `smallest`
columns, or None."""
u = table.loc[table["smallest"] >= smallest]
if u.empty:
return None
threshold = u["silhouette"].max() - SILHOUETTE_TIE - _EPS
return int(u.loc[u["silhouette"] >= threshold, "k"].min())
The rule has three steps. A k whose smallest cluster has fewer than 3 stores is dropped; this is a business constraint, as Lumoda does not set up a planning group smaller than three stores. Among the rest the highest silhouette is found. The k’s at most 0.01 below that silhouette count as tied, and the smallest of them is chosen. A 0.01 difference in silhouette does not tell splits apart; and fewer groups are handier in planning.
For S1, k-means looks like this:
| k | Silhouette | Smallest cluster | Eligible |
|---|---|---|---|
| 3 | 0.231 | 7 | yes |
| 4 | 0.275 | 7 | yes |
| 5 | 0.308 | 7 | yes |
| 6 | 0.267 | 7 | yes |
| 7 | 0.267 | 7 | yes |
| 8 | 0.267 | 6 | yes |
| 9 | 0.272 | 3 | yes |
| 10 | 0.272 | 2 | no |
For S1 the choice is easy: the silhouette peaks at five clusters, and its nearest rival is 0.275. For S2 the rule’s first step does the work. For S2, k-means always builds a one-store cluster at six clusters and above; even though their silhouette goes up as far as 0.291, these splits are dropped. Among the remaining three, four and five clusters the highest silhouette is at three, 0.278. Five’s 0.277 counts as tied too, and the rule picks the smaller, three.
Those who know the elbow method may ask: the within-cluster sum of squares is printed in the report too, but it does not enter the rule. It always falls as k grows; saying where the elbow is would need a second threshold.
Four candidates, one recommendation
The rule picks one k for each family and method. Two families, two methods, four candidates:
| Candidate | k | Silhouette | Stability | Cluster sizes |
|---|---|---|---|---|
| S1, k-means | 5 | 0.308 | 0.851 | 32/14/7/7/7 |
| S1, Ward | 5 | 0.308 | 0.877 | 32/14/7/7/7 |
| S2, k-means | 3 | 0.278 | 0.992 | 38/24/5 |
| S2, Ward | 5 | 0.277 | 0.974 | 22/18/15/7/5 |
Stability is a second measure that needs no key: how well does the split hold when some of the stores are missing?
# store_clustering/learn.py (stability; check lines left out)
X = _sorted(X_std)
n = len(X)
m = int(np.floor(fraction * n + 0.5))
full = cluster(X, method, k, seed=seed).to_numpy()
rng = np.random.default_rng(seed)
ari = []
for _ in range(samples):
pick = np.sort(rng.choice(n, size=m, replace=False))
sub = cluster(X.iloc[pick], method, k, seed=seed).to_numpy()
ari.append(adjusted_rand_score(full[pick], sub))
return float(np.mean(ari))
80% of the stores are drawn at random 50 times and clustered again with only those. In each draw the ARI between the new split and the full split, on the drawn stores, is measured; their mean is the stability. Here ARI compares two splits with each other, not with the answer key.
The recommendation is picked from these four candidates like this:
# store_clustering/learn.py (recommendation_rule; docstring left out)
def recommendation_rule(candidates: pd.DataFrame) -> tuple[int, pd.Series, pd.Series]:
a = candidates.reset_index(drop=True)
partition = a.groupby("identity")["stability"].transform("mean")
tied = a["silhouette"] >= a["silhouette"].max() - SILHOUETTE_TIE - _EPS
st = partition[tied]
e = a.loc[tied].loc[st >= st.max() - STABILITY_TIE - _EPS]
ranked = sorted(e.index, key=lambda i: (int(e.at[i, "k"]), RECOMMENDED_FAMILIES.index(e.at[i, "family"]),
METHODS.index(e.at[i, "method"])))
return int(ranked[0]), tied, partition
Silhouette first again. Among the four candidates the highest silhouette is 0.308; those at most 0.01 below it are tied. S1’s two candidates are tied, S2’s are not. Among the tied, stability decides, but with a single number for candidates that give the same split. In S1, k-means and Ward find the same five clusters. Because the two methods can behave differently on a subsample, their stabilities come out different, but since the split is the same neither can count as more stable than the other; the mean of the two is 0.864. A stability difference of up to 0.02 counts as a tie too. If the tie still holds, the smaller k wins, then S1, then k-means.
The recommendation: S1, k-means, five clusters. Their sizes are 32, 14, 7, 7 and 7 stores.
We also checked that the silhouette can be compared across the two families. S2 has 62 columns, S1 45; the number of dimensions could be shifting the silhouette on its own. We shuffled each column across the stores within itself to build data with no structure, and clustered it with the same method, ten times. On the structureless data the silhouette averages 0.048 for S1 and 0.052 for S2; a gap of 0.004, below the tie margin. The recommendation’s silhouette is 0.308, its structureless twin’s 0.047. The real data has a structure, and the two families’ silhouettes speak on the same scale.
A turn
Here I have a confession. The recommendation rule I wrote before seeing the results was the one above: silhouette first, stability on a tie. In the code’s first draft, though, the order was the other way round: stability first. That draft picked S2, k-means, three clusters; stability 0.992, silhouette 0.278.
Measured against the answer key, that split’s ARI came out at 0.055. We put the rule back to its written form after seeing this result. The rule itself was written before the result; but which form of it would be used was decided with the answer key’s result already seen. That is why I cannot say the choice of recommendation is entirely independent of the answer key.
The turn shows something else too: the two key-free measures do not agree. Stability likes a small k and crude splits along a single strong axis. Such a split does not break when stores are missing, but it may not be the structure’s real axis. S2’s three clusters look like an example of this: stability 0.992, agreement with the answer key 0.055. If you do not write down which measure you will look at before you see the result, you are very close to picking the measure that gives the result you like.
Against the answer key
Once the choice is made, we measure the four candidates against the answer key:
| Candidate | ARI with the answer key |
|---|---|
| S1, k-means, 5 clusters (recommended) | 1.000 |
| S1, Ward, 5 clusters | 1.000 |
| S2, k-means, 3 clusters | 0.055 |
| S2, Ward, 5 clusters | 0.137 |
The recommendation is exactly the answer key: five clusters, five profiles, one profile in each cluster. Had we picked with the key from all the eligible rows, we would have picked the same split.
S2, though, breaks down in both its candidates. The only difference between S1 and S2 is the size curve and seasonality. It looks as though at Lumoda these two blocks split along something other than the customer profile, and pull the clusters that way. More information does not always mean better clusters.
What the clusters say
A split does not turn into a plan on its own; Pelin wants to know what each cluster sells. To find each cluster’s most distinctive features we turn each column into a z-score across all the stores and look at the cluster’s mean z:
# store_clustering/learn.py (profile)
sd = A.std(axis=0, ddof=0)
A = A.loc[:, sd > _EPS]
Z = (A - A.mean(axis=0)) / sd[A.columns]
mean = Z.groupby(label.to_numpy()).mean()
If a feature’s mean z is +2, this share in the cluster’s stores is two standard deviations above the mean of all stores. A minus z says the share is below the mean.
| Cluster | Feature | z | In cluster | Overall |
|---|---|---|---|---|
| 0 (32 stores) | Basic and NOS, regular fit | +0.83 | 49.7% | 38.7% |
| Collection, regular fit | +0.77 | 29.1% | 24.4% | |
| Basic and NOS, bags | +0.73 | 1.1% | 0.8% | |
| 1 (7 stores) | Basic and NOS, oversized fit | +2.45 | 44.2% | 20.3% |
| Collection, oversized fit | +2.25 | 44.7% | 26.1% | |
| Basic and NOS, dresses | +2.09 | 6.2% | 2.6% | |
| 2 (7 stores) | Basic and NOS, sweatshirts | +2.33 | 23.7% | 12.9% |
| Basic and NOS, jeans | −1.77 | 7.9% | 14.9% | |
| Basic and NOS, entry price segment | +1.66 | 37.6% | 25.3% | |
| 3 (14 stores) | Basic and NOS, slim fit | +1.41 | 19.3% | 10.8% |
| Collection, slim fit | +1.37 | 35.6% | 26.9% | |
| Collection, shirts | +1.33 | 16.0% | 11.5% | |
| 4 (7 stores) | Basic and NOS, mid price segment | +2.75 | 76.5% | 47.9% |
| Basic and NOS, shorts | +2.69 | 14.9% | 4.5% | |
| Basic and NOS, relaxed fit | +2.55 | 55.0% | 30.2% |
In the table “Overall” is that share’s mean over the 67 stores.
The largest cluster is the one closest to the chain’s average: even its most distinctive feature has a z of only +0.83. What makes it stand out is regular fit, in both line groups. The small clusters are much sharper. Cluster 1 sells oversized, in both line groups. Cluster 2 is high on sweatshirts and low on jeans. Cluster 3 sells slim fit and shirts. In cluster 4’s stores an average of 76.5% of Basic and NOS sales are in the mid price segment; the shorts share averages 14.9%, against an average of 4.5% across all stores.
According to the answer key, cluster 0 is the Anatolian family profile, cluster 1 metro young, cluster 2 metro premium, cluster 3 warm coast and cluster 4 cold climate. These names come from the data’s storyline; the clustering does not know them. In a real chain, naming a cluster starts with this table: Pelin will not have the storyline’s names, only what the clusters sell.
The trace of the assortment
In the second article we gave a warning: a store sells only what it has. The sales mix reflects partly the customer and partly the assortment sent to the store. At Lumoda this matters especially, because in the storyline the assortment each store carries was chosen by the store’s profile and, along with it, by revenue, the share of women customers and square metres, and it is fixed in this series.
To separate the trace of the assortment we built an adjusted mix. The
in_stock branch of _mix builds the share not from raw units but from a
rate: a value’s gross units are divided by the number of option-days on which
the products with that value were in stock on the rail.
# store_clustering/features.py
def _rate(units: pd.DataFrame, days: pd.DataFrame, kind: str | None = None) -> tuple[pd.DataFrame, int]:
"""Rate = units ÷ days; NaN where days are 0 (or missing) (unobserved). Second value: the sales
of the cells with 0 days (gross units that do not enter the rate, dropped)."""
columns = _ordered(days.columns.union(units.columns), kind)
a = units.reindex(columns=columns, fill_value=0)
g = days.reindex(index=a.index, columns=columns, fill_value=0)
dropped = int(round(a.where(~(g > 0), 0).to_numpy().sum()))
return (a / g.where(g > 0)).dropna(axis=1, how="all"), dropped
In a category a store never carried, the rate is undefined. Counting it as zero would bring the assortment back in. These cells are filled neutrally: the column’s median rate across the other stores, scaled by the store’s own overall level. In a category it does not carry, the store counts as an average store at its own level. The adjusted mix has 7 cells in this position.
The result came out the opposite of what we expected: in this data the trace of the assortment is small. On the adjusted mix the same k rule picks five clusters with Ward, and the agreement with the answer key is 1.000 again. k-means picks four clusters: 0.948. Forced to five clusters, k-means stays at 0.682; but that is a solution the method itself gets stuck in, because on the same features Ward is perfect at five clusters. S2 and its adjusted twin S4 also give exactly the same split at five clusters: the two splits’ agreement is 1.000, and both agree with the answer key at 0.137.
Why is it small? I have no firm answer. One possible explanation: because at Lumoda the assortment was chosen largely by the store’s profile, the trace of the assortment and the trace of the customer point the same way. If in your chain the assortment was built by something that has nothing to do with the customer, say the store type or the distance from the warehouse, the two may come apart. Then the raw mix clusters the assortment more than the customer.
Customer data
There is no S3 among the family names. That family was customer data: the age and gender of Lumoda’s identified customers, store by store. In real life this may be the most direct way to understand a store’s customer. In this series we did not bring customer data into the case at all. In a check before we built the case, we saw that in this synthetic data the customer’s age is derived almost directly from the store’s hidden profile; in other words, customer data carries the answer key almost as it is. Making it a feature would hand the key back to the clustering, and the agreement we measured would be the success not of the method but of the way the data was built. In a real chain customer data is a strong signal, but it has its own problems: the identified customers’ share of all sales, and which store a customer counts as belonging to.
What’s hard in your data
The first is the attribute data. Everything these clusters see comes from three fields in the product record: subcategory, price segment, fit. At Lumoda these fields are complete on every product. In a real ERP the same fit may have been entered under three different names, and the price segment may never have been defined. The clusters are only as good as that record; the first job is probably fixing the record.
The second is having no answer key to measure against. In this article we could measure the clusters against a key. You will have the silhouette, the stability and the quality of the decisions made by cluster; and we saw that the first two do not agree. Write the rule down before the result and stick to the rule you wrote. Even we stumbled on that once.
The third is the assortment. At Lumoda the trace of the assortment turned out small; there is no guarantee it will be small in your chain. And sales alone are not enough to measure it: you need a record, for every store and every product, of the days the rail was stocked.
In the next article we move on to using the clusters: how well do they hold from year to year, which cluster does a new store with no sales go into, and how is a plan built by cluster?