Foundations to Frontier
Tests
D. Classical Machine Learning › D0 Core Concepts (concept pages)

The scikit-learn API: Estimators, Transformers, Pipelines and ColumnTransformer

scikit-learn's power comes from a small, consistent interface. Every estimator is configured by constructor hyperparameters, learns from data in fit, and exposes learned attributes with a trailing underscore; predictors add predict and score, and transformers add transform. Because all objects follow this contract, they compose: a Pipeline chains transformers and a final model into one estimator, a ColumnTransformer applies different preprocessing to different columns, and tools such as cross_val_score and GridSearchCV work with any of them, tuning nested hyperparameters through 'step__parameter' names and cloning unfitted copies for each fold. This page explains the contract and the composition tools. In the exercises you build a miniature scikit-learn with these pieces; then you measure how caching fitted pipeline steps speeds up hyperparameter search.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Building with standard bricks

LEGO bricks all have the same studs, so any brick fits any other. scikit-learn works the same way. Every tool, whether it fills in blanks, scales numbers or makes predictions, has the same “studs”: a fit method to learn and a transform or predict method to use what it learned. That lets you snap tools together into a pipeline that behaves like a single tool.

Inside a scikit-learn pipeline
fit() learned: mean = [65.75, 3.02], std = [3.19, 0.88]
tempmode=Amode=Bmode=Ccurrent
train-1.49100-1.16
train0.080100.08
train1.33100-0.48
train0.080011.56
test7.600106.76
test0.08000-0.03
pipe = make_pipeline(ColumnTransformer([("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), ["temp", "current"]), ("cat", OneHotEncoder(handle_unknown="ignore"), ["mode"])]), Ridge()) — calling pipe.fit(X_train, y_train) runs fit/transform through every step; pipe.predict(X_test) only transforms. Note the test row with the unseen mode "D" and the extreme temperature: the learned statistics do not change.
Why engineers care

Production ML systems fail when preprocessing in deployment differs from training. A pipeline packages every step with its learned numbers into one object you can cross-validate, save, version and ship, so the satellite ground station runs exactly what was tested.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Every scikit-learn estimator learns with…
  2. 2. A pipeline lets you…
  3. 3. In the demo, test rows are…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

The estimator contract

Kind Methods Examples
estimator fit(X, y), get_params, set_params everything
predictor predict, score, and predict_proba or decision_function for classifiers LogisticRegression, RandomForestRegressor
transformer transform, fit_transform StandardScaler, OneHotEncoder, PCA
meta-estimator wraps estimators Pipeline, ColumnTransformer, GridSearchCV, CalibratedClassifierCV

Conventions:

  • hyperparameters go in __init__ and are stored unchanged;
  • learned attributes end in _ (coef_, mean_, classes_);
  • fit returns self;
  • clone creates an unfitted copy with the same hyperparameters.
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.model_selection import GridSearchCV
pre = ColumnTransformer([("num", Pipeline([("imp", SimpleImputer(strategy="median")), ("sc", StandardScaler())]), num_cols),
                         ("cat", OneHotEncoder(handle_unknown="ignore"), cat_cols)])
pipe = Pipeline([("pre", pre), ("model", Ridge())])
search = GridSearchCV(pipe, {"model__alpha": [0.1, 1, 10], "pre__num__imp__strategy": ["mean", "median"]}, cv=5).fit(X, y)
print(search.best_params_, search.best_score_)
📝 Quick check (Level 1)
0/3 answered
  1. 1. A learned attribute is named like…
  2. 2. To tune Ridge's alpha inside a pipeline step called 'model':
  3. 3. clone(est) returns…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

How the pieces work

  • get_params / set_params read and write the constructor arguments. With deep=True, nested estimators appear as step__param, recursively.
  • Pipeline.fit calls fit_transform on each transformer in turn and fit on the last step. predict calls transform on each and predict on the last.
  • ColumnTransformer fits each transformer on its own columns and stacks the outputs horizontally.
  • GridSearchCV builds every parameter combination; for each one and each fold it clones the pipeline, sets the parameters, fits on the training part and scores on the held-out part; finally it refits the best on all data. Because the whole pipeline is cross-validated, preprocessing cannot leak (D0.3).
  • Caching: Pipeline(memory=...) stores fitted transformers keyed by their parameters and data, so changing only the final model’s settings doesn’t refit expensive upstream steps.
🐍 Exercise 1: a miniature scikit-learn
Implement BaseEstimator with get_params/set_params (including nested step__param names), clone, TransformerMixin, a StandardScaler and Ridge regressor following the conventions, a Pipeline, a ColumnTransformer with a one-hot encoder, and a grid search with cross-validation that clones the pipeline for every fold.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Pipeline.predict calls, on the transformers…
  2. 2. Why does GridSearchCV clone the estimator for each fold?
  3. 3. Pipeline caching helps when…

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

Writing your own components

  • Custom estimators: inherit from BaseEstimator (and TransformerMixin, RegressorMixin or ClassifierMixin); set only hyperparameters in __init__; validate inputs in fit. Use sklearn.utils.estimator_checks.check_estimator to test compliance.
  • FunctionTransformer wraps stateless functions (log, cyclic encoding).
  • Output: set_output(transform="pandas") keeps column names through pipelines; get_feature_names_out traces features.
  • Persistence: joblib.dump(pipe), or ONNX/skops for safer deployment. Pin library versions, since pickles are version-specific.
  • Beyond scikit-learn: XGBoost, LightGBM and many libraries implement the same API, so they drop into pipelines and searches.

Interview questions.

  • Why should __init__ not modify or validate parameters? clone and set_params must reproduce the object exactly from its parameters, and grid search sets them after construction.
  • How do you prevent leakage when combining feature selection and cross-validation? Put the selector in the pipeline.
📝 Quick check (Level 3)
0/3 answered
  1. 1. check_estimator is used to…
  2. 2. A stateless transformation (log) can be wrapped with…
  3. 3. Pickled scikit-learn models are…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Exercise 1.

  • get_params and set_params handle nested names such as model__alpha and scale__with_mean.
  • clone copies settings but not learned coefficients.
  • A scaler + ridge pipeline handles features on scales from 0.01 to 100 (test R² above 0.9).
  • A ColumnTransformer stacks a scaled numeric column with three one-hot columns.
  • Grid search chooses α = 0.01 with CV R² 0.985.

Exercise 2: PCA → ridge on 400 × 200 data with 20 latent factors. The grid covers 4 numbers of components × 8 ridge strengths × 5 folds.

PCA fits Time
no cache 160 0.53 s
cache keyed by (components, fold) 20 0.09 s
  • Caching gives exactly the same scores while doing 8× fewer SVDs, and runs about 6× faster. (Laptop timings; in the browser both runs are several times slower and the speed-up is about 4×, because the SVD is a smaller share of the cost there.)
  • The search picks 20 components with α = 1000 (CV R² 0.906; 50 and 150 are within 0.001, since the data have 20 latent factors), while 10 components underfit badly (R² 0.50).
  • The speed-up grows with the number of final-step settings, which is why scikit-learn’s Pipeline(memory=...) exists.
🐍 Exercise 2 (research): how much does pipeline caching save?
Grid-search a PCA → ridge pipeline over numbers of components and ridge strengths with 5-fold CV, with and without caching fitted PCA objects by (parameters, fold); count PCA fits, time both runs, check the scores are identical, and report the best configuration.

The scikit-learn API in AI, robotics and aerospace

  • Telemetry models: one pipeline object with imputation, scaling, features and model, versioned with its data (C7.5).
  • Interoperability: XGBoost, LightGBM, CatBoost, imbalanced-learn and skorch (PyTorch models) all follow the API.
  • Deployment: pipelines exported to ONNX for embedded inference.
  • Research code: consistent interfaces make benchmark comparisons fair (same CV, same preprocessing).

References

  1. F. Pedregosa et al. (2011). “Scikit-learn: machine learning in Python.” JMLR 12.
  2. L. Buitinck et al. (2013). “API design for machine learning software: experiences from the scikit-learn project.” ECML PKDD workshop.
  3. scikit-learn developers. Developing scikit-learn estimators, developer guide.
  4. scikit-learn developers. Pipelines and composite estimators, user guide.
  5. A. Géron (2022). Hands-On Machine Learning with Scikit-Learn, Keras and TensorFlow, 3rd ed. O’Reilly.