MLOps for Beginners: Model Monitoring, Data Drift, Versioning and Retraining

A student has trained a Random Forest to estimate historical house-sale prices. It passed validation and was made accessible through a web application and a FastAPI service. Several months later, the incoming properties look different: the median living area appears larger, one feature contains more blanks, and the distribution of predictions has shifted. Does this mean the model has become inaccurate? Should the student retrain it immediately, or first check for a broken data pipeline? Those questions mark the beginning of Machine Learning Operations (MLOps).

This comprehensive MLOps for beginners tutorial explains how to monitor a model after deployment, diagnose data drift and concept drift, evaluate performance when actual labels arrive, version models, compare a champion with a challenger, and plan safe approval and rollback. It builds directly on Topic 93: Building Machine Learning APIs with FastAPI, but shifts the focus from serving predictions to maintaining an evidence-based system over time.

Reproducibility disclosure — 25 November 2026: The downloadable Python monitoring package was created and executed against unit-test examples. Five tests passed; the real-model test skipped because the historical OpenML Ames Housing data could not be obtained in this environment. The constructed three-bin PSI example was independently calculated as 0.17147984. MLflow and Evidently were not installed locally, so no fabricated runs, registry aliases or Evidently reports are claimed. This article and its original charts teach a historical 2006–2010 simulation, not a deployed monitoring system, scheduled job or live housing service.

What is MLOps?

MLOps means Machine Learning Operations: the collection of engineering, data-management, experimental, operational and governance practices used to manage machine-learning systems throughout their lifecycle. It joins the work of building models to the work of releasing, observing, correcting and replacing them responsibly. A developer may be able to train an accurate model once, but the organisation must also know which version is currently serving, whether inputs still match expectations and how to recover from a harmful release.

MLOps is not synonymous with installing one platform or scheduling automatic retraining. People, documentation, quality controls, authorization, repeatable experiments and independent evaluation are equally important. A small educational project can practise MLOps by saving model metadata, checking distribution changes, writing monitoring reports and documenting decisions without paying for a complex cloud stack.

The machine learning lifecycle after deployment

A practical lifecycle is Data → Validation → Training → Evaluation → Versioning → Deployment → Monitoring → Investigation → Candidate Retraining → Comparison → Approval → Controlled Release → Continued Monitoring. Feedback can return to any stage. For example, a sudden rise in missing values may lead to a data-collection repair; an invalid feature unit may require updating the API; a verified decline in prediction quality might justify collecting new labels and training a challenger.

In Topic 93, students learned to expose a saved Scikit-learn Pipeline through FastAPI. Topic 94 adds monitoring and management around that Pipeline. A prediction endpoint can return HTTP 200 every time while the underlying model is giving unreliable estimates. Conversely, a strong model may be unavailable because its server crashes. Reliability requires observing both the service and the statistical behaviour.

Conceptual time-separated historical monitoring workflow
Original timeline illustration. Dates indicate planned retrospective windows; no live monitor was deployed.

MLOps versus DevOps and DataOps

DevOps emphasizes collaborative, repeatable software development and operations, including testing, delivery and infrastructure. DataOps emphasizes reliable data pipelines, data quality and coordinated analytical workflows. MLOps extends these ideas to trained statistical models, adding issues such as training data provenance, evaluation datasets, changing populations, model versions and predictive performance after release.

These disciplines overlap rather than compete. A model-serving team may use DevOps to release its API, DataOps to validate incoming records and MLOps to decide if the trained estimator remains suitable. A school project can practise all three without using commercial infrastructure.

DisciplineTypical emphasisProject example
DevOpsSoftware delivery and availabilityFastAPI tests and deployment
DataOpsData quality and pipeline reliabilitySchema and missingness checks
MLOpsTrained-model lifecycle and behaviourDrift reports, champion/challenger review

Five dimensions of model monitoring

Data quality asks whether expected features are present, correctly typed and plausibly measured. Data drift asks whether input distributions differ between relevant periods. Prediction behaviour asks whether the distribution of outputs, including median estimates, has changed. Predictive performance asks how accurate the model is once true outcomes become available. Operational reliability asks whether the serving API responds safely, correctly and within reasonable resource limits.

These dimensions must not be collapsed into one status light. Input quality may remain excellent while predictive error grows. Data drift may be statistically evident without measurable loss of accuracy. A web API can remain technically healthy while returning misleading outputs. Record each dimension separately, with time window, sample count, model version and evidence.

Understanding data drift: P(X) may change

Data drift means the distribution of model inputs has changed between a chosen reference population and the current population: conceptually P_reference(X) versus P_current(X). For historical housing, later records might have larger living areas or different quality-rating frequencies. That change may reflect actual differences among houses, altered data collection or random sampling variation.

