Skip to main content

12 - End-to-End ML Pipeline: From Dataset to Production

Chain validation, a shared pipeline, baseline comparison, a saved artifact, a FastAPI service and drift checks into one churn system, tried step by step.

What do you think about this article?

At a Glance

Chain validation, a shared pipeline, baseline comparison, a saved artifact, a FastAPI service and drift checks into one churn system, tried step by step.

A model in a notebook is not yet a system

A model that works in a notebook has solved the most visible problem, not the hardest one. To really use it you need data checked before training, the same transformations in training and in serving, an honest comparison among candidates, a saved artifact that someone can load, an interface that rejects wrong inputs and an eye on the data that arrive after launch. Sculley and colleagues, in a Google paper on the technical debt of Machine Learning systems, show that only a small fraction of the code of a real system is learning code, and observe that a mature system might end up being, at most, 5% Machine Learning code and at least 95% glue code. This article builds the whole chain on a concrete case, the prediction of customer churn of an operator, with listings that run one after the other. It takes up the techniques of the previous stages: preprocessing in a pipeline, metrics for imbalanced classes and the choice among models.

The data are synthetic: the first listing generates them, with a relationship that I chose (churn grows with price and with support calls, falls with tenure and with long contracts). I do not have a real customer dataset and I do not simulate a fake one presenting it as real. Two things follow to keep in mind: simple models are not "better" in general if they win here, and the numbers are not the expected performance of any real system. The value of the exercise is the structure, not the figure.

StageWhere in the codeWhat it prevents
Data validationvalida() in churn_lib.pyTraining on missing columns, impossible values, unknown categories
Preprocessing and featurescostruisci_pipeline()Different transformations between training and serving
Comparison and choicetraining listingChoosing a model without a baseline or dispersion
Savingjoblib.dumpLosing the version, or saving the model without its preprocessing
ServingFastAPI listingAnswering malformed requests as if they were valid
Monitoringdrift listingNot noticing that the real data no longer resemble the training data

Data, validation and preprocessing in a single module

The first file, churn_lib.py, is shared by training, serving and monitoring, and it is the cheapest countermeasure to training-serving skew, the divergence between what the model saw and what it sees in production: if the same function does the transformations in both places, they cannot diverge. It contains four things. genera creates the synthetic customers. valida returns a list of errors, which stop the pipeline, and one of warnings, which let it proceed. FeatureEngineer is a custom transformer that adds the total spend and a tenure group; its fit does nothing because it learns nothing from the data, but it must exist to respect the interface. costruisci_pipeline joins features, imputation, scaling, one-hot and model into a single object, so fit and predict run the whole chain.

Python - churn_lib.py: synthetic data, validation and pipeline
"""churn_lib.py - data, validation and preprocessing shared by training, serving and monitoring."""
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

COLONNE = ["tenure", "monthly_charges", "support_calls", "contract", "payment_method"]
NUMERICHE = ["tenure", "monthly_charges", "support_calls", "total_spent"]
CATEGORICHE = ["contract", "payment_method", "tenure_group"]

def genera(n, seed, spostamento_prezzi=0.0):
    """Synthetic customers of an operator: churn really depends on tenure, price, support and contract."""
    rng = np.random.default_rng(seed)
    df = pd.DataFrame({
        "tenure": rng.integers(0, 73, n),                                   # months of tenure
        "monthly_charges": np.round(np.clip(rng.normal(65, 25, n), 18, 120) + spostamento_prezzi, 2),
        "support_calls": rng.poisson(1.5, n),
        "contract": rng.choice(["mensile", "annuale", "biennale"], n, p=[0.55, 0.25, 0.20]),
        "payment_method": rng.choice(["carta", "bonifico", "bollettino"], n),
    })
    z = (-0.5 + 0.02 * (df["monthly_charges"] - 65) - 0.04 * df["tenure"] + 0.35 * df["support_calls"]
         + np.where(df["contract"] == "mensile", 1.0, 0.0) - np.where(df["contract"] == "biennale", 0.8, 0.0))
    df["churn"] = (rng.random(n) < 1 / (1 + np.exp(-z))).astype(int)
    df.loc[rng.random(n) < 0.03, "monthly_charges"] = np.nan                # 3% of the prices are missing
    return df

