# Customer segments with clustering (design, declared before any clustering is fitted)

Part four of the online retail study. Question: on the same public orders, when a team builds customer segments by
clustering instead of the study's hand-built recency-and-value rule, how much do the choice of features, scaling,
distance and number of segments change who would get a win-back contact? Are the segments stable when the customers are
resampled, and do they separate who orders again in a later period, which the clustering never saw, better than the rule?

This file and `protocol-segments.json` (the same settings in machine form, with the predictions) are committed before
any clustering is fitted. `segments_pipeline.py` refuses to fit unless the protocol matches its pinned SHA-256 and,
inside a git checkout, is committed unmodified. The scoring stage then refuses unless the fitted segments are committed.

## Why this is a part of this study and not a new one

Overlap test (improve an existing study when the question family or the data matches; a new study only when both
differ). Data: the same Online Retail II orders, which are also the standard public data for recency, frequency and
value clustering. Question family: which customers get which action, the decision the first part's list makes. Both
match, so this is part four of the online retail study. No published page of the study, or any other, fits a clustering:
every segment elsewhere is a predefined group. The nearest other study on the same data asks whether the average order
changed (a mix and rate split), an unrelated question.

## What was already known before this design

The published first part, at the same two decision dates: the value tiers, the quiet flag (90 days without an order),
the list (quiet customers in the top 30% by past-year revenue; 330 customers on 1 June 2011), and, for the list and the
tiers, how many ordered again within 180 days. Its derived tables (`data/derived/customers-*.csv`) hold the rule's cells
and the outcome per hashed customer. The second part's monthly flows cover the same months. No clustering, segment
profile, stability figure or per-segment outcome had been computed on this data for this study. The predictions below
were written from general experience with these methods and from the published figures above.

## 1. Data, population and the holdout split

- Lines: the study's own cleaning, unchanged (`pipeline.read_sheets` and `retail/clean.py`), keeping quantity, unit price
  and product code as well, for the product mix features.
- Decision dates: 1 June 2011 (primary) and 1 December 2010 (replication), the first part's two dates.
- Population at a date D: the active customers of the first part (positive net revenue and at least one sale in the 365
  days before D), so the rule is exactly the first part's list.
- Features use lines in the 365 days before D only. The outcome uses the 180 days from D only: ordered again (at least one product sale
  line) and, as a secondary outcome, log(1 + net revenue) in that window, with negative net revenue counted as zero.
- Enforcement: `prepare` writes lines before 1 June 2011 and lines from 1 June 2011 to two separate files. `fit` opens
  only the first file and filters each date's features to lines before that date. `score` opens the second file, and
  reads any outcome at all, only after `require_fit_committed()` passes: the fitted results file must be committed
  unmodified, and the per-customer segment file it names must match its recorded SHA-256. For the December 2010 date the
  outcome window sits inside the first file, so there the separation is the code's date filter and the commit order.

## 2. Features (four sets)

