Rule-based allocation
Lumoda's plan share, an equal split for every store and the trace of lookalike products race with the same stock. The best "lookalike" turned out cruder than expected, and the coverage cap's gain does not come from where you would think.
Initial Allocation · 3 / 6
For two articles we talked about the decision as an idea. Now we write the sum down.
The Python below is taken from the working code under
cases/initial-allocation/, and Lumoda’s own rule from the published data
generator. The SQL query runs on the published tables. Every number in the
article comes from the case’s report.
The skeleton every method shares
Every method racing in this series is built as an “arm”. For an option, the arms all take the same steps. The only thing that tells one arm from another is the share by which it splits the stock between stores:
# initial_allocation/policy.py (InitialAllocationArm.__call__; logging lines left out)
candidate = candidate_mask(view, o, self.cmap)
U = upper_bound(view, o, self.cmap)
t = self._hold(view, o)
total = int(_floor(U * (1.0 - t)))
packs, cap, level, fallback = self._decision(view, o, candidate, U, t, total)
candidate is Lumoda’s set of candidate stores; the code copies Lumoda’s
definition exactly. U is the most packs that can go out, which we
discussed in the last article. t is the share held back in the warehouse.
In the main comparison t is zero: every arm sends the whole of U, 824,165
units in total. So the stock is the same; the only thing that changes is who
it goes to.
The code for U is short:
# initial_allocation/apportion.py
def upper_bound(view, o: int, cmap) -> int:
"""The shippable upper bound `U` (packs) for option `o`; see the module note."""
w = view.world
order, content = _pack_rows(w, o)
# bit for bit Lumoda's expression (floating point; see the module note): np.int64 * float // int
u = int(w.initial_buy[o] * constants.LUMODA_INITIAL_SHARE // int(content.sum()))
skus = np.flatnonzero(cmap.sku_option == o)
sku_size = dict(zip(cmap.sku_size_order[skus].tolist(), skus.tolist()))
for b, c in zip(order.tolist(), content.tolist()):
if b not in sku_size:
raise ValueError(f"option {o}: no SKU for size {b} in the pack")
u = min(u, int(view.dc_stock[sku_size[b]]) // c)
return max(u, 0)
The first line is Lumoda’s rule: seventy per cent of the initial buy, divided
by the units in a pack. Each step of the loop is a size: it divides the
units in the warehouse by the units in the pack and keeps the smaller. That
min is the code for what we called, in the last article, “the size that
runs out first in the pack, relative to its share”.
Shares are turned into packs by the largest remainder method: everyone gets the whole part of their share, and the packs left over go to the largest fractions. Our arms also have a minimum display: candidates whose share is below one pack get the leftover packs first; if no packs are left, they get none. So such a candidate gets either one pack or nothing. Lumoda’s rule does not have this.
Lumoda’s rule: the plan share
Lumoda’s rule is written in the data generator like this (shown with the English dataset’s names):
# the data generator, perakende_veri v4 (Lumoda's initial allocation rule;
# the candidate-set lines left out)
sp = w.plan_tables["store_plan"]
sel = sp[(sp.season_code == opt.at[o, "season_code"]) & (sp.category == opt.at[o, "category"])]
target = (
sel.set_index("store_id")["sales_target"]
.reindex(stores["store_id"]).fillna(0).to_numpy(dtype=float)
)
share = np.where(candidate, target, 0.0)
if share.sum() <= 0:
share = candidate.astype(float)
_, set_idx, content = pack_table(w.packs)
pack_units = int(content[set_idx[opt.at[o, "size_set"]]].sum())
total = int(w.initial_buy[o] * constants.INITIAL_ALLOCATION_SHARE // pack_units)
return largest_remainder(total, share)
A store’s share is the sales target Pelin’s plan sets for it in that season and that category. If none of the candidates has a plan target, the share is equal. No coverage cap, no minimum display.
This decision can also be read back from the published tables. The query below is not the case’s code; it puts an option’s initial allocation side by side with the stores’ plan targets:
-- An option's initial allocation and the plan target of the stores that got packs.
-- $option_id: the option under study.
with initial as (
select s.destination::varchar as store_id,
sum(s.units) as initial_units
from shipment s
join product u on u.product_id = s.product_id::varchar
where s.type = 'initial_allocation'
and u.option_id = $option_id
group by 1
),
plan as (
select p.store_id, p.sales_target
from store_plan p
join (select distinct season_code, category
from product where option_id = $option_id) o
using (season_code, category)
)
select m.name,
i.initial_units,
p.sales_target,
round(100.0 * i.initial_units / sum(i.initial_units) over (), 1) as option_share,
round(100.0 * p.sales_target / sum(p.sales_target) over (), 1) as plan_share
from initial i
join plan p using (store_id)
join store m using (store_id)
order by i.initial_units desc;
Put the first article’s dress (MDL0553-IND) in place of $option_id and the
query returns 25 stores. At the top is Izmir 4: 448 units, a target of
18,132. Erzurum 2 has 112 units and a target of 4,631. The two share columns
are almost the same, store by store; the small gap between them comes from
rounding to packs. The rule, as in the first article, allocates the way it
does because the plan says so.
The plan share has a habit: it concentrates the stock. In half of the options the biggest store takes at least 9.1% of the stock; at the extreme, 15.2%. Split equally, the median of that share would have been 4.0%. The correlation between initial units and the first four weeks’ sales is 0.58. It should not be read too much into: a store can only sell as much as it is sent, so part of that relationship is created by the initial allocation itself.
Equal for every store
The equal arm’s share is one line:
# initial_allocation/policy.py (EqualArm; docstring left out)
class EqualArm(InitialAllocationArm):
name = "equal"
CAPPABLE = False
def _share(self, view, o, candidate):
return candidate.astype(float), None, -1
Every candidate store’s share is 1. This arm has no cap, because we wanted it to be a pure “equal for every store”.
Let us also define here what we will compare the arms with. For each option we compare the arm’s store shares with those stores’ shares of true demand in the first six weeks. Add up the absolute differences store by store and halve the total, and you get how much of the share went to the wrong place: 0 means identical shares, 1 completely disjoint. We average over the options, weighting each by its initial buy. I will call this the share error (in the trade it goes by WAPE).
In the game season the referee knows the true demand share and the arms do not. This can only be measured in a synthetic chain like Lumoda. We do not use the referee to calibrate the share error: in place of the true share we put demand corrected for censoring from the published sales.
In the previous spring-summer season, running nothing, from the published data alone: Lumoda’s share error is 0.236, the equal split’s 0.292. In the game season: 0.235 against 0.297. The gap points the same way in both seasons and is of a similar size. The plan knows something.
The lookalike product’s trace
A new product has no history, but the products that resemble it do. That is the idea of the lookalikeA way of forecasting demand for a new product with no history from the sales of past products whose attributes resemble it. method: wherever similar products sold well in the past, the new product will sell well too.
Two questions need answers. What does “similar” mean? And how do we combine the sales of past products when their scale and their set of stores differ?
We defined similarity with a hierarchy, from the most specific to the most general:
# initial_allocation/lookalike.py
HIERARCHY = (("subcategory", "price_segment", "fit"), ("subcategory", "price_segment"),
("subcategory",), ("category",), ())
For a new product, the first level with enough lookalikes is chosen. The last level is empty: the store’s whole past spring-summer Collection. The lookalike arm learns only from past spring-summer seasons. The choice is one line:
# initial_allocation/lookalike.py (LookalikeIndex._compute_index)
chosen = next((i for i, e in enumerate(match) if e.sum() >= self.min_count), len(HIERARCHY) - 1)
To combine them we use relative speed. For each past product, we divide the store’s demand by the mean demand of the stores that received the product. An average store comes out at 1, one that sells twice as much at 2. That way big and small products meet in the same unit:
# initial_allocation/lookalike.py (learn)
relative = demand / mean[:, None]
The store’s share of the new product is its mean relative speed over the lookalike products at the chosen level. A candidate with no history at that level takes the value of the level above; a candidate with no history at all counts as an average store.
How many is “enough lookalikes”? We measured that in the previous spring-summer season, without looking at the game season at all. The result was the opposite of what we expected:
| Minimum lookalike products | Share error |
|---|---|
| 3 | 0.256 |
| 5 | 0.249 |
| 10 | 0.243 |
| 20 | 0.238 |
| 40 | 0.235 |
| 80 | 0.235 |
As the threshold grows the error falls; after 40 it stays flat, but it does not rise again. So the looser the similarity, the better. The most likely explanation is noise: a few lookalike products’ store-by-store sales are full of chance, and the mean of many products wipes that chance out. But a set this wide no longer counts as “similar”.
At the chosen threshold, for 143 of the game season’s 210 new products “lookalike” means every past product of the same category; for the other 67, the store’s whole past spring-summer Collection. None of the more specific levels is chosen for even a single product. Let us give this arm an honest name: not lookalike products but the store’s past share. That is what I will call it for the rest of the article.
The store’s past share of a category is something very like Lumoda’s plan. The plan is built at exactly this level too: store × category. The results are close as well: in calibration 0.235 against Lumoda’s 0.236; in the game season 0.229 against 0.235. In availability the store’s past share is 0.53 points ahead of Lumoda: 69.51% against 68.98%.
When stores come together
The noise explanation leaves a question open. If a single store’s sales of a few lookalike products are full of chance, putting similar stores together should reduce that chance. The product’s sales are averaged over a group of stores, not one store. Would fine similarity work then?
We tested this with the groups of the Store Grouping series. We took four of that series’ groupings: region, sales volume grade, the grid of the two (Lumoda’s own groups) and clusters found by machine learning from the sales mix; I will call these sales-mix clusters for short. The fifth is the stores’ hidden profile, that is, the answer key of that series. It is only a yardstick; in real life nobody knows this profile. It shows the best structure clustering could reach.
The sum is the same as in this article, only one level up. In a past product, the cluster’s relative speed is the mean of its member stores’ relative speeds. The store’s share is its cluster’s relative speed times the store’s size within its cluster.
We did the calibration in the previous spring-summer season again, without looking at the game season. We added a dimension to the grid: the level of the hierarchy at which similarity starts. The result was the same as for the single store. The setting that starts from the most specific level and makes do with 3 lookalike products is the worst in all five groupings; in the sales-mix clusters the share error is 0.259. There, as the threshold grows, the error falls and comes down to that of the coarse levels: 0.237.
The settings the calibration chose amount to the coarse level in the past season: they either start straight from the category or ask for a sample threshold so high that no product of the past season goes down to a finer level. The fine level only comes into play when there are a great many lookalike products. In the game season the same setting, in the sales-mix clusters, goes down to the subcategory for 68 of the 210 products; 109 stay at the category and 33 at the most general level.
At the best setting the share error is 0.238 in the sales volume grade and 0.235 in the region; in Lumoda’s groups, the sales-mix clusters and the answer key, 0.237. The store’s own past share in the same season was 0.235. Grouping did not lower the error.
So the gain from keeping similarity loose is not just a single store’s noise; in the cluster too, the best setting is the one that keeps similarity loose. A plausible explanation: clusters pool stores, not products. A few lookalike products, however many stores they are averaged over, remain a few products.
In the game season too, the sales-mix clusters’ share error is 0.230, the store’s own past share’s 0.229. What a plan by cluster gives at the end of the season we add up in the sixth article.
Correcting for censoring
The past sales of lookalike products hide something. If a product sold out early in a store, that store’s sales look lower than its demand. A customer who comes in while the rail is empty is not rung up at any till. This is called censored demandDemand that arrives while the shelf is empty and is never recorded. Sales data show not demand but the smaller of demand and stock.; the Lost Sales series is entirely about it.
We correct the demand of past products for the first six weeks, size by size. A size’s sales in that window are divided by the number of days it was on the rail and multiplied by the length of the window:
# initial_allocation/learning.py (early_demand)
rate = np.divide(sku_sales * L, sku_in_stock, out=np.zeros(len(j)), where=sku_in_stock > 0)
sku_demand = np.where(sku_in_stock >= MIN_IN_STOCK_DAYS, rate, sku_sales.astype(np.float64))
For a size with very few days in stock the rate is unreliable, so the sales are taken as they are. A size with no days in stock at all does not enter the sum. We did not use the Lost Sales series’ estimator here. Dividing by days in stock is cruder (it ignores the day of the week and the product’s age), but it can be worked out directly from the closed records of past seasons. It has a cost too: the day the product sells out counts as a full day in stock. We did not measure the effect of this correction separately. The model in the next article learns from the same corrected demand.
The coverage cap
In the second article we mentioned a constraint: no store should get more than it can sell in the first few weeks. In the arms that have a forecast, that is the store’s past share and the next article’s model, we can build that cap:
# initial_allocation/policy.py (InitialAllocationArm._coverage_cap)
def _coverage_cap(self, view, o: int, forecast_: np.ndarray) -> np.ndarray:
"""[M] packs: ⌈forecast × CAP_COVERAGE ÷ pack units⌉, at least 1; a NaN forecast
`UNCAPPED`."""
forecast_ = np.asarray(forecast_, dtype=float)
known = np.isfinite(forecast_)
cap = np.full(len(forecast_), UNCAPPED, dtype=np.int64)
pk = pack_units(view.world, o)
cap[known] = np.maximum(_ceil(np.maximum(forecast_[known], 0.0) * constants.CAP_COVERAGE / pk), 1)
return cap
A store’s cap is as many packs as its forecast demand for the first six weeks, rounded up, and at least one pack. The excess of a store that hits its cap is spread over the other stores by their shares. If every store is at its cap, the remaining packs stay in the warehouse.
Note that last sentence. A capped arm does not send part of U. So the cap
is also a hidden hold-back. In the store’s past share the cap leaves 20.9% of
U in the warehouse, in the model 34.1%: 172,289 and 281,011 units.
In calibration the cap had looked good: it raised availability by 1.71 points in the store’s past share and by 1.30 in the model. We chose to switch the cap on. But that measurement did not separate two effects: the cap steering stock to other stores, and the cap leaving stock in the warehouse.
In the game season we separated the two. We ran the uncapped arm once more, this time holding back ourselves as much stock as the capped arm leaves in the warehouse. The capped arm and this matched arm send almost the same stock. The gap between them comes from the cap’s way of allocating: which store it sends the stock to, and also which product it leaves more of in the warehouse (the matched arm holds back the same ratio in every product). The gap between the matched arm and the uncapped arm is the effect of holding back. In availability, in points:
| Total | Way of allocating | Holding back | |
|---|---|---|---|
| Store’s past share | +0.95 | −0.18 | +1.13 |
| Model | +0.96 | +0.02 | +0.94 |
The gap that comes from the cap’s way of allocating is close to zero in both arms. In the model it even points slightly the wrong way on the other measures: stock left at the end of the season +0.45 points, full-price STRSTR; the percentage of the stock a store received that has sold. In fashion retail the figure that matters is the part sold at full price. −0.56 points.
Why? In the store’s past share arm, 5,146 of the 5,354 candidate pairs hit their cap; in the model, 4,733. If the cap binds almost everywhere, it does not shift stock from one store to another; it cuts the total. The shares hardly change either: the capped arm’s share error differs from the matched arm’s by only +0.004 and +0.001. All of the gain in availability comes from the stock the cap leaves in the warehouse.
Pars sums it up in one sentence:
“The cap didn’t change how the stock was split between stores; it changed how much of it stayed in the warehouse.”
That is why, for the rest of the series, we compare the methods uncapped, with the same stock. And holding back we will build in the fifth article not as a hidden side effect but as a decision of its own.
Three rules, the same stock
Let us put this article’s three arms side by side. All three send the same stock, uncapped and without holding back any extra stock in the warehouse. By the same stock I mean the initial allocation: during the season the RPT reacts separately to each arm’s sales, and the fifth article comes back to that.
| Share error | Availability | Stock left at the end of the season | Gross profit | |
|---|---|---|---|---|
| Equal | 0.297 | 67.62% | 22.23% | TRY 519,113,339 |
| Lumoda (plan share) | 0.235 | 68.98% | 19.77% | TRY 534,433,105 |
| Store’s past share | 0.229 | 69.51% | 19.65% | TRY 535,147,736 |
We ran these three arms on four more customer streams. On every path the products’ success is the same; only which customers come to which store on which day, and what they buy, changes. So this is a test against chance, not against products succeeding differently. The equal split is behind the plan share on five paths out of five (path median in availability −1.36 points). The store’s past share is ahead of Lumoda on five paths out of five (path median +0.71 points); the +0.53 on the published stream is the smallest of the five paths.
The plan share is clearly better than equal. The store’s past share is a little better than the plan, but both know the same thing: which store is big. Neither knows where this product will take off. The first article’s dress fell into exactly that gap.
What is hard in your data
The first thing is attribute data. Defining a lookalike product needs fields such as subcategory, price segment and fit to be recorded correctly and consistently on every product. At Lumoda these fields are complete, and still fine similarity gained nothing, even with stores pooled into clusters. In a real chain the same fit may have been given three different names, and half the fields may have been left blank. There the lookalike method falls even shorter than it looks on paper.
The second is censored history. To correct the demand of past products you need the answer to “was the rail empty?” for every store, every size and every day. If that record is missing, a product that sold out early looks slow in the store where it sold best, and the method sends the next product there in small quantities.
In the next article we stop defining similarity by hand and teach it to a model. Let us see whether the model can see more than the store’s past share.