A drift statistic is a diagnostic, not a verdict. It does not prove model failure, establish the underlying cause or mandate retraining. Before reacting, check whether the reference period is suitable, whether features retain their original meanings, whether missing values or duplicate records increased, and whether enough observations exist for a stable comparison.

Concept drift: the relationship between X and Y may change

Concept drift refers to a change in the relationship between features and outcomes, represented by P_reference(Y | X) versus P_current(Y | X). In a property-price setting, wider financial or market changes might alter the sale price associated with the same recorded characteristics. This differs from simply seeing more large homes in a later period.

Concept drift usually needs labelled outcomes or defensible additional assumptions to establish. Observing living-area drift alone cannot demonstrate that prices now respond differently to living area. Even where labelled errors increase, further investigation is needed to distinguish relationship change from data bugs, evaluation differences and sampling noise.

Target drift is not prediction drift

Target drift means the distribution of actual outcomes changes: perhaps recorded sale prices in the later historical period are higher. Observing the true target distribution requires the corresponding outcome labels. Prediction drift instead means the distribution of the model’s estimated outputs changes, which can be measured while those labels are still unavailable.

A model might predict larger prices simply because its input batch contains larger houses. A change in predictions says nothing definitive about actual errors. Conversely, the model might continue predicting similar amounts while actual sale prices change, so prediction drift alone is insufficient. Always label distributions as actual outcomes or model-generated outputs.

SignalWhat changed?Requires current labels?
Data driftInput-feature distributionOften no
Prediction driftDistribution of model outputsNo
Target driftDistribution of actual outcomesYes
Concept driftConditional relation between inputs and outcomesUsually labelled evidence or extra assumptions

Training–serving skew: a software mismatch that looks like drift

Training–serving skew occurs when features or transformations differ between model training and inference. Perhaps the model was trained using square feet, but a website submits square metres; a missing-value rule changes; categories are encoded differently; or a six-field DataFrame arrives in a different order. These problems can produce errors even when the actual population has not changed.

The prevention is to retain the fitted preprocessing Pipeline, validate exact names and order, record measurement units and feature versions, and compare test inference between the training and serving code. Investigate schema failures before calculating drift. A broken measurement pipeline should generally be repaired, not treated as evidence that a new machine-learning algorithm is needed.

Choose reference and monitoring windows deliberately

A reference dataset provides the comparison distribution. It might be a training sample, a designated validation sample or an approved stable period. Our primary historical replay uses records sold in 2006–2008 for model training, 2009 for validation and monitoring reference, and 2010 as a simulated later serving batch. The sale-year field YrSold determines the chronological separation; it is not secretly added to the model’s six prediction inputs.

The code checks source columns and prints actual period counts when the OpenML download succeeds. Exact counts are not invented here. A year-long window can conceal seasonal shifts; real systems may prefer daily, weekly, monthly or rolling monitoring depending on traffic and sample size. Any reference should represent the population and prediction question the team intends to monitor.

The six historical housing features

The project keeps the six-feature schema established in Topics 91–93: GrLivArea, OverallQual, YearBuilt, TotalBsmtSF, GarageCars and FullBath. It also reads MoSold and YrSold as historical time metadata and SalePrice as the outcome for later retrospective performance evaluation. The source is OpenML Ames Housing dataset 42165, commonly described as containing 1,460 historical observations.

The dataset is historical and geographically specific. This is not current global real-estate monitoring or a professional valuation service. The model is deliberately incomplete: many property, neighborhood and market factors are excluded. A student should preserve the data dictionary, source provenance, available licence details, and model’s intended educational use.

Monitor data quality before statistical drift

Data quality checks should report missing-value counts, invalid ranges, type changes, unexpected field names, duplicates, empty batches, date conversion failures and unit mismatches. Even a visually persuasive distribution shift can come from faulty ingestion. For example, a broken square-feet conversion may multiply all areas by an incorrect factor, creating a large synthetic change that is not real population behaviour.

Do not delete unusual values simply because they are inconvenient: inspect source definitions and the reason they arose. For ordinal features such as house quality, allowed ratings are meaningful; for numerical area, nonnegative values and physical plausibility matter. Separate genuinely absent data from documented zeros and not-applicable values. Record both counts and percentages so a change in batch size does not create a misleading comparison.

Verified missing-rate arithmetic

Suppose a fictional reference batch contains 3 missing values among 100 records. Its missing rate is 3/100 × 100 = 3%. A fictional later batch contains 12 missing values among 100; the missing rate is 12%. The difference is 9 percentage points, while the relative change is (12−3)/3 × 100 = 300%. Confusing a nine-percentage-point change with a nine-percent relative increase would misstate the magnitude.

