Skip to content

19. Inheritance and polymorphism — Mini-project

minilearn is the small scikit-learn-like library that you build across Part 3, in pure Python. In module 18 you wrote its first classes: Dataset, StandardScaler, a one-feature LinearRegression and two metric functions. Each class works, but each one stands alone. None of them can report or change its settings, the scaler has no fit_transform(), and the regression has no score().

In this project you give the library its backbone, in the same shape as scikit-learn’s sklearn.base module:

  • a BaseEstimator with get_params() and set_params(), built on inspect.signature;
  • three mixins: TransformerMixin.fit_transform(), RegressorMixin.score() (R²) and ClassifierMixin.score() (accuracy);
  • a NotFittedError and a check_is_fitted() helper;
  • the module 18 classes refactored onto these bases, two baseline models, and a new KNNClassifier.

Then you use polymorphism: one loop evaluates every regressor on house prices, and another loop evaluates every classifier on customer churn, without a single if on the model type.

Two course datasets, read with Dataset.from_csv():

Task File Features Target Rows used
Regression data/houses.csv sqft price all 3,000: the first 2,400 sales train, the last 600 test
Classification data/customers.csv tenure_months, logins_last_30d churned (0 or 1) every 5th customer (1,000 rows); every 4th of those is a test row

houses.csv is sorted by sale date, so the house split tests on the most recent sales. customers.csv is sorted by signup date, so the customer sample takes every 5th row to cover old and new customers alike. 19.3% of all customers churned. The data dictionary describes every column.

The reference solution builds on the module 18 code below: the five files of the minilearn package, joined into one script. It is restated here so that this page runs on its own. Copy it into the top of your script, or keep your module 18 package and edit its files.

