Last updated: 27 November 2026
A better machine learning pipeline is one you can rerun, trust and debug. It checks data before training, learns preprocessing only from training data, compares every new model with a baseline, serves predictions with the same logic used in training, and tells you when something drifts.
You do not need a large platform to get there. Start by fixing correctness, then add automation where it saves real work. This guide follows that order, with a Python example you can adapt.
What a machine learning pipeline includes
The term has two common meanings. In a library such as scikit-learn, a Pipeline chains preprocessing steps and a model into one object. In MLOps, a pipeline is the whole workflow that turns raw data into a monitored prediction service.
Google Cloud’s MLOps guide breaks that workflow into data extraction, analysis, preparation, training, evaluation, validation, serving and monitoring. A good design uses both meanings: a model-level pipeline inside a system-level one.

Start with a simple, testable baseline
Google’s Rules of Machine Learning advise keeping the first model simple and getting the infrastructure right. They also recommend testing the infrastructure separately from the learning.
Before choosing algorithms, write down:
- The prediction moment: when is the prediction made, and which data exists at that instant?
- The target: how is the label defined, and how long until you know it?
- The metric: which score reflects the cost of being wrong?
- The baseline: what would a rule, a constant prediction or the current model achieve?
- Freshness: how quickly does quality fall as the model ages?
Then run a plain model end to end. An early working path exposes broken joins, missing fields and deployment limits while they are still cheap to fix.
Validate data before training on it
Bad data often fails quietly. A stale table or a feature that is suddenly half empty may raise no error while model quality slowly drops. Make these problems loud.
- Schema: expected columns, types and allowed categories.
- Values: ranges, missing-value rates and duplicate keys.
- Volume and freshness: row counts and the newest timestamp.
- Distribution: large changes compared with a reference window.
Treat failures differently. Google Cloud’s guidance says schema skew should stop the pipeline for investigation, while significant changes in data values should trigger retraining. In practice, confirm that a shift is real and not an upstream bug before retraining on it.
Prevent data leakage
Leakage happens when model building uses information that will not be available at prediction time. Offline scores look excellent, then production results disappoint.
The core rules from the scikit-learn documentation are straightforward:
- Split the data before fitting any preprocessing.
- Never call
fitorfit_transformon test data. - Put preprocessing inside a
Pipeline, so each cross-validation fold fits it on that fold’s training rows only.
The documentation shows why with purely random data, where honest accuracy should be about 0.5. Selecting features on the full dataset before splitting produced 0.76. Selecting them from the training data alone brought the score back to 0.5.
If you oversample or undersample an imbalanced dataset, keep that step inside the pipeline too. The imbalanced-learn library provides a pipeline that handles resampling for this purpose.
Choose a split that matches reality
| Situation | Split approach | Risk it reduces |
|---|---|---|
| Independent rows, no time effect | Random or stratified folds | Unrepresentative test sets |
| Many rows per customer, patient or device | Group-based split | The same entity appearing on both sides |
| Predicting future events | Time-ordered split | Learning from the future |
The Rules of Machine Learning make the time case concrete: if a model uses data up to January 5th, test it on data from January 6th onward. Also check that each feature’s value was actually known at the prediction moment. A pipeline object cannot detect a column that was filled in after the outcome.
A practical pipeline example
This example uses synthetic, hypothetical churn data. It validates input, splits by time, keeps preprocessing with the model, tunes one setting, applies a quality gate and saves metadata. It has not been tested here.
import json
import sys
import joblib
import numpy as np
import pandas as pd
import sklearn
from sklearn.compose import ColumnTransformer
from sklearn.dummy import DummyClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
NUM = ["monthly_spend", "support_tickets"]
CAT = ["plan"]
def make_data(n=3000, seed=0):
rng = np.random.default_rng(seed)
df = pd.DataFrame({
"snapshot_date": pd.date_range("2024-01-01", periods=n, freq="6h"),
"monthly_spend": rng.gamma(2.0, 30.0, n),
"support_tickets": rng.poisson(1.5, n),
"plan": rng.choice(["basic", "pro", "team"], n),
})
logit = -2 + 0.6 * df["support_tickets"] - 0.01 * df["monthly_spend"]
df["churned"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
df.loc[rng.random(n) < 0.05, "monthly_spend"] = np.nan
return df
def validate(df):
required = set(NUM + CAT + ["snapshot_date", "churned"])
missing = required - set(df.columns)
if missing:
raise ValueError(f"Missing columns: {missing}")
if (df["monthly_spend"] < 0).any():
raise ValueError("Negative spend")
if df["monthly_spend"].isna().mean() > 0.10:
raise ValueError("Too many missing spend values")
if not df["plan"].isin(["basic", "pro", "team"]).all():
raise ValueError("Unknown plan")
df = make_data()
validate(df)
df = df.sort_values("snapshot_date")
cut = int(len(df) * 0.8)
train, test = df.iloc[:cut], df.iloc[cut:]
X_train, y_train = train[NUM + CAT], train["churned"]
X_test, y_test = test[NUM + CAT], test["churned"]
numeric = Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
])
prep = ColumnTransformer([
("num", numeric, NUM),
("cat", OneHotEncoder(handle_unknown="ignore"), CAT),
])
pipe = Pipeline([
("prep", prep),
("model", LogisticRegression(max_iter=1000)),
])
search = GridSearchCV(
pipe,
{"model__C": [0.1, 1.0, 10.0]},
cv=TimeSeriesSplit(n_splits=5),
scoring="average_precision",
)
search.fit(X_train, y_train)
baseline = DummyClassifier(strategy="prior").fit(X_train, y_train)
def score(model):
return average_precision_score(y_test, model.predict_proba(X_test)[:, 1])
new_score, base_score = score(search), score(baseline)
if new_score < base_score + 0.05:
sys.exit("Quality gate failed: model not saved")
joblib.dump(search.best_estimator_, "model.joblib")
with open("model_meta.json", "w") as f:
json.dump({
"sklearn_version": sklearn.__version__,
"features": NUM + CAT,
"train_end": str(train["snapshot_date"].max()),
"cv_score": float(search.best_score_),
"test_score": float(new_score),
"baseline_score": float(base_score),
}, f, indent=2)
The 0.05 margin and 10% missing-value limit are illustrative. Set yours from business needs and observed variation. If you keep changing the model until it passes the same test window, that window is no longer an unbiased check. Use a separate validation period for decisions and refresh the final holdout.
Make runs reproducible
For each run, record the code version, data snapshot, parameters, dependency versions, metrics and output location. This lets you trace a prediction problem to its cause and roll back to an earlier model.
Set random seeds deliberately. In scikit-learn, an integer random_state repeats results across calls, and integers are usually the safest choice for cross-validation splitters. For estimators, the documentation notes that passing a NumPy RandomState instance can give a better view of robustness across folds.
Save models safely
- joblib or pickle: convenient, but loading a file can execute arbitrary code. Load only files you trust.
- skops: a more secure option that lets you inspect untrusted types before loading.
- ONNX: serves predictions without the Python object, though not every model is supported.
Loading a scikit-learn model under a different library version is unsupported. Pin dependencies or ship the same container to training and serving.
Avoid training-serving skew
Skew is a gap between how a model behaves in training and in live use. Different feature code, changing lookup tables and shifting data can all contribute.
- Reuse the same transformation code in training and serving where possible.
- Log the features used at serving time and use those logs for later training.
- Be careful with joins to tables that change between training and serving.
- Test that the same input gets the same score in both environments.
A feature store can help larger teams define features once and use them in both places. It adds operational work, so adopt it when reuse or consistency problems justify it.
Automate in stages and monitor
Google Cloud describes three MLOps maturity levels. They are a useful roadmap, not a score you must maximize.
| Level | How it works | Next improvement |
|---|---|---|
| 0: Manual | Script or notebook steps, manual handoffs, infrequent releases | Turn steps into modular, repeatable code |
| 1: Pipeline automation | Automated training with data and model validation, triggers and metadata | Automate building, testing and deploying pipeline code |
| 2: CI/CD automation | Pipeline changes are tested and deployed automatically | Refine tests, monitoring and release controls |
Retraining can run on demand, on a schedule, when new data arrives, when performance falls or when distributions shift. Whatever the trigger, the new model should pass the same gates.
Before full release, compare it with the current model overall and across important segments. Then use a canary release or A/B test. In production, monitor input quality, prediction distributions, latency, errors and, once labels arrive, real accuracy. Give every alert an owner and a response.
Common mistakes and troubleshooting
| Symptom | Likely cause | What to check |
|---|---|---|
| Suspiciously high offline score | Leakage | Feature timestamps, preprocessing before the split, duplicate entities |
| Good cross-validation, weak later data | Wrong split or changing data | Time-ordered evaluation and recent distributions |
| Good next-day test, weak live results | Often an engineering discrepancy | Serving features, defaults, joins and code paths |
| Serving fails on a new category | Encoder or validator rejects it | Decide whether to ignore, map or block unknown values |
| Results differ between runs | Unfixed randomness or changed inputs | Seeds, data snapshot and dependency versions |
Note that the example blocks unknown plans during training validation, while its encoder ignores unknown values at prediction time. That can be a reasonable policy, but log those cases so they do not go unnoticed.
Hands-on exercise
- Run the example and read the metadata file.
- Set 30% of
monthly_spendto missing before validation. Confirm that the run stops. - Add a leaking column, such as a noisy copy of
churned, to the data and toNUM. Watch how the score changes, then explain why the quality gate cannot catch this. - Write a test that loads the saved model and checks that its probabilities match the in-memory model for the same rows.
- Add a check that rejects data whose newest date is older than a limit you choose.
FAQ
What is the most important improvement to make first?
Check for leakage and confirm that your evaluation resembles real use. Automating a flawed evaluation only produces misleading results faster.
Do I need an orchestration tool?
Not at the start. A versioned script run by a simple scheduler can be enough. An orchestrator becomes useful when you have dependent steps, retries, several models or a need to resume failed runs.
How often should a model be retrained?
There is no universal interval. Measure how performance changes with model age, and weigh that against data availability and retraining cost.
Does a scikit-learn Pipeline cover MLOps?
No. It keeps preprocessing and modeling consistent. Data validation, release controls, serving and monitoring still need to be built around it.