def valida(df):
    """Returns (errors, warnings). Errors stop the pipeline, warnings do not."""
    errori, avvisi = [], []
    mancanti = set(COLONNE) - set(df.columns)
    if mancanti:
        return [f"missing columns: {sorted(mancanti)}"], avvisi
    if (df["tenure"] < 0).any():
        errori.append(f"negative tenure in {int((df['tenure'] < 0).sum())} rows")
    if not pd.api.types.is_numeric_dtype(df["monthly_charges"]):
        errori.append("monthly_charges is not numeric")
    elif (df["monthly_charges"] <= 0).any():
        errori.append("monthly_charges <= 0")
    nuovi = set(df["contract"].dropna()) - {"mensile", "annuale", "biennale"}
    if nuovi:
        errori.append(f"unknown contracts: {sorted(nuovi)}")
    quota_null = df[COLONNE].isnull().mean()
    for colonna in quota_null[quota_null > 0.30].index:
        avvisi.append(f"{colonna}: {quota_null[colonna]:.0%} of missing values")
    if df.duplicated().sum():
        avvisi.append(f"{int(df.duplicated().sum())} duplicate rows")
    return errori, avvisi

class FeatureEngineer(BaseEstimator, TransformerMixin):
    """Creates the derived columns. It learns nothing from the data, so fit does nothing."""
    def fit(self, X, y=None):
        return self
    def transform(self, X):
        df = X.copy()
        df["total_spent"] = df["tenure"] * df["monthly_charges"]
        gruppi = pd.cut(df["tenure"], bins=[-1, 12, 24, 48, np.inf], labels=["nuovo", "in crescita", "maturo", "fedele"])
        df["tenure_group"] = gruppi.astype(str)
        return df

def costruisci_pipeline(modello):
    numeriche = Pipeline([("imputa", SimpleImputer(strategy="median")), ("scala", StandardScaler())])
    categoriche = Pipeline([("imputa", SimpleImputer(strategy="most_frequent")),
                            ("codifica", OneHotEncoder(handle_unknown="ignore"))])
    prep = ColumnTransformer([("num", numeriche, NUMERICHE), ("cat", categoriche, CATEGORICHE)])
    return Pipeline([("features", FeatureEngineer()), ("prep", prep), ("modello", modello)])

if __name__ == "__main__":
    df = genera(2000, seed=0)
    print("churn rate:", round(df["churn"].mean(), 3), "- missing prices:", int(df["monthly_charges"].isnull().sum()))
    print("healthy data ->", valida(df))
    rotto = df.copy()
    rotto.loc[0, "tenure"] = -3
    rotto.loc[1, "contract"] = "trimestrale"
    print("broken data  ->", valida(rotto))
    print("missing column ->", valida(df.drop(columns=["contract"])))

    # The bins trap: with bins=[0, 12, 24, 48, 72] whoever has tenure 0 or more than 72 months becomes NaN
    ingenuo = pd.cut(df["tenure"], bins=[0, 12, 24, 48, 72], labels=["nuovo", "in crescita", "maturo", "fedele"])
    print("customers without a group with the naive bins:", int(ingenuo.isnull().sum()), "out of", len(df))
    print("customers without a group with FeatureEngineer:", int((FeatureEngineer().transform(df)["tenure_group"] == "nan").sum()))

# Output:
# churn rate: 0.29 - missing prices: 49
# healthy data -> ([], ['2 duplicate rows'])
# broken data  -> (['negative tenure in 1 rows', "unknown contracts: ['trimestrale']"], ['2 duplicate rows'])
# missing column -> (["missing columns: ['contract']"], [])
# customers without a group with the naive bins: 29 out of 2000
# customers without a group with FeatureEngineer: 0

