MODELCATALOG

Small helpers you will eventually want.

sklearn.utils

utils

Small helpers you will eventually want.

1 Get data Something to practise on
2 Split & tune An honest test set
3 Prepare Into numbers a model accepts
4 Compose One object, no leakage
5 Model The algorithm itself
6 Unsupervised No labels available
7 Measure Is it any good, and why
8 Utilities Glue and extension

What it is for

Resampling, validation, and the global configuration switch that makes debugging far easier.

Contents

resample, shuffle Bootstrap sampling and shuffling
class_weight.compute_class_weight Weights for imbalanced targets
Bunch The dict-like object datasets return

Global configuration

sklearn.set_config(transform_output='pandas') common Transformers return DataFrames with column names instead of bare arrays (1.2+). Enormously helpful when debugging a ColumnTransformer
sklearn.set_config(display='diagram') Renders pipelines as an interactive diagram in a notebook

Experimental gate

Some features need an explicit opt-in import before the real one, because the API is still settling.

from sklearn.experimental import enable_iterative_imputer Required before importing IterativeImputer
from sklearn.experimental import enable_halving_search_cv Required before the Halving searches

Worked examples 2

Runnable, with the arguments that change the outcome called out. Output shapes are shown as comments where they help.

Two settings that make debugging much easier

Set these once at the top of a notebook.

import sklearn

# 1. Transformers return DataFrames with column names instead of bare
#    numpy arrays. Transforms debugging a ColumnTransformer from
#    guesswork into reading.
sklearn.set_config(transform_output="pandas")

out = preprocessor.fit_transform(X_train)
print(out.columns.tolist()[:6])
# ['num__income', 'num__age', 'cat__product_current', ...]

# 2. Renders a fitted Pipeline as an interactive diagram in a notebook,
#    which is the fastest way to see what is actually in the chain.
sklearn.set_config(display="diagram")
model          # just evaluate it in a cell

print(sklearn.get_config())

Class weights, computed rather than guessed

class_weight='balanced' does this internally. Compute it explicitly when you need to pass weights to something outside sklearn, like XGBoost.

from sklearn.utils.class_weight import compute_class_weight
import numpy as np

classes = np.unique(y_train)
weights = compute_class_weight("balanced", classes=classes, y=y_train)
print(dict(zip(classes, weights.round(3))))
# {0: 0.503, 1: 96.154}

# For XGBoost's binary case the equivalent is a single ratio
neg, pos = (y_train == 0).sum(), (y_train == 1).sum()
print("scale_pos_weight:", round(neg / pos, 2))     # 191.31

# Same idea, different interface - which is the small friction of
# stepping outside sklearn.