Technical

Putting the clusters to use

Do the clusters hold from year to year, where does a new store with no sales go, and how does a share by cluster enter the initial allocation? One year of sales unsettles the clusters, a new store is hard to place in the metros, and the cluster share only matches the store's own history.

Store Grouping · 5 / 6

For four articles we built clusters. We measured Lumoda’s rules, found five clustersA group of stores with similar sales mixes. The plan and the initial allocation treat the stores in a cluster as one unit. from the sales mix, and saw that all five match the answer key exactly. But until it is used, a cluster is only a table. In this article we move on to using it, and ask three questions.

How well do the clusters hold from year to year? Which cluster does a new store with no sales go into? And how does a share built by cluster enter the initial allocation?

The code again comes from the working code under cases/store-clustering/, and the numbers from the case’s report. The numbers in the last section come from the Initial Allocation case’s report.

How well the clusters hold

In the third article we saw that the sales volume grade hardly changes from year to year: build the groups separately with the data of two different years, and the two groupings’ agreement came out at 0.834. We applied the same measure to the sales-mix clusters. The same method, the same five clusters; but each time with only one year’s sales, 52 weeks. The two windows do not touch. Ankara 3 and Antalya 1 are left out again because in one of the years they did not see enough sales; the comparison is on 65 stores.

The agreement between the two years’ clusters is 0.642.

“That’s shakier than my volume grade,” says Pelin. “Am I going to get different clusters every season?”

“Let’s first see what’s moving,” says Pars.

We can do this only at Lumoda, because we have the answer key. We measured each year’s clusters against the key. The clusters built with the older year’s sales agree with the key at 0.950; those built with the last year up to the decision day, at 0.688. The actual clusters, though, see both years’ sales together, and their agreement with the key is 1.000.

In the data’s storyline each store’s customer profile was given once; it does not change between the two years. So what is moving is not the customer. It looks as though a single year’s sales do not show what a store sells as clearly as two years’ do; the two-year window seats the clusters on the key. The difference between the two years, 0.950 against 0.688, we did not explain separately.

In the third article we said we would see this from the other side. The sales volume grade holds from year to year at 0.834, and its agreement with the answer key is 0.035. The sales-mix clusters hold at 0.642, and they match the key exactly. Stability is not accuracy; and accuracy does not always look stable.

Which stores move

The year-to-year measure looks at the whole split. What Pelin really wants to know is the single stores: which one stands at the edge of its cluster?

We measured this with a bootstrap. From the 67 stores we draw 67 stores again, in such a way that the same store can come up more than once, and cluster the drawn table with the same method. The draw’s clusters are matched one to one to the actual clusters so that they share as many stores as possible. A store whose matched cluster differs from its actual cluster counts as changed in that draw.

# store_clustering/metrics.py (stability, bootstrap; the lines naming copies left out)
rng = np.random.default_rng(seed)
for _ in range(samples):
    draw = np.sort(rng.integers(0, len(ids), size=len(ids)))
    B = pd.DataFrame(Z.to_numpy()[draw], index=pd.Index(names_, name="store_id"), columns=Z.columns)
    e = cluster_fn(B)
    distinct = np.unique(draw)
    de = e.loc[[ids[j] for j in distinct]].to_numpy()
    changed[distinct] += _matched_changed(de, full[distinct])
    seen[distinct] += 1
    aris.append(adjusted_rand_score(full[distinct], de))

The feature table is built once; the draw changes only which rows go into the clustering. Over 50 draws the splits’ average agreement with the actual split is 0.803. A store changes cluster in an average of 12.0% of the draws it is in. 22 of the 67 stores (32.8%) do not change in any draw.

The most volatile store is Denizli 2: in 52% of the draws it is in, it lands in another cluster. Gaziantep 2 and Samsun 2 follow it, both at 41%.

“All three are mine,” says Veli.

“A store whose cluster changes often is a store standing on the clusters’ border,” says Pars. “When you write such a store’s plan from its cluster, you need to know its cluster may change every season; otherwise you start looking for the change in its plan in its customers.”