The final block runs three tests. On healthy data the validation finds no errors and reports 2 duplicate rows as a simple warning. On a copy ruined by hand (a tenure of -3 months and a "trimestrale" (quarterly) contract that the system does not know) it lists exactly the two errors; removing a whole column, it stops immediately with "missing columns". The last test concerns a subtle error, common in examples online: grouping tenure with pd.cut(bins=[0, 12, 24, 48, 72]) leaves customers with zero tenure (and anyone beyond 72 months) without a group, because the intervals of cut are open on the left. Out of 2000 customers, 29 receive NaN with the naive bins, 0 with those of FeatureEngineer (-1 as the left end and infinity as the right). It is not an error that Python reports: the wrong group slips into imputation and the model trains anyway.

Comparing candidates and choosing without fooling yourself

The second file trains. It refuses to start if the validation finds errors (the line assert not errori), sets aside 25% of the data as the test set and leaves it closed, and compares four candidates with a five-fold cross-validation on the training set only: a baseline that predicts the churn frequency, logistic regression, a random forest and a gradient boosting. Each candidate is inside the same pipeline, so imputation and scaling are recomputed in each fold. The experiment log is a JSON Lines file in a temporary folder: one row per candidate, with the scores. Tools such as MLflow do the same with an interface and a persistent store; here it is not installed and I do not use it, but the idea to keep is this, that every experiment leaves a re-readable row. At the end the chosen model is retrained on the training set, evaluated once on the test set and saved with joblib together with the version and the expected columns.

Python - Training: validation, baseline, comparison, test and saving
import json
import tempfile
import joblib
import numpy as np
import sklearn
from sklearn.dummy import DummyClassifier
from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, roc_auc_score
from sklearn.model_selection import StratifiedKFold, cross_validate, train_test_split

from churn_lib import COLONNE, costruisci_pipeline, genera, valida

df = genera(4000, seed=1)
errori, avvisi = valida(df)
assert not errori, errori                                    # the pipeline stops if the data are broken

X, y = df[COLONNE], df["churn"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)

candidati = {
    "baseline (most frequent class)": DummyClassifier(strategy="prior"),
    "logistic regression": LogisticRegression(max_iter=1000),
    "random forest": RandomForestClassifier(n_estimators=200, min_samples_leaf=5, random_state=0),
    "gradient boosting": HistGradientBoostingClassifier(random_state=0),
}
registro = tempfile.NamedTemporaryFile("w", suffix=".jsonl", delete=False)     # an append-only log of the experiments
risultati = {}
for nome, modello in candidati.items():
    r = cross_validate(costruisci_pipeline(modello), X_train, y_train, cv=cv, scoring=["roc_auc", "average_precision"])
    risultati[nome] = r["test_roc_auc"].mean()
    registro.write(json.dumps({"modello": nome, "roc_auc": round(risultati[nome], 4),
                               "average_precision": round(r["test_average_precision"].mean(), 4)}) + "\n")
    print(f"{nome:32s} ROC-AUC {risultati[nome]:.3f} (+/- {r['test_roc_auc'].std():.3f})   AP {r['test_average_precision'].mean():.3f}")
registro.close()
print("rows in the experiment log:", sum(1 for _ in open(registro.name)))

migliore = max((n for n in risultati if "baseline" not in n), key=risultati.get)
finale = costruisci_pipeline(candidati[migliore]).fit(X_train, y_train)
p = finale.predict_proba(X_test)[:, 1]
print(f"chosen in cross-validation: {migliore}")
print(f"never-seen test set: ROC-AUC {roc_auc_score(y_test, p):.3f}   average precision {average_precision_score(y_test, p):.3f}   (churn rate: {y_test.mean():.3f})")