These are constructed classroom numbers, not Ames observations. In a real report, a feature’s actual missingness rate must be computed from the period-specific source data. A sudden increase could justify examining the data collection process before anyone decides to retrain a model.

Explore distributions with appropriate charts

Compare histograms of continuous features using the same units and bins; box plots of relative spreads; numerical medians, quantiles and standard deviations; bar charts for ordinal or categorical fields; and missingness by period. When the batch sizes differ, use proportions or normalized density rather than only raw counts. Charts must name the reference and current periods and make clear whether data are actual or simulated.

An attractive chart without an explicit source, denominator and unit can mislead. A bar that doubles in height may represent a larger batch instead of a higher proportion. Check the raw tables before drawing conclusions; a single unusual observation can strongly influence the mean while barely moving a median.

Population Stability Index: the formula and its meaning

Population Stability Index (PSI) is a binned distribution-change summary. For each corresponding bin, calculate (current proportion − reference proportion) × ln(current proportion/reference proportion), then add the results. The natural logarithm term captures how the relative weights of bins changed. Bins must be defined consistently and ordinarily based on the reference data, then applied without refitting to the current batch.

A PSI score does not measure the probability that a model failed, nor is it an automatically calibrated statistical test of model accuracy. Its value depends on the number and position of bins, sample size and handling of empty cells. Our source code documents a small smoothing constant for empty proportions. Thresholds such as 0.1 and 0.25 are sometimes quoted as rules of thumb, but they are not universal scientific laws.

A fully verified three-bin PSI calculation

Take fictional reference proportions (0.50, 0.30, 0.20) and current proportions (0.30, 0.40, 0.30). Bin 1 contributes (0.30−0.50)ln(0.30/0.50) ≈ 0.102165. Bin 2 contributes (0.40−0.30)ln(0.40/0.30) ≈ 0.028768. Bin 3 contributes (0.30−0.20)ln(0.30/0.20) ≈ 0.040547. Adding them gives PSI = 0.17147984. This calculation was checked in Python and its test passes.

The example establishes a binned distribution difference, not deterioration in model predictive accuracy. The project plots the same fictional proportions so that learners can connect the formula to a visible shift. It deliberately does not call that plot an authentic Ames Housing result.

Fictional binReference shareCurrent shareContribution
10.500.300.102165
20.300.400.028768
30.200.300.040547
Total1.001.000.171480
Original binned distribution-shift exercise, fictional reference and current proportions
Computed teaching chart using fictional bins; not measured Ames Housing drift.
import numpy as np
reference = np.array([0.50, 0.30, 0.20])
current = np.array([0.30, 0.40, 0.30])
psi = np.sum((current - reference) * np.log(current / reference))
print(round(float(psi), 8))  # 0.17147984

Why PSI needs careful interpretation

PSI can change when the choice of bin boundaries changes, especially for skewed or highly discrete features. Empty bins require an explicit policy because the logarithm of zero is undefined. A small sample can produce unstable bin proportions. Smoothing changes the statistic, so code and reports should document the rule instead of hiding it.

It is also possible for several correlated features to shift together. Counting six triggered PSI alerts as six independent failures may exaggerate one underlying change. A monitoring report should combine distributions, sample sizes, statistical tests, domain context and observed model errors when available.

The two-sample Kolmogorov–Smirnov test

The two-sample Kolmogorov–Smirnov (KS) statistic compares two empirical cumulative distributions and reports the largest absolute vertical difference: D = supₓ |F_reference(x) − F_current(x)|. For suitable independent continuous samples, a p-value evaluates evidence against the null hypothesis that the distributions are identical. A small p-value is evidence of a difference under the test’s assumptions, not a measure of price error or direct retraining need.

Our script applies scipy.stats.ks_2samp to approximately continuous area features when each sample has at least twenty valid observations. Ordinal quality ratings, garage-car counts and bathroom counts contain ties; standard continuous KS p-value assumptions do not cleanly apply to those variables. Their descriptive distributions are still reported, but the script does not present invalid discrete-feature p-values as fully calibrated.

from scipy.stats import ks_2samp
reference_values = reference_df["GrLivArea"].dropna().to_numpy()
current_values = current_df["GrLivArea"].dropna().to_numpy()
result = ks_2samp(
    reference_values, current_values,
    alternative="two-sided", method="auto"
)
print("KS D:", result.statistic)
print("p-value:", result.pvalue)
# Actual numbers require real historical reference/current data.

Statistical significance does not equal operational importance

