TExcelTAD

The ML System Lifecycle

A model in a notebook with a good test score is not yet a working ML system. Before it helps anyone, it has to be fed with the right data, trained reproducibly, evaluated honestly, put into service and watched once it is running. These stages form a lifecycle, and it is a loop: what you learn in production sends you back to the data.

The five stages

1 datacollect, label,clean, split 2 trainingfit featuresand model 3 evaluationunseen data,right metric 4 deploymentserve: batchor live 5 monitoringwatch inputs,drift, errors feedback: new data, fixes, retraining

Before stage 1 comes problem framing: what decision will the model support, what is the input and the target, what metric reflects success, and what does a wrong answer cost? A crisp answer here saves weeks later. Then:

Stage Key questions Typical outputs Course
1 Data Where does the data come from? Is it legal and representative? Are the labels right? How do we split it? a versioned data set, a data report, train/validation/test splits Data for ML, Data Preparation
2 Training Which features and model? Which loss and optimiser? Which hyperparameters? a fitted pipeline (preprocessing + model), training logs Classical ML Algorithms, Training Strategies
3 Evaluation Is it good enough on data it never saw? Better than a simple baseline? Fair across groups? Where does it fail? metrics on the test set, error analysis, a go/no-go decision Training, Evaluation & Improvement
4 Deployment Batch or real-time? Which latency and cost? How do we roll back? a saved model, a service or batch job, a model registry entry Deployment & MLOps
5 Monitoring Do live inputs still look like the training data? Is accuracy holding? Any errors or slowdowns? dashboards, alerts, a retraining trigger Deployment & MLOps

The whole loop in one program

The example runs every stage once on the breast-cancer data set that ships with scikit-learn (569 tumour samples, 30 measurements each, labels benign or malignant). The "deployment" saves the fitted pipeline to bytes and loads it back, as a separate serving program would. The "monitoring" simulates a common accident: a measuring device is recalibrated after deployment and every reading is now 30 % higher.

python · try it yourself
import pickle
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

# 1. Data: collect, then split before looking at results.
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
print(f"1 data:       {len(X_train)} training rows, {len(X_test)} test rows, {X.shape[1]} features")

# 2. Training: preprocessing and model fitted on the training rows only.
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
print("2 training:   fitted", type(model[-1]).__name__)

# 3. Evaluation: once, on rows the model never saw.
print(f"3 evaluation: test accuracy {model.score(X_test, y_test):.3f}")

# 4. Deployment: save the fitted pipeline, load it in the "serving" program, predict.
blob = pickle.dumps(model)
served = pickle.loads(blob)
print("4 deployment: prediction for one new record ->", served.predict(X_test[:1])[0])

# 5. Monitoring: compare live inputs with the training data.
live = X_test * 1.3                                       # a sensor recalibrated after deployment
shift = np.abs(live.mean(axis=0) - X_train.mean(axis=0)) / X_train.std(axis=0)
print(f"5 monitoring: {np.sum(shift > 0.5)} of {X.shape[1]} features drifted; accuracy on live data {served.score(live, y_test):.3f}")
1 data:       426 training rows, 143 test rows, 30 features
2 training:   fitted LogisticRegression
3 evaluation: test accuracy 0.958
4 deployment: prediction for one new record -> 1
5 monitoring: 20 of 30 features drifted; accuracy on live data 0.643

The model is 95.8 % accurate on the 143 held-out rows. After the recalibration, the same model on the same patients drops to 64.3 %, and nothing crashed: the service keeps answering, just wrongly. Only monitoring notices. Here a simple check finds that 20 of the 30 features moved by more than half a training standard deviation, which is the signal to investigate and, once the cause is understood, to fix the input or retrain.

Monitoring the inputs matters because in many applications the true labels arrive late (was the loan repaid? did the patient have cancer?) or never, so you cannot watch accuracy directly.

Who does what

Role Main stages
Domain expert (doctor, analyst, engineer) framing, labels, error analysis
Data engineer collecting, storing and versioning data; pipelines
Data scientist / ML engineer features, training, evaluation
ML or platform engineer (MLOps) deployment, serving, monitoring, retraining automation

In a small team one person does all of it. The stages are the same.

Why it is a loop

Monitoring feeds back into data:

  • Data drift: inputs change (new customers, new sensors, a new season), as in the example.
  • Concept drift: the relationship between input and label changes (fraudsters change tactics; a word changes meaning).
  • New failure cases: error analysis in production shows where to collect more data or fix labels.

Each turn of the loop produces a new model version, which must be evaluated against the current one before it replaces it. Keeping data versions, code versions, settings and metrics recorded for every turn is what makes the loop safe; the Deployment & MLOps course shows the tools.

Pitfalls

  • Ending at evaluation. A model that is never deployed helps nobody; a model that is deployed and not monitored fails silently.
  • Training and serving with different preprocessing. If the service scales inputs differently from the training code, predictions are wrong. Saving the whole pipeline, as the example does, avoids that.
  • Evaluating on data that leaked into training. Split first, then fit every preprocessing step on the training part only.
  • Unpickling untrusted files. pickle.loads can execute code. Only load model files you created or trust.

Practice

  1. Assign each activity to a lifecycle stage: (a) checking that the share of tumours predicted malignant is still about 37 %, (b) choosing between logistic regression and a random forest, (c) removing duplicate rows, (d) putting the model behind an HTTP endpoint, (e) computing recall on the test set.
Answer

(a) monitoring, (b) training (model choice, decided with a validation set), (c) data, (d) deployment, (e) evaluation.

  1. In the example, why is the StandardScaler inside the saved pipeline rather than applied to the data before training?
Answer

So that the serving program applies exactly the same scaling, with the means and standard deviations learned from the training rows, to every new record. If scaling lived in separate code, it could drift out of sync with the model. Fitting it inside the pipeline also guarantees it sees only training data.

  1. Why might the recalibrated sensor lower accuracy so much even though the patients are the same?
Answer

The model learned weights for measurements on the original scale. Multiplying all readings by 1.3 moves benign tumours into the region where large measurements meant malignant, so many are now classified as malignant. The model has no way to know the units changed.

Test yourself

What is the correct order of the lifecycle stages?

  1. Training, data, deployment, evaluation, monitoring
  2. Data, training, evaluation, deployment, monitoring
  3. Data, deployment, training, monitoring, evaluation
  4. Evaluation, data, training, monitoring, deployment

In the example, accuracy fell from 0.958 to 0.643 after deployment. What caused it?

  1. The model was retrained badly
  2. The input data shifted: a recalibrated sensor scaled every reading by 1.3
  3. Pickle damaged the model
  4. The test set was too small

Why do monitoring systems often watch input distributions rather than accuracy?

  1. Accuracy cannot be computed
  2. True labels often arrive late or never in production
  3. Inputs are more important than outputs
  4. It is required by scikit-learn

Fraudsters change their tactics, so the same transaction features now mean something different. What is this called?

  1. Data leakage
  2. Concept drift
  3. Underfitting
  4. Batch learning