Technical

Grouping by rule

Region, sales volume grade, the grid of the two, and location: the code of four rules and how well each fits the answer key. The volume grade hardly changes from year to year, but it knows next to nothing about the customer.

Store Grouping · 3 / 6

For two articles we talked about store grouping as an idea. Now we write the code. In this article we build the three rules Lumoda has to hand: region, sales volume gradeRanking stores by turnover over the last twelve months and splitting them into three, A, B and C. It says how much a store sells, not what it sells. and the grid of the two. There is also a fourth rule that we added: location. We measure all four on the same stores.

The Python below is taken from the working code under cases/store-clustering/; docstrings have been shortened. Every number in the article comes from the case’s report.

Which stores

The rules work on the decision day, with only the data published up to that day. There are 69 candidate stores: stores that are open on the decision day or will open by the launch, that have no closure decision, and that are not outlet or online. 67 of them have at least 26 weeks with sales; these are the stores that get grouped. The other two are new: Izmir 2 has no sales at all, and Kocaeli 1 has 19 weeks with sales.

Of the 67 grouped stores, 21 are in the metros: 12 in Istanbul, 5 in Ankara and 4 in Izmir. The other 46 are outside the metros. This split will matter halfway through the article.

All four rules are written the same way: they give a group label to every store in scope, the new ones included. The rules module is a decision module; it cannot read the answer key. A test checks this: the module cannot import anything that reaches the hidden tables.

Region

This is the shortest piece of the code:

# store_clustering/rules.py
def region(scope: pd.DataFrame) -> pd.Series:
    """K1: the published region."""
    return _by_id(scope, scope["region"].astype(str)).rename("k1")

Region is written in the published store table; the rule takes it as it is. The 67 stores fall into seven regions: Marmara 18, Central Anatolia 14, the Mediterranean 11, the Aegean 9, Eastern Anatolia 7, Southeastern Anatolia and the Black Sea 4 each.

Region has two things going for it. It needs no calculation, and a new store knows its region on the day it opens. It also has a problem: it puts Istanbul’s 12 stores in the same group as the rest of Marmara’s stores. That is what Ali objected to in the first article.

Sales volume grade

The sales volume grade is the second leg of Pelin’s grid. Its definition is a single sentence: rank by net turnover over the last twelve months before the decision day, call the top 20% A, the next 30% B and the rest C. In the code there are two steps. The first is turnover:

# store_clustering/rules.py (net_revenue; docstring left out)
decision = pd.Timestamp(decision_day).normalize()
start = decision - pd.DateOffset(years=1)
window_days = (decision - start).days
s = sales.loc[(sales["date"] >= start) & (sales["date"] < decision)].drop_duplicates()
ids_ = s["store_id"].astype(str)
revenue = s["revenue"].groupby(ids_.to_numpy()).sum()
first = s["date"].dt.normalize().groupby(ids_.to_numpy()).min()
ids = scope["store_id"].astype(str)
c = ids.map(revenue).fillna(0.0).astype("float64")
g = (decision - ids.map(first)).dt.days.astype("float64")          # no sales: NaN
short = (scope["history_weeks"].to_numpy() < constants.FULL_YEAR_WEEKS) & g.notna().to_numpy()
factor = (window_days / g.clip(lower=1.0, upper=window_days)).where(short, 1.0)
return _by_id(scope, (c * factor).to_numpy()).astype("float64").rename("net_revenue")

Net turnover is the sum of the revenue column. A return row’s amount is negative; so this is turnover after markdowns, with returns taken off sales. drop_duplicates throws away rows that are exact copies in the published data. Lumoda’s sales table has dirty records, like a real chain’s.

The second half of the code is for stores with a short history. If a store has at least 26 weeks with sales but has not completed twelve months, its turnover is annualised: its daily turnover rate since its first day of sales is multiplied by the twelve-month window. Without this a store would drop to C just because of its missing months. At Lumoda only one store is in this position, Antalya 1: it has 46 weeks with sales, its annualised turnover is TRY 55.4 million and its grade is B.

This has a price. A short history sees only part of the year, and annualising does not correct for the season.

The second step is the ranking:

# store_clustering/rules.py
def volume_grade(sales: pd.DataFrame, scope: pd.DataFrame, decision_day) -> pd.Series:
    """K2: A / B / C (module note). A new store does not enter the ranking and gets C."""
    revenue = net_revenue(sales, scope, decision_day)
    clusterable = pd.Series(scope["clusterable"].to_numpy(dtype=bool), index=revenue.index)
    ranked = ordering.sort_frame(
        pd.DataFrame({"revenue": revenue[clusterable], "store": revenue.index[clusterable]}),
        ["revenue", ("store", "store_id")], ascending=[False, True])
    n = len(ranked)
    n_a = _round_half_up(constants.GRADE_A * n)
    n_b = _round_half_up(constants.GRADE_B * n)
    grade = pd.Series("C", index=revenue.index, dtype=object, name="k2")
    grade.loc[ranked["store"].iloc[:n_a]] = "A"
    grade.loc[ranked["store"].iloc[n_a:n_a + n_b]] = "B"
    return grade