If a system processes millions of observations, a tiny input change may become statistically significant without meaningfully changing model quality. Small monitoring samples may fail to detect changes that matter greatly. Statistical evidence is only one component: examine effect size, sample count, economic or safety consequences, model error and whether the reference period is appropriate.

Monitoring many features every day also creates multiple-comparison concerns. Under repeated testing, some low p-values arise by chance. A team may control false discoveries with an appropriate procedure or use pre-specified priority features and confirmation windows; no one correction solves every time-dependent monitoring problem. Never invent p-values or draw decisive failure claims from an extremely small batch.

What can be measured while true outcomes are delayed?

A model serving house-price estimates has immediate access to input properties and the estimates it generates. It may not know the actual sale price until a transaction has occurred and records become available. While labels are delayed, the team can measure missingness, schema failures, input distributions, prediction distributions, API availability and operational latency. None directly establishes historical pricing accuracy for the new batch.

For this historical exercise, monitor_model.py intentionally ignores SalePrice in the simulated 2010 monitoring stage. The separate evaluate_labels.py reveals that year’s labels only for a clearly identified retrospective test. Keeping these tasks separate helps students avoid the common mistake of treating predicted prices as if they were verified ground truth.

Monitor regression performance once labels arrive

When verified actual outcomes are available, regression monitoring may calculate MAE, the mean absolute difference; RMSE, the square root of mean squared error; and R², relative squared-error improvement over a constant mean reference. Inspect residual distributions and error by suitable population segment. For a classification service, other metrics such as precision, recall, F1, balanced accuracy, Average Precision and calibration may be more appropriate.

The metric must fit the task. The historical housing project reports regression error in the target’s original nominal US dollars, not percentages or modern inflation-adjusted prices. Sample sizes and evaluation conditions matter: an apparently poor later-year MAE could reflect a change in the target mix, an input error or different case difficulty as well as a changed relationship.

Verified performance-degradation arithmetic

Imagine a separate fictional system whose reference MAE is $20,000 and later MAE is $27,000. The absolute increase is $7,000. Relative to the reference, the increase is 7,000/20,000 × 100 = 35%. These values may justify investigation under a hypothetical policy, but they do not identify the cause of the change.

The numbers are mathematical teaching examples and are not obtained from the Ames Housing model. An operational alert should include the comparison period, sample size, confidence or variability consideration, model version and recommended next action. A thirty-five-percent rise is not an automatic instruction to replace the model.

How to build the real historical monitoring workflow

The downloadable project contains train_and_version.py, monitor_model.py, evaluate_labels.py and compare_candidates.py. Each script has a clearly limited responsibility. The first downloads OpenML 42165 and verifies source columns and year partitions; the second compares 2009 and 2010 features without reading later labels; the third evaluates the original model on actual later outcomes in a separate retrospective step; the fourth compares candidate metrics on the 2009 validation period.

Running the source in order produces versioned artifacts and reports only after real data are available. The project does not fabricate files under artifacts/champion_v1 or artifacts/challenger_v2. It also does not register aliases or schedule recurring checks in this task.

python -m venv .venv
python -m pip install -r requirements.txt pytest
python train_and_version.py
python monitor_model.py
python evaluate_labels.py   # Separate retrospective label reveal
python compare_candidates.py
python -m pytest -q

Train and version champion and challenger models

The offline training script creates two different Scikit-learn Pipelines. Both use training-only median imputation and a RandomForestRegressor. Champion v1 has 80 estimators and minimum leaf size 2; challenger v2 has 140 estimators and minimum leaf size 4. Both use random seed 94 and are trained using only 2006–2008 examples. Their predictions are compared against known 2009 outcomes using identical features and an identical evaluation metric.

These are candidate configurations, not a guarantee that v2 is better. The script saves each fitted Pipeline in its own version folder, records the actual validation MAE/RMSE/R², software versions, source dataset and SHA-256 checksum, then verifies that a trusted local reload reproduces predictions. A version name records identity rather than improvement.

Why model versioning matters

Imagine a teacher noticing an unexpected prediction during a demonstration. Without version information, it may be impossible to determine whether the value came from an old model, a new model, changed preprocessing or altered training data. A good version record contains the model identifier, training period, dataset source, ordered feature schema, hyperparameters, environment, evaluation metrics, saved artifact, approval and intended use.

Do not overwrite the previously approved file merely because another training script has finished. Separate directories and metadata create a basic auditable trail. A stored model’s checksum helps detect changes relative to recorded bytes; it does not by itself prove a file is safe when both checksum and binary are attacker-controlled.

MLflow: experiments, runs and model registries