Module 18 code: NotFittedError, Dataset, StandardScaler, LinearRegression and metrics
minilearn_m18.py
import csv
from typing import Self
# --- minilearn/base.py ---------------------------------------------------
class NotFittedError(ValueError):
"""Raised when a model or transformer is used before fit()."""
# --- minilearn/datasets.py -----------------------------------------------
class Dataset:
"""Features X (one row per sample) and a target y (one value per sample)."""
def __init__(self, X: list[list[float]], y: list[float], feature_names: list[str]):
if not X:
raise ValueError("a Dataset needs at least one sample")
if len(X) != len(y):
raise ValueError(f"X has {len(X)} rows but y has {len(y)} values")
width = len(feature_names)
for i, row in enumerate(X):
if len(row) != width:
raise ValueError(f"row {i} has {len(row)} values, expected {width}")
self.X = X
self.y = y
self.feature_names = list(feature_names)
@property
def n_samples(self) -> int:
return len(self.X)
@property
def n_features(self) -> int:
return len(self.feature_names)
@staticmethod
def _parse(text: str, column: str, line: int) -> float | None:
"""Return the number in a CSV cell, or None for a blank cell."""
if not text.strip():
return None
try:
return float(text)
except ValueError:
message = f"line {line}: {column!r} is not a number: {text!r}"
raise ValueError(message) from None
@classmethod
def from_csv(
cls, path: str, target: str, features: list[str], skip_missing: bool = False
) -> Self:
"""Load the given feature columns and the target column of a CSV file.
A row with a blank cell in one of these columns raises ValueError, or is
skipped when skip_missing is True.
"""
X: list[list[float]] = []
y: list[float] = []
with open(path, newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
header = reader.fieldnames or []
missing = [name for name in [*features, target] if name not in header]
if missing:
raise ValueError(f"{path}: unknown columns {missing}")
for line, row in enumerate(reader, start=2): # line 1 is the header
values = [cls._parse(row[name], name, line) for name in features]
label = cls._parse(row[target], target, line)
numbers = [v for v in values if v is not None]
if label is None or len(numbers) < len(values):
if skip_missing:
continue
raise ValueError(f"line {line}: blank value; use skip_missing=True")
X.append(numbers)
y.append(label)
return cls(X, y, features)
def column(self, name: str) -> list[float]:
"""Return the values of one feature."""
index = self.feature_names.index(name)
return [row[index] for row in self.X]
def split_at(self, n_first: int) -> tuple[Self, Self]:
"""Split into the first n_first samples and the rest, keeping the order."""
if not 0 < n_first < self.n_samples:
raise ValueError(f"n_first must be between 1 and {self.n_samples - 1}")
cls = type(self)
first = cls(self.X[:n_first], self.y[:n_first], self.feature_names)
rest = cls(self.X[n_first:], self.y[n_first:], self.feature_names)
return first, rest
# --- minilearn/preprocessing.py ------------------------------------------
class StandardScaler:
"""Standardize features: z = (x - mean_) / scale_, column by column."""
def fit(self, X: list[list[float]]) -> Self:
if not X:
raise ValueError("cannot fit on an empty X")
n = len(X)
columns = list(zip(*X, strict=True)) # one tuple per feature
self.mean_ = [sum(col) / n for col in columns]
self.scale_ = [
self._population_std(col, mean)
for col, mean in zip(columns, self.mean_, strict=True)
]
self.n_features_in_ = len(columns)
return self
def transform(self, X: list[list[float]]) -> list[list[float]]:
self._check(X)
params = list(zip(self.mean_, self.scale_, strict=True))
return [
[(v - m) / s for v, (m, s) in zip(row, params, strict=True)] for row in X
]
def inverse_transform(self, Z: list[list[float]]) -> list[list[float]]:
self._check(Z)
params = list(zip(self.mean_, self.scale_, strict=True))
return [[z * s + m for z, (m, s) in zip(row, params, strict=True)] for row in Z]
@staticmethod
def _population_std(values: tuple[float, ...], mean: float) -> float:
variance = sum((v - mean) ** 2 for v in values) / len(values)
std = variance**0.5
return std if std > 0 else 1.0 # a constant column stays unchanged
def _check(self, X: list[list[float]]) -> None:
if not hasattr(self, "mean_"):
raise NotFittedError("StandardScaler is not fitted yet; call fit() first")
for row in X:
if len(row) != self.n_features_in_:
raise ValueError(
f"X has {len(row)} features, but the scaler was fitted "
f"with {self.n_features_in_}"
)
# --- minilearn/linear_model.py -------------------------------------------
class LinearRegression:
"""Fit y = coef_ * x + intercept_ for a single feature x."""
def __init__(self, fit_intercept: bool = True):
self.fit_intercept = fit_intercept # stored unchanged, scikit-learn style
@staticmethod
def _single_column(X: list[list[float]]) -> list[float]:
for row in X:
if len(row) != 1:
raise ValueError(
f"LinearRegression supports exactly 1 feature, got {len(row)}"
)
return [row[0] for row in X]
def fit(self, X: list[list[float]], y: list[float]) -> Self:
x = self._single_column(X)
if len(x) != len(y) or len(x) < 2:
raise ValueError("X and y need the same length, with at least 2 samples")
if self.fit_intercept:
x_mean = sum(x) / len(x)
y_mean = sum(y) / len(y)
else:
x_mean = y_mean = 0.0 # no intercept: the line goes through (0, 0)
sxx = sum((xi - x_mean) ** 2 for xi in x)
sxy = sum((xi - x_mean) * (yi - y_mean) for xi, yi in zip(x, y, strict=True))
if sxx == 0:
raise ValueError("cannot fit a line: all x values are equal")
self.coef_ = sxy / sxx
self.intercept_ = y_mean - self.coef_ * x_mean
return self
def predict(self, X: list[list[float]]) -> list[float]:
if not hasattr(self, "coef_"):
raise NotFittedError("LinearRegression is not fitted yet; call fit() first")
return [self.coef_ * x + self.intercept_ for x in self._single_column(X)]
# --- minilearn/metrics.py ------------------------------------------------
def _check_lengths(y_true: list[float], y_pred: list[float]) -> None:
if len(y_true) != len(y_pred):
raise ValueError(f"lengths differ: {len(y_true)} vs {len(y_pred)}")
if not y_true:
raise ValueError("y_true is empty")
def mean_squared_error(y_true: list[float], y_pred: list[float]) -> float:
"""Mean of the squared differences between the truth and the predictions."""
_check_lengths(y_true, y_pred)
return sum((t - p) ** 2 for t, p in zip(y_true, y_pred, strict=True)) / len(y_true)
def r2_score(y_true: list[float], y_pred: list[float]) -> float:
"""1 - SS_res / SS_tot: the share of the variance of y that the model explains."""
_check_lengths(y_true, y_pred)
mean = sum(y_true) / len(y_true)
ss_res = sum((t - p) ** 2 for t, p in zip(y_true, y_pred, strict=True))
ss_tot = sum((t - mean) ** 2 for t in y_true)
if ss_tot == 0: # constant y_true: scikit-learn returns 1.0 or 0.0 here
return 1.0 if ss_res == 0 else 0.0
return 1 - ss_res / ss_tot
houses = Dataset.from_csv("data/houses.csv", target="price", features=["sqft"])
print(houses.n_samples, houses.n_features, houses.X[0], houses.y[0])
Output
3000 1 [2420.0] 1097500.0

Your refactored library must:

  1. Give NotFittedError a second parent: it subclasses both ValueError and AttributeError, as scikit-learn’s does. Add check_is_fitted(estimator), which raises it when the object has no attribute that ends with _.
  2. Define BaseEstimator with get_params() and set_params(**params). Both read the parameter names from the __init__ signature with inspect.signature. set_params() returns self and raises ValueError for an unknown name.
  3. Define TransformerMixin (fit_transform), RegressorMixin (score = R²) and ClassifierMixin (score = accuracy). Add accuracy_score() next to the module 18 metrics.
  4. Rebuild StandardScaler as StandardScaler(TransformerMixin, BaseEstimator) and LinearRegression as LinearRegression(RegressorMixin, BaseEstimator). Keep their module 18 behavior and error checks. Replace the hasattr() tests with check_is_fitted(). Give the scaler two hyperparameters, with_mean=True and with_std=True (with False, the scaler skips centering or scaling), and let its fit() accept y=None, because fit_transform() passes y on.
  5. Add two baselines: MeanRegressor (predicts the training mean) and MajorityClassifier (predicts the most common label).
  6. Add KNNClassifier(n_neighbors=5). It stores the training rows in fit(), and predict() takes a majority vote of the n_neighbors nearest training rows by Euclidean distance (math.dist). Ties are broken deterministically: equal distances by the lower training index, equal vote counts by the smaller label. fit() raises ValueError when n_neighbors is less than 1.
  7. Follow the conventions: __init__ stores each argument unchanged under its own name and does nothing else, so all checks run in fit() (the lesson’s note on validation explains why estimators do not use the @property setters of module 18); learned attributes end with _; fit() returns self.
  8. Print the MRO and the parameters of every estimator, then evaluate the regressors and the classifiers in two loops that never test a model’s type.
  9. End with assert checks for get_params(), set_params(), NotFittedError and at least one score.
  1. Errors first. Write NotFittedError and check_is_fitted(). Test them on a plain object: check_is_fitted(object()) must raise.

  2. The base class. Write BaseEstimator._get_param_names() as a class method that filters self, *args and **kwargs out of inspect.signature(cls.__init__). Build get_params() and set_params() on it.

  3. The mixins. Each mixin is three or four lines. Write accuracy_score() first, so that ClassifierMixin.score() can use it.

  4. Refactor the scaler and the regression. Change the class lines, replace the hasattr() tests with check_is_fitted(), add the scaler’s __init__ and its y=None parameter. Print the MRO of StandardScaler and check that fit_transform() comes from the mixin.

  5. Add the baselines. They are the bar every real model must beat. A model that does not beat its baseline has learned nothing.

  6. Add the KNN classifier. Sort the training indices by (distance, index) and keep the first n_neighbors. Count the votes with collections.Counter. To break ties, look at the labels in sorted order and keep the first one with the highest count.

  7. Prepare the data. Load both files with Dataset.from_csv(). Split the houses with split_at(2400). Sample every 5th customer, then split off every 4th sampled row for testing. Scale the customer features with the scaler’s fit_transform() on the training rows and transform() on the test rows.

  8. Write the two loops. Each loop iterates over a list of estimators, calls fit() and score(), and prints the class name, the parameters and the score.

  9. Add the asserts and run the whole script.

A skeleton to start from:

minilearn_m19.py (starter)
import inspect
from collections import Counter
from typing import Any, Self
# The module 18 code (Dataset, metrics) goes above this line.
class NotFittedError(ValueError, AttributeError):
"""An estimator was used before fit()."""
def check_is_fitted(estimator: object) -> None:
... # TODO
class BaseEstimator:
... # TODO: _get_param_names, get_params, set_params
class TransformerMixin:
... # TODO: fit_transform
class RegressorMixin:
... # TODO: score with r2_score
class ClassifierMixin:
... # TODO: score with accuracy_score
class StandardScaler(TransformerMixin, BaseEstimator):
... # TODO: the module 18 code, plus check_is_fitted
class LinearRegression(RegressorMixin, BaseEstimator):
... # TODO
class MeanRegressor(RegressorMixin, BaseEstimator):
... # TODO
class MajorityClassifier(ClassifierMixin, BaseEstimator):
... # TODO
class KNNClassifier(ClassifierMixin, BaseEstimator):
def __init__(self, n_neighbors: int = 5) -> None:
self.n_neighbors = n_neighbors
... # TODO: fit, _predict_one, predict
# TODO: load the data, split it, run the two polymorphic loops, add the asserts
Criterion Points Full points when
BaseEstimator 3 get_params() and set_params() read the __init__ signature; unknown names raise ValueError; set_params() returns self
Mixins 2 fit_transform() and both score() methods are written once and inherited
Class lines and MRO 2 every estimator lists its mixin before BaseEstimator; the printed MRO matches
Fitted checks 2 NotFittedError inherits from ValueError and AttributeError; using an unfitted model raises it
KNN classifier 3 correct neighbors and votes, deterministic ties, n_neighbors validated in fit()
Baselines 1 both baselines exist and appear in the comparisons
Polymorphism 3 the two loops call only shared methods (fit(), predict(), score(), get_params()), with no type checks
Conventions 2 __init__ only stores arguments; learned attributes end with _; fit() returns self
Self-checks 1 asserts cover parameters, errors and a score
Interpretation 1 a comment states whether each real model beats its baseline
Total 20 16 or more: you are ready for module 20
  1. Add clone(estimator), which returns type(estimator)(**estimator.get_params()), and use it to fit five fresh KNNClassifier objects with different n_neighbors on the same training data.
  2. Add a weights parameter to KNNClassifier: "uniform" (one vote per neighbor) or "distance" (a vote of 1 / (distance + 1e-9)). get_params() must show it with no extra code.
  3. Add an ABC AbstractPredictor with the abstract methods fit and predict, and make every model a subclass (not the scaler, which has no predict()). Check that a class without predict() can no longer be instantiated.
  4. Write a typing.Protocol named SupportsScore and type the evaluation loop with it. Run mypy on your file.
  5. Give MeanRegressor a strategy parameter ("mean" or "median") and compare both on the house prices.

Try the project yourself first. Then compare your code with this solution. It continues the module 18 code from Starting point, which must run first. Dataset, mean_squared_error and r2_score stay unchanged; everything else is new or rebuilt.

Reference solution
minilearn_m19.py
import inspect
import math
from collections import Counter
from typing import Any
# --- base.py: errors --------------------------------------------------------
class NotFittedError(ValueError, AttributeError):
"""Raised when a model or transformer is used before fit()."""
def check_is_fitted(estimator: object) -> None:
"""Raise NotFittedError if the object has no learned attribute (name ending _)."""
learned = [k for k in vars(estimator) if k.endswith("_") and not k.startswith("__")]
if not learned:
name = type(estimator).__name__
raise NotFittedError(f"{name} is not fitted yet; call fit() first")
# --- metrics.py: one more metric --------------------------------------------
def accuracy_score(y_true: list[Any], y_pred: list[Any]) -> float:
"""Share of predictions that equal the true label."""
_check_lengths(y_true, y_pred)
return sum(t == p for t, p in zip(y_true, y_pred, strict=True)) / len(y_true)
# --- base.py: BaseEstimator and the mixins ------------------------------------
class BaseEstimator:
"""get_params() and set_params() for every estimator."""
@classmethod
def _get_param_names(cls) -> list[str]:
params = inspect.signature(cls.__init__).parameters.values()
return [
p.name
for p in params
if p.name != "self" and p.kind not in (p.VAR_POSITIONAL, p.VAR_KEYWORD)
]
def get_params(self) -> dict[str, Any]:
return {name: getattr(self, name) for name in self._get_param_names()}
def set_params(self, **params: Any) -> Self:
valid = self._get_param_names()
for name, value in params.items():
if name not in valid:
raise ValueError(
f"Invalid parameter {name!r} for {type(self).__name__}. "
f"Valid: {valid}"
)
setattr(self, name, value)
return self
class TransformerMixin:
"""fit_transform() for every transformer."""
def fit_transform(self, X: list[list[float]], y: Any = None) -> list[list[float]]:
return self.fit(X, y).transform(X)
class RegressorMixin:
"""score() as R² for every regressor."""
def score(self, X: list[list[float]], y: list[float]) -> float:
return r2_score(y, self.predict(X))
class ClassifierMixin:
"""score() as accuracy for every classifier."""
def score(self, X: list[list[float]], y: list[Any]) -> float:
return accuracy_score(y, self.predict(X))
# --- preprocessing.py -----------------------------------------------------------
class StandardScaler(TransformerMixin, BaseEstimator):
"""Standardize features: z = (x - mean_) / scale_, column by column."""
def __init__(self, with_mean: bool = True, with_std: bool = True) -> None:
self.with_mean = with_mean
self.with_std = with_std
def fit(self, X: list[list[float]], y: Any = None) -> Self:
if not X:
raise ValueError("cannot fit on an empty X")
n = len(X)
columns = list(zip(*X, strict=True))
means = [sum(col) / n for col in columns]
stds = [
self._population_std(col, mean)
for col, mean in zip(columns, means, strict=True)
]
self.mean_ = means if self.with_mean else [0.0] * len(columns)
self.scale_ = stds if self.with_std else [1.0] * len(columns)
self.n_features_in_ = len(columns)
return self
def transform(self, X: list[list[float]]) -> list[list[float]]:
self._check(X)
params = list(zip(self.mean_, self.scale_, strict=True))
return [
[(v - m) / s for v, (m, s) in zip(row, params, strict=True)] for row in X
]
def inverse_transform(self, Z: list[list[float]]) -> list[list[float]]:
self._check(Z)
params = list(zip(self.mean_, self.scale_, strict=True))
return [[z * s + m for z, (m, s) in zip(row, params, strict=True)] for row in Z]
@staticmethod
def _population_std(values: tuple[float, ...], mean: float) -> float:
variance = sum((v - mean) ** 2 for v in values) / len(values)
std = variance**0.5
return std if std > 0 else 1.0 # a constant column stays unchanged
def _check(self, X: list[list[float]]) -> None:
check_is_fitted(self)
for row in X:
if len(row) != self.n_features_in_:
raise ValueError(
f"X has {len(row)} features, but the scaler was fitted "
f"with {self.n_features_in_}"
)
# --- linear_model.py ------------------------------------------------------------
class LinearRegression(RegressorMixin, BaseEstimator):
"""Fit y = coef_ * x + intercept_ for a single feature x."""
def __init__(self, fit_intercept: bool = True) -> None:
self.fit_intercept = fit_intercept
@staticmethod
def _single_column(X: list[list[float]]) -> list[float]:
for row in X:
if len(row) != 1:
raise ValueError(
f"LinearRegression supports exactly 1 feature, got {len(row)}"
)
return [row[0] for row in X]
def fit(self, X: list[list[float]], y: list[float]) -> Self:
x = self._single_column(X)
if len(x) != len(y) or len(x) < 2:
raise ValueError("X and y need the same length, with at least 2 samples")
if self.fit_intercept:
x_mean = sum(x) / len(x)
y_mean = sum(y) / len(y)
else:
x_mean = y_mean = 0.0
sxx = sum((xi - x_mean) ** 2 for xi in x)
sxy = sum((xi - x_mean) * (yi - y_mean) for xi, yi in zip(x, y, strict=True))
if sxx == 0:
raise ValueError("cannot fit a line: all x values are equal")
self.coef_ = sxy / sxx
self.intercept_ = y_mean - self.coef_ * x_mean
return self
def predict(self, X: list[list[float]]) -> list[float]:
check_is_fitted(self)
return [self.coef_ * x + self.intercept_ for x in self._single_column(X)]
# --- baselines --------------------------------------------------------------------
class MeanRegressor(RegressorMixin, BaseEstimator):
"""Baseline: predict the training mean for every row."""
def fit(self, X: list[list[float]], y: list[float]) -> Self:
self.mean_ = sum(y) / len(y)
return self
def predict(self, X: list[list[float]]) -> list[float]:
check_is_fitted(self)
return [self.mean_ for _ in X]
class MajorityClassifier(ClassifierMixin, BaseEstimator):
"""Baseline: predict the most common training label (the smaller one on a tie)."""
def fit(self, X: list[list[float]], y: list[Any]) -> Self:
counts = Counter(y)
top = max(counts.values())
self.majority_ = min(label for label, n in counts.items() if n == top)
return self
def predict(self, X: list[list[float]]) -> list[Any]:
check_is_fitted(self)
return [self.majority_ for _ in X]
# --- neighbors.py -----------------------------------------------------------------
class KNNClassifier(ClassifierMixin, BaseEstimator):
"""Majority vote of the k nearest training rows (Euclidean distance)."""
def __init__(self, n_neighbors: int = 5) -> None:
self.n_neighbors = n_neighbors
def fit(self, X: list[list[float]], y: list[Any]) -> Self:
if self.n_neighbors < 1:
raise ValueError(f"n_neighbors must be >= 1, got {self.n_neighbors}")
self.X_train_ = [list(row) for row in X]
self.y_train_ = list(y)
self.classes_ = sorted(set(y))
return self
def _predict_one(self, row: list[float]) -> Any:
def distance(i: int) -> tuple[float, int]:
return math.dist(row, self.X_train_[i]), i # equal distances: lower index
nearest = sorted(range(len(self.X_train_)), key=distance)
votes = Counter(self.y_train_[i] for i in nearest[: self.n_neighbors])
return max(self.classes_, key=lambda label: votes[label]) # ties: smaller
def predict(self, X: list[list[float]]) -> list[Any]:
check_is_fitted(self)
return [self._predict_one(row) for row in X]
estimators = [
StandardScaler(),
LinearRegression(),
MeanRegressor(),
MajorityClassifier(),
KNNClassifier(n_neighbors=15),
]
for est in estimators:
mro = " -> ".join(cls.__name__ for cls in type(est).__mro__[1:-1])
print(f"{type(est).__name__:<18} {mro:<34} {est.get_params()}")
Output
StandardScaler TransformerMixin -> BaseEstimator {'with_mean': True, 'with_std': True}
LinearRegression RegressorMixin -> BaseEstimator {'fit_intercept': True}
MeanRegressor RegressorMixin -> BaseEstimator {}
MajorityClassifier ClassifierMixin -> BaseEstimator {}
KNNClassifier ClassifierMixin -> BaseEstimator {'n_neighbors': 15}

Every estimator shares one get_params(). The MRO column skips the class itself and object, and shows the mixin first, then the base.

Now the regressors. The loop calls the same three methods on every model:

train, test = houses.split_at(2400)
regressors = [
MeanRegressor(),
LinearRegression(),
LinearRegression(fit_intercept=False),
]
for model in regressors:
model.fit(train.X, train.y)
r2 = model.score(test.X, test.y)
rmse = math.sqrt(mean_squared_error(test.y, model.predict(test.X)))
params = str(model.get_params())
print(f"{type(model).__name__:<17} {params:<24} R² {r2:6.3f} RMSE {rmse:9,.0f}")
# Beats the baseline: both lines (R² 0.561 and 0.531 against -0.014).
Output
MeanRegressor {} R² -0.014 RMSE 349,424
LinearRegression {'fit_intercept': True} R² 0.561 RMSE 229,936
LinearRegression {'fit_intercept': False} R² 0.531 RMSE 237,642

The numbers match module 18: the refactor changed the structure, not the results. The line explains about 56% of the price variance and cuts the RMSE by about a third compared with the mean baseline. The mean baseline scores just below 0, because the test houses sold later, at higher prices than the training mean. Forcing the line through the origin costs a little R².

Then the classifiers. The features are scaled first, because KNN measures distances and the two features have different spreads:

customers = Dataset.from_csv(
"data/customers.csv",
target="churned",
features=["tenure_months", "logins_last_30d"],
)
labels = [int(v) for v in customers.y[::5]]
sample = Dataset(customers.X[::5], labels, customers.feature_names)
is_test = [i % 4 == 0 for i in range(sample.n_samples)]
X_tr = [row for row, t in zip(sample.X, is_test, strict=True) if not t]
X_te = [row for row, t in zip(sample.X, is_test, strict=True) if t]
y_tr = [label for label, t in zip(sample.y, is_test, strict=True) if not t]
y_te = [label for label, t in zip(sample.y, is_test, strict=True) if t]
scaler = StandardScaler()
X_tr_s = scaler.fit_transform(X_tr)
X_te_s = scaler.transform(X_te)
churn_rate = sum(y_te) / len(y_te)
print(f"train {len(X_tr)} rows, test {len(X_te)} rows, test churn {churn_rate:.1%}")
means = [round(m, 1) for m in scaler.mean_]
scales = [round(s, 1) for s in scaler.scale_]
print("scaler:", means, scales)
classifiers = [MajorityClassifier()]
classifiers += [KNNClassifier(n_neighbors=k) for k in (1, 5, 15)]
for model in classifiers:
acc = model.fit(X_tr_s, y_tr).score(X_te_s, y_te)
params = str(model.get_params())
print(f"{type(model).__name__:<18} {params:<20} accuracy {acc:.3f}")
# Beats the baseline: only n_neighbors=15, by one test customer (0.824 vs 0.820).
Output
train 750 rows, test 250 rows, test churn 18.0%
scaler: [23.1, 11.2] [19.8, 7.2]
MajorityClassifier {} accuracy 0.820
KNNClassifier {'n_neighbors': 1} accuracy 0.724
KNNClassifier {'n_neighbors': 5} accuracy 0.800
KNNClassifier {'n_neighbors': 15} accuracy 0.824

The majority baseline never predicts churn and still scores 0.82, because 82% of the test customers stayed. KNNClassifier(n_neighbors=1) copies the label of the single nearest customer, so it follows noise and falls below the baseline. With 15 neighbors, it scores 0.824: one more correct answer out of 250 than the baseline. Interpretation: on these two features, accuracy cannot show that KNN has learned anything useful. Module 36 measures churn models with recall and precision, which reveal how many churners a model catches.

Finally, the errors and the asserts:

KNNClassifier().predict(X_te_s[:1])
Output
NotFittedError: KNNClassifier is not fitted yet; call fit() first
try:
LinearRegression().predict([[1500.0]])
except AttributeError as err: # code that expects AttributeError still works
print("caught as AttributeError:", type(err).__name__)
knn = KNNClassifier()
assert knn.set_params(n_neighbors=7) is knn and knn.get_params() == {"n_neighbors": 7}
try:
knn.set_params(k=3)
except ValueError as err:
print("caught:", err)
try:
KNNClassifier(n_neighbors=0).fit(X_tr_s, y_tr)
except ValueError as err:
print("caught:", err)
tie = KNNClassifier(n_neighbors=2).fit([[0.0], [1.0], [5.0]], ["b", "a", "a"])
print("tie between 'a' and 'b' ->", tie.predict([[0.4]]))
assert tie.predict([[0.4]]) == ["a"]
assert isinstance(StandardScaler(), TransformerMixin)
assert issubclass(NotFittedError, ValueError)
assert issubclass(NotFittedError, AttributeError)
round_trip = scaler.inverse_transform(X_te_s)
assert all(math.isclose(a, b) for r, s in zip(round_trip, X_te) for a, b in zip(r, s))
assert StandardScaler(with_mean=False).fit(X_tr).mean_ == [0.0, 0.0]
assert round(regressors[1].score(test.X, test.y), 3) == 0.561
print("all checks passed")
Output
caught as AttributeError: NotFittedError
caught: Invalid parameter 'k' for KNNClassifier. Valid: ['n_neighbors']
caught: n_neighbors must be >= 1, got 0
tie between 'a' and 'b' -> ['a']
all checks passed

How it works:

  1. One base, many estimators. BaseEstimator._get_param_names() reads cls.__init__, so every subclass reports its own hyperparameters. The baselines have no __init__ and report {}.
  2. Mixins write each shared method once. fit_transform() exists in one place and serves every transformer; score() exists once for regressors and once for classifiers. Swapping the mixin changes the metric.
  3. The MRO decides. Every class line lists the mixin before BaseEstimator, so a mixin could extend a base method if it ever needed to.
  4. Fitted checks with a two-parent error. check_is_fitted() looks for a learned attribute (a name that ends with _). NotFittedError is now both a ValueError and an AttributeError, so module 18 code that catches ValueError and other code that catches AttributeError both still work.
  5. KNN with deterministic ties. Sorting by (distance, index) fixes the order of equal distances. max() over the sorted classes_ returns the first label with the highest count, so a 1–1 vote between "a" and "b" returns "a".
  6. Polymorphism. Both loops call only shared methods: fit(), predict(), score() and get_params(). Adding a model means adding one list item.
  7. The scaler’s new settings. with_mean=False keeps the data uncentered (mean_ is all zeros), which the last-but-one assert checks. get_params() shows both settings with no extra code.

Alternative: KNNClassifier could inherit from an ABC AbstractPredictor to force fit() and predict() (stretch goal 3), or the loops could be typed with a Protocol and checked by mypy (stretch goal 4). scikit-learn itself uses neither for its estimators: it relies on duck typing plus the conventions that BaseEstimator enforces. Module 20 adds __repr__ so that print(model) shows KNNClassifier(n_neighbors=15), and a Pipeline that holds a scaler and a model by composition.