joblib.dump({"pipeline": finale, "versione_modello": "1.0.0", "sklearn": sklearn.__version__, "colonne": COLONNE},
            "churn_model.joblib")

# Output:
# baseline (most frequent class)   ROC-AUC 0.500 (+/- 0.000)   AP 0.297
# logistic regression              ROC-AUC 0.784 (+/- 0.018)   AP 0.616
# random forest                    ROC-AUC 0.757 (+/- 0.023)   AP 0.568
# gradient boosting                ROC-AUC 0.732 (+/- 0.021)   AP 0.539
# rows in the experiment log: 4
# chosen in cross-validation: logistic regression
# never-seen test set: ROC-AUC 0.804   average precision 0.619   (churn rate: 0.297)

The baseline gets ROC-AUC 0.500 (no ability to rank) and average precision 0.297, that is the share of customers who leave: it is the floor. Logistic regression reaches 0.784 with a standard deviation of 0.018 and wins; the random forest follows at 0.757 and the gradient boosting at 0.732. The simplest model wins because I generated the data with a logistic relationship, so it is by construction the right model: on real data the order could be the opposite, and that is why the comparison is made. The difference between regression and random forest, 0.027, is about one and a half standard deviations: indicative, not proof. On the never-seen test set the regression gets 0.804, within the dispersion of the cross-validation, which is what you want to see: no surprise. The saved file contains the whole pipeline, not just the classifier, and it is the reason why the service will not have to redo any transformation by hand.

A precaution about the artifact. The scikit-learn guide on persistence warns that pickle-based formats, joblib included, allow arbitrary code execution at load time, so a model file must be loaded only if it comes from a trusted source, and that reloading it with a different version of scikit-learn can produce wrong results or errors. That is why the listing saves the scikit-learn version next to the model; the guide suggests skops.io when the security risk matters, and ONNX when a Python-independent format is needed.

Serving the model: rejecting wrong data before it reaches the model

The third file is the interface. FastAPI uses pydantic models to validate requests: the Cliente class declares types and constraints (ge=0 for tenure, gt=0 for price), and for the categories a Literal with only the known values. The model is loaded once at module startup, not on every request. The listing does not start a server: it uses FastAPI's TestClient, which calls the application in-process, to try five requests, two valid and three wrong. It needs the packages fastapi, pydantic and httpx, present here (FastAPI 0.136.3, pydantic 2.13.4, httpx 0.28.1); to really expose it you would start it with uvicorn, which I did not start.

Python - FastAPI service with validation, tested without a server
import joblib
import pandas as pd
from fastapi import FastAPI
from fastapi.testclient import TestClient
from typing import Literal

from pydantic import BaseModel, Field

from churn_lib import COLONNE

pacchetto = joblib.load("churn_model.joblib")                 # loaded once at startup, not on every request
pipeline = pacchetto["pipeline"]

class Cliente(BaseModel):
    tenure: int = Field(ge=0, le=600)
    monthly_charges: float = Field(gt=0)
    support_calls: int = Field(ge=0)
    contract: Literal["mensile", "annuale", "biennale"]           # a different value is rejected with 422
    payment_method: Literal["carta", "bonifico", "bollettino"]

app = FastAPI(title="Churn API")

@app.post("/predict")
def predici(cliente: Cliente):
    riga = pd.DataFrame([cliente.model_dump()])[COLONNE]
    p = float(pipeline.predict_proba(riga)[0, 1])
    return {"churn_probability": round(p, 3), "model_version": pacchetto["versione_modello"]}

# In-process test, without starting a server
client = TestClient(app)
fedele = {"tenure": 60, "monthly_charges": 40.0, "support_calls": 0, "contract": "biennale", "payment_method": "carta"}
a_rischio = {"tenure": 2, "monthly_charges": 100.0, "support_calls": 5, "contract": "mensile", "payment_method": "bollettino"}
for nome, corpo in (("loyal customer", fedele), ("at-risk customer", a_rischio)):
    r = client.post("/predict", json=corpo)
    print(nome, "->", r.status_code, r.json())