MLflow supports experiment tracking and other model lifecycle workflows. An experiment can group related runs; each run may record parameters, metrics, artifacts, tags and links to a training dataset. A model registry can organize named models and versions. A registry is useful because a team should know not only what artifact exists, but who reviewed it and which one is approved for serving.

The current MLflow documentation supports model-version aliases such as champion, allowing a named reference to a registered version instead of relying on legacy stage conventions. A model URI such as models:/house-price-model@champion is an illustrative syntax example, not a URI actually created in this project. We did not install MLflow or create any experiment/run/alias here, so students must execute and verify those optional steps separately.

Model aliases do not automatically update a running server

Changing an MLflow alias may alter which version future registry lookups resolve. But a FastAPI process that already loaded a Pipeline into memory will usually continue using that object until its serving logic deliberately reloads it or the process is restarted/redeployed. A safe update plan must therefore include artifact verification, compatibility tests, controlled replacement and confirmation of the version actually returned to callers.

The alias mechanism is a convenience for model governance, not a complete deployment system. Only authorized operators should approve changes to which artifact is serving. A classroom exercise can use a metadata field to represent the approved model until the learner has a real registry and deployment workflow.

Evidently: richer monitoring reports

Evidently provides tools for data and model quality evaluation and structured reports. It can help compare reference and current data, examine distributions and create monitoring visualizations. The supported Python interfaces have changed across releases, so copying an old DataDriftPreset example with outdated Report.run() calls may fail on a current installation.

Evidently is optional for our core project, which calculates missingness, PSI and selected KS statistics with Pandas, NumPy and SciPy. Because Evidently was unavailable for installation and execution here, this article does not assert that an untested snippet generated a report. Learners should install a supported version, consult its current API reference, then validate a report using their actual historical datasets before publishing its results.

A safe simulation of changing input distributions

The project includes a synthetic input-shift exercise: copy the six-feature 2010 input table and multiply GrLivArea by 1.25. Compare this manipulated copy with the 2009 reference, and inspect how living-area medians and binned PSI change. This is useful for demonstrating whether the monitoring logic detects a deliberately introduced change.

It is essential that the exercise labels the modified data as synthetic. The original 2010 sale prices do not become valid labels for imaginary enlarged houses. You must not calculate supervised prediction accuracy using the modified features against the unchanged sale-price target and call it a real experiment. The manipulation is designed to test input drift detection only, not causal housing price effects.

A second simulation: increased missingness

Another controlled activity selects a documented fraction of later input rows and makes GarageCars missing. The final missingness rate may exceed the chosen injection percentage if the original data already contained missing values. Students should report the number newly modified, the original missing count and the resulting rate rather than assuming the final share is exactly the injection share.

This is an artificial data-quality problem, not a claim that historical Ames garage records were corrupted. A useful monitoring test should detect the problem, explain its likely operational consequence and recommend verifying the data source before initiating any retraining.

What a practical monitoring report should contain

A reproducible report begins with model version, source, reference period, current period, execution date, sample counts and feature schema. Data-quality sections show missingness, invalid values and changed fields. Distribution sections show medians, quantiles, histograms, selected PSI values and qualified statistical results. A prediction section describes median and spread of model outputs. Performance metrics appear only when suitable actual outcomes are available.

End the report with action categories: no action, investigate, repair a data pipeline, increase observation frequency, develop a challenger, pause a harmful feature or roll back a defective release. Report the evidence separately from an operator’s decision. A simulated report must not be represented as a live production dashboard.

Retraining is an option, not an alarm response

Retraining means fitting a model again using an explicit procedure and suitable data. Reasons to consider it include sustained, verified performance degradation, newly collected and validated outcomes, corrected labels, changed business processes or a newly justified modelling design. However, retraining can improve, worsen or barely change performance. It can also fail to address a root cause such as wrong feature units or a broken API.

The first question after an alert should therefore be What changed, and why? Inspect source quality, schema, deployment and the monitoring method before training a replacement. A future-labelled dataset used repeatedly to tune the challenger is no longer an untouched evaluation sample.

Build a conservative retraining decision policy

A classroom policy might call for investigation when labelled MAE increases more than 20% relative to an approved reference and the monitoring sample is sufficiently large. Separately, sustained changes in priority features, widespread schema errors or missing critical fields may trigger investigation. These percentages are illustrative policy choices—not universal industry thresholds—and should be adapted to actual risk, sample sizes and data quality.

Before approval, obtain representative labels, validate the new data, compare against the current model on exactly the same appropriate validation examples, inspect important subgroups, verify feature schema and latency, review artifact safety and prepare a rollback. A small apparent MAE gain by itself is not enough to conclude that a model is safer or better.