Per customer, from the 365 days before D:
- recency: days since the last order (as in the first part);
- frequency: distinct orders with a product sale;
- value: past-year net revenue (the first part's ranking measure);
- product mix: mean units per sale line (wholesale buyers order in bulk), median unit price paid, distinct product
  codes bought, and the share of gross sales bought in September to November (the gift season).

Sets: `rv` (recency and value: the rule's own inputs), `rfm` (recency, frequency, value), `rfm_mix` (all seven), `mix`
(the four product mix features alone).

## 3. Scaling, algorithms and distance

- Scalings: `standard` (log(1 + x) on every feature except the autumn share, then z-scores), `raw` (no change at all:
  money, days and counts in their own units) and `rank` (each feature's percentile rank).
- Algorithms, each with its distance:
  - k-means (squared Euclidean), 10 starts;
  - Gaussian mixture with full covariance (each segment its own shape: a Mahalanobis distance per segment), 3 starts;
  - hierarchical clustering with Ward linkage (Euclidean);
  - hierarchical clustering with average linkage and Manhattan distance.
- Grid at each date: k-means on every feature set and every scaling; the other three algorithms on every feature set
  with `standard` scaling. Number of segments k from 2 to 8. That is 4 sets x 6 combinations x 7 values of k = 168 fits.
- Choosing k: the k with the highest silhouette (Manhattan for the average-Manhattan fits, Euclidean otherwise), ties to
  the smaller k. This is the default a team reaches for; the Gaussian mixture's BIC is reported beside it, not used.

## 4. The rule as a segmentation

The first part's rule cut into six cells: three value tiers (top 10%, next 20%, bottom 70% by past-year revenue) times
quiet (no order for over 90 days) or recent. Its list is the quiet top 10% and next 20% cells.

## 5. Stability (primary date)

- 100 bootstrap resamples of the active customers (with replacement). Each fit is refitted on each resample with the
  same settings; the scaling is fitted once on all customers and held fixed. Every customer is then assigned to a
  segment of the resample's fit: k-means and the mixture by their own prediction, the hierarchical fits by the nearest
  segment centre (the mean for Ward with Euclidean distance, the median with Manhattan distance).
- Measure, declared: the adjusted Rand index (ARI) between the full-data segments and each resample's segments, over all
  customers; reported as the mean and the 5th percentile over the 100 resamples. Second measure: after matching each
  resample's segments to the full-data ones (Hungarian matching on overlap counts), the share of customers who stay in
  their segment in at least 90 of the 100 resamples.
- The rule gets the same treatment: tier cut points set on each resample and applied to everyone; the 90-day gap fixed.
- Stability is not run at the replication date.

## 6. Usefulness on the holdout period

- Score per customer: the share of its segment that ordered again, estimated on the other four of five folds of
  customers (folds by a seeded permutation of the hashed keys). Segments are fitted on features only; only these segment
  rates touch the outcome, and always out of fold.
- Primary measure: out-of-fold AUC for ordered again within 180 days, all active customers. Secondary: the same AUC among
  quiet customers only (the win-back population), and out-of-fold R-squared of log(1 + next-period revenue) from segment
  means.
- References: the rule's six cells (same out-of-fold rates); recency alone (customers ranked by days since the last order,
  nothing fitted); and a supervised logistic regression on the `rfm_mix` features with `standard` scaling, trained out of
  fold for the outcome itself (the best a score built for this outcome does here, for scale).
- Intervals: 95% percentile intervals of each AUC difference against the rule, from 1,000 paired resamples of customers
  with the scores held fixed (they show sampling of customers, not refitting).

## 7. What a team would do with the segments

A team reading a segmentation picks the segments for a win-back contact by a fixed rule, declared here: every segment
whose median days since the last order is over 90 and whose median past-year revenue is at or above the median of all
active customers. The list is every member of the picked segments. For each list: its size, its overlap with the rule's
list (Jaccard: shared customers over customers on either list), the share of its members not yet quiet, and the first
part's own measure: the share of lost revenue it holds (lost = quiet and did not order again within 180 days), against
the first part's bar (at least 50% of the lost revenue with at most 35% of quiet customers).

## 8. Predictions (written before any fit; scored on the primary date unless stated)

Scored on the point estimates: held when the estimate falls inside the band, missed when it falls outside, untestable
when the measure cannot be computed (for example, no segment meets the win-back rule). Each AUC comparison also shows
its interval; where the interval reaches past a band's edge, the page says so beside the score. "Silhouette k" means the
k chosen in section 3. The predictions are listed with their bands in `protocol-segments.json`:

1. k-means on `rfm` (standard, silhouette k): AUC within 0.03 of the rule's, either way.
2. No configuration at its silhouette k (24 of them) has an AUC more than 0.03 above the rule's.
3. The logistic regression beats the rule's AUC by at least 0.04, and every configuration at its silhouette k.
4. Recency alone reaches an AUC no more than 0.02 below the rule's.
5. Every `mix` configuration at its silhouette k has an AUC at least 0.05 below the rule's.
6. k-means on `rfm` (standard): mean ARI at least 0.80 at k = 2, 3 and 4.
7. k-means on `rfm` (standard): mean ARI at k = 8 at least 0.10 below the mean ARI at k = 3.
8. At k = 4, the Gaussian mixture is less stable (lower mean ARI) than k-means on each of the four feature sets.
9. k-means on `rfm` with `raw` scaling puts at least 90% of customers in its largest segment at every k from 2 to 5.
10. Average linkage with Manhattan distance (standard) puts at least 90% of customers in its largest segment at k = 4, on
    each of the four feature sets.
11. The silhouette picks k = 2 or 3 in at least 12 of the 16 `standard` combinations (4 sets x 4 algorithms).
12. The win-back list from k-means on `rv` (standard, silhouette k) overlaps the rule's list with a Jaccard of at least 0.4.
13. The win-back list from k-means on `mix` (standard, silhouette k) overlaps the rule's list with a Jaccard of at most 0.2.
14. No `standard` configuration at its silhouette k yields a win-back list that meets the first part's bar.
15. Replication, 1 December 2010: k-means on `rfm` (standard, silhouette k) has an AUC within 0.03 of the rule's.

No prediction may be edited, dropped or added after the first fit; any later idea is labelled as added after the
results and is not scored. A change before the results is a numbered "Change N to the protocol", committed before use.

## 9. Worked example (chosen by a declared rule)

On the primary date, among the rule's list, the customer closest to the list's median recency and median value (sum of
absolute differences in percentile rank within the list), among those whose win-back status under k-means (standard,
silhouette k) differs between at least two feature sets; if no list customer's status differs, the closest one overall.
Ties by hashed key. The page shows its features rounded (days to the week, money to the nearest £10, counts as ranges
when under 5) and never its key.

## 10. Public tables

Aggregates only. Any segment with fewer than 11 customers is shown as "fewer than 11" with its profile withheld. The
per-customer segment file stays in `data/work/` (not committed, not exported); the fit stage rebuilds it.

## 11. Outputs

`results-segments-fit.json` (segments, profiles, silhouettes, stability, the lists; no outcome), committed before
scoring; `results-segments.json` (usefulness, list measures, prediction scores); the page `customer-segments.html` from
`render_segments.py`, linked from the main page with one sentence; `README-segments.md`; tests in
`tests/test_segments.py` and `tests/test_render_segments.py`.

## 12. Changes made after the results

These were made after the holdout period was scored, after review. None changes a fit, a prediction or its verdict.

- Change 1 to the protocol, made after the results: a win-back list with fewer than 11 customers is withheld like a
  segment. Its size, overlap with the rule's list, share of quiet customers and every holdout measure are published as
  null with the note "fewer than 11 customers". Three lists are affected (average linkage on `rfm` at 6 and 7 segments
  on the primary date; k-means on raw `mix` at 8 segments on the replication date). The score stage withholds after the
  predictions are scored, so the predictions read the same lists as before.
- Change 2 to the protocol, made after the results: the worked example's features are published coarser than section 9
  says. Orders and products are shown as bands (under 5, 5 to 9, 10 to 19, 20 to 49, 50 to 99, 100 to 199, 200 or more),
  past-year revenue to the nearest £100 and the autumn share to 0.1, because exact counts with the other features could
  single the customer out of the public file. The private work file keeps the rounding of section 9.
- Change 3 to the protocol, made after the results: paired intervals against the rule are also computed for every
  combination at 5 to 8 segments, not only k-means on logs and z-scores. They use the same 1,000 resamples and are
  appended after the declared comparisons, so every earlier interval is unchanged. They are not scored.
