Sub topic 8
Building a custom classifier
This chapter assumes you know Python classes, NumPy indexing, and the fit/predict pattern. It also assumes you have seen BaseEstimator and the constructor rules from earlier chapters. Here you build a small classifier that works with score, cross_val_score, and pipelines.
What a classifier must provide
A classifier needs a fit(X, y) method that returns self, and a predict(X) method that returns one label per row. ClassifierMixin then adds a score(X, y) method that returns accuracy.
The classifier also needs one attribute, classes_. It holds the sorted unique labels. Scikit-learn tools such as predict_proba consumers and scorers rely on it.
The implementation
The classifier learns one centroid (the mean row) per class. It predicts the class whose centroid is closest.
import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.utils.validation import check_array, check_is_fitted, check_X_y
class MeanCentroidClassifier(ClassifierMixin, BaseEstimator):
def fit(self, X, y):
X, y = check_X_y(X, y)
self.classes_, y_idx = np.unique(y, return_inverse=True)
self.centroids_ = np.vstack(
[X[y_idx == k].mean(axis=0) for k in range(len(self.classes_))]
)
self.n_features_in_ = X.shape[1]
return self
def predict(self, X):
check_is_fitted(self)
X = check_array(X)
dist = np.linalg.norm(X[:, None, :] - self.centroids_[None, :, :], axis=2)
return self.classes_[np.argmin(dist, axis=1)]How it works
check_X_yconverts both inputs to arrays, checks that they have the same number of rows, and rejects NaN and infinite values.np.unique(..., return_inverse=True)givesclasses_and also an integer index for each row ofy. The index lets you select rows by class without comparing raw labels. Labels can be strings.- Each learned attribute ends in an underscore:
classes_,centroids_,n_features_in_.check_is_fittedlooks for attributes with this suffix. If you callpredictbeforefit, it raisesNotFittedError. - In
predict,X[:, None, :]has shape(n, 1, d)andcentroids_[None, :, :]has shape(1, k, d). Broadcasting gives(n, k, d), and the norm over the last axis gives an(n, k)distance matrix. argminreturns column positions. Indexingclasses_with them turns positions back into the original labels.- This class defines no
__init__. It has no hyperparameters, soBaseEstimatorneeds nothing more. If you add one, store it unchanged, as in the transformer chapter.
Using it
from sklearn.datasets import load_iris
from sklearn.model_selection import cross_val_score
X, y = load_iris(return_X_y=True)
clf = MeanCentroidClassifier().fit(X, y)
print(clf.classes_)
print(clf.score(X, y))
print(cross_val_score(MeanCentroidClassifier(), X, y, cv=5).mean())score comes from ClassifierMixin. cross_val_score works because it clones the estimator for each fold. Cloning calls get_params, which BaseEstimator supplies. Each fold gets a fresh unfitted copy, so no state leaks between folds.
Common errors
| Symptom | Likely cause |
|---|---|
| `NotFittedError` after calling `fit` | `fit` forgot `return self`, so a chained `fit(...).predict(...)` fails. Or no attribute ends in `_`. |
| Predictions are integers 0, 1, 2 instead of your labels | `predict` returned `argmin` positions instead of `classes_[...]`. |
| Cross-validation score looks too good | Scaling or selection was fitted on all data before splitting. Put those steps in a `Pipeline`. |
Exercise
Why does predict return self.classes_[np.argmin(dist, axis=1)] rather than just np.argmin(dist, axis=1)?
Show answer
argmin returns the column position of the closest centroid, which is an index into centroids_. The real labels may be strings or non-contiguous integers. Indexing classes_ with those positions maps each position back to its original label, so predictions match the labels seen in y during fit.