Only the 67 grouped stores enter the ranking. The result is 13 A, 20 B, 34 C. A’s lower bound is TRY 116.4 million, B’s TRY 53.4 million. The smallest store’s turnover is TRY 12.5 million, the largest’s TRY 169.7 million. The middle store’s turnover is TRY 52.5 million; below the B threshold, so C. Because more than half the stores are grade C, the middle store stays in C too.

A new store does not enter the ranking; it gets C. In the second article we mentioned Kocaeli 1: its 19 weeks of sales, scaled up to a year, come to TRY 125.9 million, above the A threshold. The rule still gives it C. That is a choice: a new store’s first weeks do not stand for a year, and in planning a new store is put in the most cautious grade.

The grid

The grid Pelin proposed for this season is region crossed with sales volume grade. On the 67 grouped stores the grid looks like this:

RegionStoresABC
Marmara180612
Central Anatolia14248
Mediterranean11344
Aegean9225
Eastern Anatolia7241
Southeastern Anatolia4202
Black Sea4202

Marmara has no grade A store at all. Of Istanbul’s 12 stores, 4 are B and 8 are C.

Some cells are very small: in Eastern Anatolia there is a single store in grade C. A one-store cell means a separate plan for that store. The rule merges a cell of fewer than 3 stores with the neighbouring grade in the same region:

# store_clustering/rules.py
def _merge(counts: dict[str, int]) -> dict[str, str]:
    """From a region's grade → store count table, grade → the group's grades (`AB`, `ABC`)."""
    groups = [[s, n] for s, n in counts.items() if n > 0]       # the filled cells in A, B, C order
    while len(groups) > 1 and min(n for _, n in groups) < constants.K3_MIN:
        i = min(range(len(groups)), key=lambda j: (groups[j][1], j))        # the smallest, on a tie the A side
        if i == 0:
            j = 1
        elif i == len(groups) - 1:
            j = i - 1
        else:                                                   # the middle one: the neighbour with fewer stores, on a tie A
            j = i - 1 if groups[i - 1][1] <= groups[i + 1][1] else i + 1
        a, b = sorted((i, j))
        groups[a] = [groups[a][0] + groups[b][0], groups[a][1] + groups[b][1]]
        del groups[b]
    return {c: name for name, _ in groups for c in name}

A region’s filled cells are lined up in A, B, C order. At each step the loop takes the smallest cell. A cell at the end has only one neighbour and is added to it. If the middle cell is small, it merges with the smaller of its two neighbours. If B is empty, A and C count as neighbours. Regions never merge with each other.

Eastern Anatolia has 2 A, 4 B and 1 C. First the single C store is added to B; then the 2 A stores join the resulting group. The result is a single 7-store Eastern Anatolia × ABC group. Southeastern Anatolia has no B: the 2 A and the 2 C merge into Southeastern Anatolia × AC. In the Aegean, A and B have 2 stores each; on a tie the A side is chosen and Aegean × AB is formed.

The result is 12 groups:

GroupStores
Marmara × C12
Central Anatolia × C8
Eastern Anatolia × ABC7
Marmara × B6
Central Anatolia × AB6
Aegean × C5
Mediterranean × B4
Mediterranean × C4
Aegean × AB4
Southeastern Anatolia × AC4
Black Sea × AC4
Mediterranean × A3

Istanbul 13 and Istanbul 10 from the first article are in the largest cell, Marmara × C.

Location

We added one rule of our own to Lumoda’s. The idea is simple: can we roughly guess a store’s customer from where it is? A big city is one thing, the coast another, a cold city another again.

# store_clustering/rules.py
def location(scope: pd.DataFrame) -> pd.Series:
    """K4: `metro` or the city's climate class; holiday resorts `warm_coast`."""
    unknown = ordering.sort_values(set(scope["city"].astype(str)) - set(source.CITY_CLIMATE), "city")
    if unknown:
        raise ValueError(f"a city not in the city → climate table: {unknown}")

    def grade(city: str) -> str:
        if city in source.METRO:
            return "metro"
        return "warm_coast" if city in source.RESORTS else source.CITY_CLIMATE[city]

    return _by_id(scope, [grade(str(c)) for c in scope["city"]]).rename("k4")

The rule asks three questions. Is the store in a metro? The metros are the three big cities: Istanbul, Ankara, Izmir. If not, is it in a holiday resort? Then it is warm coast. If neither, it gets the city’s climate class. The classes come from a table written out in the open in the case:

