Gradient LabOpen in Gradient Lab

Lessons › Projects

A screening classifier that doesn’t miss cases

A logistic regression model on a real medical dataset, tuned for high recall by moving its decision threshold.

No setup needed. Run every step in your browser on Gradient Lab, or download it.

Open the notebook

Level: Intermediate · Time: 35 min · You’ll practise: pipelines, feature scaling, cross-validation, thresholds, AUC

Steps

1. Load the data. Here 1 = malignant

Load scikit-learn’s built-in breast cancer dataset. We relabel it so 1 means malignant: the case we must not miss.

data = load_breast_cancer()
X, y = data.data, 1 - data.target
print(f"{X.shape[0]} samples, {X.shape[1]} features, {y.mean():.0%} malignant")

2. Scale the features, then logistic regression, in one pipeline

Build a pipeline: scale every feature, then logistic regression. Pipelines stop scaling from leaking test data into training.

model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))

3. 5-fold cross-validation for an honest score

Score it with 5-fold cross-validation, using AUC.

scores = cross_val_score(model, X, y, cv=5, scoring="roc_auc")
print("AUC per fold:", np.round(scores, 3), f"-> mean {scores.mean():.3f}")

4. Train once, then look at the probabilities

Train once and get a probability for every test sample.

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
model.fit(X_train, y_train)
prob = model.predict_proba(X_test)[:, 1]
print(f"Test AUC: {roc_auc_score(y_test, prob):.3f}")

5. Move the threshold and watch precision and recall trade off

Slide the threshold from strict to loose and watch precision and recall trade off.

print("threshold  precision  recall  missed cases")
for t in [0.9, 0.7, 0.5, 0.3, 0.1]:
    pred = (prob >= t).astype(int)
    missed = int(((pred == 0) & (y_test == 1)).sum())
    print(f"   {t:.1f}       {precision_score(y_test, pred):.0%}      {recall_score(y_test, pred):.0%}       {missed}")
print("For screening, pick a low threshold: a few extra follow-ups beat a missed case.")

Expected output

$ python screening.py
569 samples, 30 features, 37% malignant
AUC per fold: [0.995 0.997 0.997 0.988 1.   ] -> mean 0.995
Test AUC: 0.996
threshold  precision  recall  missed cases
   0.9       100%      89%       6
   0.7       100%      89%       6
   0.5       100%      96%       2
   0.3       89%      96%       2
   0.1       83%      100%       0
For screening, pick a low threshold: a few extra follow-ups beat a missed case.

Stretch goals

Download p05-cancer-screening.zip