Your First End-to-End Model
Read a little, play a little. No scary maths, and no rush.
The whole track in one script
Everything you've learned — cleaning, splitting, training, evaluating — assembles into a single Pipeline object that carries data from raw CSV to prediction with no leakage gaps. This is what "shipping a model" actually looks like at beginner scale: 40 lines, no magic.
Read it top to bottom
import joblib
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
pipe = Pipeline([
("prep", ColumnTransformer([
("num", SimpleImputer(strategy="median"), ["age", "bill"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["city"]),
])),
("model", RandomForestClassifier(n_estimators=200, random_state=7)),
])
print("CV:", cross_val_score(pipe, X, y, cv=5).mean())
pipe.fit(X, y)
joblib.dump(pipe, "churn_model.pkl")
Three ideas doing the heavy lifting: the ColumnTransformer applies different cleaning per column type; cross_val_score rotates validation slices so the number is trustworthy; the Pipeline wraps it all so preprocessing and model travel together.
Why pipelines prevent the classic disaster
Without one, it's easy to fit the imputer on full data, tune on test, or serve with different preprocessing than training — three flavors of leakage and skew. Inside a pipeline, the same steps run in training, validation, and serving. What you evaluated is literally what you ship: joblib.load("churn_model.pkl").predict(new_row).
After shipping: watch it like software
Models rot — customer behavior shifts, features drift. Monitor prediction distributions and business metrics like any other dashboard, keep a data snapshot + code version per model file, and schedule retraining before decay becomes an incident.
Decide these before writing code
- The exact label. "Churn" is vague; "cancels within 30 days of this snapshot" is something you can compute and check.
- The snapshot date. Features must come only from before it, or the model sees the future.
- A baseline. Predicting the majority class, or a simple rule such as "no login in 14 days," sets the score the model has to beat.
- The success metric. For churn, perhaps recall at a precision the retention team can handle: "catch 70% of churners while keeping alerts mostly correct."
Using the saved model
Load it with joblib.load and pass a DataFrame with the same column names used in training. Because the pipeline includes the preprocessing, raw values go straight in. handle_unknown="ignore" means a city the model never saw produces no error; it simply contributes nothing. Use predict_proba to get risk scores rather than bare yes or no answers.
The simplest deployment: a nightly job
You do not need an API to get value. A scheduled script can load the model each night, score every active customer, and write the 100 highest-risk accounts to a file or dashboard for the retention team. It is easy to run, easy to check, and easy to roll back. Build a real-time service only when someone needs answers within seconds.
Signs it is time to retrain
- The live metric drifts below what it scored at launch.
- Inputs change shape: a new plan type, a new country, a redesigned app.
- The business changes the question, for example a new definition of churn.
Retraining on a schedule, with the same evaluation before each release, turns these from surprises into routine.
Remember this
- Pipeline = cleaning + model in one leak-proof object. Cross-validate, dump with joblib, version everything.
- You now own the full loop: load → clean → train → evaluate → save → monitor.
Check your understanding
5 questions · first-try answers earn the most XP
My notes
Saved in this browser. Highlight a line above and save it, or write it in your own words.
Nothing saved yet. Your highlights will live here.
References
Finished reading?
Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.
End of Evaluate & Ship
Take the section checkpoint
A short mixed quiz on all 3 chapters, to check you are ready to move on.
Related chapters
Spotted a mistake or want a topic covered? Report an issue