Skip to content

scikit-learn API

Every scikit-learn object follows one small contract: settings go into __init__, fit learns from data, and the other methods use what fit learned. This page covers that contract, pipelines, column-wise preprocessing, pandas output, custom estimators and saving models. The examples use data/customers.csv (churn). The blocks share one session:

import numpy as np
import pandas as pd
import sklearn
from sklearn.model_selection import train_test_split
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
customers = pd.read_csv("data/customers.csv")
X = customers.drop(columns=["customer_id", "signup_date", "churned"])
y = customers["churned"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
I want to… Use… Notes
learn from data est.fit(X, y) returns est, so calls chain
apply a learned transformation est.transform(X) transformers only
fit and transform training rows est.fit_transform(X_train) never on test rows
predict labels or numbers est.predict(X) classifiers, regressors
predict class probabilities est.predict_proba(X)[:, 1] columns follow est.classes_
get a ranking score est.decision_function(X) linear models, SVMs
get the default score est.score(X, y) accuracy or R²
read or change hyperparameters est.get_params(), est.set_params(C=0.1) set_params returns est
an unfitted copy with the same settings sklearn.base.clone(est)
a fitted copy copy.deepcopy(est) clone drops what was learned
check that a model is fitted check_is_fitted(est) raises NotFittedError
know the input columns est.feature_names_in_, est.n_features_in_ set by fit
know the output columns est.get_feature_names_out() transformers and pipelines
chain steps Pipeline([("name", step), ...]), make_pipeline(...) last step: any estimator
set a parameter inside a pipeline pipe.set_params(model__C=0.1) step__param, double underscore
list every valid parameter name sorted(pipe.get_params())
reach a step pipe["model"], pipe[-1], pipe.named_steps.model
the preprocessing part only pipe[:-1] a new Pipeline sharing fitted steps
skip a step (in a search) pipe.set_params(scale="passthrough")
cache slow steps Pipeline(steps, memory="cache_dir") for searches over the last step
put features side by side FeatureUnion([...]), make_union(...) outputs are concatenated
different steps per column group ColumnTransformer([(name, step, cols), ...])
select columns by dtype make_column_selector(dtype_include="number") "str" for pandas 3 text
select columns by name make_column_selector(pattern="^log_") a regular expression
keep the other columns ColumnTransformer(..., remainder="passthrough") default "drop"
short output names verbose_feature_names_out=False age, not num__age
DataFrames out of transformers est.set_output(transform="pandas") before fit; "polars" also works
pandas output everywhere sklearn.set_config(transform_output="pandas") or with sklearn.config_context(...)
a plain function as a step FunctionTransformer(np.log1p, feature_names_out="one-to-one") stateless
model a transformed target TransformedTargetRegressor(regressor, func=np.log, inverse_func=np.exp) predictions in original units
write a transformer class T(TransformerMixin, BaseEstimator) mixins first
write a classifier class C(ClassifierMixin, BaseEstimator) set classes_ in fit
validate input in my estimator validate_data(self, X); later reset=False sklearn.utils.validation
test my estimator check_estimator(est), @parametrize_with_checks([...]) dozens of checks (80 for Ridge)
route sample_weight through a search or pipeline set_config(enable_metadata_routing=True), model.set_fit_request(sample_weight=True).set_score_request(sample_weight=True) every consumer must state its request
use a prefit model inside a meta-estimator CalibratedClassifierCV(FrozenEstimator(fitted)) from sklearn.frozen import FrozenEstimator
save a fitted pipeline joblib.dump(pipe, "output/model.joblib") trusted files only
save without pickle risks skops.io.dump(pipe, "model.skops") load with a trusted-types list
Kind Mixin Main methods Examples
transformer TransformerMixin fit, transform, fit_transform StandardScaler, OneHotEncoder, SimpleImputer
classifier ClassifierMixin fit, predict, predict_proba, score (accuracy) LogisticRegression, RandomForestClassifier
regressor RegressorMixin fit, predict, score (R²) Ridge, HistGradientBoostingRegressor
clusterer ClusterMixin fit, fit_predict, labels_ KMeans, DBSCAN
outlier detector OutlierMixin fit_predict (−1 = outlier) IsolationForest
meta-estimator wraps another estimator the methods of what it wraps Pipeline, GridSearchCV, CalibratedClassifierCV
What Where Naming Example
hyperparameters __init__ arguments, stored unchanged no underscore C, max_depth, strategy
learned attributes set by fit trailing underscore coef_, mean_, classes_, categories_
input checks set by fit trailing underscore n_features_in_, feature_names_in_ (DataFrame input)
fit diagnostics set by fit trailing underscore n_iter_, best_params_, oob_score_
private state anything leading underscore _tree, _n_features_out
from sklearn.base import clone
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.utils.validation import check_is_fitted
num_cols = ["tenure_months", "monthly_charges", "support_tickets"]
model = LogisticRegression(C=0.5) # settings only; nothing learned yet
print(model, model.get_params()["C"]) # repr shows non-default settings
model.fit(X_train[num_cols], y_train)
print(model.classes_, model.coef_.round(3), model.n_features_in_)
fresh = clone(model) # same settings, not fitted
print(hasattr(fresh, "coef_"), fresh.set_params(C=2.0))
Output
LogisticRegression(C=0.5) 0.5
[0 1] [[-0.056 0.019 0.441]] 3
False LogisticRegression(C=2.0)
check_is_fitted(fresh) # predict, transform and score raise the same error
Output
sklearn.exceptions.NotFittedError: This LogisticRegression instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
pipe = Pipeline([
("impute", SimpleImputer(strategy="median")), # (name, estimator) pairs
("scale", StandardScaler()), # every step but the last is a transformer
("model", LogisticRegression(max_iter=1000)), # the last: any estimator
])
pipe.set_params(model__C=0.3, impute__strategy="mean") # step__param
pipe.fit(X_train[num_cols], y_train)
print([name for name, _ in pipe.steps], pipe["model"].C)
print(pipe[:-1].transform(X_test[num_cols].head(2)).round(2)) # preprocessing only
print(round(pipe.score(X_test[num_cols], y_test), 3))
print([n for n in pipe.get_params() if n.startswith("scale__")])
Output
['impute', 'scale', 'model'] 0.3
[[-0.62 -0.11 -1.07]
[-0.77 0.14 -1.07]]
0.825
['scale__copy', 'scale__with_mean', 'scale__with_std']
Call on a pipeline Runs
fit(X, y) fit_transform on each transformer in order, then fit on the last step
predict, predict_proba, score, decision_function transform on each transformer, then that method of the last step
transform(X) transform on every step (the last must be a transformer)
fit_transform(X, y) as fit, and returns the last step’s output
get_feature_names_out() output names of the last transformer
pipe[1:], pipe[:-1] a sub-pipeline that shares the fitted steps
set_params(step="passthrough") removes a step without rebuilding the pipeline
Builder Step names Use when
Pipeline([("a", A()), ("m", M())]) yours you tune or inspect steps by name
make_pipeline(A(), M()) lowercase class names: standardscaler quick pipelines
FeatureUnion([("a", A()), ("b", B())]) / make_union yours / automatic several feature sets from the same input
TransformedTargetRegressor(regressor=pipe, func=np.log, inverse_func=np.exp) regressor__... the target needs a transform
from sklearn.compose import ColumnTransformer, make_column_selector
from sklearn.preprocessing import OneHotEncoder
prep = ColumnTransformer(
[
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()),
make_column_selector(dtype_include="number")), # int and float columns
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False),
make_column_selector(dtype_include="str")), # pandas 3 text columns
],
verbose_feature_names_out=False, # "age", not "num__age"
)
prep.set_output(transform="pandas") # before fit
Xt = prep.fit_transform(X_train)
print(Xt.shape, list(Xt.columns[:3]), Xt.columns[-1])
print(prep.named_transformers_["cat"].categories_[0]) # learned categories
clf = make_pipeline(prep, LogisticRegression(max_iter=1000)).fit(X_train, y_train)
print(round(clf.score(X_test, y_test), 3))
Output
(3750, 22) ['age', 'has_autopay', 'tenure_months'] payment_method_paypal
['East' 'North' 'South' 'West']
0.836
Column spec Selects
["age", "plan"] these names (DataFrame input)
"age" (a string, not a list) one column, passed as 1-D: only for text vectorizers
make_column_selector(dtype_include="number") numeric columns
make_column_selector(dtype_include="str") pandas 3 text columns (object warns)
make_column_selector(dtype_include="category") category columns
make_column_selector(dtype_exclude="number") everything that is not numeric
make_column_selector(pattern="charges$") names that match a regular expression
[0, 2], slice(0, 3), a boolean mask columns by position (NumPy input)
Option or attribute Meaning
remainder="drop" (default), "passthrough", or an estimator what happens to unlisted columns
"drop" or "passthrough" as a transformer drop or keep that group unchanged
sparse_threshold=0.3 the output is sparse when the share of nonzeros is below this
n_jobs fit the groups in parallel
transformers_, named_transformers_ the fitted groups
output_indices_ which output columns came from which group
make_column_transformer((step, cols), ...) the same with automatic names
Setting Scope Notes
est.set_output(transform="pandas") one estimator and its inner steps call it before fit
est.set_output(transform="polars") same needs polars installed
sklearn.set_config(transform_output="pandas") the whole process global state: affects every later estimator
with sklearn.config_context(transform_output="pandas"): one block restores the old value after the block
transform="default" NumPy arrays (or sparse) the default

