Sub topic 15
When and how to retrain
This chapter covers the retraining step of the lifecycle: what causes a model to need new training, how to decide when to do it, and how to run it safely. It assumes you can train and evaluate a supervised model in Python, know basic Git and the command line, and have read the earlier chapters on monitoring and drift detection. It also assumes you know what a model registry and a release gate are.
Why a deployed model needs retraining
A trained model is a snapshot. It captures the patterns in the data it saw at training time. Production data keeps changing after that, and the snapshot does not. Typical causes are:
- Data drift. The input distribution changes. For example, a new customer segment arrives, or a sensor is replaced and reads slightly higher.
- Concept drift. The relationship between inputs and the label changes. For example, fraudsters change tactics, so the same transaction features now mean something different.
- Upstream changes. A feature pipeline changes its units, a column is renamed, or a source system starts sending nulls.
- Seasonality. Demand, traffic and behaviour follow calendars, so a model trained in spring may be weak in December.
Retraining is the standard response to the first two, and it helps with seasonality if the new data covers the new period. It does not fix upstream bugs. If a feature is broken, retraining on broken data produces a broken model that passes its own tests. Diagnose first, retrain second.
Choosing a trigger
A trigger is the rule that starts a retraining run. There are four common kinds.
| Trigger | Starts a run when | Strengths | Weaknesses |
|---|---|---|---|
| Schedule | A fixed time passes (daily, weekly, monthly) | Simple, predictable cost, easy to audit | Retrains when nothing changed, and can be too slow when something did |
| Data volume | Enough new labelled rows have accumulated | Ties cost to the amount of new information | Says nothing about whether the data is different |
| Drift signal | A drift test on inputs or predictions fires | Reacts to real change in inputs | Needs no labels, so drift may not hurt accuracy, and false alarms are common |
| Performance | A live metric drops below a threshold | Directly measures the harm you care about | Needs ground-truth labels, which often arrive late |
Most teams combine them. A common setup is a schedule as the baseline, plus drift and performance alerts that can start an early run.
Label delay decides what you can use
The performance trigger depends on how soon you learn the true outcome. A click is labelled in seconds. A loan default may take a year. When labels are slow, you monitor proxies in the meantime: input drift, prediction distribution, and any early partial outcomes. You then confirm with real performance once labels arrive. Write down the label delay for your use case, because it sets how fast you can react at all.
Drift is a reason to look, not an order to retrain
A drift alert tells you the inputs moved. It does not tell you the model got worse. The check below compares a feature's training values with recent production values using a two-sample Kolmogorov-Smirnov test.
import numpy as np
from scipy.stats import ks_2samp
rng = np.random.default_rng(0)
reference = rng.normal(loc=0.0, scale=1.0, size=5000) # feature values seen at training time
live_same = rng.normal(loc=0.0, scale=1.0, size=5000) # production data, unchanged
live_shifted = rng.normal(loc=0.5, scale=1.0, size=5000) # production data after a shift
for name, live in [("same", live_same), ("shifted", live_shifted)]:
result = ks_2samp(reference, live)
drifted = result.pvalue < 0.01
print(name, round(result.statistic, 3), "drift" if drifted else "no drift")With large samples, the test flags tiny shifts that have no effect on accuracy, because the p-value shrinks as sample size grows. Look at the statistic (the size of the shift) as well as the p-value, and set a threshold on the effect size. Also run the test on many features, and the chance of at least one false alarm rises with the count. Apply a correction or require several features to drift together before you act.
Deciding whether to retrain
Treat the decision as a short sequence of questions.
- Is the data pipeline healthy? Check for nulls, schema changes and unit changes first.
- Is there evidence of harm? Compare recent performance, or the best proxy, with the baseline.
- Is there new labelled data that reflects the change? Without it, retraining cannot learn the new pattern.
- Does the cost of a run and a rollout pay off? Compute, review time and rollout risk are real costs.
How to retrain
Strategies for the training data
- Full retrain on a sliding window. Train from scratch on the most recent N months. This forgets old behaviour on purpose, which suits concept drift.
- Full retrain on all history. Train from scratch on everything. It keeps rare old patterns, but old data may now be misleading.
- Weighted retrain. Train on all data but give recent rows higher weight. It is a compromise between the first two.
- Incremental or warm-start training. Continue from the current weights with new data. It is cheap and fast, but it can accumulate errors and forget earlier patterns, so it needs periodic full retrains.
Pick the window by testing. Train candidates with several window sizes and compare them on a recent held-out period, not on a random split of the same data.
Treat a retrain as a normal training run
Retraining is not a special path. It should use the same pipeline, the same code and the same tracking as the first training run. Pin the data snapshot, the code commit and the random seed, and log them. Then every retrained model can be reproduced and compared with the model it replaces.
import mlflow
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
SEED = 42
C = 1.0
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=SEED
)
with mlflow.start_run():
model = LogisticRegression(C=C, max_iter=200).fit(X_train, y_train)
accuracy = accuracy_score(y_test, model.predict(X_test))
mlflow.log_param("C", C)
mlflow.log_param("seed", SEED)
mlflow.log_metric("accuracy", accuracy)In a real retrain you would also log the data snapshot identifier and the trigger that started the run, for example mlflow.set_tag("trigger", "drift"). That tag lets you later ask which triggers produced useful models.
Gate the result before it ships
A retrained model is a candidate, not a replacement. It should pass the same release criteria as any new model, including a comparison with the model now in production on the same recent data.
def should_promote(candidate_accuracy, production_accuracy, min_gain=0.0, floor=0.90):
"""Release gate: the candidate must clear an absolute floor and not be worse than production."""
if candidate_accuracy < floor:
return False
return candidate_accuracy >= production_accuracy + min_gain
print(should_promote(0.94, 0.92)) # True
print(should_promote(0.89, 0.85)) # False: below the absolute floor
print(should_promote(0.93, 0.95)) # False: worse than productionEvaluate both models on the same recent data. If you score the production model on its old test set and the candidate on new data, the comparison means nothing. Setting min_gain above zero avoids swapping models over noise. When the gate fails, the right outcome is to keep the current model and open an investigation.
Closing the loop
After the gate passes, register the candidate, then roll it out with a staged pattern such as shadow deployment or a canary release, so a bad model reaches few users first. Keep the previous version in the registry so you can roll back quickly. Then monitor the new model against its own baseline, since the reference data for drift checks should now be the new training data.
Common errors
- Retraining on every alert. This wastes compute and creates churn. Add the harm check before you start a run.
- Retraining on broken data. The new model learns the bug. Validate data first.
- Feedback loops. If the model's own decisions decide which examples get labelled, the new data is biased. For example, a lending model only sees outcomes for loans it approved. Keep some random exploration or use another labelling source.
- Evaluating on a random split of drifted data. Use a time-based split so the test set is the most recent period.
- Unlogged retrains. If a retrain cannot be traced to a data snapshot and commit, you cannot explain or reproduce its behaviour later.
- No rollback path. Always keep the last good version deployable.
Exercise
A drift test on one input feature fires with p < 0.001, but live accuracy, measured on labels that arrive after two days, has not changed. List two reasons not to retrain immediately and the next step you would take.
Show answer
Possible reasons: with large samples the test detects shifts too small to affect the model, and one feature among many can fire by chance. The data pipeline may also have a fault that retraining would not fix. Next step: check the data pipeline for schema or unit changes, look at the size of the shift (the test statistic) and not just the p-value, and keep monitoring accuracy as labels arrive. Retrain only if there is evidence of harm and new labelled data that reflects the change.
Exercise
Your candidate model scores 0.93 on its test set. The production model scored 0.95 on the test set it was evaluated on six months ago. Should should_promote approve the candidate? What should you change about the comparison?
Show answer
Do not decide from these numbers, because the two scores come from different datasets. Evaluate both models on the same recent held-out data, then pass those two scores to shouldpromote. With the same data, the candidate is promoted only if it clears the floor and is at least as good as production plus mingain.