Paper commentary
API design for machine learning software: experiences from the scikit-learn project
Scikit-learn gives every object one shared interface so models compose and reuse easily
- Problem Machine learning libraries often add framework code and custom classes, which makes their parts hard to combine and reuse. Users must learn a different pattern for each piece.
- Method Scikit-learn gives all its objects one shared API built from three small interfaces. Estimators fit a model, predictors add prediction and scoring, and transformers change data.
- Results The authors argue the shared interface makes composition and reuse possible without class inheritance. The paper reports design reasoning and project statistics rather than benchmark measurements.
One interface and batch-based data
Every object in scikit-learn shares one of three small interfaces, so a user learns one pattern and reuses it everywhere. The estimator interface fits a model, the predictor interface adds prediction and scoring, and the transformer interface changes data. Non-proliferation of classes means learning algorithms are the only objects with custom classes.
Users still need basic Python knowledge, because the library offers no command-line or graphical interface.
Datasets are plain NumPy arrays for dense data and SciPy sparse matrices for sparse data, not custom dataset classes. Each row is a sample and each column a variable, which matches how most scientific Python users already think about data. Working on arrays lets the code call vectorized NumPy and SciPy operations and stay short and readable.
The authors also point out that these formats come with loading and conversion tools, and vectorizers turn text into them.
The public interface processes batches of samples per call, not single samples. Per-call Python overhead and per-element dynamic type checking slow down single-sample calls, so batching avoids that cost. The authors argue that an API shouldn't lock a library into a suboptimal implementation strategy. Batching therefore leaves room for fast lower-level code, where memory hierarchy effects and internal parallelization come into play.
Why fit returns the estimator itself
An estimator becomes a fitted model when fit learns from training data and then hands back the same object. Construction and learning are strictly separated, similar to partial function application. The constructor does not see any actual data and does not perform any learning. All the constructor does is attach the given parameters to the object.
Hyper-parameters are set as public attributes, which matters for model inspection and model selection. Default hyper-parameter values are provided for all built-in estimators, so non-experts can run them out of the box.
Inside fit, the estimator runs a learning algorithm on the training data and determines model-specific parameters. The learned parameters become public attributes whose names carry a trailing underscore, such as coef_ for linear models. The authors kept one object for both roles, because two coupled instances would decrease ease of use and confuse newcomers.
On the developer side, separating estimators from models would create parallel class hierarchies and raise maintenance complexity. The authors believe decoupling is not worth the effort for these practical reasons. Decoupling would pay off when a model must ship to a new environment without complex software dependencies. Instead, estimators could export a fitted model to an agnostic description such as PMML, using their public attributes.
A logistic regression example shows the sequence in code, with the estimator constructed first. The estimator is initialized with penalty set to "l1" for ℓ1 regularization. Other hyper-parameters, such as C, are not given and keep their default values. Calling fit learns a model from X_train and y_train and stores it within the object. Swapping in a different algorithm only changes the constructor, for example RandomForestClassifier() in place of LogisticRegression.
That works because every estimator shares the same interface.
Composing and tuning workflows
Meta-estimators take an existing base estimator as input and use it internally for learning and prediction. All meta-estimators implement the regular estimator interface, so they can be used wherever an estimator can. OneVsOneClassifier wrapping logistic regression clones the base estimator, producing K(K-1)/2 binary estimators for K-way classification.
At prediction time, each binary estimator classifies a sample and the estimators vote to make the final decision. Logistic regression already uses a one-vs-rest scheme by default, so the wrapper only matters in advanced use cases.
Pipeline chains multiple estimators into one, and every step but the last must be a transformer. Fitting runs recursively: when one step remains its fit method is called, otherwise the first step is fitted and used to transform the training set. The rest of the pipeline is then fitted on the transformed data, so the chain behaves like a single estimator.
If the last step is a predictor, the pipeline exposes predict; if it is a transformer, the pipeline is a transformer. FeatureUnion concatenates the outputs of its transformers, so a union of inputs with d′ and d′′ features yields d′ + d′′ features. Calling fit on a FeatureUnion is the same as calling fit on each transformer and then joining their outputs.
One example combines linear PCA and kernel PCA through a FeatureUnion, selects the 10 best features with SelectKBest, and feeds them to an l2-regularized logistic regression. The selection step uses an ANOVA test to choose the features in the combination. Pipeline and FeatureUnion can be nested, so a complex workflow still fits and predicts as one object.
GridSearchCV enumerates the full cartesian product of parameter settings, while RandomizedSearchCV samples a fixed number of times from parameter distributions. Randomized search avoids the combinatorial explosion of grid search. Both fit the base estimator on each training split and evaluate it on the validation split, and the default score is the estimator's score method.
The SVC example uses two grids and 10-fold cross-validation to maximize the F1 score on the training set. A linear kernel ignores gamma, so a single grid would waste computing time on equivalent settings. GridSearchCV delegates predict, predict_proba, transform and score to the best estimator, optionally refitted on the whole training set.
Extending without inheritance
scikit-learn extends itself through duck typing, so an object counts as an estimator because it follows the interface, not because it inherits from a base class. An external estimator that follows the API and conventions can stand in for a built-in estimator. For example, it can be plugged into pipelines or grid search. External developers aren't forced to inherit from any scikit-learn class.
Extensibility also reaches the vectorization code for unstructured input, where estimators provide hooks for user-defined code. Objects or functions that follow a specific API can be passed as arguments when the vectorizer is constructed. The library then calls into this user code and passes it objects of standard Python or NumPy types. Because of this, external user code can stay independent of the scikit-learn class hierarchy.
The authors state a rule of thumb: user code shouldn't be tied to scikit-learn, because scikit-learn is a library and not a framework. This principle avoids a well-known problem of object-oriented design. Programs using scikit-learn shouldn't be intimately tied to it.
Limits and open problems
Scikit-learn objects aren't optimized for single-sample calls, because the public interface is built around batches of samples. Batch processing lets NumPy and SciPy avoid per-call Python overhead and per-element dynamic type checking. The few online learners implemented in the library take mini-batches instead of single samples. Parallelism stays coarse, because some estimators use multicore processors only at a coarse-grained level.
CPython, the main implementation the project targets, can't execute Python code on multiple CPUs simultaneously. Finer-grained multicore support could come from OpenMP, which recent versions of Cython support.
Model persistence is still unresolved, because the project has no long-term solution for it. Python's pickle module is the recommended tool, but it only offers a file format. Pickle doesn't preserve compatibility between versions, so saved models can break as the library changes. Its deserializer may execute arbitrary Python code, so models from untrusted sources can't be safely unpickled.
The library doesn't yet support neural networks, ensemble meta-estimators for bagging or subsampling, or missing value completion algorithms. Structured prediction and reinforcement learning are out of scope, because they would require quite different data representations and APIs.
The usability case rests on design argument and project statistics rather than on measurements. Project statistics include 183 unique contributors to the codebase and 37,000 unique visitors per month to the documentation. The comparison with other packages concerns API design, and the paper doesn't measure performance against them. Those packages focus on GUIs or command-line use, which is a different design goal from scikit-learn's.
Paper info
- Authors
- Buitinck, Lars, Louppe, Gilles, Blondel, Mathieu, Pedregosa, Fabian, Mueller, Andreas, Grisel, Olivier, Niculae, Vlad, Prettenhofer, Peter, Gramfort, Alexandre, Grobler, Jaques, Layton, Robert, Vanderplas, Jake, Joly, Arnaud, Holt, Brian, Varoquaux, Gaël
- Venue
- arXiv · Preprint
- First published
- 2013-9-1
- Added
- 2026-11-12
- Updated
- 2013-9-1
- Version
- v1
- arXiv
- 1309.0238
- Category
- cs.LG · cs.MS
- Original paper terms
- arXiv non-exclusive 1.0
- What we show
- Paper info and commentary
AI commentary is a separate explanation from the original paper and may contain errors. The original paper and figures follow each source's terms of use and any rights noted separately.
Quote from the paper
Buitinck, Lars, Louppe, Gilles, Blondel, Mathieu, Pedregosa, Fabian, Mueller, Andreas, Grisel, Olivier, Niculae, Vlad, Prettenhofer, Peter, Gramfort, Alexandre, Grobler, Jaques, Layton, Robert, Vanderplas, Jake, Joly, Arnaud, Holt, Brian, Varoquaux, Gaël (2013). API design for machine learning software: experiences from the scikit-learn project. arXiv:1309.0238v1. https://arxiv.org/abs/1309.0238v1
BibTeX
@misc{lars2013design,
title = {{API design for machine learning software: experiences from the scikit-learn project}},
author = {Buitinck, Lars and Louppe, Gilles and Blondel, Mathieu and Pedregosa, Fabian and Mueller, Andreas and Grisel, Olivier and Niculae, Vlad and Prettenhofer, Peter and Gramfort, Alexandre and Grobler, Jaques and Layton, Robert and Vanderplas, Jake and Joly, Arnaud and Holt, Brian and Varoquaux, Gaël},
year = {2013},
eprint = {1309.0238},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/1309.0238v1}
}