Sparse outputs (for example OneHotEncoder() with its default sparse_output=True) cannot become DataFrames. Set sparse_output=False first.

with sklearn.config_context(transform_output="pandas"):
scaled = StandardScaler().fit_transform(X_train[num_cols]) # a DataFrame
print(type(scaled).__name__, list(scaled.columns))
print(sklearn.get_config()["transform_output"]) # back to the default
Output
DataFrame ['tenure_months', 'monthly_charges', 'support_tickets']
default
from sklearn.compose import TransformedTargetRegressor
from sklearn.linear_model import Ridge
from sklearn.preprocessing import FunctionTransformer
def add_charge_ratio(df: pd.DataFrame) -> pd.DataFrame:
"""Stateless: uses only the row itself, so nothing can leak."""
return df.assign(charge_ratio=df["total_charges"] / df["monthly_charges"])
def ratio_names(transformer, names):
return [*names, "charge_ratio"] # output names for get_feature_names_out
ratio = FunctionTransformer(add_charge_ratio, feature_names_out=ratio_names)
cols = ["monthly_charges", "total_charges"]
print(ratio.fit_transform(X_train[cols].head(2)))
print(ratio.get_feature_names_out(cols))
log_y = TransformedTargetRegressor(Ridge(), func=np.log1p, inverse_func=np.expm1)
log_y.fit(X_train[["tenure_months"]], X_train["monthly_charges"]) # fit on log1p(y)
print(log_y.predict(X_test[["tenure_months"]].head(2)).round(2)) # back in USD
Output
monthly_charges total_charges charge_ratio
53 29.09 1985.26 68.245
4249 55.95 220.18 3.935
['monthly_charges' 'total_charges' 'charge_ratio']
[56.69 56.68]
Need Tool
a fixed function of the features FunctionTransformer(func)
a function with arguments FunctionTransformer(np.clip, kw_args={"a_min": 0, "a_max": 100})
names for get_feature_names_out feature_names_out="one-to-one" or a callable (transformer, input_names) -> names
an inverse inverse_func=np.expm1; check_inverse=True (default) tests it on a sample
something learned from data (means, categories, quantiles) a real transformer, never FunctionTransformer
a transform of y TransformedTargetRegressor; regressor_ holds the fitted inner model

