Skip to content

ML workflow

Most failed ML projects fail at a step, not at the model: a vague goal, a leaky split, no baseline or a test set used ten times. This page gives the whole workflow as a flowchart and a numbered checklist. Every step links to the module that teaches it and to the cheat sheet page with the code. A compact run of the steps in code follows the checklist.

flowchart TD
    A["1. Frame the problem"] --> B["2. Get and check the data"]
    B --> C["3. Split: lock the test set"]
    C --> D["4. Baseline"]
    D --> E["5. Features in a pipeline"]
    E --> F["6. CV, tuning,<br/>leak check"]
    F -->|"not good enough"| E
    F --> G["7. Evaluate once on test"]
    G -->|"fails: report it,<br/>new test set"| A
    G --> H["8. Interpret"]
    H --> I["9. Deploy"]
    I --> J["10. Monitor"]
    J -->|"drift or a drop"| B
I want to… Use… Page
turn a business question into a task target, unit of prediction, decision, metric Which metric
choose a model family the task, the data size, the need to explain Which ML algorithm
load and check the data df.info(), df.isna().mean(), df.describe() pandas
a hold-out test set train_test_split(X, y, test_size=0.2, stratify=y, random_state=42) scikit-learn API
a split for groups or time GroupShuffleSplit, a cut-off date Which CV strategy
a baseline to beat DummyClassifier(strategy="prior"), DummyRegressor() Models
a forecast baseline seasonal naive Time series
preprocessing without leakage Pipeline + ColumnTransformer Preprocessing
mixed column types OneHotEncoder(handle_unknown="ignore"), StandardScaler, SimpleImputer Preprocessing
a strong tabular model HistGradientBoostingClassifier, LightGBM Boosting
a score with an error bar cross_val_score(pipe, X, y, cv=StratifiedKFold(5, shuffle=True, random_state=42)) CV and tuning
the right CV splitter StratifiedKFold, GroupKFold, TimeSeriesSplit Which CV strategy
tune hyperparameters GridSearchCV, RandomizedSearchCV, Optuna CV and tuning
handle rare positives class_weight="balanced", a tuned threshold Metrics
an honest final score roc_auc_score(y_test, best.predict_proba(X_test)[:, 1]) (your chosen metric), once Metrics
curves and reports classification_report, ROC and PR curves Metrics
check for leaks before the test permutation_importance on validation or out-of-fold data Interpretability
what drives the final model coefficients, PDP, SHAP Interpretability
save the model with metadata joblib bundle + JSON sidecar Deployment
serve predictions FastAPI + pydantic Deployment
track experiments MLflow with sqlite:///mlflow.db Deployment
detect drift PSI and KS per feature Deployment
find groups without a target k-means, HDBSCAN Unsupervised learning
model text TfidfVectorizer in a pipeline NLP
a neural network PyTorch training loop PyTorch
  1. Frame the problem. Write the question as a prediction: the target, the unit (one row per customer, per day), the moment of prediction and the decision it drives. Choose the metric from the cost of each error, and a target value for it. Check that every feature is known at prediction time. Module: 34 scikit-learn workflow, 36 classification. Cheat sheet: Which metric, Which ML algorithm.
  2. Get and check the data. Load it, check dtypes, missing values, duplicates, ranges and the target balance. Explore with plots. Fingerprint the snapshot (SHA-256). Module: 26 data cleaning, 27 exploratory data analysis. Cheat sheet: pandas, Which chart.
  3. Split and lock the test set. Split before any fitting: stratified for classes, by group when rows share an entity, by time for time series. Do not look at the test set again until step 7. Module: 34 scikit-learn workflow, 37 model evaluation and tuning. Cheat sheet: Which CV strategy, scikit-learn API.
  4. Build a baseline. A dummy model, a simple rule or a seasonal naive forecast, then a simple linear model. Every later model must beat it by more than the CV spread. Module: 34 scikit-learn workflow, 35 regression. Cheat sheet: scikit-learn API, Models.
  5. Engineer features inside a pipeline. Imputation, scaling, encoding and feature creation go into a Pipeline with a ColumnTransformer, so every CV fold refits them. Module: 33 feature engineering, 34 scikit-learn workflow. Cheat sheet: Preprocessing.
  6. Cross-validate and tune. Compare model families with the same CV splitter, then tune the best one or two. Report the mean and the spread. Use learning curves to see whether more data or a bigger model helps. Check for leaks here, before the test: run permutation importance on validation or out-of-fold data, and drop any feature that is too good to be true. Module: 37 model evaluation and tuning, 38 ensembles. Cheat sheet: CV and tuning, Boosting, Models.
  7. Evaluate once on the test set. Refit the chosen pipeline on all training rows, score the test set once, and compare with the baseline and the goal from step 1. Choose the decision threshold on validation data, not on the test set. If you change the model after this step, the test set is used up: report that, or set aside a new one. Module: 36 classification, 37 model evaluation and tuning. Cheat sheet: Metrics.
  8. Interpret. Explain the final model: coefficients or SHAP for the main drivers, partial dependence for effects, SHAP for single predictions. This step explains; it makes no modeling decisions. Module: 43 interpretability. Cheat sheet: Interpretability.
  9. Deploy. Save the pipeline with its metadata (versions, features, metrics, threshold), load it with checks, serve it behind a validated API and test the API. Module: 44 ML in production. Cheat sheet: Deployment.
  10. Monitor. Watch service health, input quality, drift (PSI) and, when labels arrive, the metric. Retrain with the same script under a written rule, and keep the previous model for rollback. Module: 44 ML in production. Cheat sheet: Deployment.