r = client.post("/predict", json={**fedele, "tenure": -4})
print("negative tenure ->", r.status_code, r.json()["detail"][0]["msg"])
r = client.post("/predict", json={k: v for k, v in fedele.items() if k != "contract"})
print("missing field ->", r.status_code, r.json()["detail"][0]["msg"])
r = client.post("/predict", json={**fedele, "contract": "trimestrale"})
print("contract never seen ->", r.status_code, r.json()["detail"][0]["msg"])

# Output:
# loyal customer -> 200 {'churn_probability': 0.015, 'model_version': '1.0.0'}
# at-risk customer -> 200 {'churn_probability': 0.941, 'model_version': '1.0.0'}
# negative tenure -> 422 Input should be greater than or equal to 0
# missing field -> 422 Field required
# contract never seen -> 422 Input should be 'mensile', 'annuale' or 'biennale'

The loyal customer (60 months, two-year contract, no calls) gets a churn probability of 0.015; the at-risk one (2 months, 100 euros, 5 calls, monthly contract) of 0.941. The three wrong requests all produce 422 before touching the model: negative tenure, missing field, "trimestrale" (quarterly) contract. The constraint on the contract is not a detail. Trying first with contract: str, the request with "trimestrale" went through with code 200 and probability 0.033: the encoder is configured with handle_unknown="ignore", so an unknown category becomes a row of zeros and the model answers confidently to a question it does not know. The tolerance of the encoder serves not to crash in production, and must be accompanied by a validation that warns you, not used in its place. The response also contains the model version, which in production lets you know which artifact produced a prediction.

Monitoring: data drift, and why it does not coincide with a performance drop

After launch the data change. We distinguish data drift, that is the distribution of the inputs shifting with respect to training, from concept drift, that is the relationship between input and outcome changing. For the first, distributions are compared with two tools. The two-sample Kolmogorov-Smirnov test (scipy.stats.ks_2samp) measures the maximum distance between the two cumulative distributions and gives a p-value. The Population Stability Index (PSI) divides the axis into bins based on training and sums the logarithmic differences between the shares of data; it is a commonly used index for comparing distributions, and the threshold of 0.25 often cited as a "relevant shift" is an industry convention, not a mathematical property. The listing simulates a month later, with prices up by 15 euros, and computes both indexes on the three numeric variables.

Python - Drift with PSI and Kolmogorov-Smirnov, and performance compared
import joblib
import numpy as np
from scipy.stats import ks_2samp
from sklearn.metrics import roc_auc_score

from churn_lib import COLONNE, genera

pipeline = joblib.load("churn_model.joblib")["pipeline"]
riferimento = genera(3000, seed=1)                                   # the data the model was trained on (same generator)
produzione = genera(3000, seed=7, spostamento_prezzi=15.0)           # a month later: prices have risen by 15 euros

def psi(atteso, osservato, bin=10):
    """Population Stability Index: how much the observed distribution has shifted compared with the expected one."""
    tagli = np.nanpercentile(atteso, np.linspace(0, 100, bin + 1)[1:-1])
    a = np.bincount(np.searchsorted(tagli, atteso[~np.isnan(atteso)]), minlength=bin) / np.sum(~np.isnan(atteso))
    o = np.bincount(np.searchsorted(tagli, osservato[~np.isnan(osservato)]), minlength=bin) / np.sum(~np.isnan(osservato))
    a, o = np.clip(a, 1e-4, None), np.clip(o, 1e-4, None)
    return float(np.sum((o - a) * np.log(o / a)))

print("variable          PSI    KS      p-value")
for colonna in ("tenure", "monthly_charges", "support_calls"):
    a, o = riferimento[colonna].to_numpy(float), produzione[colonna].to_numpy(float)
    ks = ks_2samp(a[~np.isnan(a)], o[~np.isnan(o)])
    print(f"{colonna:16s} {psi(a, o):6.3f}  {ks.statistic:.3f}  {ks.pvalue:.2g}")

