Assignment 2: Model Selection and Ensembles

This is voluntary, ungraded practice. Nothing is submitted and there is no deadline. Work through it after Lecture 12, when all of the model families below have been introduced.

The task

Compare several model families on the Wisconsin breast-cancer dataset using one defensible selection protocol. You will treat detecting a malignant tumour as the positive class, tune models using training data only, and inspect whether the apparent winner is meaningfully better than the alternatives.

The data ships with scikit-learn, so it does not require a download.

from sklearn.datasets import load_breast_cancer

data = load_breast_cancer(as_frame=True)
X = data.data

# In the original data, malignant is encoded as 0.
# Recode it so the clinically important class is the positive class.
y = (data.target == 0).astype(int)
y.name = "malignant"

Your numbers will be lower than the slides’ — that is expected. Lectures 10—12 use this dataset with the same split and folds but keep scikit-learn’s coding, where the positive class is benign, so their F1 values are F1 for the benign class. Here you recode so that F1 measures malignant detection, as Lecture 5 did. The majority class is easier to get right, so every F1 below is a few points lower than the slide figure for the same model. The ranking and the story do not change.

Part 1: Define one protocol

Create a stratified 80/20 train-test split with random_state=42. Keep the test set untouched until Part 5.

For all model selection, use the same five-fold StratifiedKFold with shuffling and random_state=42. Use F1 for malignant cases as the primary metric, but also track precision, recall, and ROC AUC.

Before fitting anything, write down:

  1. Why malignant cases should be treated as the positive class
  2. Which error is likely more costly in practice
  3. Why every candidate must use the same folds

Part 2: Establish the incumbent

Fit two reference workflows:

  1. A most-frequent DummyClassifier
  2. Standardisation followed by logistic regression

Use cross-validation on the training data. Record the mean and standard deviation for each metric. The logistic model is your incumbent: a more complex model should offer a convincing reason to replace it.

Part 3: Add three challengers

Construct and tune:

Random forest

Keep n_estimators reasonably large (Lecture 10 used 300; past about 100 trees more of them changes nothing) and search a small grid over:

  • max_depth
  • min_samples_leaf
  • max_features

No scaler is needed: trees split on thresholds, so units do not matter.

Support vector machine

Use a pipeline with standardisation and SVC. Search a small grid over:

  • Linear and RBF kernels
  • C, on a log scale
  • gamma for the RBF kernel, on a log scale

Tune C and gamma together, as a two-dimensional grid, never one with the other frozen (Lecture 11, Pitfall 3). A parameter grid can be a list of dictionaries, one per kernel, so gamma is only searched where it applies.

Gradient boosting

Use HistGradientBoostingClassifier and follow the Lecture 12 recipe. Do not put the number of trees in the grid: give a generous budget and let early stopping pick the count inside every fit.

gb = HistGradientBoostingClassifier(
    max_iter=2000, early_stopping=True, random_state=42
)

Then search a small grid over the two interacting knobs:

  • learning_rate
  • max_depth

Reach for l2_regularization or max_features only if the training-versus-validation gap suggests overfitting.

Keep the grids modest. The exercise is about the selection procedure, not consuming as much compute as possible. Since you track several metrics, pass them all to GridSearchCV as a list and set refit="f1" so the search still knows which one decides.

Part 4: Compare honestly

Create one comparison table containing, for every candidate:

  • Best hyperparameters
  • Mean cross-validation F1
  • Standard deviation across folds
  • Mean precision and recall
  • Approximate fitting time

Then answer:

  1. Is the highest-scoring model ahead by more than ordinary fold-to-fold variation?
  2. Does the ranking change when recall replaces F1?
  3. Which model would you choose if interpretability mattered?
  4. Which model would you choose if missing a malignant case were especially costly?

If two models are effectively tied, prefer the simpler workflow and explain why.

Part 5: Open the test set once

Select one workflow using only the cross-validation evidence. Refit it on all training data and evaluate it once on the held-out test set.

Inspect:

  • Confusion matrix
  • Precision, recall, F1, and ROC AUC
  • The individual false-negative cases

Do not return to model selection after seeing the test score. Explain why doing so would turn the test set into another validation set.

Part 6: Interpret with care

Use permutation importance on the held-out data for the selected model. Compare the result with random-forest impurity importance if you fitted a forest.

Consider:

  • Do correlated measurements divide or hide importance?
  • Does importance tell you that a feature causes malignancy?
  • Would you be comfortable making a clinical decision from this model alone?

Check your numbers

Nothing is handed in, so here are the figures a correct run produces (scikit-learn 1.9; forest grid max_depth in [None, 5, 10], min_samples_leaf in [1, 5], max_features in ["sqrt", 0.5]; SVM grid C in [0.1, 1, 10, 100], gamma in [0.001, 0.01, 0.1, 1]; boosting grid learning_rate in [0.02, 0.05, 0.1, 0.2], max_depth in [3, 4, 6]). Your grids may differ, so expect the second decimal to move; the pattern should not.

CandidateCV F1PrecisionRecallROC AUC
Dummy0.0000.0000.0000.500
Logistic regression (scaled)0.964 ± 0.0210.9770.9530.996
Random forest, best0.955 ± 0.0250.9710.9410.987
SVM, best (RBF, C = 10, γ = 0.01)0.967 ± 0.0160.9830.9530.995
Boosting, best (η = 0.1, depth 4)0.952 ± 0.0200.9700.9350.991

Every real model is within one fold-standard-deviation of the best one, the SVM. Ranking by recall instead puts logistic regression first. The tie-break rule therefore selects the incumbent: scaled logistic regression. On the test set it reaches F1 0.951, precision 0.975, recall 0.929, ROC AUC 0.996 — 39 of 42 malignant cases found, 3 missed, 1 false alarm. One of the three misses has predicted probability 0.49: almost on the threshold, which is the point of the threshold extension below.

Permutation importance for the logistic model is nearly flat — only four of thirty features move F1 by more than 0.01 — because the ten measurements each appear as mean, error and “worst”, and shuffling one copy leaves the model its twins. The forest’s impurity importance tells the opposite story, concentrating on worst perimeter, worst radius and worst area, which are three versions of the same quantity. Neither says anything about cause.

The complete reference solution is assignment_02_breast_cancer.py. Try to finish on your own before reading it.

Optional extensions

  • Plot a validation curve for the most influential hyperparameter.
  • Replace the single split with nested cross-validation and compare the estimated performance.
  • Tune a decision threshold for higher recall using training data only.
  • Check calibration and compare raw SVM scores with calibrated probabilities.

Useful references

MST0052 Predictive Modelling with Machine Learning · Fall 2026 · BI Norwegian Business School