A transformer that groups rare categories (it learns the frequent ones in fit):

from sklearn.base import BaseEstimator, OneToOneFeatureMixin, TransformerMixin
from sklearn.utils.validation import validate_data
class RareGrouper(OneToOneFeatureMixin, TransformerMixin, BaseEstimator):
"""Replace categories seen fewer than min_count times with `other`."""
def __init__(self, min_count: int = 10, other: str = "other") -> None:
self.min_count = min_count # store arguments unchanged, same names
self.other = other
def fit(self, X, y=None): # y=None: pipelines pass y to every step
X = validate_data(self, X, dtype=None) # sets n_features_in_, names
self.keep_ = []
for col in X.T:
values, counts = np.unique(col, return_counts=True)
self.keep_.append(values[counts >= self.min_count])
return self # always return self
def transform(self, X):
check_is_fitted(self)
X = validate_data(self, X, dtype=None, reset=False) # same columns?
out = X.astype(object)
for j, keep in enumerate(self.keep_):
out[~np.isin(X[:, j], keep), j] = self.other
return out
towns = pd.DataFrame({"town": ["Oslo"] * 12 + ["Rome"] * 11 + ["Lima", "Kyiv"]})
grouper = RareGrouper().set_output(transform="pandas").fit(towns)
print(grouper.transform(towns)["town"].value_counts().to_dict())
print(grouper, grouper.get_feature_names_out(), clone(grouper).get_params())
Output
{'Oslo': 12, 'Rome': 11, 'other': 2}
RareGrouper() ['town'] {'min_count': 10, 'other': 'other'}

A classifier needs classes_, predict and, when it can, predict_proba:

from sklearn.base import ClassifierMixin
from sklearn.utils.multiclass import check_classification_targets
class NearestMean(ClassifierMixin, BaseEstimator):
"""Predict the class whose training mean is closest."""
def fit(self, X, y):
X, y = validate_data(self, X, y) # checks X and y together
check_classification_targets(y) # rejects a continuous y
self.classes_ = np.unique(y) # sorted labels: the column order
self.means_ = np.array([X[y == c].mean(axis=0) for c in self.classes_])
return self
def predict(self, X):
check_is_fitted(self)
X = validate_data(self, X, reset=False)
dist = ((X[:, None, :] - self.means_[None]) ** 2).sum(axis=2)
return self.classes_[dist.argmin(axis=1)]
nm = make_pipeline(StandardScaler(), NearestMean()).fit(X_train[num_cols], y_train)
print(nm[-1].classes_, round(nm.score(X_test[num_cols], y_test), 3)) # a template only
Output
[0 1] 0.676
Rule Why
__init__ only stores its arguments, with the same names get_params, set_params and clone read them back
validate hyperparameters in fit, not __init__ set_params would bypass checks in __init__
learned attributes end with _ and are set in fit check_is_fitted looks for them
fit returns self chaining and pipelines need it
fit(self, X, y=None) in transformers pipelines always pass y
mixins first, BaseEstimator last the method resolution order
validate_data(self, X) in fit, reset=False later sets and then checks n_features_in_ and feature_names_in_
no randomness without random_state use check_random_state(self.random_state) in fit
tags change behavior override __sklearn_tags__() (for example tags.input_tags.allow_nan = True)
Base class Adds
BaseEstimator get_params, set_params, repr, clone support, HTML display
TransformerMixin fit_transform; set_output when the class has get_feature_names_out
ClassifierMixin score = accuracy; marks a classifier (stratified cv=5)
RegressorMixin score = R²
OneToOneFeatureMixin get_feature_names_out = the input names
ClassNamePrefixFeaturesOutMixin get_feature_names_out = classname0, classname1, … (set _n_features_out)

Test a custom estimator against the full API contract with pytest:

test_estimators.py
from sklearn.utils.estimator_checks import parametrize_with_checks
from my_package.estimators import NearestMean, RareGrouper # importable module
@parametrize_with_checks([NearestMean(), RareGrouper()])
def test_sklearn_compatible(estimator, check):
check(estimator) # one pytest test per check
import json
from pathlib import Path
import joblib
Path("output").mkdir(exist_ok=True)
joblib.dump(clf, "output/churn.joblib") # the whole fitted pipeline
meta = {"sklearn": sklearn.__version__, "features": list(X_train.columns)}
Path("output/churn.json").write_text(json.dumps(meta)) # metadata next to it
loaded = joblib.load("output/churn.joblib") # only files you trust
print(np.array_equal(loaded.predict(X_test), clf.predict(X_test)))
Output
True
Format Save, load Safe for untrusted files? Notes
joblib (pickle) joblib.dump(m, path), joblib.load(path) no: loading runs code the default; same library versions to load
pickle pickle.dump, pickle.load no the same risks as joblib
skops skops.io.dump(m, path), skops.io.load(path, trusted=[...]) yes, with a reviewed type list skops.io.get_untrusted_types(file=path) lists what to review
ONNX skl2onnx.to_onnx(m, X[:1]), onnxruntime yes no Python or scikit-learn at serving time; not every estimator converts
XGBoost / LightGBM native model.save_model("m.json"), booster_.save_model("m.txt") yes stable across library versions; the booster only, not the pipeline
Caveat Fix
another scikit-learn version warns InconsistentVersionWarning and may predict differently pin the version; save it in the metadata; retrain on upgrade
custom classes defined in a notebook or __main__ cannot be found at load time put them in an importable module
a lambda in a FunctionTransformer cannot be pickled by pickle use a named function
loading a file from the internet runs arbitrary code load only your own files; use skops or ONNX to share
the model alone does not say what it expects store feature names, dtypes, metrics and the training date next to it
Trap Symptom Fix
fit_transform on test rows the test set gets its own statistics; scores look better than in production transform on everything but training rows
learned preprocessing outside the pipeline leakage in cross-validation put every learned step inside the pipeline
one underscore in a parameter name ValueError: Invalid parameter 'model_C' model__C; sorted(pipe.get_params()) lists valid names
set_output after fit a warning about feature names from inner steps call it before fit, or use config_context
make_column_selector(dtype_include=object) Pandas4Warning in pandas 3 dtype_include="str"
OneHotEncoder() meets a new category ValueError: Found unknown categories handle_unknown="ignore"
set_output(transform="pandas") with a sparse step ValueError about sparse output sparse_output=False
a column list as a string, "age" the step gets a 1-D input and fails ["age"]
a custom __init__ that renames or converts clone and get_params lose or change settings store each argument unchanged
fit without return self AttributeError: 'NoneType'... in a chain return self
clone(fitted) to copy a model the copy is unfitted copy.deepcopy or joblib
one transformer object in two pipelines the second fit overwrites the first clone(step) for each pipeline
predict_proba(X)[:, 1] with string labels the wrong class’s probability check est.classes_ first
sklearn.set_config(...) in a library changes every later estimator in the process config_context or set_output per estimator
joblib.load on a shared file arbitrary code can run trusted files only; skops with a reviewed list