The new store

In the second article we mentioned the two new stores. Izmir 2 opens on the first day of the season; it has no sales at all. Kocaeli 1 has 19 weeks with sales and has not completed half a year. You cannot cluster a store with no sales mix by its mix. All you have is what is known before the store opens:

# store_clustering/new_store.py
STATICS = ("region", "metro", "climate", "type", "log_area", "latitude")

Region, whether it is in a metro, the city’s climate class, mall or high street, the logarithm of the square metres, and latitude. Turnover, sales and capacity do not come in. Each is a block; they are standardised over the clustered stores and the blocks get equal weight, on the principle of the fourth article.

The new store is put in the majority cluster of the five clustered stores nearest to it in this space:

# store_clustering/new_store.py (assign; 5 nearest neighbours)
d = ((B[:, None, :] - A[None, :, :]) ** 2).sum(axis=2)
rank = ordering.rank("store_id", ref.index)
out = []
for r in d:
    nearest = np.lexsort((rank, np.round(r, 12)))[:neighbours]
    vote = pd.Series(e[nearest]).value_counts()
    top = set(vote.index[vote == vote.max()])
    out.append(next(e[j] for j in nearest if e[j] in top))

d is the new store’s distance to each clustered store. The neighbours are sorted by distance, and five of them vote. If the votes are tied, the cluster of the nearest neighbour among the tied clusters is chosen. For comparison we also ran a second method: the nearest cluster centroid, that is, the cluster whose mean statics are closest.

How right, without seeing a sale

Two real new stores are not enough to measure anything. So we treated each of the 67 stores, once, as if it were new. The clusters are rebuilt without that store, the store is assigned to those clusters by its statics alone, and the cluster it is assigned to is compared with the cluster its sales put it in. We call this leave-one-out.

# store_clustering/new_store.py (leave_one_out)
for m in ids:
    others = [i for i in ids if i != m]
    e = cluster_fn(Z.loc[others]).copy()
    e.index = e.index.astype(str)
    mapping = _to_full_label(e, full)
    a = assign(st.loc[[m]], st.loc[others], e, method=method, neighbours=neighbours).iloc[0]

When one store is taken out the clusters hardly change: in 65 of the 67 leave-one-outs (97.0%) the split of the remaining stores is the same as the actual split.

This measure has one nice side: it needs no answer key. The comparison is made with the store’s own sales cluster; it can be set up in a real chain too. At Lumoda, because the clusters match the answer key exactly, the numbers below are also hits on the right customer profile.

MethodAllMetroNon-metro
5 nearest neighbours55/67 (82.1%)10/21 (47.6%)45/46 (97.8%)
Nearest cluster centroid47/67 (70.1%)6/21 (28.6%)41/46 (89.1%)
Largest cluster for everyone32/67 (47.8%)7/21 (33.3%)25/46 (54.3%)

The last row is a baseline: putting every new store, without looking at anything, into the most crowded cluster, the Anatolian family cluster.

Outside the metros the job is easy. The five neighbours put 45 of the 46 stores in the right cluster. In the third article we saw that the location rule also hits 46/46 outside the metros; there the city tells you a lot about the customer.

In the metros, though, the five neighbours find 10 of the 21 stores. The baseline is 7. The 21 metro stores hold three profiles, and the static information is hardly enough to tell them apart. The nearest cluster centroid falls even below the baseline in the metros. A possible reason is the shape of the clusters; we did not measure that separately. The largest cluster carries both Anatolia’s non-metro stores and part of Istanbul. Its centroid very likely falls between these two groups and fully resembles neither. The neighbour method looks only at what is close by. Across all stores the gap between the two methods is 11.9 points.

I need to say something plainly about this choice. We wrote down the number of neighbours, five, before seeing the results. But which of the two methods would be the default we decided after seeing them. The measure was not the answer key but the store’s own sales cluster; even so, the choice was made by looking at the result. That is why I print both methods.