# store_clustering/source.py (part of CITY_CLIMATE)
METRO = {"Istanbul", "Ankara", "Izmir"}

CITY_CLIMATE: dict[str, str] = {
    # cold: high altitude, long and hard winter
    "Erzurum": "cold",
    "Sivas": "cold",
    # warm coast: Mediterranean and Aegean coast, a hot and long summer, a mild winter
    "Antalya": "warm_coast",
    "Mersin": "warm_coast",
    # temperate: Marmara, the Black Sea coast, inner Aegean
    "Bursa": "temperate",
    "Trabzon": "temperate",
    # continental: Central Anatolia, the south-eastern and eastern interior
    "Eskisehir": "continental",
    "Gaziantep": "continental",
}

RESORTS = {"Antalya", "Alanya", "Kemer", "Fethiye", "Bodrum"}

If a city that is not in the table turns up, the code raises an error; the store is not quietly put in some group. The 67 stores fall into five groups: metro 21, warm coast 14, continental 13, temperate 12, cold 7.

All four rules also give the two new stores a group without seeing any sales. Izmir 2 is Aegean, C, Aegean × C and metro. Kocaeli 1 is Marmara, C, Marmara × C and temperate.

I need to say something about this table up front. I wrote the climate classes by hand, from general geography. The simulator that generates Lumoda’s data has hidden climate labels of its own, and the two tables agree in 24 of 25 cities; the only difference is Izmir. That is no coincidence: the synthetic chain was built on top of real geography. So part of the location rule’s success, which you will see below, comes from the way the data was built. In a real chain the link between a city’s climate and what its customers buy may not be this clean.

Four rules, one answer key

To measure the rules we use the answer key from the first two articles. Lumoda is a synthetic chain and I generated its data; I gave every store a customer profile that does not appear in the published data. The 67 grouped stores hold five profiles: Anatolian family 32, warm coast 14, metro young 7, metro premium 7, cold climate 7. The rules do not see the profile; I use it only to measure afterwards. In real life there is no such key.

We introduced ARI in the second article: a grouping’s agreement with the answer key; 1 is perfect, 0 the level of a random grouping. The table has two more columns.

“Isn’t one number enough?” says Pelin.

“It’s good not to trust a single number,” says Pars. “AMI asks the same question another way: how much information do the two groupings carry about each other? It runs between 1 and 0 too.”

Purity is the easiest: in each group count the stores of the most common profile, add them up and divide by all the stores. But do not read purity on its own; it goes up by itself as the number of groups grows.

RuleGroupsARIAMIPurity
Region70.2090.33470.1%
Sales volume grade30.0350.01247.8%
Region × sales volume grade120.1040.25671.6%
Location50.4320.67979.1%

The sales volume grade is at the random level. Look inside the grades and you see why:

Volume gradeAnatolian familyMetro youngMetro premiumWarm coastCold climate
A53032
B81254
C193561

Grade A’s 13 stores hold four profiles, and B and C hold all five. In every grade the most common profile is Anatolian family, because almost half the chain has that profile. The volume grade’s purity is 47.8%; you would get that by putting all the stores in a single group as well, because 32 of the 67 stores are Anatolian family.

Region knows something, but not much. All 11 of the Mediterranean’s stores are warm coast. Marmara’s 18 stores, though, hold three profiles: 13 Anatolian family, 3 metro premium, 2 metro young. The Aegean’s 9 stores hold four profiles.

The grid is worse than region. It has 12 groups, but its ARI is 0.104; far below region’s 0.209. Because the volume grade knows nothing about the profile, it splits region’s groups along an axis that has nothing to do with the customer. Its purity of 71.6% looks slightly higher than region’s, but that is misleading: purity goes up by itself as the number of groups grows. Put every store in a group of its own and purity would be 100.0%. ARI penalises that.

Location is the best by a clear margin: 0.432.

What location knows

Let us look at location’s groups profile by profile:

LocationAnatolian familyMetro youngMetro premiumWarm coastCold climate
Continental130000
Temperate120000
Warm coast000140
Cold00007
Metro77700

Outside the metros the table is almost perfect. All 13 stores in the continental group are Anatolian family, and so are the temperate group’s 12. The warm coast’s 14 stores are warm coast, the cold group’s 7 are cold climate. The only flaw is that the Anatolian family profile is split in two, continental and temperate.

In the metros, though, the rule knows nothing. There is a single 21-store group, holding three profiles of 7 stores each.

Take the same measure separately inside and outside the metros and this shows up more clearly. The last row is the clusters we will build from the sales mix in the next article; I put it here for comparison:

GroupingGroups in metrosARI in metrosGroups outsideARI outside
Region30.13470.270
Sales volume grade30.04930.087
Region × sales volume grade60.068120.124
Location10.00040.664
Sales-mix clusters31.00031.000

