Sub topic 15
An end-to-end scikit-learn pipeline
This chapter assumes you know Python, NumPy, train/test splits, and the log loss and L2 penalty from earlier chapters. Here you combine them into one workflow with scikit-learn.
Why use a pipeline
Scaling, fitting, and prediction must use the same steps on training and test data. A Pipeline bundles them into one estimator. Calling fit learns the scaler's mean and standard deviation from the training rows only, so no test information leaks into training. Calling predict applies the same scaling automatically.
Fit and evaluate
The code below uses the breast cancer dataset. It splits the data with stratify=y, so both sets keep the same class proportions.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, roc_auc_score
X, y = load_breast_cancer(return_X_y=True)
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))
model.fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]
print(roc_auc_score(y_test, proba))
print(classification_report(y_test, model.predict(X_test)))Three details matter here:
Cis the inverse of the regularization strength. Smaller values mean a stronger L2 penalty. The defaultC=1.0is a reasonable starting point.predict_probareturns one column per class. Column 1 is the probability of the positive class.- ROC AUC uses probabilities, which makes it independent of any threshold.
classification_reportusespredict, which applies a 0.5 threshold.
Read the coefficients
Because the features were standardized, coefficients are comparable in size. Exponentiating a coefficient gives the odds ratio for a one-standard-deviation increase in that feature, with the others held fixed.
import numpy as np
clf = model.named_steps["logisticregression"]
odds_ratios = np.exp(clf.coef_[0])
for i in np.argsort(np.abs(clf.coef_[0]))[::-1][:3]:
print(i, clf.coef_[0][i], odds_ratios[i])The step name logisticregression is the lowercase class name that make_pipeline assigns.
Move the threshold
predict always uses 0.5. To trade precision for recall, threshold the probabilities yourself.
threshold = 0.3
y_pred = (proba >= threshold).astype(int)
print(classification_report(y_test, y_pred))Lowering the threshold labels more examples positive. Recall for the positive class typically rises and precision falls.
Common errors
- A
ConvergenceWarningusually means unscaled features or too few iterations. Scale first, then raisemax_iter. - Reading coefficients from an unscaled model makes features with large units look unimportant.
- Choosing the threshold on the test set makes the final score optimistic. Pick it on validation data or with cross-validation.
Exercise
You change threshold from 0.5 to 0.3 on a fitted pipeline. Will roc_auc_score(y_test, proba) change, and why or why not?
Show answer
No. ROC AUC is computed from the probabilities, which the threshold does not touch. Only the labels, and therefore precision, recall, and the confusion matrix, change.