Skip to content

scikit-learn

scikit-learn gives every model the same fit, predict, and transform methods, so a scaler, a classifier, and a search over both fit together into one object. The examples use three datasets that ship inside the package and need no download: Wisconsin breast cancer for binary classification, wine for three classes, and diabetes for regression. Every block below ran with scikit-learn 1.9.

Task Call
Stratified split train_test_split(x, y, stratify=y, random_state=42)
Pipeline Pipeline([("scaler", StandardScaler()), ("clf", model)])
Mixed columns ColumnTransformer([("num", ..., cols), ("cat", ..., cols)])
Pandas output transformer.set_output(transform="pandas")
CV score cross_val_score(pipe, x, y, cv=cv, scoring="roc_auc")
Several metrics cross_validate(pipe, x, y, cv=cv, scoring=[...])
Grouped stratified CV StratifiedGroupKFold(n_splits=5, shuffle=True)
Impute in a pipeline Pipeline([("impute", SimpleImputer(strategy="median")), ...])
Select in a pipeline Pipeline([("select", SelectKBest(f_classif, k=20)), ...])
Class weights LogisticRegression(class_weight="balanced")
Tune threshold TunedThresholdClassifierCV(pipe, scoring=..., cv=cv)
ROC curve RocCurveDisplay.from_predictions(y, score)
Multi-class AUC roc_auc_score(y, proba, multi_class="ovr")
RMSE root_mean_squared_error(y, pred)
Grid search GridSearchCV(pipe, {"clf__C": [...]}, cv=cv)
Random search RandomizedSearchCV(model, dists, n_iter=10, cv=cv)
Importance permutation_importance(model, x, y, n_repeats=10)
Save joblib.dump(pipe, "model.joblib")
from pathlib import Path
import joblib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.stats import randint
from sklearn.cluster import KMeans
from sklearn.compose import ColumnTransformer
from sklearn.datasets import load_breast_cancer, load_diabetes, load_wine
from sklearn.decomposition import PCA
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.impute import SimpleImputer
from sklearn.inspection import permutation_importance
from sklearn.linear_model import LogisticRegression, Ridge
from sklearn.metrics import (
ConfusionMatrixDisplay, PrecisionRecallDisplay, RocCurveDisplay,
adjusted_rand_score, classification_report, confusion_matrix,
mean_absolute_error, precision_score, r2_score, recall_score,
roc_auc_score, root_mean_squared_error,
)
from sklearn.model_selection import (
GridSearchCV, KFold, RandomizedSearchCV, RepeatedStratifiedKFold,
StratifiedGroupKFold, StratifiedKFold, TunedThresholdClassifierCV,
cross_val_score, cross_validate, train_test_split,
)
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
rng = np.random.default_rng(42)
Path("outputs").mkdir(exist_ok=True)
pd.set_option("display.width", 100)

The breast cancer table holds 30 measurements of cell nuclei from fine needle aspirates. The package codes malignant as 0, so flip it and make malignant the positive class that recall and precision refer to. stratify keeps the class ratio equal in train and test.

The observations come from the Wisconsin Diagnostic Breast Cancer dataset, credited by UCI to Wolberg, Mangasarian, Street, and Street, 1993. UCI licenses the data under CC BY 4.0. This lesson reverses the target coding, partitions and scales the observations, and derives model results and figures.

cancer = load_breast_cancer(as_frame=True)
features = cancer.data
target = (cancer.target == 0).astype(int)
print(f"{features.shape[0]} tumours, {features.shape[1]} features")
print(f"malignant {target.sum()}, benign {(target == 0).sum()}")
x_train, x_test, y_train, y_test = train_test_split(
features, target, test_size=0.2, stratify=target, random_state=42
)
print(f"train {x_train.shape}, test {x_test.shape}")
569 tumours, 30 features
malignant 212, benign 357
train (455, 30), test (114, 30)
Method What it does
fit(x, y) learn parameters from training data
predict(x) hard labels or values
predict_proba(x) class probabilities, for classifiers
score(x, y) default metric: accuracy for classifiers, R-squared for regressors
transform(x) apply a fitted preprocessing step
fit_transform(x) fit and transform in one call

