scikit-learn is the standard Python library for classic machine learning: one consistent fit/predict interface for preprocessing and models, joined into a Pipeline so the exact same steps run in training and in production. Its real value is honest evaluation: cross-validation, the right metric, and a decision threshold chosen for the business. This lesson builds a fraud model end to end, and shows the two ways a model looks good and is not: preprocessing fitted on all the data, and accuracy on a rare class.
Difficulty: Intermediate · Know this first: Lesson 251, Lesson 241
This bar adds up minutes from data to a model you can trust. It is a worked example, not a measurement. The metric and preprocessing hops decide whether the reported score is real.
Set the fraud rate and the share of fraud the model catches. Compare its accuracy with a model that never flags anything.
Accuracy prefers the useless model; recall and precision tell the truth
Three questions. No score is saved anywhere — this is just you against the material.
scikit-learn grows in four levels: fit and predict, pipelines, honest evaluation, and models in production.
At the basic level you can train and score a model.
model.fit(X_train, y_train), predict, predict_proba.train_test_split(..., stratify=y); DummyClassifier as a baseline.classification_report and confusion_matrix.Where it breaks: evaluating on the training data, which measures memory, not learning.
Try it: Basic
A model scores 100% on the data it was trained on. What does that prove?
Now do it: Compare training and test scores for one model.
At the intermediate level preprocessing and model are one object.
Pipeline, ColumnTransformer, SimpleImputer, StandardScaler, OneHotEncoder(handle_unknown="ignore").cross_validate with the right scoring; StratifiedKFold, TimeSeriesSplit, GroupKFold.model__max_depth.Try it: Intermediate
Why use OneHotEncoder(handle_unknown="ignore") in production?
Now do it: Predict on a row with an unseen category with and without the option.
At the advanced level the reported score matches production.
CalibratedClassifierCV).Try it: Advanced
You tuned hyperparameters by checking the test set score after each try. What is the problem?
Now do it: Rewrite one tuning loop to use cross-validation on training data only.
At the master level models are reproducible artifacts.
Trade-off: a complex model may add a few points of PR-AUC and cost explainability and latency; a simple baseline is easy to trust, debug, and serve.
Try it: Master
Why should you never joblib.load a model file from an untrusted source?
Now do it: Check where your model files come from and who can write there.
The fraud pipeline on synthetic data, end to end. Install with pip install scikit-learn.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.dummy import DummyClassifier
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import accuracy_score, average_precision_score, precision_recall_curve, recall_score
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = make_classification(n_samples=100_000, n_features=20, weights=[0.995], flip_y=0.001, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
pipe = make_pipeline(StandardScaler(), HistGradientBoostingClassifier(random_state=0)) # scaler inside
print("CV PR-AUC:", cross_val_score(pipe, X_tr, y_tr, cv=5, scoring="average_precision").round(3))
dummy = DummyClassifier().fit(X_tr, y_tr)
print("dummy accuracy:", accuracy_score(y_te, dummy.predict(X_te)), "recall:", recall_score(y_te, dummy.predict(X_te)))
pipe.fit(X_tr, y_tr)
scores = pipe.predict_proba(X_te)[:, 1]
print("test PR-AUC:", round(average_precision_score(y_te, scores), 3))
prec, rec, thr = precision_recall_curve(y_te, scores) # in practice: on a validation split
i = np.argmax(rec[:-1] <= 0.8)
print(f"threshold {thr[i]:.3f}: recall {rec[i]:.2f}, precision {prec[i]:.2f}")
This is a composite of a failure pattern that keeps repeating; the details are illustrative. A fraud model with record accuracy stopped catching fraud.
Model selection uses PR-AUC and recall at the review budget, promotion requires beating the current model on those, and the daily alert count is monitored with an alarm when it drops sharply.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Before you start: A virtual environment: python3 -m venv ~/py-lab && . ~/py-lab/bin/activate. Then pip install scikit-learn for the commands.
Type each one, read what it prints, and compare it with the note above it.
On rare fraud, a model that never flags anything has excellent accuracy.
python3 -c "from sklearn.datasets import make_classification; from sklearn.dummy import DummyClassifier; from sklearn.metrics import accuracy_score, recall_score
X, y = make_classification(n_samples=20000, weights=[0.998], random_state=0)
d = DummyClassifier().fit(X, y); p = d.predict(X)
print('accuracy', accuracy_score(y, p), 'recall', recall_score(y, p))"A Pipeline fits the scaler inside each cross-validation fold.
python3 -c "from sklearn.datasets import make_classification; from sklearn.pipeline import make_pipeline; from sklearn.preprocessing import StandardScaler; from sklearn.linear_model import LogisticRegression; from sklearn.model_selection import cross_val_score X, y = make_classification(n_samples=5000, weights=[0.95], random_state=0) print(cross_val_score(make_pipeline(StandardScaler(), LogisticRegression()), X, y, cv=5, scoring='average_precision').round(3))"
The installed version, to record next to a saved model.
python3 -c "import sklearn; print(sklearn.__version__)"
metrics_by_hand.pyThis program computes accuracy, precision, and recall by hand for a "never fraud" model and a real one on rare fraud, then picks a threshold for a review budget. Save it as metrics_by_hand.py, then run it.
# metrics_by_hand.py
import random
random.seed(0)
n, rate = 100_000, 0.002
labels = [1 if random.random() < rate else 0 for _ in range(n)]
scores = [min(1.0, max(0.0, random.gauss(0.7 if y else 0.15, 0.15))) for y in labels]
def evaluate(pred):
tp = sum(p and y for p, y in zip(pred, labels)); fp = sum(p and not y for p, y in zip(pred, labels))
fn = sum((not p) and y for p, y in zip(pred, labels))
acc = sum(p == y for p, y in zip(pred, labels)) / n
prec = tp / (tp + fp) if tp + fp else 0.0
rec = tp / (tp + fn) if tp + fn else 0.0
return acc, prec, rec, tp + fp
print(f"fraud cases: {sum(labels)} of {n:,}")
for name, pred in [("never fraud", [0] * n), ("score > 0.5", [s > 0.5 for s in scores])]:
acc, prec, rec, flagged = evaluate(pred)
print(f"{name:<12} accuracy {acc:.2%} precision {prec:.0%} recall {rec:.0%} flagged {flagged:,}")
budget = 400
thr = sorted(scores, reverse=True)[budget - 1]
acc, prec, rec, flagged = evaluate([s >= thr for s in scores])
print(f"threshold {thr:.2f} for {budget} reviews: precision {prec:.0%}, recall {rec:.0%}")
Run it, and you should see this output:
$ python3 metrics_by_hand.py fraud cases: 190 of 100,000 never fraud accuracy 99.81% precision 0% recall 0% flagged 0 score > 0.5 accuracy 99.03% precision 15% recall 92% flagged 1,125 threshold 0.57 for 400 reviews: precision 38%, recall 79%
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/scikit-learn-pipelines-and-evaluation && cd ~/labs/scikit-learn-pipelines-and-evaluation) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "scikit-learn: Pipelines, Cross-Validation, and Honest Evaluation", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'On rare fraud, a model that never flags anything has excellent accuracy.'
'A Pipeline fits the scaler inside each cross-validation fold.'
'The installed version, to record next to a saved model.'
)
step_1() {
python3 -c "from sklearn.datasets import make_classification; from sklearn.dummy import DummyClassifier; from sklearn.metrics import accuracy_score, recall_score
X, y = make_classification(n_samples=20000, weights=[0.998], random_state=0)
d = DummyClassifier().fit(X, y); p = d.predict(X)
print('accuracy', accuracy_score(y, p), 'recall', recall_score(y, p))"
}
step_2() {
python3 -c "from sklearn.datasets import make_classification; from sklearn.pipeline import make_pipeline; from sklearn.preprocessing import StandardScaler; from sklearn.linear_model import LogisticRegression; from sklearn.model_selection import cross_val_score
X, y = make_classification(n_samples=5000, weights=[0.95], random_state=0)
print(cross_val_score(make_pipeline(StandardScaler(), LogisticRegression()), X, y, cv=5, scoring='average_precision').round(3))"
}
step_3() {
python3 -c "import sklearn; print(sklearn.__version__)"
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
Build a model that predicts which servers will fail a hardware health check within the next 7 days, from daily telemetry.
What is the positive rate, and which metric fits? How do you split, given that each server has many days? Which preprocessing goes in the pipeline? How is the threshold set from the operations team's capacity?
Say 20,000 servers, two years of daily rows, 0.5% positive days, and capacity to inspect 30 servers a day.
PR-AUC and recall at 30 alerts a day; a time split plus GroupKFold by server inside training; a Pipeline with imputers, scaling, and HistGradientBoosting; a DummyClassifier baseline; RandomizedSearchCV with average_precision; a threshold set so about 30 servers are flagged daily on validation; the pipeline saved with versions and monitored for drift.
Grouping by server prevents a model from memorising servers and gives lower, honest scores. A threshold fixed by capacity is easy to operate and must be revisited as the fleet grows.