The metros have 21 stores and three profiles; outside the metros there are 46 stores and again three profiles. Location’s ARI outside the metros is 0.664; inside them it is zero, because it sets up a single group. The sales-mix clusters match the answer key exactly on both sides. In other words, the mix finds what location knows, and what it does not.

You can see this without the answer key too. Compared with the sales-mix clusters, location’s 21-store metro group scatters across three different clusters, 7 stores each.

“So the sales mix splits the metro stores into three clusters,” says Pelin. “And the map sees them all as one group.”

“To the map, Istanbul, Ankara and Izmir are the same place,” says Pars. “Outside the metros the map tells you a lot; inside them, nothing.”

Without seeing a sale

The rules have one advantage over the sales mix: they work without seeing a sale. They give a group even to Izmir 2, which has no sales at all. But is that group right?

To measure this we treated each grouped store, once, as if it were new. The store takes the group the rule puts it in; if the most common profile among the other stores in that group is the store’s own profile, it is a hit.

RuleAllMetroNon-metro
Region44/67 (65.7%)7/21 (33.3%)37/46 (80.4%)
Location46/67 (68.7%)0/21 (0.0%)46/46 (100.0%)

Outside the metros location puts every store on the right profile: 46/46. In the metros, not one. Because the group holds the three profiles in equal numbers, once the store itself is taken out the majority always falls to the other two profiles.

Izmir 2 is in exactly this position: in a metro and with no sales at all. We come back to the new-store question separately in the fifth article.

Stable but wrong

In real life there is no answer key. One of the measures you do have is how well a grouping holds from season to season. To measure it we built the groups separately with the data of two different years and measured the two groupings’ agreement with the same ARI. Here 1 means the same groups in both years. Two stores, Ankara 3 and Antalya 1, are out of this comparison because in one of the years they did not have enough history; 65 stores are left.

Region and location do not change, by definition: both are 1. The sales volume grade’s agreement is 0.834. Only 4 of the 65 stores change grade (6.2%). The grid’s agreement is 0.910.

The volume grade hardly changes from year to year, but it is also the rule that fits the answer key worst. Turnover changes slowly; a big store is still big the next year. But because size says nothing about the customer, this is not the stability of something right.

“Stability isn’t accuracy,” says Pars. “A rule that makes the same mistake every season is stable too.”

We will see this from the other side in the fifth article. The sales-mix clusters fit the answer key exactly, but they do not hold from year to year as well as the volume grade does.

Adding scale to the mix

The sales volume grade is a scale rule: it looks at how much a store sells. In the second article we mentioned one of the trade’s mistakes: putting scale on the same footing as the sales mix. We measured it with an ablation.

To the fourth article’s 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. features we added three scale columns: the logarithms of daily turnover, square metres and capacity. Then we split the stores into five clusters with the same method. When the features are standardised each block gets equal weight; so these three columns carry as much weight as the mix’s 45 columns together.

Features (5 clusters)ARI with the answer keyARI with the volume grade
Sales mix1.0000.035
Sales mix + scale0.1060.322

Once scale comes in, the clusters break away from the answer key and move towards the volume grade. Choose the number of clusters with the fourth article’s rule too, without looking at the answer key, and things get more dangerous. On the features with scale the rule picks three clusters, with a silhouette of 0.351. The clusters built from the sales mix have a silhouette of 0.308. So on paper the split with scale is cleaner. But its agreement with the volume grade is 0.582, and with the answer key 0.138.

Scale easily sorts stores into big and small; the sharper the split, the higher the silhouette. We did not take scale among the fourth article’s candidate features in the first place. This ablation shows what would have happened if we had: a rule deciding by the silhouette would have picked the split with scale in it. The place for scale is the second step of the plan: when the cluster’s plan is split across its stores.

What’s hard in your data

The first is the definition of turnover. At Lumoda there is a single revenue field; returns are in the same table as a negative amount, and markdowns are inside the amount. In a real chain turnover is often kept in several systems, under several definitions. Is a return booked to the store that made the sale, or to the store that took the return? If a promotion month inflated a store’s turnover, does that store stay A for a whole year? Do you annualise a store with a short history, or does it quietly drop to C? The sales volume grade looks like a simple rule, but the answers to these questions decide the grade of the stores on either side of the threshold.

The second is where region comes from. Region is often not geography but an organisation chart: whichever stores a regional manager looks after, that is the group. When the manager changes or the regions are redrawn, the plan’s groups change too. That is a change with nothing to do with the customer.

The third is how much location knows. At Lumoda location almost knows the profile outside the metros, but part of that is the way the data was built. In your chain, measure the link between city and customer before you assume it. In the metros it tells you nothing anyway.

In the next article we leave the rules and look at the sales themselves: turning a store’s sales mix into 45 numbers, finding the clusters from those numbers, and choosing how many clusters to set up without looking at the answer key.

By Sabri Suyunu