A pipeline fits the scaler on the training rows only, then hands the scaled data to the model. Inside cross-validation this keeps the held-out fold out of the scaling, which is the leak a hand-scaled matrix brings in.

pipe = Pipeline([
("scaler", StandardScaler()),
("clf", LogisticRegression(max_iter=1000, random_state=42)),
])
pipe.fit(x_train, y_train)
test_prob = pipe.predict_proba(x_test)[:, 1]
print(f"test accuracy = {pipe.score(x_test, y_test):.3f}")
print(f"test ROC AUC = {roc_auc_score(y_test, test_prob):.3f}")
test accuracy = 0.965
test ROC AUC = 0.996

pipe.named_steps["clf"] or pipe[-1] returns the fitted model. scikit-learn 1.8 deprecated the penalty argument of LogisticRegression. Older code passes penalty="l1" or penalty=None, which now map to l1_ratio=1 and C=np.inf.

A sample sheet mixes numbers and categories. ColumnTransformer scales the numeric columns, one-hot encodes the categorical ones, and set_output(transform="pandas") keeps the column names on the result.

sample_sheet = pd.DataFrame({
"age": [55, 60, 65, 70, 50, 45],
"tumour_size_cm": [2.1, 3.5, 1.8, 4.2, 2.9, 1.5],
"stage": ["I", "II", "I", "III", "II", "I"],
"grade": ["low", "high", "low", "high", "high", "low"],
})
preprocess = ColumnTransformer([
("num", StandardScaler(), ["age", "tumour_size_cm"]),
("cat", OneHotEncoder(drop="first", sparse_output=False),
["stage", "grade"]),
])
preprocess.set_output(transform="pandas")
print(preprocess.fit_transform(sample_sheet).round(2))
num__age num__tumour_size_cm cat__stage_II cat__stage_III cat__grade_low
0 -0.29 -0.59 0.0 0.0 1.0
1 0.29 0.87 1.0 0.0 0.0
2 0.88 -0.90 0.0 0.0 1.0
3 1.46 1.60 0.0 1.0 0.0
4 -0.88 0.24 1.0 0.0 0.0
5 -1.46 -1.21 0.0 0.0 1.0

Put a ColumnTransformer first in a Pipeline and the whole object goes into cross_val_score or GridSearchCV unchanged.

The folds come from the training set only, so the test set stays untouched for the final number.

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(pipe, x_train, y_train, cv=cv, scoring="roc_auc",
n_jobs=1)
print(f"ROC AUC per fold: {scores.round(3)}")
print(f"mean {scores.mean():.3f}, sd {scores.std():.3f}")
ROC AUC per fold: [0.995 0.999 1. 0.987 0.998]
mean 0.996, sd 0.005
cv_res = cross_validate(
pipe, x_train, y_train, cv=cv, n_jobs=1,
scoring=["roc_auc", "balanced_accuracy", "recall"],
)
cv_table = pd.DataFrame(cv_res).drop(columns=["fit_time", "score_time"])
print(cv_table.mean().round(3))
test_roc_auc 0.996
test_balanced_accuracy 0.969
test_recall 0.953
dtype: float64

Use StratifiedKFold for classes and KFold for a continuous target. When one patient gives several samples, split by patient instead, as in the next block.

The example has 60 patients with three samples each and one label per patient. StratifiedGroupKFold keeps every sample of a patient in the same fold and keeps the class balance close across folds. GroupKFold does the first without the second.