Task Specific steps Module Cheat sheet
clustering, segmentation no target: steps 3 and 7 become stability checks and profiles 39 Unsupervised learning
forecasting split by time, seasonal naive baseline, TimeSeriesSplit 40 Time series
text the vectorizer is a pipeline step 41 NLP
neural networks a validation set for early stopping inside step 6 42 PyTorch

A compact run of steps 3 to 9 on data/customers.csv (churn). Each comment names the step.

import json
from pathlib import Path
import joblib
import numpy as np
import pandas as pd
import sklearn
from sklearn.base import clone
from sklearn.compose import ColumnTransformer
from sklearn.dummy import DummyClassifier
from sklearn.inspection import permutation_importance
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import (
GridSearchCV,
StratifiedKFold,
cross_val_score,
train_test_split,
)
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
customers = pd.read_csv("data/customers.csv")
categorical = ["plan", "contract", "payment_method"]
numeric = ["tenure_months", "monthly_charges", "support_tickets", "logins_last_30d"]
X, y = customers[categorical + numeric], customers["churned"]
# 3. Split once and lock the test set
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
# 4. Baseline
dummy = cross_val_score(DummyClassifier(), X_train, y_train, cv=cv, scoring="roc_auc")
# 5. Features in a pipeline
pipe = Pipeline([
("prep", ColumnTransformer([
("cat", OneHotEncoder(handle_unknown="ignore"), categorical),
("num", StandardScaler(), numeric),
])),
("model", LogisticRegression(max_iter=1000)),
])
# 6. Cross-validate and tune on the training rows only
search = GridSearchCV(pipe, {"model__C": [0.01, 0.1, 1.0]}, cv=cv, scoring="roc_auc")
search.fit(X_train, y_train)
spread = search.cv_results_["std_test_score"][search.best_index_]
print(f"baseline CV AUC {dummy.mean():.3f}")
print(f"best {search.best_params_} CV AUC {search.best_score_:.3f} ± {spread:.3f}")
# 6. Leak check before the test: permutation importance on a validation split
X_fit, X_val, y_fit, y_val = train_test_split(
X_train, y_train, test_size=0.25, stratify=y_train, random_state=42
)
check = clone(search.best_estimator_).fit(X_fit, y_fit)
perm = permutation_importance(check, X_val, y_val, scoring="roc_auc",
n_repeats=5, random_state=42)
top = pd.Series(perm.importances_mean, index=X.columns).nlargest(3)
print(top.round(3).to_dict()) # no single column dominates: no obvious leak
# 7. Evaluate once on the test set: no decisions after this line
best = search.best_estimator_ # refitted on all training rows
test_auc = roc_auc_score(y_test, best.predict_proba(X_test)[:, 1])
print(f"test AUC {test_auc:.3f}")
# 8. Interpret the final model: odds ratios of its coefficients
odds = pd.Series(np.exp(best[-1].coef_[0]), index=best[0].get_feature_names_out())
print(odds.sort_values().iloc[[0, -1]].round(2).to_dict()) # strongest down / up
# 9. Save the model with its metadata
Path("models").mkdir(exist_ok=True)
meta = {"model_version": "1.0.0", "sklearn_version": sklearn.__version__,
"features": list(X.columns), "test_roc_auc": round(test_auc, 4)}
joblib.dump({"pipeline": best, "metadata": meta}, "models/churn.joblib")
Path("models/churn.json").write_text(json.dumps(meta, indent=2))
print(sorted(meta), np.round(best.predict_proba(X_test.head(2))[:, 1], 3))
Output
baseline CV AUC 0.500
best {'model__C': 1.0} CV AUC 0.813 ± 0.015
{'contract': 0.086, 'tenure_months': 0.074, 'support_tickets': 0.05}
test AUC 0.815
{'cat__contract_two-year': 0.43, 'cat__contract_month-to-month': 2.61}
['features', 'model_version', 'sklearn_version', 'test_roc_auc'] [0.012 0.487]
Trap Symptom Fix
no clear target or decision a model nobody uses step 1: write the decision and the metric first
features not known at prediction time great CV scores, useless in production check each feature’s timestamp against the prediction moment
scaling or encoding before the split optimistic scores (leakage) fit preprocessing inside a Pipeline
a random split for grouped or time data the same customer or the future in train and test GroupKFold, TimeSeriesSplit, a cut-off date
no baseline “0.85 accuracy” when 81% of rows are one class DummyClassifier, seasonal naive
accuracy on imbalanced classes a model that never predicts the rare class looks good ROC-AUC, PR-AUC, recall at a threshold
tuning on the test set the final score is optimistic tune with CV; touch the test set once
a single CV number differences smaller than the noise look real report the spread; compare with the same splitter
threshold chosen on the test set an optimistic precision or recall choose it on validation data or out-of-fold predictions
a target leak one feature with huge importance step 6: permutation importance on validation data, before the test; drop leaks, rerun
going back after the test score the test set has guided a decision; the score is optimistic report it, or set aside a new test set
a model saved without metadata nobody knows which data, versions or threshold bundle + sidecar with versions, features, metrics
no monitoring silent decay after a change upstream PSI per feature, the metric on new labels
retraining by hand a new model that differs for unknown reasons one training script, a config file, tracked runs