Sub topic 14
Keeping segments fresh: refresh, drift and activation
A segment is a snapshot. The day after you build it, customers buy, lapse, change devices and withdraw consent. This chapter covers how to keep segments current, how to detect when they have stopped describing your customers, and how to deliver them to the channels that use them.
This chapter assumes you have read the chapters on feature engineering and clustering. You should be comfortable with RFM features, scaled k-means, and the idea that a segment ID is what decisioning and templates consume. You should also be able to read short NumPy and scikit-learn snippets.
Why segments go stale
Three things change after a segmentation ships.
- Membership changes. A customer with a 3-day recency today has a 45-day recency next month if they do not return. Their segment should change with them.
- The inputs change. Prices rise, a promotion inflates order counts, or a tracking change alters how events are logged. The feature distributions move, so the cluster boundaries no longer fit.
- The meaning changes. Customers behave differently after a market shift. A "high value" cluster defined by last year's spending may now contain half your customers.
The first is routine and handled by refreshing assignments. The second and third are drift, and they need monitoring and sometimes retraining.
Refreshing: assignment versus retraining
Two operations are often confused.
| Operation | What it does | Typical cadence | Risk |
|---|---|---|---|
| Re-assignment | Recomputes features and assigns each customer to the nearest existing segment, with the model unchanged | Daily or hourly, or on key events | Low. Segment definitions stay stable |
| Retraining | Refits the clustering or predictive model on recent data | Monthly or quarterly, or when drift triggers | Higher. Segment meanings and sizes can shift |
Re-assignment keeps membership current without changing what "Loyal" means. Retraining changes the definitions themselves, so treat it like a release: review it, compare it with the old version, and roll it out deliberately.
Rule-based segments only need re-assignment, because the rule is the definition. Predictive segments need fresh scores, and they also need retraining when the relationship between features and outcome changes.
Keeping segment identities stable
Clustering does not know what you named things. If you refit k-means, cluster 0 may now be what used to be cluster 1. Any template or rule keyed to the raw label would send the wrong message with no error.
Two defences work together. First, store the business name (champions, lapsed) as the segment identity, not the cluster number. Second, after retraining, match new clusters to old ones by centroid distance and carry the old names forward. The Hungarian algorithm finds the best one-to-one pairing:
import numpy as np
from scipy.optimize import linear_sum_assignment
from sklearn.cluster import KMeans
def align_labels(old_centroids, new_centroids):
"""Return {new_label: old_label} that minimises total centroid distance."""
cost = np.linalg.norm(
old_centroids[:, None, :] - new_centroids[None, :, :], axis=2
)
old_idx, new_idx = linear_sum_assignment(cost)
return {int(n): int(o) for o, n in zip(old_idx, new_idx)}
rng = np.random.default_rng(7)
group_a = rng.normal([0.0, 0.0], 0.3, size=(100, 2))
group_b = rng.normal([4.0, 4.0], 0.3, size=(100, 2))
x_old = np.vstack([group_a, group_b])
x_new = x_old + rng.normal(0, 0.1, size=x_old.shape)
old_model = KMeans(n_clusters=2, n_init=10, random_state=0).fit(x_old)
new_model = KMeans(n_clusters=2, n_init=10, random_state=1).fit(x_new)
mapping = align_labels(old_model.cluster_centers_, new_model.cluster_centers_)
print("new label -> old label:", mapping)The mapping may swap the labels or leave them alone. Either way, you can translate new labels back to the old names. Also compare the matched centroids: if a new centroid sits far from every old one, the segment has really changed and a person should review it before activation.
Stop customers flapping
A customer near a boundary can move between segments on every refresh. The content then alternates, which looks erratic and pollutes your measurement. Common fixes:
- Hysteresis. Require a customer to cross the boundary by a margin, or stay across it for two consecutive refreshes, before the segment changes.
- Minimum dwell time. Once assigned, keep the segment for a set number of days unless a strong event occurs, such as a purchase or a cancellation.
- Event overrides. Let high-signal events change the segment immediately. A refund request should not wait for the nightly job.
Detecting drift
Drift monitoring compares today's data with a reference, usually the training data. Watch three layers.
- Input drift. Has the distribution of each feature moved?
- Segment drift. Have the segment sizes or centroids moved?
- Outcome drift. Do segments still behave differently from each other? For example, does the click rate by segment still show clear separation?
Population Stability Index
The Population Stability Index (PSI) measures how much a feature's distribution has moved. It bins the reference data, then compares the share of the new data falling in each bin.
import numpy as np
def psi(reference, current, bins=10):
"""Population Stability Index of `current` against `reference`."""
edges = np.quantile(reference, np.linspace(0, 1, bins + 1))
edges[0], edges[-1] = -np.inf, np.inf
ref_share = np.histogram(reference, edges)[0] / len(reference)
cur_share = np.histogram(current, edges)[0] / len(current)
ref_share = np.clip(ref_share, 1e-4, None) # avoid log(0)
cur_share = np.clip(cur_share, 1e-4, None)
return float(np.sum((cur_share - ref_share) * np.log(cur_share / ref_share)))
rng = np.random.default_rng(0)
last_quarter = rng.gamma(shape=2.0, scale=20.0, size=5000) # recency_days
this_week = rng.gamma(shape=2.0, scale=30.0, size=1000) # customers returning less often
print(f"PSI: {psi(last_quarter, this_week):.3f}")A common rule of thumb reads the score like this. These cut-offs are conventions from credit scoring, not laws, so tune them against your own history.
| PSI | Reading | Action |
|---|---|---|
| Below 0.10 | Stable | None |
| 0.10 to 0.25 | Moderate shift | Investigate and watch |
| Above 0.25 | Large shift | Review, and consider retraining |
Segment-level signals
Feature PSI can miss problems that appear only in the segments. Track these each refresh:
- Share of customers per segment. A segment that grows from 10% to 30% in a week usually signals a data change, not a behavioural one.
- Centroid movement. Distance between this period's segment centroid and the reference centroid, in scaled units.
- Unassigned or fallback rate. The share of customers who receive the default experience because features are missing.
- Between-segment separation. Whether outcome metrics still differ across segments. If every segment converts at about the same rate, the segmentation no longer informs decisions.
Activation: getting segments to the channels
Activation is the step that makes a segment usable: writing membership to the email platform, the website personalisation layer, the ad audiences or the app. Most production failures happen here, not in the model.
The flow below shows a typical loop, with checks placed where they catch the most problems.
Activation practices that prevent incidents
- Filter consent at activation time. Consent can change between scoring and sending. Apply the current consent state as the last step before publishing, not only when features are built.
- Version everything. Record the model version and segment version used for each send. Without this, you cannot explain a result or reproduce an audience later.
- Expire memberships. Give each assignment a time-to-live. If the refresh job fails, stale segments should lapse to a safe default and not persist for weeks.
- Publish atomically. Write the new membership to a staging table and swap it in, so a half-finished job never leaves some customers on new segments and others on old ones.
- Match latency to the channel. Email can use a nightly refresh. An on-site banner that should react to the current session needs near-real-time updates, or rules evaluated at request time.
- Handle failure explicitly. If feature computation fails, fall back to the previous segment or the default experience. Never let missing data produce an empty or wrong segment.
Choosing a refresh strategy
Pick cadence by how fast the behaviour you segment on changes and how costly a wrong message is.
- Fast-moving behaviour such as browsing intent or cart activity: refresh on events or hourly, and prefer simple rules or scores that are cheap to recompute.
- Slow-moving attributes such as lifetime value tier: refresh weekly or monthly. More frequent refreshes mostly add flapping.
- Retraining: schedule it (quarterly is a common start) and add drift-triggered retraining as a second path. Require a comparison with the previous version before release.
Common errors
- Keying templates to raw cluster numbers, which silently swap meaning after a refit.
- Retraining on a schedule without comparing against the old segments, so definitions drift unnoticed.
- Computing PSI against a reference that is itself already drifted. Keep the training-time reference frozen.
- Checking consent only when building features and not when sending.
- Refreshing without hysteresis, so customers flap and holdout groups contaminate.
- Treating a failed refresh job as "no change" instead of an alert.
Exercise
Your weekly monitoring shows PSI of 0.31 on recency_days, and the "lapsed" segment has grown from 12% to 28% of customers. Name two checks you would run before retraining, and say what you would do if the cause turned out to be a tracking change that stopped logging mobile app sessions.
Show answer
First, compare against the same period last year to rule out seasonality, and check outcome metrics by segment to see whether the segments still separate behaviour. Also inspect the event pipeline for volume changes by source or device. If mobile sessions stopped being logged, customers who use the app look inactive, so "lapsed" is inflated by a data fault. Fix the tracking and recompute features instead of retraining, because retraining would bake the broken data into the new segment definitions. In the meantime, hold the segment at its previous version or route affected customers to the default experience.