patient_id = np.repeat(np.arange(60), 3)
y_group = np.repeat(rng.integers(0, 2, size=60), 3)
patient_shift = np.repeat(rng.normal(size=(60, 1)), 3, axis=0)
x_group = rng.normal(size=(180, 5)) + 0.8 * y_group[:, None] + patient_shift
sgkf = StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=42)
splits = sgkf.split(x_group, y_group, groups=patient_id)
for fold, (train_idx, test_idx) in enumerate(splits):
shared = np.intersect1d(patient_id[train_idx], patient_id[test_idx])
print(f"fold {fold}: {np.unique(patient_id[test_idx]).size} patients, "
f"positive rate {y_group[test_idx].mean():.2f}, "
f"shared with train {shared.size}")
group_scores = cross_val_score(pipe, x_group, y_group, groups=patient_id,
cv=sgkf, scoring="roc_auc", n_jobs=1)
print(f"grouped ROC AUC = {group_scores.mean():.3f}")
fold 0: 12 patients, positive rate 0.58, shared with train 0
fold 1: 12 patients, positive rate 0.58, shared with train 0
fold 2: 12 patients, positive rate 0.58, shared with train 0
fold 3: 12 patients, positive rate 0.50, shared with train 0
fold 4: 12 patients, positive rate 0.50, shared with train 0
grouped ROC AUC = 0.796

Five percent of the training values are blanked at random here. The imputer learns each column’s median from the training folds only, for the same reason the scaler does. LogisticRegression cannot take NaN; HistGradientBoostingClassifier can.

x_missing = x_train.mask(rng.random(x_train.shape) < 0.05)
print(f"missing values: {int(x_missing.isna().sum().sum())}")
impute_pipe = Pipeline([
("impute", SimpleImputer(strategy="median")),
("scaler", StandardScaler()),
("clf", LogisticRegression(max_iter=1000, random_state=42)),
])
impute_scores = cross_val_score(impute_pipe, x_missing, y_train, cv=cv,
scoring="roc_auc", n_jobs=1)
print(f"ROC AUC with imputation = {impute_scores.mean():.3f}")
missing values: 660
ROC AUC with imputation = 0.994

Add add_indicator=True to SimpleImputer to give the model one extra column per feature that flags which values were missing.

Selecting features on all rows before cross-validation lets the labels of the held-out fold pick the features, so the score is inflated. The block shows it on pure noise: 200 samples, 5,000 random features, and random labels, where an honest ROC AUC sits near 0.5. Ten repeats of five-fold cross-validation steady the estimate.

noise = rng.normal(size=(200, 5000))
noise_label = rng.integers(0, 2, size=200)
repeated_cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=10,
random_state=42)
select_pipe = Pipeline([
("select", SelectKBest(f_classif, k=20)),
("clf", LogisticRegression(max_iter=1000, random_state=42)),
])
inside = cross_val_score(select_pipe, noise, noise_label, cv=repeated_cv,
scoring="roc_auc", n_jobs=1)
preselected = SelectKBest(f_classif, k=20).fit_transform(noise, noise_label)
outside = cross_val_score(
LogisticRegression(max_iter=1000, random_state=42), preselected,
noise_label, cv=repeated_cv, scoring="roc_auc", n_jobs=1,
)
print(f"selection inside the pipeline: ROC AUC {inside.mean():.3f}")
print(f"selection before the split: ROC AUC {outside.mean():.3f}")
selection inside the pipeline: ROC AUC 0.465
selection before the split: ROC AUC 0.869

predict cuts the probability at 0.5. A lower cut catches more malignant tumours at the cost of more false alarms. This sweep reads the test set only to show the trade-off; choose the threshold on training data, as in the next block.

for threshold in [0.3, 0.5, 0.7]:
pred = (test_prob >= threshold).astype(int)
print(f"threshold {threshold:.1f}: "
f"precision {precision_score(y_test, pred):.3f}, "
f"recall {recall_score(y_test, pred):.3f}")
threshold 0.3: precision 0.976, recall 0.976
threshold 0.5: precision 0.975, recall 0.929
threshold 0.7: precision 1.000, recall 0.905

