34. The scikit-learn workflow — Cheat sheet
The essentials of module 34 on one page. Every runnable block on this page is checked against its output. The blocks run top to bottom and share their variables.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… |
|---|---|
| learn from training data | est.fit(X_train, y_train) (returns est) |
| apply a learned transformation | est.transform(X) |
| fit and transform the training rows in one call | est.fit_transform(X_train) |
| predict labels or numbers | est.predict(X) |
| predict class probabilities | est.predict_proba(X)[:, 1] (column 1 = positive class) |
| get the default score | est.score(X, y) (accuracy or R²) |
| read the hyperparameters | est.get_params() |
| change hyperparameters | est.set_params(C=0.1) (returns est) |
| get an unfitted copy with the same settings | sklearn.base.clone(est) |
| check that an estimator is fitted | sklearn.utils.validation.check_is_fitted(est) |
| hold out a test set, same class shares | train_test_split(X, y, test_size=0.25, stratify=y, random_state=42) |
| get a baseline score | DummyClassifier(strategy="most_frequent"), DummyRegressor(strategy="median") |
| chain preprocessing and a model | Pipeline([("prep", ...), ("model", ...)]) or make_pipeline(...) |
| set a parameter of a step | pipe.set_params(model__C=0.1) |
| reach a step | pipe["model"], pipe[-1], pipe.named_steps["model"] |
| get the preprocessing part only | pipe[:-1] |
| treat column groups differently | ColumnTransformer([(name, transformer, columns), ...]) |
| select columns by dtype | make_column_selector(dtype_include="number"), dtype_include="str" |
| select columns by name pattern | make_column_selector(pattern="charges$") |
| keep unlisted columns | ColumnTransformer(..., remainder="passthrough") |
| name the output columns | est.get_feature_names_out() |
drop the num__ prefixes |
ColumnTransformer(..., verbose_feature_names_out=False) |
| get DataFrames out of transformers | est.set_output(transform="pandas") (before fit) |
| wrap a plain function as a step | FunctionTransformer(np.log1p, feature_names_out="one-to-one") |
| model a log-transformed target | TransformedTargetRegressor(regressor=..., func=np.log, inverse_func=np.exp) |
| ignore new categories at prediction time | OneHotEncoder(handle_unknown="ignore") |
| write my own transformer | class T(TransformerMixin, BaseEstimator) |
| validate input in a custom estimator | validate_data(self, X) in fit, validate_data(self, X, reset=False) after |
reject a continuous y in a custom classifier |
sklearn.utils.multiclass.check_classification_targets(y) |
| test a custom estimator against the API contract | check_estimator(est) or @parametrize_with_checks([...]) in pytest |
| k folds | KFold(n_splits=5, shuffle=True, random_state=42) |
| k folds with equal class shares | StratifiedKFold(n_splits=5, shuffle=True, random_state=42) |
| one CV metric | cross_val_score(est, X, y, cv=cv, scoring="roc_auc") |
| several CV metrics and train scores | cross_validate(est, X, y, cv=cv, scoring=[...], return_train_score=True) |
| save a fitted pipeline | joblib.dump(pipe, "output/model.joblib") |
| load it | joblib.load("output/model.joblib") (trusted files only) |
Estimator API
Section titled “Estimator API”| Method or attribute | Transformer | Classifier | Regressor | Notes |
|---|---|---|---|---|
fit(X, y=None) |
yes | yes | yes | returns self; transformers accept and usually ignore y |
transform(X) |
yes | no | no | uses the learned attributes |
fit_transform(X, y=None) |
yes | no | no | from TransformerMixin; training rows only |
predict(X) |
no | yes | yes | labels or numbers |
predict_proba(X) |
no | most | no | one column per class in classes_ order |
score(X, y) |
no | accuracy | R² | from ClassifierMixin / RegressorMixin |
get_params(), set_params() |
yes | yes | yes | from BaseEstimator; read the __init__ signature |
get_feature_names_out() |
yes | no | no | output column names |
n_features_in_, feature_names_in_ |
yes | yes | yes | set by fit (names only for DataFrame input) |
classes_ |
no | yes | no | sorted labels seen in fit |
coef_, mean_, statistics_, … |
learned attributes end with _ |
import numpy as npimport pandas as pdfrom sklearn.base import clonefrom sklearn.linear_model import LogisticRegression
customers = pd.read_csv("data/customers.csv")X = customers.drop(columns=["customer_id", "signup_date", "churned"])y = customers["churned"]
model = LogisticRegression(C=0.5) # hyperparameters go into __init__print(model, model.get_params()["C"]) # repr shows non-default values onlymodel.set_params(max_iter=500) # returns modelfresh = clone(model) # unfitted, same hyperparametersprint(fresh, hasattr(fresh, "coef_"))LogisticRegression(C=0.5) 0.5LogisticRegression(C=0.5, max_iter=500) FalseTrain/test split
Section titled “Train/test split”from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, stratify=y, random_state=42 # order: X_tr, X_te, y_tr, y_te)print(X_train.shape, X_test.shape, round(y_train.mean(), 4), round(y_test.mean(), 4))(3750, 12) (1250, 12) 0.1925 0.1928| Data | Split |
|---|---|
| classification | stratify=y |
| regression | plain random split; KFold(shuffle=True) for CV |
| time-ordered rows | train on the past, test on the future; shuffle=False or TimeSeriesSplit (module 40) |
| several rows per customer, patient or store | group-aware split: GroupShuffleSplit, GroupKFold (module 37) |
Pipeline
Section titled “Pipeline”from sklearn.impute import SimpleImputerfrom sklearn.pipeline import Pipeline, make_pipelinefrom sklearn.preprocessing import StandardScaler
pipe = Pipeline([ ("impute", SimpleImputer(strategy="median")), # (name, estimator) ("scale", StandardScaler()), # every step but the last: a transformer ("model", LogisticRegression()), # the last step: any estimator])auto = make_pipeline(SimpleImputer(), StandardScaler(), LogisticRegression())print([name for name, _ in auto.steps]) # automatic lowercase namespipe.set_params(impute__strategy="mean", model__C=0.1) # step__paramprint(pipe["model"].C, len(pipe), type(pipe[:-1]).__name__)['simpleimputer', 'standardscaler', 'logisticregression']0.1 3 Pipeline| Call on the pipeline | Runs |
|---|---|
fit(X, y) |
fit_transform on each transformer, then fit on the last step |
predict(X), predict_proba(X), score(X, y) |
transform on each transformer, then that method of the last step |
transform(X) |
transform on every step (the last must be a transformer) |
set_params(step__param=v) |
set_params(param=v) on that step; nests: prep__num__strategy |
"passthrough" or None as a step |
skips that step (useful in searches) |
ColumnTransformer
Section titled “ColumnTransformer”from sklearn.compose import ColumnTransformer, make_column_selectorfrom sklearn.preprocessing import OneHotEncoder
prep = ColumnTransformer( [ ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), make_column_selector(dtype_include="number")), ("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), make_column_selector(dtype_include="str")), # pandas 3 text columns ], remainder="drop", # default; "passthrough" keeps unlisted columns verbose_feature_names_out=False, # "tenure_months", not "num__tenure_months")prep.set_output(transform="pandas") # before fitXt = prep.fit_transform(X_train)print(Xt.shape, list(Xt.columns[8:11]))(3750, 22) ['region_East', 'region_North', 'region_South']| Column spec | Selects |
|---|---|
["age", "plan"] |
these names |
make_column_selector(dtype_include="number") |
int and float columns |
make_column_selector(dtype_include="str") |
pandas 3 text columns |
make_column_selector(dtype_exclude="number") |
everything that is not numeric |
make_column_selector(pattern="^log_") |
names matching a regular expression |
slice(0, 3) or [0, 1, 2] |
columns by position (arrays) |
FunctionTransformer and target transforms
Section titled “FunctionTransformer and target transforms”from sklearn.preprocessing import FunctionTransformer
log_step = FunctionTransformer(np.log1p, feature_names_out="one-to-one") # statelessprint(log_step.fit_transform(X_train[["monthly_charges"]].head(2)).round(3)) monthly_charges53 3.4044249 4.042| Need | Tool |
|---|---|
| a fixed function of the features | FunctionTransformer(func); use a named function, not a lambda, if you save the model |
| a function with arguments | FunctionTransformer(np.clip, kw_args={"a_min": 0, "a_max": 100}) |
a transform of the target y |
TransformedTargetRegressor(regressor=model, func=np.log, inverse_func=np.exp) |
| a learned transform | a stateful transformer (built-in or custom), never a FunctionTransformer |
Custom estimator template
Section titled “Custom estimator template”from sklearn.base import BaseEstimator, OneToOneFeatureMixin, TransformerMixinfrom sklearn.utils.validation import check_is_fitted, validate_data
class QuantileClipper(OneToOneFeatureMixin, TransformerMixin, BaseEstimator): """Mixins first, BaseEstimator last."""
def __init__(self, lower: float = 0.01, upper: float = 0.99) -> None: self.lower = lower # store unchanged, same name, no checks here self.upper = upper
def fit(self, X, y=None): # y=None: pipelines pass y to every step if not 0 <= self.lower < self.upper <= 1: # validate in fit raise ValueError("need 0 <= lower < upper <= 1") X = validate_data(self, X, dtype=np.float64) # sets n_features_in_ self.lower_, self.upper_ = np.quantile(X, [self.lower, self.upper], axis=0) return self # always
def transform(self, X): check_is_fitted(self) # NotFittedError before fit X = validate_data(self, X, dtype=np.float64, reset=False) # same columns? return np.clip(X, self.lower_, self.upper_)
clip = QuantileClipper(upper=0.95).fit(X_train[["support_tickets"]])print(clip, clip.upper_, clip.get_feature_names_out(), clone(clip).get_params())QuantileClipper(upper=0.95) [3.] ['support_tickets'] {'lower': 0.01, 'upper': 0.95}| Base class | Adds |
|---|---|
BaseEstimator |
get_params, set_params, repr, clone support |
TransformerMixin |
fit_transform; set_output only if the class has get_feature_names_out |
ClassifierMixin |
score = accuracy; marks a classifier (stratified CV by default) |
RegressorMixin |
score = R²; marks a regressor |
OneToOneFeatureMixin |
get_feature_names_out = input names |
ClassNamePrefixFeaturesOutMixin |
get_feature_names_out = classname0, classname1, … (needs _n_features_out) |
Test a custom estimator with scikit-learn’s own checks (about 50 per estimator: unfitted errors, clone, row-order invariance, pickling, …). Each check is one pytest test:
from sklearn.utils.estimator_checks import parametrize_with_checks
from my_estimators import QuantileClipper # import from a module, not __main__
@parametrize_with_checks([QuantileClipper()])def test_sklearn_compatible(estimator, check): check(estimator)Run it with pytest -q test_estimators.py. Outside pytest, check_estimator(QuantileClipper(), on_fail=None) returns one result dict per check (it also warns for every skipped check).
Cross-validation
Section titled “Cross-validation”from sklearn.model_selection import StratifiedKFold, cross_val_score, cross_validate
model = make_pipeline(prep, LogisticRegression(max_iter=1000))cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) # one object for allscores = cross_val_score(model, X_train, y_train, cv=cv, scoring="roc_auc")print(f"ROC-AUC {scores.mean():.3f} ± {scores.std():.3f}")res = cross_validate(model, X_train, y_train, cv=cv, scoring={"acc": "accuracy", "auc": "roc_auc"}, return_train_score=True)print(sorted(res))ROC-AUC 0.813 ± 0.011['fit_time', 'score_time', 'test_acc', 'test_auc', 'train_acc', 'train_auc']| Splitter | Use for |
|---|---|
KFold(5, shuffle=True, random_state=42) |
regression, i.i.d. rows |
StratifiedKFold(5, shuffle=True, random_state=42) |
classification |
RepeatedStratifiedKFold(n_splits=5, n_repeats=3, random_state=42) |
small data: a steadier mean |
GroupKFold(5) |
several rows per group (module 37) |
TimeSeriesSplit(5) |
time-ordered rows (module 40) |
cv=5 (an int) |
StratifiedKFold(5) for classifiers, KFold(5) otherwise, without shuffle |
scoring= name |
Task | Higher is better? |
|---|---|---|
"accuracy", "balanced_accuracy" |
classification | yes |
"roc_auc", "average_precision" |
binary classification, ranking | yes |
"f1", "precision", "recall" |
binary classification at threshold 0.5 | yes |
"neg_log_loss" |
probabilities | yes (negated loss) |
"r2" |
regression | yes |
"neg_root_mean_squared_error", "neg_mean_absolute_error" |
regression | yes (negated error) |
cross_validate keys: fit_time, score_time, test_<name> and, with return_train_score=True, train_<name>. With one metric the names are test_score and train_score. Add return_estimator=True to get the fitted clones.
Persistence
Section titled “Persistence”import jsonfrom pathlib import Path
import joblibimport sklearn
model.fit(X_train, y_train)Path("output").mkdir(exist_ok=True)joblib.dump(model, "output/churn.joblib") # the whole pipelinemeta = {"sklearn_version": sklearn.__version__, "features": list(X_train.columns)}Path("output/churn.json").write_text(json.dumps(meta))loaded = joblib.load("output/churn.joblib") # only files you trustprint(np.array_equal(loaded.predict(X_test), model.predict(X_test)))True| Rule | Why |
|---|---|
| save the whole pipeline | the preprocessing is part of the model |
| load only trusted files | unpickling can run arbitrary code; consider skops.io for shared files |
| same scikit-learn version to load | another version warns (InconsistentVersionWarning) and may predict differently |
| pin the whole environment | the file also depends on Python, NumPy, SciPy and joblib; save their versions in the metadata |
| custom classes in an importable module | the file stores module.ClassName; __main__ classes cannot be found later |
| named functions, no lambdas | pickle cannot save a lambda |
| save metadata next to the file | version, features, scores, training date |
Gotchas
Section titled “Gotchas”fit_transformon test data refits the step on the test rows. Usetransform.- Learned preprocessing outside a pipeline leaks into cross-validation. Put every learned step inside the pipeline.
make_column_selector(dtype_include=object)warns in pandas 3. Use"str".set_output(transform="pandas")must come beforefit, or inner steps warn about feature names.OneHotEncoder()raises on a category it has not seen. Production data always has new values; passhandle_unknown="ignore".- One underscore (
model_C) or a wrong step name raisesValueError: Invalid parameter. Uselist(pipe.get_params())to see the valid names. - A custom
__init__that renames, validates or computes breaksget_params()andclone(). Store arguments unchanged. fit()withoutreturn selfreturnsNone; chained calls and pipelines fail.cv=5does not shuffle. Pass a splitter withshuffle=True, random_state=42, and reuse that one object for every model you compare.neg_scores are negative on purpose. Flip the sign to report an error.- A CV mean without a standard deviation hides noise. Differences smaller than about one standard deviation are not evidence.
- Accuracy on imbalanced classes flatters every model. Compare with a dummy baseline and report ROC-AUC or recall.
- Score the test set once, at the end. Tuning on it makes it part of training.
clone()returns an unfitted copy. Usecopy.deepcopyor joblib to copy a fitted model.