for nome, d in (("reference", riferimento), ("production", produzione)):
    p = pipeline.predict_proba(d[COLONNE])[:, 1]
    print(f"{nome:11s}: ROC-AUC {roc_auc_score(d['churn'], p):.3f}   mean predicted probability {p.mean():.3f}   observed churn {d['churn'].mean():.3f}")

# Output:
# variable          PSI    KS      p-value
# tenure            0.004  0.011  0.99
# monthly_charges   0.353  0.242  1.9e-75
# support_calls     0.000  0.008  1
# reference  : ROC-AUC 0.774   mean predicted probability 0.306   observed churn 0.320
# production : ROC-AUC 0.798   mean predicted probability 0.350   observed churn 0.367

The drift is very clear on prices: PSI 0.353, KS 0.242 with a p-value of 10^-75, while tenure and support calls are stable (PSI close to zero). The KS test with 3000 points recognizes tiny differences: the p-value tells you that there is a difference, not that it is important, so it is the size (0.242) that you should look at. The most useful observation is in the last two lines. The data drift is there, but performance has not worsened: the ROC-AUC is 0.798 against 0.774, and the mean predicted probability (0.350) follows the observed churn rate (0.367). The model changed its prediction because prices are higher and higher prices, in the data, mean more churn, exactly as it had learned. A drift alarm is therefore a reason to look, not to retrain automatically. There is also a structural delay: to know whether a customer has really left takes months, so real performance arrives late and the tests on the inputs are the signal you get immediately. A true concept drift, for example a competitor giving away the first year, would only be seen in the labels that arrived later.

The signals to keep under control before putting a model into production are few, and none requires heavy tools. The list is not in order of importance and can be read in any order.

  • Training data versioned and reproducible, with the seed fixed where needed
  • Input validation upstream, in training and in serving
  • Baseline and dispersion reported next to every score
  • Artifact saved with model version and library version
  • Distribution of inputs and predictions recorded over time
  • A procedure to go back to the previous version

Each of these items prevents a kind of failure you have seen in this article: wrong data accepted (validation), change of preprocessing between training and serving (shared module), apparent victory of a model (baseline and dispersion), version incompatibility (artifact metadata), unnoticed degradation (distributions over time) and no way back (previous version). Data versioning is done with dedicated tools (DVC and the like), tracking with MLflow, data quality with specific libraries, and the choice depends on the size of the project; none of these packages is installed here and I did not run them. I also did not containerize the service: a container packages your environment, but it fixes none of the problems above.

What you can do now

You can build a chain in which every step can stop with a clear error: data validated before training, requests validated before prediction. You can compare several candidates against a baseline with cross-validation, keep the test set closed until the end and save an artifact that contains both the preprocessing and the model, with its version. You can serve it with FastAPI rejecting out-of-contract input and you can tell a data drift from a real drop in performance. This is the conclusion of the series: if you want to start again from the beginning, the map of the paradigms is in the introduction.

Starting from a pre-trained model is the alternative to training from scratch: see transfer learning before deciding what to serve.

Frequently asked questions

Why save the whole pipeline and not just the model?

Because the model was trained on transformed data: if in serving the preprocessing is redone by hand, a single difference is enough to get wrong predictions. By saving the Pipeline, imputation, scaling and one-hot travel with the classifier.

Does a data drift alarm require retraining right away?

No. In the example prices rise by 15 euros (PSI 0.353) but the ROC-AUC stays 0.798 and the predictions follow the real churn rate. Data drift is a reason to investigate; retraining is decided on performance, when the labels arrive.

Is it safe to load a model saved with joblib?

Only if the source is trusted: pickle-based formats allow arbitrary code execution at load time. The scikit-learn guide indicates skops.io as an alternative when security matters.

Sources

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects