Developing scikit-learn estimators#
Whether you are proposing an estimator for inclusion in scikit-learn,developing a separate package compatible with scikit-learn, orimplementing custom components for your own projects, this chapterdetails how to develop objects that safely interact with scikit-learnpipelines and model selection tools.
This section details the public API you should use and implement for a scikit-learncompatible estimator. Inside scikit-learn itself, we experiment and use some privatetools and our goal is always to make them public once they are stable enough, so thatyou can also use them in your own projects.
APIs of scikit-learn objects#
There are two major types of estimators. You can think of the first group as simpleestimators, which consists of most estimators, such asLogisticRegression
orRandomForestClassifier
. And the second group aremeta-estimators, which are estimators that wrap other estimators.Pipeline
andGridSearchCV
are two examples of meta-estimators.
Here we start with a few vocabulary terms, and then we illustrate how you can implementyour own estimators.
Elements of the scikit-learn API are described more definitively in theGlossary of Common Terms and API Elements.
Different objects#
The main objects in scikit-learn are (one class can implement multiple interfaces):
- Estimator:
The base object, implements a
fit
method to learn from data, either:estimator=estimator.fit(data,targets)
or:
estimator=estimator.fit(data)
- Predictor:
For supervised learning, or some unsupervised problems, implements:
prediction=predictor.predict(data)
Classification algorithms usually also offer a way to quantify certaintyof a prediction, either using
decision_function
orpredict_proba
:probability=predictor.predict_proba(data)
- Transformer:
For modifying the data in a supervised or unsupervised way (e.g. by adding, changing,or removing columns, but not by adding or removing rows). Implements:
new_data=transformer.transform(data)
When fitting and transforming can be performed much more efficientlytogether than separately, implements:
new_data=transformer.fit_transform(data)
- Model:
A model that can give agoodness of fit measure or a likelihood ofunseen data, implements (higher is better):
score=model.score(data)
Estimators#
The API has one predominant object: the estimator. An estimator is anobject that fits a model based on some training data and is capable ofinferring some properties on new data. It can be, for instance, aclassifier or a regressor. All estimators implement the fit method:
estimator.fit(X,y)
Out of all the methods that an estimator implements,fit
is usually the one youwant to implement yourself. Other methods such asset_params
,get_params
, etc.are implemented inBaseEstimator
, which you should inherit from.You might need to inherit from more mixins, which we will explain later.
Instantiation#
This concerns the creation of an object. The object’s__init__
method might acceptconstants as arguments that determine the estimator’s behavior (like thealpha
constant inSGDClassifier
). It should not, however, takethe actual training data as an argument, as this is left to thefit()
method:
clf2=SGDClassifier(alpha=2.3)clf3=SGDClassifier([[1,2],[2,3]],[-1,1])# WRONG!
Ideally, the arguments accepted by__init__
should all be keyword arguments with adefault value. In other words, a user should be able to instantiate an estimator withoutpassing any arguments to it. In some cases, where there are no sane defaults for anargument, they can be left without a default value. In scikit-learn itself, we havevery few places, only in some meta-estimators, where the sub-estimator(s) argument isa required argument.
Most arguments correspond to hyperparameters describing the model or the optimisationproblem the estimator tries to solve. Other parameters might define how the estimatorbehaves, e.g. defining the location of a cache to store some data. These initialarguments (or parameters) are always remembered by the estimator. Also note that theyshould not be documented under the “Attributes” section, but rather under the“Parameters” section for that estimator.
In addition,every keyword argument accepted by__init__
shouldcorrespond to an attribute on the instance. Scikit-learn relies on this tofind the relevant attributes to set on an estimator when doing model selection.
To summarize, an__init__
should look like:
def__init__(self,param1=1,param2=2):self.param1=param1self.param2=param2
There should be no logic, not even input validation, and the parameters should not bechanged; which also means ideally they should not be mutable objects such as lists ordictionaries. If they’re mutable, they should be copied before being modified. Thecorresponding logic should be put where the parameters are used, typically infit
.The following is wrong:
def__init__(self,param1=1,param2=2,param3=3):# WRONG: parameters should not be modifiedifparam1>1:param2+=1self.param1=param1# WRONG: the object's attributes should have exactly the name of# the argument in the constructorself.param3=param2
The reason for postponing the validation is that if__init__
includes inputvalidation, then the same validation would have to be performed inset_params
, whichis used in algorithms likeGridSearchCV
.
Also it is expected that parameters with trailing_
arenot to be setinside the__init__
method. More details on attributes that are not initarguments come shortly.
Fitting#
The next thing you will probably want to do is to estimate some parameters in the model.This is implemented in thefit()
method, and it’s where the training happens.For instance, this is where you have the computation to learn or estimate coefficientsfor a linear model.
Thefit()
method takes the training data as arguments, which can be onearray in the case of unsupervised learning, or two arrays in the caseof supervised learning. Other metadata that come with the training data, such assample_weight
, can also be passed tofit
as keyword arguments.
Note that the model is fitted usingX
andy
, but the object holds noreference toX
andy
. There are, however, some exceptions to this, as inthe case of precomputed kernels where this data must be stored for use bythe predict method.
Parameters | |
---|---|
X | array-like of shape (n_samples, n_features) |
y | array-like of shape (n_samples,) |
kwargs | optional data-dependent parameters |
The number of samples, i.e.X.shape[0]
should be the same asy.shape[0]
. If thisrequirement is not met, an exception of typeValueError
should be raised.
y
might be ignored in the case of unsupervised learning. However, tomake it possible to use the estimator as part of a pipeline that canmix both supervised and unsupervised transformers, even unsupervisedestimators need to accept ay=None
keyword argument inthe second position that is just ignored by the estimator.For the same reason,fit_predict
,fit_transform
,score
andpartial_fit
methods need to accept ay
argument inthe second place if they are implemented.
The method should return the object (self
). This pattern is usefulto be able to implement quick one liners in an IPython session such as:
y_predicted=SGDClassifier(alpha=10).fit(X_train,y_train).predict(X_test)
Depending on the nature of the algorithm,fit
can sometimes also accept additionalkeywords arguments. However, any parameter that can have a value assigned prior tohaving access to the data should be an__init__
keyword argument. Ideally,fitparameters should be restricted to directly data dependent variables. For instance aGram matrix or an affinity matrix which are precomputed from the data matrixX
aredata dependent. A tolerance stopping criteriontol
is not directly data dependent(although the optimal value according to some scoring function probably is).
Whenfit
is called, any previous call tofit
should be ignored. Ingeneral, callingestimator.fit(X1)
and thenestimator.fit(X2)
shouldbe the same as only callingestimator.fit(X2)
. However, this may not betrue in practice whenfit
depends on some random process, seerandom_state. Another exception to this rule is when thehyper-parameterwarm_start
is set toTrue
for estimators thatsupport it.warm_start=True
means that the previous state of thetrainable parameters of the estimator are reused instead of using thedefault initialization strategy.
Estimated Attributes#
According to scikit-learn conventions, attributes which you’d want to expose to yourusers as public attributes and have been estimated or learned from the data must alwayshave a name ending with trailing underscore, for example the coefficients of someregression estimator would be stored in acoef_
attribute afterfit
has beencalled. Similarly, attributes that you learn in the process and you’d like to store yetnot expose to the user, should have a leading underscore, e.g._intermediate_coefs
.You’d need to document the first group (with a trailing underscore) as “Attributes” andno need to document the second group (with a leading underscore).
The estimated attributes are expected to be overridden when you callfit
a secondtime.
Universal attributes#
Estimators that expect tabular input should set an_features_in_
attribute atfit
time to indicate the number of features that the estimatorexpects for subsequent calls topredict ortransform.SeeSLEP010for details.
Similarly, if estimators are given dataframes such as pandas or polars, they shouldset afeature_names_in_
attribute to indicate the features names of the input data,detailed inSLEP007.Usingvalidate_data
would automatically set theseattributes for you.
Rolling your own estimator#
If you want to implement a new estimator that is scikit-learn compatible, there areseveral internals of scikit-learn that you should be aware of in addition tothe scikit-learn API outlined above. You can check whether your estimatoradheres to the scikit-learn interface and standards by runningcheck_estimator
on an instance. Theparametrize_with_checks
pytestdecorator can also be used (see its docstring for details and possibleinteractions withpytest
):
>>>fromsklearn.utils.estimator_checksimportcheck_estimator>>>fromsklearn.treeimportDecisionTreeClassifier>>>check_estimator(DecisionTreeClassifier())# passes[...]
The main motivation to make a class compatible to the scikit-learn estimatorinterface might be that you want to use it together with model evaluation andselection tools such asGridSearchCV
andPipeline
.
Before detailing the required interface below, we describe two ways to achievethe correct interface more easily.
Project template:
We provide aproject template which helps in thecreation of Python packages containing scikit-learn compatible estimators. Itprovides:
an initial git repository with Python package directory structure
a template of a scikit-learn estimator
an initial test suite including use of
parametrize_with_checks
directory structures and scripts to compile documentation and examplegalleries
scripts to manage continuous integration (testing on Linux, MacOS, and Windows)
instructions from getting started to publishing onPyPi
base.BaseEstimator
and mixins:
We tend to use “duck typing” instead of checking forisinstance
, which meansit’s technically possible to implement an estimator without inheriting fromscikit-learn classes. However, if you don’t inherit from the right mixins, eitherthere will be a large amount of boilerplate code for you to implement and keep insync with scikit-learn development, or your estimator might not function the sameway as a scikit-learn estimator. Here we only document how to develop an estimatorusing our mixins. If you’re interested in implementing your estimator withoutinheriting from scikit-learn mixins, you’d need to check our implementations.
For example, below is a custom classifier, with more examples included in thescikit-learn-contribproject template.
It is particularly important to notice that mixins should be “on the left” whiletheBaseEstimator
should be “on the right” in the inheritance list for properMRO.
>>>importnumpyasnp>>>fromsklearn.baseimportBaseEstimator,ClassifierMixin>>>fromsklearn.utils.validationimportvalidate_data,check_is_fitted>>>fromsklearn.utils.multiclassimportunique_labels>>>fromsklearn.metricsimporteuclidean_distances>>>classTemplateClassifier(ClassifierMixin,BaseEstimator):......def__init__(self,demo_param='demo'):...self.demo_param=demo_param......deffit(self,X,y):......# Check that X and y have correct shape, set n_features_in_, etc....X,y=validate_data(self,X,y)...# Store the classes seen during fit...self.classes_=unique_labels(y)......self.X_=X...self.y_=y...# Return the classifier...returnself......defpredict(self,X):......# Check if fit has been called...check_is_fitted(self)......# Input validation...X=validate_data(self,X,reset=False)......closest=np.argmin(euclidean_distances(X,self.X_),axis=1)...returnself.y_[closest]
And you can check that the above estimator passes all common checks:
>>>fromsklearn.utils.estimator_checksimportcheck_estimator>>>check_estimator(TemplateClassifier())# passes
get_params and set_params#
All scikit-learn estimators haveget_params
andset_params
functions.
Theget_params
function takes no arguments and returns a dict of the__init__
parameters of the estimator, together with their values.
It takes one keyword argument,deep
, which receives a boolean value that determineswhether the method should return the parameters of sub-estimators (only relevant formeta-estimators). The default value fordeep
isTrue
. For instance consideringthe following estimator:
>>>fromsklearn.baseimportBaseEstimator>>>fromsklearn.linear_modelimportLogisticRegression>>>classMyEstimator(BaseEstimator):...def__init__(self,subestimator=None,my_extra_param="random"):...self.subestimator=subestimator...self.my_extra_param=my_extra_param
The parameterdeep
controls whether or not the parameters of thesubestimator
should be reported. Thus whendeep=True
, the output will be:
>>>my_estimator=MyEstimator(subestimator=LogisticRegression())>>>forparam,valueinmy_estimator.get_params(deep=True).items():...print(f"{param} ->{value}")my_extra_param -> randomsubestimator__C -> 1.0subestimator__class_weight -> Nonesubestimator__dual -> Falsesubestimator__fit_intercept -> Truesubestimator__intercept_scaling -> 1subestimator__l1_ratio -> Nonesubestimator__max_iter -> 100subestimator__multi_class -> deprecatedsubestimator__n_jobs -> Nonesubestimator__penalty -> l2subestimator__random_state -> Nonesubestimator__solver -> lbfgssubestimator__tol -> 0.0001subestimator__verbose -> 0subestimator__warm_start -> Falsesubestimator -> LogisticRegression()
If the meta-estimator takes multiple sub-estimators, often, those sub-estimators havenames (as e.g. named steps in aPipeline
object), in which case thekey should become<name>__C
,<name>__class_weight
, etc.
Whendeep=False
, the output will be:
>>>forparam,valueinmy_estimator.get_params(deep=False).items():...print(f"{param} ->{value}")my_extra_param -> randomsubestimator -> LogisticRegression()
On the other hand,set_params
takes the parameters of__init__
as keywordarguments, unpacks them into a dict of the form'parameter':value
and sets theparameters of the estimator using this dict. It returns the estimator itself.
Theset_params
function is used to set parameters duringgrid search for instance.
Cloning#
As already mentioned that when constructor arguments are mutable, they should becopied before modifying them. This also applies to constructor arguments which areestimators. That’s why meta-estimators such asGridSearchCV
create a copy of the given estimator before modifying it.
However, in scikit-learn, when we copy an estimator, we get an unfitted estimatorwhere only the constructor arguments are copied (with some exceptions, e.g. attributesrelated to certain internal machinery such as metadata routing).
The function responsible for this behavior isclone
.
Estimators can customize the behavior ofbase.clone
by overriding thebase.BaseEstimator.__sklearn_clone__
method.__sklearn_clone__
must return aninstance of the estimator.__sklearn_clone__
is useful when an estimator needs to holdon to some state whenbase.clone
is called on the estimator. For example,FrozenEstimator
makes use of this.
Estimator types#
Among simple estimators (as opposed to meta-estimators), the most common types aretransformers, classifiers, regressors, and clustering algorithms.
Transformers inherit fromTransformerMixin
, and implement atransform
method. These are estimators which take the input, and transform it in some way. Notethat they should never change the number of input samples, and the output oftransform
should correspond to its input samples in the same given order.
Regressors inherit fromRegressorMixin
, and implement apredict
method.They should accept numericaly
in theirfit
method. Regressors user2_score
by default in theirscore
method.
Classifiers inherit fromClassifierMixin
. If it applies, classifiers canimplementdecision_function
to return raw decision values, based on whichpredict
can make its decision. If calculating probabilities is supported,classifiers can also implementpredict_proba
andpredict_log_proba
.
Classifiers should accepty
(target) arguments tofit
that are sequences (lists,arrays) of either strings or integers. They should not assume that the class labels area contiguous range of integers; instead, they should store a list of classes in aclasses_
attribute or property. The order of class labels in this attribute shouldmatch the order in whichpredict_proba
,predict_log_proba
anddecision_function
return their values. The easiest way to achieve this is to put:
self.classes_,y=np.unique(y,return_inverse=True)
infit
. This returns a newy
that contains class indexes, rather than labels,in the range [0,n_classes
).
A classifier’spredict
method should return arrays containing class labels fromclasses_
. In a classifier that implementsdecision_function
, this can beachieved with:
defpredict(self,X):D=self.decision_function(X)returnself.classes_[np.argmax(D,axis=1)]
Themulticlass
module contains useful functions for working withmulticlass and multilabel problems.
Clustering algorithms inherit fromClusterMixin
. Ideally, they shouldaccept ay
parameter in theirfit
method, but it should be ignored. Clusteringalgorithms should set alabels_
attribute, storing the labels assigned to eachsample. If applicable, they can also implement apredict
method, returning thelabels assigned to newly given samples.
If one needs to check the type of a given estimator, e.g. in a meta-estimator, one cancheck if the given object implements atransform
method for transformers, andotherwise use helper functions such asis_classifier
oris_regressor
.
Estimator Tags#
Note
Scikit-learn introduced estimator tags in version 0.21 as a private API and mostlyused in tests. However, these tags expanded over time and many third partydevelopers also need to use them. Therefore in version 1.6 the API for the tags wasrevamped and exposed as public API.
The estimator tags are annotations of estimators that allow programmatic inspection oftheir capabilities, such as sparse matrix support, supported output types and supportedmethods. The estimator tags are an instance ofTags
returned bythe method__sklearn_tags__
. These tags are usedin different places, such asis_regressor
or the common checks run bycheck_estimator
andparametrize_with_checks
, where tags determinewhich checks to run and what input data is appropriate. Tags can depend on estimatorparameters or even system architecture and can in general only be determined at runtimeand are therefore instance attributes rather than class attributes. SeeTags
for more information about individual tags.
It is unlikely that the default values for each tag will suit the needs of your specificestimator. You can change the default values by defining a__sklearn_tags__()
methodwhich returns the new values for your estimator’s tags. For example:
classMyMultiOutputEstimator(BaseEstimator):def__sklearn_tags__(self):tags=super().__sklearn_tags__()tags.target_tags.single_output=Falsetags.non_deterministic=Truereturntags
You can create a new subclass ofTags
if you wish to add newtags to the existing set. Note that all attributes that you add in a child class needto have a default value. It can be of the form:
fromdataclassesimportdataclass,asdict@dataclassclassMyTags(Tags):my_tag:bool=TrueclassMyEstimator(BaseEstimator):def__sklearn_tags__(self):tags_orig=super().__sklearn_tags__()as_dict={field.name:getattr(tags_orig,field.name)forfieldinfields(tags_orig)}tags=MyTags(**as_dict)tags.my_tag=Truereturntags
Developer API forset_output
#
WithSLEP018,scikit-learn introduces theset_output
API for configuring transformers tooutput pandas DataFrames. Theset_output
API is automatically defined if thetransformer definesget_feature_names_out and subclassesbase.TransformerMixin
.get_feature_names_out is used to get thecolumn names of pandas output.
base.OneToOneFeatureMixin
andbase.ClassNamePrefixFeaturesOutMixin
are helpful mixins for definingget_feature_names_out.base.OneToOneFeatureMixin
is useful whenthe transformer has a one-to-one correspondence between input features and outputfeatures, such asStandardScaler
.base.ClassNamePrefixFeaturesOutMixin
is useful when the transformerneeds to generate its own feature names out, such asPCA
.
You can opt-out of theset_output
API by settingauto_wrap_output_keys=None
when defining a custom subclass:
classMyTransformer(TransformerMixin,BaseEstimator,auto_wrap_output_keys=None):deffit(self,X,y=None):returnselfdeftransform(self,X,y=None):returnXdefget_feature_names_out(self,input_features=None):...
The default value forauto_wrap_output_keys
is("transform",)
, which automaticallywrapsfit_transform
andtransform
. TheTransformerMixin
uses the__init_subclass__
mechanism to consumeauto_wrap_output_keys
and pass all otherkeyword arguments to its super class. Super classes’__init_subclass__
shouldnot depend onauto_wrap_output_keys
.
For transformers that return multiple arrays intransform
, auto wrapping willonly wrap the first array and not alter the other arrays.
SeeIntroducing the set_output APIfor an example on how to use the API.
Developer API forcheck_is_fitted
#
By defaultcheck_is_fitted
checks if thereare any attributes in the instance with a trailing underscore, e.g.coef_
.An estimator can change the behavior by implementing a__sklearn_is_fitted__
method taking no input and returning a boolean. If this method exists,check_is_fitted
simply returns its output.
See__sklearn_is_fitted__ as Developer APIfor an example on how to use the API.
Developer API for HTML representation#
Warning
The HTML representation API is experimental and the API is subject to change.
Estimators inheriting fromBaseEstimator
displaya HTML representation of themselves in interactive programmingenvironments such as Jupyter notebooks. For instance, we can display this HTMLdiagram:
fromsklearn.baseimportBaseEstimatorBaseEstimator()
The raw HTML representation is obtained by invoking the functionestimator_html_repr
on an estimator instance.
To customize the URL linking to an estimator’s documentation (i.e. when clicking on the“?” icon), override the_doc_link_module
and_doc_link_template
attributes. Inaddition, you can provide a_doc_link_url_param_generator
method. Set_doc_link_module
to the name of the (top level) module that contains your estimator.If the value does not match the top level module name, the HTML representation will notcontain a link to the documentation. For scikit-learn estimators this is set to"sklearn"
.
The_doc_link_template
is used to construct the final URL. By default, it can containtwo variables:estimator_module
(the full name of the module containing the estimator)andestimator_name
(the class name of the estimator). If you need more variables youshould implement the_doc_link_url_param_generator
method which should return adictionary of the variables and their values. This dictionary will be used to render the_doc_link_template
.
Coding guidelines#
The following are some guidelines on how new code should be written forinclusion in scikit-learn, and which may be appropriate to adopt in externalprojects. Of course, there are special cases and there will be exceptions tothese rules. However, following these rules when submitting new code makesthe review easier so new code can be integrated in less time.
Uniformly formatted code makes it easier to share code ownership. Thescikit-learn project tries to closely follow the official Python guidelinesdetailed inPEP8 thatdetail how code should be formatted and indented. Please read it andfollow it.
In addition, we add the following guidelines:
Use underscores to separate words in non class names:
n_samples
rather thannsamples
.Avoid multiple statements on one line. Prefer a line return aftera control flow statement (
if
/for
).Use relative imports for references inside scikit-learn.
Unit tests are an exception to the previous rule;they should use absolute imports, exactly as client code would.A corollary is that, if
sklearn.foo
exports a class or functionthat is implemented insklearn.foo.bar.baz
,the test should import it fromsklearn.foo
.Please don’t use
import*
in any case. It is considered harmfulby theofficial Python recommendations.It makes the code harder to read as the origin of symbols is nolonger explicitly referenced, but most important, it preventsusing a static analysis tool likepyflakes to automaticallyfind bugs in scikit-learn.Use thenumpy docstring standardin all your docstrings.
A good example of code that we like can be foundhere.
Input validation#
The modulesklearn.utils
contains various functions for doing inputvalidation and conversion. Sometimes,np.asarray
suffices for validation;donot usenp.asanyarray
ornp.atleast_2d
, since those let NumPy’snp.matrix
through, which has a different API(e.g.,*
means dot product onnp.matrix
,but Hadamard product onnp.ndarray
).
In other cases, be sure to callcheck_array
on any array-like argumentpassed to a scikit-learn API function. The exact parameters to use dependsmainly on whether and whichscipy.sparse
matrices must be accepted.
For more information, refer to theUtilities for Developers page.
Random Numbers#
If your code depends on a random number generator, do not usenumpy.random.random()
or similar routines. To ensurerepeatability in error checking, the routine should accept a keywordrandom_state
and use this to construct anumpy.random.RandomState
object.Seesklearn.utils.check_random_state
inUtilities for Developers.
Here’s a simple example of code using some of the above guidelines:
fromsklearn.utilsimportcheck_array,check_random_statedefchoose_random_sample(X,random_state=0):"""Choose a random point from X. Parameters ---------- X : array-like of shape (n_samples, n_features) An array representing the data. random_state : int or RandomState instance, default=0 The seed of the pseudo random number generator that selects a random sample. Pass an int for reproducible output across multiple function calls. See :term:`Glossary <random_state>`. Returns ------- x : ndarray of shape (n_features,) A random point selected from X. """X=check_array(X)random_state=check_random_state(random_state)i=random_state.randint(X.shape[0])returnX[i]
If you use randomness in an estimator instead of a freestanding function,some additional guidelines apply.
First off, the estimator should take arandom_state
argument to its__init__
with a default value ofNone
.It should store that argument’s value,unmodified,in an attributerandom_state
.fit
can callcheck_random_state
on that attributeto get an actual random number generator.If, for some reason, randomness is needed afterfit
,the RNG should be stored in an attributerandom_state_
.The following example should make this clear:
classGaussianNoise(BaseEstimator,TransformerMixin):"""This estimator ignores its input and returns random Gaussian noise. It also does not adhere to all scikit-learn conventions, but showcases how to handle randomness. """def__init__(self,n_components=100,random_state=None):self.random_state=random_stateself.n_components=n_components# the arguments are ignored anyway, so we make them optionaldeffit(self,X=None,y=None):self.random_state_=check_random_state(self.random_state)deftransform(self,X):n_samples=X.shape[0]returnself.random_state_.randn(n_samples,self.n_components)
The reason for this setup is reproducibility:when an estimator isfit
twice to the same data,it should produce an identical model both times,hence the validation infit
, not__init__
.
Numerical assertions in tests#
When asserting the quasi-equality of arrays of continuous values,do usesklearn.utils._testing.assert_allclose
.
The relative tolerance is automatically inferred from the provided arraysdtypes (for float32 and float64 dtypes in particular) but you can overrideviartol
.
When comparing arrays of zero-elements, please do provide a non-zero value forthe absolute tolerance viaatol
.
For more information, please refer to the docstring ofsklearn.utils._testing.assert_allclose
.