Two real stores

Kocaeli 1 is in Marmara, outside the metros, a 916-square-metre mall store. The five neighbours put it in the largest cluster, the Anatolian family cluster. According to the answer key its customer is Anatolian family too: a hit.

Izmir 2 is a metro store: in Izmir, a 770-square-metre mall. The five neighbours put it in the metro young cluster, and so does the nearest centroid. According to the answer key its customer is Anatolian family: a miss.

Ali and Veli do not know this; only I see the answer key. But Izmir 2 is in the position of Istanbul 13 from the first article: an Anatolian family store in a metro. We got to know Istanbul 13 from its sales. Izmir 2 has no sales; its place on the map makes it look like the metro’s young customer.

“So what do I write Izmir 2’s plan by?” says Pelin.

“By its neighbours’ cluster,” says Pars. “You have no other information. But treat this cluster as provisional. Once the store has half a year of sales, cluster it again by its mix. In the metros this first guess is right only half the time.”

Share by cluster

Now let us tie the cluster to a decision: the initial allocation. In the Initial Allocation series a new product’s packs were split across the stores by a share. One of the arms looked at the history of lookalike productsA way of forecasting demand for a new product with no history from the sales of past products whose attributes resemble it.: the faster similar products sold in a store in the past, the bigger the new product’s share in that store. The rate was relative; a store’s demand for a product was divided by the average demand of the stores that received that product. Because calibration brought this arm down to a crude level, in the end we called it the store’s past share.

In the second article we put forward an idea. A store on its own may not have enough history; the seven stores in the same cluster will. The cluster share is the sum behind that idea: the same index, at cluster level instead of store level.

# store_clustering/cluster_share.py (learn; check lines left out)
t = _observations(table, season_kind)
options, stores, g = _relative(t)
clusters = tuple(ordering.label_sort(set(lb.values())))
G = np.full((len(options), len(clusters)), np.nan)
member = np.array([lb.get(m) for m in stores], dtype=object)
for j, c in enumerate(clusters):
    col = member == c
    if col.any() and len(options):
        G[:, j] = _mean(g[:, col], axis=1)

g is each past product’s relative rate in each store; exactly the definition in Initial Allocation. G is the cluster’s relative rate: the mean of the relative rates of the cluster’s stores that received that product. For a new product, the cluster’s index is the mean of G over the past products at the chosen similarity level.

The cluster’s index is the same for all the cluster’s stores. What sets a store apart from its cluster is its scale:

# store_clustering/cluster_share.py (_scale)
for c in ordering.label_sort(set(lb.values())):
    members = [m for m, k in lb.items() if k == c]
    observed = [m for m in members if m in r]
    mean = float(np.mean([r[m] for m in observed])) if observed else 0.0
    ratio = {m: r[m] / mean for m in observed} if mean > 0 else {m: 1.0 for m in observed}
    median = float(np.median(list(ratio.values()))) if ratio else 1.0
    for m in members:
        out[m] = float(ratio.get(m, median))

r(m) is the store’s mean relative rate over all past products, that is, how big a store it is. The scale is this divided by the cluster’s mean. The share is the cluster’s index times the store’s scale:

# store_clustering/cluster_share.py (ClusterIndex.shares; inside the loop)
v = float(index[position[self.label[m]]] * float(scale[m]))

In the second article we said that scale is not lost but comes in at the second step of the plan. Here is that step: the mix comes from the cluster, the size from the store.

The new store takes its share from the cluster

Look at the last line of the scale code: ratio.get(m, median). A store with no sales at all in the past spring-summer season takes the scale of its cluster’s middle store. Izmir 2 and Kocaeli 1 are in this position. Both take their mix from their cluster, and their size from the middle of their cluster.

The store’s past share arm in Initial Allocation counted such a store as an average store: the same relative rate for every product. That is the first thing the cluster gives a new store: instead of the chain’s average, the mix of the stores that resemble it. This group was chosen right for Kocaeli 1 and wrong for Izmir 2. We did not measure these two stores’ results at the end of the season separately.