Champion–challenger comparison

The champion is the currently accepted model; a challenger is a candidate under review. A fair comparison evaluates both on the same 2009 validation records, which neither model used for training. The project captures validation MAE and an illustrative 2% relative improvement criterion, but deliberately sets automatically_promoted=False even when the candidate exceeds the threshold. Human review and operational tests remain necessary.

If challenger v2 looks worse on the agreed validation measure, it may be rejected. If it looks better, the investigation should extend to variability, subgroup performance, reliability, dependency compatibility and potential trade-offs. The 2010 outcomes are reserved for the separate retrospective evaluation and should not be repeatedly consulted for hyperparameter selection.

Model promotion, shadow releases and canaries

A controlled release verifies the candidate’s approved dataset provenance, reproducible artifact, schema, security, expected latency and rollback readiness. Shadow deployment gives a candidate copies of authorized traffic so it can generate predictions without controlling user-facing decisions; it helps inspect compatibility and latency but needs real outcomes for predictive accuracy estimates.

Canary deployment exposes a small, controlled share of suitable traffic to a new version while monitoring errors and consequences. It requires real routing and operational controls and may be inappropriate without strong safeguards in sensitive applications. This educational project describes both methods; it does not create actual traffic-splitting infrastructure.

Why rollback must be rehearsed

Rollback means restoring a previously approved model and compatible operational configuration when a new release introduces unacceptable problems. Keep the old trusted artifact, dependency versions, feature schema and deployment instructions. Confirm that the previous version still loads successfully, receives the expected six fields and produces valid responses. Record the event and any corrective action.

Changing an MLflow alias alone will not necessarily replace a model already loaded by a FastAPI worker. A real rollback may require restarting or redeploying processes, verifying readiness and repeating sample predictions. The provided rollback runbook is educational documentation, not evidence that a rollback was performed.

Connect monitoring to a FastAPI service

A monitored FastAPI service can record limited operational metadata such as request time, model version, HTTP status, processing duration and aggregate schema errors. Where permitted, approved and appropriately aggregated feature distributions can be analyzed without storing all raw individual requests. Inference latency should remain reasonable; complex monitoring reports can run outside the serving path.

Avoid collecting private addresses, personal identifiers, raw education records or authentication tokens unnecessarily. Appropriate privacy controls include access restrictions, documented retention, aggregation and security review. Monitoring logs reveal service behaviour, not automatically the correctness of a house-price model.

Service reliability is not predictive performance

Service monitoring tracks uptime, HTTP errors, request latency, CPU/memory pressure and failed model loads. Model monitoring tracks data quality, distribution shifts, output changes and accuracy when labels are available. A system can be responsive but statistically unreliable, or statistically strong but unavailable. An educational dashboard should keep these separate so that action owners can diagnose the correct problem.

Likewise, a model’s explanation values may drift even when overall error remains stable. Explanation drift is an advanced diagnostic, not a standalone measure of harmful behaviour. Start with reliable data and clearly defined predictions before adding sophisticated observability tools.

Monitoring dashboards and actionable alerts

A useful dashboard shows the approved model version, last known evaluation date, monitoring window, valid record count, missingness, important distribution comparisons, output medians, measured MAE if available, service error rate and open investigation items. Alert design should be actionable: each notice states what changed, when, how much, relevant sample size, model version and recommended investigation.

Avoid alerts that trigger on every small PSI fluctuation or transient traffic change. Too many false alarms teach operators to ignore warnings. A tiered policy might distinguish information, warning, high-priority incident and critical service/security incident. Assign an escalation owner and document the decision without automatically sending sensitive inputs through email or chat.

Automation does not mean uncontrolled retraining

Recurring monitoring can be scheduled with cron, an approved workflow orchestrator or a managed cloud scheduler. A job might ingest an authorized batch, validate it, compute statistics, save a report and notify an operator if thresholds and minimum sample sizes are met. That is different from replacing the active model every time a statistic exceeds a number.

Uncontrolled automated retraining risks using noisy labels, poisoned data, unrepresentative samples, incompatible software or an unsuitable candidate. A safer beginner pattern automates repeatable reporting while requiring documented evaluation and approval before promotion. No ongoing schedule or infrastructure has been configured by this article.

Security, fairness and responsible monitoring

Models can reinforce historical inequalities even when personal attributes are not explicit input fields. A geographic proxy or measurement process can create differences in error across groups. Where lawful, statistically meaningful and appropriate, evaluate subgroup reliability and monitor whether performance changes unevenly. Sparse subgroup samples require careful interpretation to avoid stigmatizing people based on noisy estimates.