Added in scikit-learn 1.5, it picks the cut that maximizes a metric across cross-validation folds of the training data, then refits the model on all of it.

tuned = TunedThresholdClassifierCV(
pipe, scoring="balanced_accuracy", cv=cv, random_state=42, n_jobs=1
)
tuned.fit(x_train, y_train)
print(f"chosen threshold = {tuned.best_threshold_:.3f}")
print(f"CV balanced accuracy = {tuned.best_score_:.3f}")
print(f"test recall = {recall_score(y_test, tuned.predict(x_test)):.3f}")
chosen threshold = 0.293
CV balanced accuracy = 0.974
test recall = 0.976

class_weight="balanced" weights each class by the inverse of its frequency, which raises recall for the smaller class at the default 0.5 cut. The cost is that the predicted probabilities no longer match the observed rate. Use it when you need a label or a ranking; when the probabilities matter, keep them unweighted and tune the threshold as above. The breast cancer classes are not far from balanced, so the block simulates a rare outcome, with 9.5% positives in the test set. Weighting lifts recall from 0.12 to 0.74 and leaves the ROC AUC almost unchanged, but the mean predicted risk jumps from 0.085 to 0.330.

x_rare = rng.normal(size=(2000, 5))
rare_logit = -3.0 + 1.2 * x_rare[:, 0] + 0.8 * x_rare[:, 1]
y_rare = rng.binomial(1, 1 / (1 + np.exp(-rare_logit)))
xr_train, xr_test, yr_train, yr_test = train_test_split(
x_rare, y_rare, test_size=0.3, stratify=y_rare, random_state=42
)
for weight in [None, "balanced"]:
clf = LogisticRegression(class_weight=weight, random_state=42)
clf.fit(xr_train, yr_train)
rare_prob = clf.predict_proba(xr_test)[:, 1]
rare_pred = clf.predict(xr_test)
rare_precision = precision_score(yr_test, rare_pred, zero_division=0)
print(f"class_weight={str(weight):>8}: "
f"recall {recall_score(yr_test, rare_pred):.3f}, "
f"precision {rare_precision:.3f}, "
f"ROC AUC {roc_auc_score(yr_test, rare_prob):.3f}, "
f"mean risk {rare_prob.mean():.3f}")
print(f"observed positive rate in test: {yr_test.mean():.3f}")
class_weight= None: recall 0.123, precision 0.538, ROC AUC 0.839, mean risk 0.085
class_weight=balanced: recall 0.737, precision 0.284, ROC AUC 0.835, mean risk 0.330
observed positive rate in test: 0.095

The display classes draw a curve straight from labels and scores.

fig, axes = plt.subplots(1, 2, figsize=(9, 4))
RocCurveDisplay.from_predictions(
y_test, test_prob, name="logistic", plot_chance_level=True, ax=axes[0]
)
PrecisionRecallDisplay.from_predictions(
y_test, test_prob, name="logistic", plot_chance_level=True, ax=axes[1]
)
axes[0].set(title="ROC curve, test set", xlabel="false positive rate",
ylabel="true positive rate")
axes[1].set(title="Precision-recall curve, test set", xlabel="recall",
ylabel="precision")
fig.tight_layout()
fig.savefig("outputs/scikit-learn-roc-pr.png", dpi=150)
plt.close(fig)

Two panels for the logistic pipeline on the 114 test tumours. Left, the ROC curve rises to a true positive rate of about 0.93 at a false positive rate near 0 and reaches 1.0 at a false positive rate of about 0.14, with the legend showing AUC 1.00 against a dashed chance line at 0.5. Right, precision stays at 1.0 up to a recall of about 0.93, then falls to about 0.8 and finally to 0.37 at a recall of 1.0, with average precision 0.99 against a chance level of 0.37.

Rows are the true class and columns the predicted class, in the order benign then malignant.

