Sub topic 8
Building a custom classifier
This chapter assumes you have read the earlier chapters on the estimator contract, BaseEstimator, constructor rules, trailing-underscore attributes, and input validation. You should also be comfortable with cross_val_score and Pipeline. Here you apply those rules to a predictor: a classifier that works with score, cross-validation, clone, and grid search.
What a classifier adds to the contract
A transformer learns in fit and outputs data in transform. A classifier also learns in fit, but it outputs labels through predict. scikit-learn expects these pieces:
fit(X, y)learns from data and returnsself.predict(X)returns one label per row, drawn from the labels seen infit.classes_is a fitted attribute holding the sorted unique labels.score(X, y)returns mean accuracy.ClassifierMixinsupplies it, and it calls yourpredict.predict_proba(X)is optional. When present, its columns follow the order ofclasses_.
ClassifierMixin also marks the estimator as a classifier. Utilities such as cross_val_score read that marker. With an integer cv, they use stratified folds only when the estimator is a classifier.
The model: nearest class centroid
The example learns one mean vector (a centroid) per class. To predict, it finds the closest centroid to each row. The model is simple, so the estimator conventions stay easy to see.
The full implementation
This version adds predict_proba and one hyperparameter, temperature. The temperature controls how sharp the probabilities are.
import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.utils.multiclass import check_classification_targets
from sklearn.utils.validation import check_array, check_is_fitted, check_X_y
class MeanCentroidClassifier(ClassifierMixin, BaseEstimator):
def __init__(self, temperature=1.0):
self.temperature = temperature
def fit(self, X, y):
if self.temperature <= 0:
raise ValueError("temperature must be positive")
X, y = check_X_y(X, y)
check_classification_targets(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 _distances(self, X):
check_is_fitted(self)
X = check_array(X)
if X.shape[1] != self.n_features_in_:
raise ValueError(
f"X has {X.shape[1]} features, but {self.__class__.__name__} "
f"is expecting {self.n_features_in_} features as input"
)
diff = X[:, None, :] - self.centroids_[None, :, :]
return np.linalg.norm(diff, axis=2)
def predict(self, X):
return self.classes_[np.argmin(self._distances(X), axis=1)]
def predict_proba(self, X):
scores = -self._distances(X) / self.temperature
scores -= scores.max(axis=1, keepdims=True)
weights = np.exp(scores)
return weights / weights.sum(axis=1, keepdims=True)Walking through the choices
The constructor only stores temperature. It does no checks and no computation. clone and set_params rebuild the object from the stored values, so the constructor must keep them unchanged. The check for a positive temperature lives in fit, which runs after set_params may have changed the value.
fit validates first. check_X_y converts inputs to arrays, rejects NaN and infinity, and checks that X and y have the same number of rows. check_classification_targets raises a clear error if someone passes continuous targets such as [0.1, 0.5]. Without it, a regression target would silently become a pile of one-sample classes.
np.unique(..., return_inverse=True) gives two things at once. classes_ holds the sorted labels, and y_idx holds each row's label as an integer from 0 to n_classes - 1. Working with integer indexes means the model does not care whether labels are integers, strings, or booleans. At prediction time, self.classes_[...] maps indexes back to the original labels.
Fitted attributes end with an underscore. classes_, centroids_, and n_features_in_ all appear only after fit. That is how check_is_fitted(self) knows the estimator is fitted: it looks for attributes ending in _. If you call predict before fit, it raises NotFittedError instead of an AttributeError about a missing field.
predict and predict_proba share one helper. _distances validates and measures in one place, so both methods stay consistent. The leading underscore marks the helper as private.
Probabilities use a numerically safe softmax. Subtracting the row maximum before np.exp avoids overflow without changing the result. The columns of predict_proba are in classes_ order, which is the order scikit-learn tools expect.
Using it like any other classifier
Because the class follows the contract, standard tools work with no extra code.
from sklearn.base import clone
from sklearn.datasets import load_iris
from sklearn.model_selection import cross_val_score
X, y = load_iris(return_X_y=True)
clf = MeanCentroidClassifier()
scores = cross_val_score(clf, X, y, cv=5)
print(scores.mean())
clf.fit(X, y)
print(clf.classes_)
print(clf.predict_proba(X[:2]).round(3))
print(clf.score(X, y))
twin = clone(clf)
print(hasattr(twin, "centroids_"))cross_val_score clones the estimator for each fold, so every fold starts unfitted. score comes from ClassifierMixin and computes accuracy through your predict. The last line prints False: clone copies the constructor parameters but not the learned state, which shows that the constructor and fitted attributes are cleanly separated.
String labels work with no changes:
labels = np.array(["cat", "dog", "cat", "dog"])
points = np.array([[0.0, 0.0], [5.0, 5.0], [0.5, 0.2], [4.5, 5.5]])
model = MeanCentroidClassifier().fit(points, labels)
print(model.classes_)
print(model.predict([[0.1, 0.1], [5.0, 4.0]]))Using it in a Pipeline
Inside a Pipeline, the classifier must be the last step. Earlier steps need transform, and only the final step may be a predictor. Nearest-centroid methods depend on feature scale, so scaling is a natural first step:
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
pipe = Pipeline([
("scale", StandardScaler()),
("clf", MeanCentroidClassifier()),
])
grid = GridSearchCV(pipe, {"clf__temperature": [0.1, 1.0, 10.0]}, cv=5)
grid.fit(X, y)
print(grid.best_params_)The clf__temperature name works because BaseEstimator builds get_params from the signature of __init__. A parameter you want to tune must be a named constructor argument.
Common errors when writing a classifier
| Symptom | Likely cause | Fix |
|---|---|---|
| `AttributeError: ... has no attribute 'classes_'` in a meta-estimator | `fit` never set `classes_` | Set `self.classes_` with `np.unique` |
| `predict` returns integers when labels were strings | Returned `argmin` indexes directly | Index into `self.classes_` |
| `score` is always poor on a regression target | No target-type check | Call `check_classification_targets` |
| `clone` raises `RuntimeError` about parameters | `__init__` modified or renamed a stored value | Store each argument unchanged under its own name |
| `predict_proba` columns look shuffled | Column order differs from `classes_` | Build columns in `classes_` order |
| `predict` works before `fit` | No `check_is_fitted` call | Call it at the start of every predict-time method |
A model that has only one class in y is an edge case worth deciding on. This implementation fits and always predicts that class. Some scikit-learn estimators raise an error instead. Either choice is acceptable if you handle it deliberately and document it.
Regressors follow the same pattern
For a regressor, swap ClassifierMixin for RegressorMixin. Skip classes_ and check_classification_targets, and return a float array from predict. RegressorMixin.score returns R², computed from your predict.
Exercise
You write __init__(self, temperature=1.0) and add the line self.temperature = max(temperature, 1e-6) to avoid a zero value. GridSearchCV with clf__temperature: [0.0, 1.0] then behaves oddly, and clone may fail. Why, and where should the check go?
Show answer
The constructor must store arguments unchanged. clone builds a new object from get_params() and checks that each stored value is the same object that was passed in. After max(...), the stored value can differ from the passed value (0.0 becomes 1e-6), so clone can raise a RuntimeError. set_params also bypasses __init__, so the clamp would not apply when the grid search sets the value. Store self.temperature = temperature in __init__ and validate or clamp in fit, for example by raising ValueError when temperature <= 0.
Exercise
After fit, clf.classes_ is array(['cat', 'dog']). A colleague's predict returns np.argmin(distances, axis=1). What does score(X, y) return for string labels, and what one-line change fixes the method?
Show answer
score compares the integer indexes returned by predict with the string labels in y, so no predictions match and the accuracy is 0.0. The fix is return self.classes_[np.argmin(distances, axis=1)], which maps indexes back to the original labels.