Use only authorized data for monitoring, minimize personally identifiable information, define retention limits, protect model artifacts and restrict who can approve releases. SHA-256 checksums help detect changed files relative to metadata but cannot prove a file trustworthy if an attacker controls both. The historical Ames exercise is educational, not an authorized current property valuation system.

A ten-task capstone for a complete MLOps investigation

Tasks 1–3: verify OpenML dataset 42165 and year fields, count records per period, validate six predictor columns and fit the champion only on 2006–2008 labels. Tasks 4–5: evaluate the champion and challenger against 2009 validation labels, save independent versioned artifacts, and verify hashes and prediction reload consistency.

Tasks 6–8: compare 2009 reference inputs with 2010 simulated serving inputs without accessing 2010 sale-price labels; produce missingness, PSI, selected KS and prediction-distribution reports; simulate a 25% area shift and a documented missingness injection. Tasks 9–10: reveal 2010 outcomes only for clearly labelled retrospective evaluation, write a proposed retraining decision and promotion report, then complete a rollback runbook and explain why no real cloud scheduler or active release is present.

Thirty original practice questions and worked answers

Question 1: What does MLOps stand for?

Worked answer: Machine Learning Operations.

Question 2: Does successful training guarantee lasting model reliability?

Worked answer: No. Data, environments and outcome relationships can change.

Question 3: Name five monitoring dimensions.

Worked answer: Data quality, data drift, prediction behaviour, performance and service reliability.

Question 4: What does data drift compare?

Worked answer: Input feature distributions between selected reference and current samples.

Question 5: What does concept drift compare?

Worked answer: The relationship between features and actual outcomes across periods.

Question 6: Does prediction drift require current labels?

Worked answer: No; it compares the model’s outputs.

Question 7: Can target drift be measured without actual target labels?

Worked answer: Not as an observed target distribution.

Question 8: What is training–serving skew?

Worked answer: A mismatch in feature definitions or preprocessing between fitting and inference.

Question 9: What is the 2009 period used for in the project?

Worked answer: Validation and the historical reference distribution.

Question 10: What is the 2010 period used for?

Worked answer: Later simulated serving inputs, followed by separate retrospective label evaluation.

Question 11: Calculate 3 missing of 100.

Worked answer: 3%.

Question 12: Calculate 12 missing of 100.

Worked answer: 12%.

Question 13: Find the percentage-point change from 3% to 12%.

Worked answer: 9 percentage points.

Question 14: Find the relative increase from 3% to 12%.

Worked answer: (12−3)/3×100=300%.

Question 15: Write the PSI formula.

Worked answer: Σ(current share−reference share)ln(current share/reference share).

Question 16: Find PSI for reference .5,.3,.2 and current .3,.4,.3.

Worked answer: Approximately 0.17147984.

Question 17: Does PSI 0.1715 prove model failure?

Worked answer: No. It indicates binned distribution change under the chosen setup.

Question 18: What does the KS statistic measure?

Worked answer: The maximum absolute difference between two empirical cumulative distributions.

Question 19: Why avoid standard continuous KS p-values for bathroom counts?

Worked answer: The variable is discrete and includes many ties, violating continuous-distribution assumptions.

Question 20: Does a low KS p-value directly measure MAE?

Worked answer: No. It tests distribution equality under assumptions.

Question 21: What is missing when only predictions are available?

Worked answer: Ground truth needed to estimate predictive error.

Question 22: Find absolute MAE change from $20k to $27k.

Worked answer: $7,000.

Question 23: Find relative MAE increase from $20k to $27k.

Worked answer: 35%.

Question 24: Should you automatically retrain when input drift appears?

Worked answer: No; investigate data and actual performance first.

Question 25: What does MLflow track?

Worked answer: Experiments, runs, parameters, metrics, artifacts and model-lifecycle metadata.

Question 26: What does a model registry alias represent?

Worked answer: A named reference to a selected registered version, not automatic live redeployment.

Question 27: Why keep champion and challenger artifacts separate?

Worked answer: To compare reproducibly and preserve a rollback path.

Question 28: What is shadow deployment?

Worked answer: Running a candidate on copied authorized requests without using its outputs for live decisions.

Question 29: What is canary deployment?

Worked answer: A controlled limited release of a new version to selected eligible traffic.

Question 30: Why must 2010 labels not repeatedly select the challenger?

Worked answer: Doing so would contaminate the intended later independent evaluation period.

Eight critical-thinking scenarios

Scenario 1: Living-area values suddenly double; the API still responds.

First inspect units and ingestion; it may be training–serving skew rather than real drift.

Scenario 2: PSI is high but verified prediction MAE is stable.