test_pred = pipe.predict(x_test)
print(confusion_matrix(y_test, test_pred))
print(classification_report(y_test, test_pred,
target_names=["benign", "malignant"]))
[[71 1]
[ 3 39]]
precision recall f1-score support
benign 0.96 0.99 0.97 72
malignant 0.97 0.93 0.95 42
accuracy 0.96 114
macro avg 0.97 0.96 0.96 114
weighted avg 0.97 0.96 0.96 114
fig, ax = plt.subplots(figsize=(4.5, 4))
ConfusionMatrixDisplay.from_predictions(
y_test, test_pred, display_labels=["benign", "malignant"],
cmap="Blues", colorbar=False, ax=ax,
)
fig.tight_layout()
fig.savefig("outputs/scikit-learn-confusion-matrix.png", dpi=150)
plt.close(fig)

Confusion matrix for the 114 test tumours at the default 0.5 cut. Of 72 benign tumours, 71 are predicted benign and 1 malignant. Of 42 malignant tumours, 3 are predicted benign and 39 malignant.

The wine data has 178 samples from three cultivars. LogisticRegression fits a multinomial model when there are more than two classes. Older code passes multi_class="multinomial", an argument scikit-learn 1.9 no longer accepts. For ROC AUC, pass the full probability matrix and choose multi_class="ovr" in roc_auc_score.

The Wine dataset is credited to Stefan Aeberhard and M. Forina, 1992, under CC BY 4.0. This lesson uses the scikit-learn representation, partitions and scales the observations, and derives classification results.

wine = load_wine(as_frame=True)
xw_train, xw_test, yw_train, yw_test = train_test_split(
wine.data, wine.target, test_size=0.25, stratify=wine.target,
random_state=42,
)
wine_pipe = Pipeline([
("scaler", StandardScaler()),
("clf", LogisticRegression(max_iter=2000, random_state=42)),
])
wine_pipe.fit(xw_train, yw_train)
wine_prob = wine_pipe.predict_proba(xw_test)
macro_auc = roc_auc_score(yw_test, wine_prob, multi_class="ovr",
average="macro")
print(f"macro ROC AUC, one-vs-rest = {macro_auc:.3f}")
print(classification_report(yw_test, wine_pipe.predict(xw_test),
target_names=wine.target_names))
macro ROC AUC, one-vs-rest = 1.000
precision recall f1-score support
class_0 1.00 1.00 1.00 15
class_1 1.00 1.00 1.00 18
class_2 1.00 1.00 1.00 12
accuracy 1.00 45
macro avg 1.00 1.00 1.00 45
weighted avg 1.00 1.00 1.00 45

The diabetes data has 442 patients, 10 baseline measures that come centered and scaled, and a disease progression score one year later. root_mean_squared_error replaces mean_squared_error(..., squared=False), which scikit-learn 1.9 no longer accepts.

The diabetes observations come from the study used by Efron, Hastie, Johnstone, and Tibshirani in Least Angle Regression. Hastie and Efron distribute these observations in lars 1.3 under GNU GPL version 2. The data notice identifies that distribution. This lesson uses the scikit-learn representation and derives ridge-regression results; its numerical precision differs from the original package matrix.

diabetes = load_diabetes(as_frame=True)
xd_train, xd_test, yd_train, yd_test = train_test_split(
diabetes.data, diabetes.target, test_size=0.2, random_state=42
)
ridge = Pipeline([("scaler", StandardScaler()), ("reg", Ridge(alpha=1.0))])
ridge.fit(xd_train, yd_train)
yd_pred = ridge.predict(xd_test)
print(f"R-squared = {r2_score(yd_test, yd_pred):.3f}")
print(f"MAE = {mean_absolute_error(yd_test, yd_pred):.1f}")
print(f"RMSE = {root_mean_squared_error(yd_test, yd_pred):.1f}")
kfold = KFold(n_splits=5, shuffle=True, random_state=42)
cv_rmse = -cross_val_score(ridge, diabetes.data, diabetes.target, cv=kfold,
scoring="neg_root_mean_squared_error", n_jobs=1)
print(f"5-fold RMSE = {cv_rmse.mean():.1f} +/- {cv_rmse.std():.1f}")
R-squared = 0.454
MAE = 42.8
RMSE = 53.8
5-fold RMSE = 54.8 +/- 2.6

