This document shows how to make third party estimators and
meta-estimators compatible with the callback infrastructure supported by
scikit-learn.
Generally speaking, a callback is a function that is provided by the user to be called
at specific steps of a process, or to be triggered by specific events. Callbacks provide
a clean mechanism for inserting custom logic like monitoring progress or metrics,
without modifying the core algorithm of the process.
In scikit-learn, callbacks take the form of classes following a protocol. This protocol requires the
callback classes to implement specific methods (referred to as callback hooks) which
are called at specific steps of the fitting of an estimator or a meta-estimator.
These hooks are setup, ,
and . The
and hooks are called only once,
respectively at the start and end of the estimator’s method, and are
responsible for setting up and shutting down the callback. The
and hooks
are respectively called at the beginning and end of each task in and are
responsible for the actual callback work. In scikit-learn estimators, a task in is
usually one step of a loop, with nested loops corresponding to nested tasks. In general,
a task can be whatever unit of work the estimator’s developer wants it to be.
In order to support the callbacks, estimators need to initialize and manage
CallbackContext objects. As the name implies, these objects hold the
contextual information necessary to run the callback hooks. They are also responsible
for calling the callback hooks at the right time.
In the following, we show how to convert an example estimator class and an example
meta-estimator class to make them compliant with the scikit-learn callback
infrastructure.
First a few imports and some random data for the rest of the script.
# Authors: The scikit-learn developers# SPDX-License-Identifier: BSD-3-Clause
Here we demonstrate how to implement a custom estimator that supports callbacks. For
the example, a simplified version of KMeans is presented. First, let’s implement our
SimpleKMeans estimator without the callback support.
classSimpleKMeans(BaseEstimator):def__init__(self,n_clusters=6,n_iter=100,random_state=None):self.n_clusters=n_clustersself.n_iter=n_iterself.random_state=random_state# controls the centroids' initializationdef_compute_labels(self,X):# Get the index of the closest centroid for each point in X.returnnp.argmin(euclidean_distances(X,self.cluster_centers_),axis=1)deffit(self,X,y=None):# `y` is not used but we need to declare it to adhere to scikit-learn's# estimators fit convention.# Input validation is a good practice in estimators, for more information about# it you can refer to# https://scikit-learn.org/stable/developers/develop.html#input-validation.X=validate_data(self,X)random_state=check_random_state(self.random_state)# Randomly initialize the centroids.self.cluster_centers_=random_state.rand(self.n_clusters,X.shape[1])foriinrange(self.n_iter):# The fit iterations consist in getting the cluster label of each data point# according to their closest centroid, and then updating the centroids as# the center of each cluster.labels=self._compute_labels(X)forkinrange(self.n_clusters):# For each centroid, if its cluster is not empty, its coordinates are# updated with the coordinates of the cluster's center.if(labels==k).any():self.cluster_centers_[k]=X[labels==k].mean(axis=0)returnselfdefpredict(self,X):check_is_fitted(self)returnself._compute_labels(X)deftransform(self,X):check_is_fitted(self)returneuclidean_distances(X,self.cluster_centers_)
Now let’s add all the elements necessary to support callbacks.
# First things first, the estimator must inherit from the `CallbackSupportMixin` class.classSimpleKMeans(CallbackSupportMixin,BaseEstimator):# noqa: F811def__init__(self,n_clusters=6,n_iter=100,random_state=None):self
Registering callbacks to the custom estimator
Now the SimpleKMeans estimator can be used with callbacks, for example with the
ProgressBar callback to monitor progress.
SimpleKMeans - fit ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:00:00
SimpleKMeans(random_state=RandomState(MT19937) at 0x7E1DF5B93340)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
SimpleKMeans
iFitted
Parameters
random_state
RandomState(M...0x7E1DF5B93340
n_clusters
6
Custom meta-estimator
Now we demonstrate how to implement a custom meta-estimator that supports callbacks.
For the example, we implement a simplified version of a grid search, where only a list
of parameter combinations is searched through instead of a grid, parallelizing the
evaluation of the parameters.
Let’s start with the implementation without the callback support.
# Function to run in parallel, it fits and scores an estimator on the folds of a CV.def_fit_and_score_cv(estimator,X,y,cv,score_func):scores_per_fold=[]# We iterate over the folds of the CV split.fortrain_idx,test_idxincv.split(X):# A clone of the estimator is used for the current fold.cloned_estimator=clone(estimator)# The split of the current fold is applied to the data.X_train,X_test=X[train_idx],X[test_idx]y_train,y_test=(y[train_idx],y[test_idx])ifyisnotNoneelse(None,None)# The clone of the estimator is fitted.cloned_estimator.fit(X_train,y_train)# Its score is computed.scores_per_fold.append(score_func(cloned_estimator,X_test,y_test))returnscores_per_foldclassSimpleGridSearch(BaseEstimator):def__init__(self,estimator,param_list,cv,score_func,n_jobs=1):# the estimator to evaluateself.estimator=estimator# the list of parameter combinations to iterate overself.param_list=param_list# the number of splits for the CV, or a CV splitter instanceself.cv=cv# the scoring functionself.score_func=score_func# number of jobs for parallelizationself.n_jobs=n_jobsdeffit(self,X,y=None):# We use a cross-validator instance to evaluate each parameter combination on# multiple folds.cv=check_cv(self.cv)# We iterate over the parameter combinations in parallel, fitting an estimator# and computing a score value for each fold.scores_per_fold=Parallel(n_jobs=self.n_jobs)(delayed(_fit_and_score_cv)(estimator=clone(self.estimator).set_params(**params),X=X,y=y,cv=cv,score_func=self.score_func,)forparamsinself.param_list)# The `cv_results_` attribute holds the score values for each parameter# combination and fold, as a list of tuples, each one of the form# (parameter combination, list of scores per fold).self.cv_results_=list(zip(self.param_list,scores_per_fold))returnself
Now let’s update the class to support callbacks.
# The parallelized function needs to receive the callback context corresponding to its# task and the instance calling it.def_fit_and_score_cv(estimator,X,y,cv,score_func,outer_subcontext,caller):# The outer sub-context's `call_on_fit_task_begin` must be called.outer_subcontext.call_on_fit_task_begin(estimator=caller,X=X,y=y
The main difference with a simple estimator is that the callbacks must be propagated
to the sub-estimators through the corresponding callback sub-context’s
propagate_callback_context context manager.
Registering callbacks to the meta-estimator
Callbacks are registered to a meta-estimator the same way as to regular estimators.
The callbacks which respect the AutoPropagatedCallback protocol (such as
ProgressBar) are propagated to the sub-estimators.
SimpleGridSearch(cv=4,
estimator=SimpleKMeans(random_state=RandomState(MT19937) at 0x7E1DF5B93340),
param_list=[{'n_clusters': 5, 'n_iter': 20},
{'n_clusters': 4, 'n_iter': 50}],
score_func=<function score_func at 0x7e1dbd4f99b0>)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
SimpleGridSearch
iFitted
Parameters
estimator
SimpleKMeans(...x7E1DF5B93340)
Total running time of the script: (0 minutes 0.238 seconds)