Sub topic 15
An End-to-End scikit-learn Pipeline
This chapter assumes you know the sigmoid model, log loss, L2 regularization, and the metrics from the earlier chapters. It also assumes basic Python, NumPy, and train/test splits. Here you assemble those pieces into one workflow with scikit-learn, and you learn which mistakes break it.
The working model
A scikit-learn Pipeline chains transformers and a final estimator into one object. Calling fit on the pipeline fits each step in order on the training data only. Calling predict or predict_proba applies the learned transformations, then the classifier.
Keeping the scaler inside the pipeline matters. If you scale the whole dataset before splitting, the test rows influence the mean and standard deviation. That is data leakage, and it makes your test scores look better than they should.
Fitting and evaluating
The script below runs the whole workflow on the breast cancer dataset. It splits with stratification, fits the pipeline, scores with ROC AUC, and prints per-class precision and recall. It also runs 5-fold cross-validation on the training set. Because the pipeline is the estimator, the scaler is refit inside every fold.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
classification_report,
precision_score,
recall_score,
roc_auc_score,
)
data = load_breast_cancer()
X, y = data.data, data.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
model = make_pipeline(StandardScaler(), LogisticRegression(C=1.0, max_iter=1000))
cv_auc = cross_val_score(model, X_train, y_train, cv=5, scoring="roc_auc")
print("CV AUC:", cv_auc.mean().round(4), "+/-", cv_auc.std().round(4))
model.fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]
print("Test AUC:", round(roc_auc_score(y_test, proba), 4))
print(classification_report(y_test, model.predict(X_test)))
clf = model.named_steps["logisticregression"]
coefs = clf.coef_[0]
for i in np.argsort(np.abs(coefs))[::-1][:3]:
print(data.feature_names[i], round(coefs[i], 3), round(np.exp(coefs[i]), 3))
for t in (0.3, 0.5, 0.9):
pred = (proba >= t).astype(int)
print(
t,
"recall(1):", round(recall_score(y_test, pred), 3),
"precision(1):", round(precision_score(y_test, pred), 3),
"recall(0):", round(recall_score(y_test, pred, pos_label=0), 3),
)Here is what each part does:
stratify=ykeeps the class proportions the same in the train and test sets. This matters most when one class is rare.C=1.0is the inverse of the regularization strength. Smaller values mean a stronger L2 penalty. The default penalty is L2.max_iter=1000raises the solver's iteration limit above the default of 100. Without it you may see aConvergenceWarning.predict_probareturns one column per class, ordered likeclf.classes_. Column 1 is the probability of class 1 only because the classes are[0, 1].predictapplies a fixed 0.5 threshold. To use another threshold, comparepredict_probaoutput yourself, as the last loop does.
Reading the output
The cross-validation scores tell you how much the metric varies with the split. A test AUC far outside that range suggests a split problem or leakage.
The coefficients belong to the standardized features. Exponentiating one gives the multiplicative change in the odds of class 1 for a one-standard-deviation increase in that feature, holding the others fixed. A value of 0.5 means the odds are halved. A value of 2 means they double.
Check which class is positive before you interpret anything. In this dataset, class 1 is benign and class 0 is malignant.
Choosing C and the threshold
Treat C as a hyperparameter. Tune it with cross-validation on the training set, for example with GridSearchCV over logisticregression__C. The double underscore addresses a parameter of a named pipeline step. Do not tune it on the test set.
The threshold is a separate decision. It does not change the fitted model, only how you turn probabilities into labels. Choose it from a precision-recall curve or from explicit error costs, using validation data. Then report the final numbers on the test set once.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `ConvergenceWarning` from lbfgs | Unscaled features or too few iterations | Add `StandardScaler`, raise `max_iter` |
| Test score better than it should be | Scaler fit on all data before splitting | Put the scaler inside the pipeline |
| Precision and recall look swapped | Positive class is not the one you care about | Check `clf.classes_` and the `pos_label` argument |
| Huge coefficients, very confident probabilities | Perfect or near-perfect separation | Lower `C`, remove leaking features |
| Coefficients cannot be compared across features | Features on different scales | Standardize before reading magnitudes |
| Poor recall on a rare class | Imbalance with a 0.5 threshold | Move the threshold or use `class_weight="balanced"` |
Quality checks before you trust the result
- Confirm the split is stratified and the random seed is fixed, so runs are reproducible.
- Compare cross-validated AUC with test AUC. They should be close.
- Look at the confusion matrix or per-class report, not accuracy alone.
- Verify that no feature is a proxy for the label, such as an ID or a post-outcome measurement.
- If you quote probabilities, check calibration. A good AUC does not guarantee trustworthy probabilities.
Exercise
You change the pipeline to call StandardScaler().fit_transform(X) on the full dataset, then split, then fit LogisticRegression. The test AUC goes up slightly. Is this a real improvement? Name the problem and the fix.
Show answer
No. The scaler learned the mean and standard deviation from the test rows too, so test information leaked into training. The score is optimistic. The fix is to split first and keep the scaler inside make_pipeline(StandardScaler(), LogisticRegression(...)), so it is fit on training data only.
Exercise
With the breast cancer pipeline, a clinician wants to catch nearly every malignant case, even if some benign cases are flagged. Should the threshold on the class-1 (benign) probability go up or down from 0.5, and which metric from the script tracks the goal?
Show answer
Up. Raising the threshold labels fewer cases as benign, so more malignant cases are caught. The metric is recall_score(y_test, pred, pos_label=0), the recall of class 0, which is malignant. It rises as the threshold increases, while recall for class 1 falls.