The Estimator Interface: Writing Your Own fit and predict
Every from-scratch model in this course is checked against a library version on the same data. That check is much easier when your model speaks the same language as the library: an object with fit(X, y) and predict(X). scikit-learn calls such an object an estimator, and the interface is small enough to learn in one lesson. Once your class follows it, scikit-learn's cross-validation, grid search and pipelines work with it unchanged.
The contract
| Rule | Why |
|---|---|
__init__ only stores the hyperparameters, under the same names as its arguments |
get_params, set_params and clone read and copy them by name |
fit(X, y) learns from data and returns self |
model.fit(X, y).predict(X_new) chains |
attributes learned in fit end with an underscore: coef_, classes_, centroids_ |
you can tell a fitted model from an unfitted one |
predict(X) returns one prediction per row |
metrics and cross-validation call it |
score(X, y) gives a default metric |
inherited: accuracy from ClassifierMixin, from RegressorMixin |
Data comes in as a matrix , one row per example and one column per feature, and labels as a vector of length (data as vectors and matrices).
A first model: the nearest centroid
The simplest useful classifier stores one point per class, the mean of its training examples (the centroid),
and predicts the class whose centroid is closest:
With this is the squared Euclidean distance (taking the root would not change which centroid is closest). Here it is as an estimator, checked against scikit-learn's NearestCentroid on the iris flowers:
import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.datasets import load_iris
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import NearestCentroid
class CentroidClassifier(ClassifierMixin, BaseEstimator):
"""Predict the class whose mean (centroid) is closest in the Minkowski p-distance."""
def __init__(self, p=2):
self.p = p # hyperparameters: stored as given, nothing else
def fit(self, X, y):
X, y = np.asarray(X, dtype=float), np.asarray(y)
self.classes_ = np.unique(y) # learned attributes end with "_"
self.centroids_ = np.array([X[y == c].mean(axis=0) for c in self.classes_])
return self # fit returns self, so calls can be chained
def predict(self, X):
X = np.asarray(X, dtype=float)
d = (np.abs(X[:, None, :] - self.centroids_[None, :, :]) ** self.p).sum(axis=2)
return self.classes_[d.argmin(axis=1)]
X, y = load_iris(return_X_y=True)
ours = CentroidClassifier().fit(X, y)
print("centroid of class 0:", ours.centroids_[0].round(3))
print("hyperparameters:", ours.get_params())
print("ours 5-fold accuracy:", cross_val_score(CentroidClassifier(), X, y, cv=5).round(3))
print("sklearn 5-fold accuracy:", cross_val_score(NearestCentroid(), X, y, cv=5).round(3))
print("same predictions:", bool((ours.predict(X) == NearestCentroid().fit(X, y).predict(X)).all()))centroid of class 0: [5.006 3.428 1.462 0.246]
hyperparameters: {'p': 2}
ours 5-fold accuracy: [0.9 0.933 0.867 0.933 0.967]
sklearn 5-fold accuracy: [0.9 0.933 0.867 0.933 0.967]
same predictions: True
The broadcasting line X[:, None, :] - self.centroids_[None, :, :] builds an array of differences between every example and every centroid; summing over the last axis gives the distance table, and argmin(axis=1) picks the closest centroid per row. This pattern returns in kNN and k-means.
get_params() works without any code of ours: BaseEstimator reads the arguments of __init__. That is why __init__ must not rename, validate or transform them.
Plugging into pipelines and grid search
Because the class follows the contract, it drops into a Pipeline and a GridSearchCV like any built-in model. The wine data has 13 features on very different scales (proline is in the hundreds, hue around 1), so distances are dominated by one feature unless the data is standardised first:
import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin, clone
from sklearn.datasets import load_wine
from sklearn.model_selection import GridSearchCV, StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
class CentroidClassifier(ClassifierMixin, BaseEstimator):
def __init__(self, p=2):
self.p = p
def fit(self, X, y):
self.classes_ = np.unique(y)
self.centroids_ = np.array([X[y == c].mean(axis=0) for c in self.classes_])
return self
def predict(self, X):
d = (np.abs(X[:, None, :] - self.centroids_[None, :, :]) ** self.p).sum(axis=2)
return self.classes_[d.argmin(axis=1)]
X, y = load_wine(return_X_y=True) # 178 wines, 13 features on very different scales
cv = StratifiedKFold(5, shuffle=True, random_state=0)
print("raw features ", cross_val_score(CentroidClassifier(), X, y, cv=cv).mean().round(3))
pipe = make_pipeline(StandardScaler(), CentroidClassifier())
print("scaled (pipeline)", cross_val_score(pipe, X, y, cv=cv).mean().round(3))
search = GridSearchCV(pipe, {"centroidclassifier__p": [0.5, 1, 2, 4]}, cv=cv).fit(X, y)
for p, s in zip([0.5, 1, 2, 4], search.cv_results_["mean_test_score"]):
print(f"p = {p:<3} CV accuracy {s:.3f}")
print("best:", search.best_params_)
fresh = clone(pipe.set_params(centroidclassifier__p=1))
print("clone copies hyperparameters, not fitted state:", fresh[-1].p, hasattr(fresh[-1], "centroids_"))raw features 0.725
scaled (pipeline) 0.972
p = 0.5 CV accuracy 0.944
p = 1 CV accuracy 0.950
p = 2 CV accuracy 0.972
p = 4 CV accuracy 0.949
best: {'centroidclassifier__p': 2}
clone copies hyperparameters, not fitted state: 1 False
Scaling lifts the cross-validated accuracy from 0.725 to 0.972. Grid search addresses the hyperparameter as <step name>__<parameter>, and clone (which cross-validation calls for every fold) builds a fresh, unfitted copy with the same hyperparameters, so no fold sees a model fitted on another fold.
Hyperparameters versus parameters
- Parameters are learned from data in
fit: the centroids here, the weights of a linear model, the splits of a tree. - Hyperparameters are chosen before fitting:
phere,kin kNN, the depth of a tree. They are picked by comparing validation scores, as the grid search did, never by looking at the test set (model selection and cross-validation).
The grid search above reports its best score on the same folds it used to choose p, which makes that score slightly optimistic. The comparison bench shows nested cross-validation, the honest version.
Pitfalls
- Work in
__init__. Converting or validating arguments there breakscloneandset_params. Do it infit. - Forgetting
return self.cross_val_scorestill works, butmodel.fit(X, y).predict(...)fails with an attribute error onNone. - State that leaks between fits. Everything learned must be recomputed in
fit; never append to a list kept from a previous call. - Mixin order. Put the mixin before
BaseEstimator(class M(ClassifierMixin, BaseEstimator)), as scikit-learn 1.7 expects.
Practice
- Add a
predict_proba-like methoddecision_function(X)that returns minus the distance to each centroid. Which column has the largest value for each row?
Answer
return -d where d is the distance table. The largest value in each row is minus the smallest distance, so its column is the predicted class: self.classes_[decision_function(X).argmax(axis=1)] equals predict(X).
- Why does the raw-feature version score only 0.725 on wine?
Answer
The squared distance sums squared differences in each feature's own units. Proline varies by hundreds while most features vary by less than 1, so the distance is essentially the proline difference alone. Standardising gives every feature a comparable spread.
Test yourself
Which of these belongs in __init__ of a scikit-learn-style estimator?
- Computing the class centroids
- Storing the hyperparameters under their argument names
- Scaling the training data
- Checking the shape of
X
What does the trailing underscore in centroids_ signal?
- A private attribute
- A hyperparameter
- An attribute learned from data during
fit - A deprecated attribute
What does clone(model) return?
- A copy with the same fitted state
- A new unfitted estimator with the same hyperparameters
- The same object
- A model fitted on the same data