Calibration

The similarity level is chosen from the same hierarchy as in Initial Allocation: starting at subcategory × price segment × fit, it steps down to category and finally to all the store’s past Collection. For a new product, the first level with enough similar products is used. How many “enough” is, as in Initial Allocation, we measured in the previous spring-summer season, without looking at the game season. We also rebuilt the clusters on that season’s decision day, with the data up to that day.

The hypothesis was this: pooling in a cluster reduces the noise, so a fine similarity that drowns in noise at store level becomes useful at cluster level. The share error with the sales-mix clusters, starting from the finest level:

Minimum lookalikesShare error
30.259
50.250
100.243
200.239
400.237
800.237

Almost the same as the table in Initial Allocation’s third article. With few lookalikes the fine level is noisy at cluster level too; the error falls as the threshold grows and levels off at 40. Starting straight from category, or from the overall level alone, gives the same error: 0.237. In the same season the store’s past share has an error of 0.235, and Lumoda’s store plan 0.236.

Calibration chose a threshold of at least 40 lookalikes. In the calibration season this threshold did not step down to subcategory for any product. In the game season there is one more past season to learn from, and the same threshold uses the subcategory level for 68 of the 210 new products, category for 109, and all the stores’ past Collection for 33. The two levels finer than subcategory are not used for any product.

So the hypothesis did not hold in this data. Calibration chose a high sample threshold that, in the past season, came down to the crude level; the fine level is used only when there are many examples. As in Initial Allocation, calibration again chose a high threshold; the difference is that at cluster level this threshold steps down to subcategory for some products in the game season.

The bridge to Initial Allocation

We ran the cluster share in Initial Allocation’s game season with five groupings: sales volume grade, region, the grid of the two (Lumoda’s own groups), the sales-mix clusters and the answer key itself. The last is only for measurement: what would happen if the grouping were perfect? All five arms send the same stock as Lumoda; only the stock is split across the stores by different shares.

The Lumoda arm in Initial Allocation, on the other hand, is not a grouping: it is Lumoda’s published plan, store by store. Below I call it Lumoda’s store plan.

Initial Allocation’s main measure was availability: on what percentage of the days with demand for a size in a physical store was that size on the rail. With the sales-mix clusters it is 69.53%. With Lumoda’s groups 69.35%, with Lumoda’s store plan 68.98%. The store’s past share gives 69.51%, and the LightGBM model that forecasts store by store 70.41%.

On the published stream, in availability the share by sales-mix cluster beats Lumoda’s groups by 0.2 points and the store plan by 0.6 points; it is ahead of both on all five of the five customer streams too. It catches up with the store’s own history, but does not beat it. The model is ahead. The other measures, the detail of the streams, and what the cluster does and does not change in this result are the subject of the last article.

What’s hard in your data

The first is when to rebuild the clusters. At Lumoda a single year of sales unsettles the clusters, and two years’ seat them. If in your chain the clusters change between two years, either the customer has changed or one year of sales is not enough. At Lumoda we could tell the two apart with the answer key. You will not have a key; and a long window notices a store whose customer really is changing only late. Knowing which stores end up at the edge every time is the first step to telling the two apart.

The second is the new store. For a store with no sales, all you have is its map. At Lumoda the map knows a lot outside the metros and very little inside them. How much does your static information know: the store type, the square metres, the city and perhaps the neighbourhood’s population data? You can measure that with leave-one-out; no answer key is needed. You also need a routine that reopens the new store’s cluster once its first sales arrive; otherwise the provisional cluster becomes permanent.

The third is the input to the cluster share. The relative rate, as in Initial Allocation, comes from demand with the censoring corrected: without estimating the demand lost while the rail was empty, you cannot measure a store’s rate. That is a problem to solve before the clustering; the Lost Sales series covers it.

In the last article we add up the account: what tells us a clustering is good, and what exactly did the share by cluster deliver in Initial Allocation?

By Sabri Suyunu