Scorers are always “higher is better”, so error metrics come negated as neg_root_mean_squared_error. Flip the sign to read them.

GridSearchCV fits every combination in the grid and scores each one by cross-validation. A double underscore reaches into a pipeline step, so clf__C is the C of the step named clf.

grid = GridSearchCV(
pipe, param_grid={"clf__C": [0.01, 0.1, 1, 10, 100]},
cv=cv, scoring="roc_auc", n_jobs=1,
)
grid.fit(x_train, y_train)
print(f"best params = {grid.best_params_}")
print(f"best CV ROC AUC = {grid.best_score_:.4f}")
best params = {'clf__C': 1}
best CV ROC AUC = 0.9958

RandomizedSearchCV draws a fixed number of settings from distributions, so its cost stays flat as you add parameters. A random forest needs no scaling, so it goes in without a pipeline.

forest_search = RandomizedSearchCV(
RandomForestClassifier(random_state=42, n_jobs=1),
param_distributions={
"n_estimators": randint(100, 400),
"max_depth": [None, 4, 8],
"min_samples_leaf": randint(1, 6),
},
n_iter=10, cv=cv, scoring="roc_auc", random_state=42, n_jobs=1,
)
forest_search.fit(x_train, y_train)
print(f"best params = {forest_search.best_params_}")
print(f"best CV ROC AUC = {forest_search.best_score_:.4f}")
best params = {'max_depth': None, 'min_samples_leaf': 1, 'n_estimators': 121}
best CV ROC AUC = 0.9884

Shuffle one feature at a time on the test set and record how much ROC AUC drops. It works for any model, unlike feature_importances_, which exists only for trees and favors features with many distinct values.

perm = permutation_importance(
forest_search.best_estimator_, x_test, y_test, scoring="roc_auc",
n_repeats=10, random_state=42, n_jobs=1,
)
perm_table = pd.DataFrame(
{"mean_drop": perm.importances_mean, "sd": perm.importances_std},
index=x_test.columns,
).sort_values("mean_drop", ascending=False)
print(perm_table.head(5).round(4))
mean_drop sd
worst area 0.0114 0.0053
worst concave points 0.0106 0.0041
worst radius 0.0072 0.0032
worst perimeter 0.0063 0.0031
mean concave points 0.0062 0.0044

Unsupervised tools follow the same API. Scale first, since PCA on raw values is dominated by the features with the largest units, then compare the k-means clusters with the diagnosis.

scaled = StandardScaler().fit_transform(features)
pca = PCA(n_components=5, random_state=42)
pcs = pca.fit_transform(scaled)
print(f"variance explained: {pca.explained_variance_ratio_.round(3)}")
kmeans = KMeans(n_clusters=2, n_init=10, random_state=42)
clusters = kmeans.fit_predict(pcs)
ari = adjusted_rand_score(target, clusters)
print(f"adjusted Rand index, clusters vs diagnosis = {ari:.3f}")
variance explained: [0.443 0.19 0.094 0.066 0.055]
adjusted Rand index, clusters vs diagnosis = 0.671

Save the whole pipeline, so the reloaded model applies the same scaling. A joblib file is a pickle, so load only files you trust, with the same scikit-learn version that wrote them.

joblib.dump(pipe, "outputs/scikit-learn-pipeline.joblib")
loaded = joblib.load("outputs/scikit-learn-pipeline.joblib")
same = np.array_equal(loaded.predict(x_test), pipe.predict(x_test))
print(f"reloaded pipeline gives the same predictions: {same}")
reloaded pipeline gives the same predictions: True

Pedregosa and colleagues, 2011 describe scikit-learn, the machine learning library for Python.