Investigate the change; do not infer an automatic retraining need.

Scenario 3: Many p-values are below .05 after hundreds of tests.

Assess effect sizes and multiple-testing procedures instead of declaring hundreds of failures.

Scenario 4: Production labels are unavailable but predicted medians increased.

Report prediction drift, not proven target or concept drift.

Scenario 5: The challenger has slightly lower MAE but much worse critical-segment errors.

Do not promote automatically; require broader review.

Scenario 6: A new model artifact fails its checksum check.

Stop unsafe loading and investigate provenance.

Scenario 7: An MLflow alias now points to v2 while FastAPI still uses v1.

The running process may need controlled reload or redeployment and verification.

Scenario 8: Simulated 25% larger houses retain old sale-price labels.

Use the modified records for input-drift demonstrations only, not labelled performance evaluation.

Four-week student learning plan

Week 1: learn MLOps lifecycle, data drift, concept drift, target drift, prediction drift and training–serving skew. Calculate missingness examples and plot reference-versus-current distributions. Week 2: calculate PSI, interpret KS statistics, investigate sample sizes and multiple-testing problems, and generate data-quality reports using the supplied code.

Week 3: obtain the historical dataset, fit chronologically separated champion and challenger models, record versioned metadata, and evaluate only on the appropriate periods. Week 4: write a monitoring policy, evaluate labels retrospectively, justify a retraining decision, create a dashboard and propose safe approval and rollback steps.

Frequently asked questions

What is MLOps for beginners?

The practices of versioning, deploying, monitoring, evaluating and safely updating machine-learning systems.

How is data drift different from concept drift?

Data drift changes the input distribution; concept drift changes the conditional relationship between inputs and outcomes.

Can I monitor models without labels?

Yes, for input quality, input drift, prediction drift and service health, but not fully verified predictive error.

Should every drift alert trigger retraining?

No. Data repair, investigation or monitoring may be more appropriate.

Does a high PSI prove my model is wrong?

No. PSI is a bin-dependent distribution-change summary.

What does a KS p-value mean?

Evidence about equal distributions under the test’s assumptions, not a direct model failure probability.

What is MLflow?

A platform for tracking experiments and organizing model-lifecycle information.

What is Evidently?

A toolkit for data and AI quality monitoring reports, with version-dependent APIs.

What is a champion model?

The currently accepted model version.

What is a challenger model?

A candidate version undergoing evaluation.

Can a new version be worse?

Yes; new training or different parameters do not guarantee improved quality.

What is a rollback?

Restoring a previously approved and compatible operational state after an unacceptable release.

Does changing an MLflow alias immediately update FastAPI?

Not necessarily; a loaded process may need controlled reload or redeployment.

Were real Ames monitoring metrics computed in this article?

No. OpenML download was unavailable; the numerical demonstrations and tests use labelled fictional examples.

Is an automated monitoring schedule active?

No. The project provides scripts and policies but no configured recurring monitoring job.

Authoritative references and related Data Science lessons

Consult the MLflow documentation and model registry, Evidently docs, SciPy’s two-sample KS reference, Scikit-learn model evaluation, common pitfalls and the NIST AI Risk Management Framework. Technical guidance and libraries evolve, so verify version-specific methods in the environment where the project is run.

Within Notes for SHS, this lesson follows Topic 93: FastAPI Model Serving, Topic 92: Streamlit Deployment, Topic 91: Explainable AI, Topic 90: Feature Engineering, and Topic 88: Imbalanced Data.

Conclusion: trustworthy operations require evidence and restraint

A model that initially performed well does not stay suitable automatically. Input distributions, data definitions, operating systems and relationships with outcomes can change. MLOps provides a disciplined response: observe, verify, investigate, evaluate, compare, approve and maintain a path back to a trusted version. The most important practical lesson is that drift detection is a reason to ask questions, not an automatic instruction to retrain.

With the companion Python package, students can reproduce a carefully separated historical monitoring workflow once they have legitimate access to Ames Housing data. They can also complete the verified PSI calculation and test the decision framework immediately without any cloud infrastructure. Good engineering means reporting the boundaries of the evidence: the monitoring script exists and its mathematical tests pass, but it is not an operating production monitor until real source data, scheduled execution, approved deployment and continuing validation are established.

Companion package: The complete Topic 94 student ZIP contains Python scripts for versioning, monitoring, retrospective evaluation and champion–challenger comparison, automated tests, original charts, verified formula sheet, monitoring and retraining policies, an educational model card and a rollback runbook. It intentionally contains no fabricated trained Ames artifacts, no MLflow experiment IDs, no fake Evidently outputs and no supposed live monitoring history.