Skip to content

19. Inheritance and polymorphism — Exercises

These exercises practice every idea of the inheritance and polymorphism lesson. They use small slices of data/houses.csv and data/customers.csv, and two challenge exercises read the full house file.

How to work:

  1. Copy the setup block below into the top of your script. Every exercise uses it.
  2. Read the task and the expected output. Copy the starter code under the setup and replace each to-do comment.
  3. Run the script and compare your output with the expected output.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

The setup holds the data slices and the small minilearn base classes from the lesson: BaseEstimator, the three mixins and three metrics. It prints nothing.

import csv
import inspect
import io
import math
from abc import ABC, abstractmethod
from collections import Counter
from statistics import mean, median
from typing import Any, Protocol, Self, runtime_checkable
type Rows = list[list[float]]
# Eight houses from data/houses.csv: [sqft] and price.
X_houses: Rows = [
[2420.0], [1610.0], [1260.0], [1790.0], [3170.0], [2190.0], [1680.0], [1730.0]
]
y_houses = [
1097500.0, 486500.0, 223000.0, 431000.0, 626500.0, 544500.0, 397500.0, 435000.0
]
# Twenty customers from data/customers.csv (every 250th row):
# [tenure_months, logins_last_30d] and churned (1 = the customer left).
X_cust: Rows = [
[72.0, 17.0], [69.0, 2.0], [54.0, 4.0], [45.0, 2.0], [39.0, 8.0],
[34.0, 28.0], [29.0, 15.0], [26.0, 3.0], [22.0, 9.0], [20.0, 8.0],
[17.0, 8.0], [15.0, 11.0], [13.0, 13.0], [11.0, 9.0], [9.0, 6.0],
[7.0, 11.0], [6.0, 4.0], [4.0, 0.0], [3.0, 17.0], [1.0, 1.0],
]
y_cust = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1]
def mae(y_true: list[float], y_pred: list[float]) -> float:
return sum(abs(t - p) 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:
mean_true = 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_true) ** 2 for t in y_true)
return 1 - ss_res / ss_tot
def accuracy_score(y_true: list[Any], y_pred: list[Any]) -> float:
return sum(t == p for t, p in zip(y_true, y_pred, strict=True)) / len(y_true)
class BaseEstimator:
"""get_params() and set_params() from the __init__ signature."""
@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}. Valid: {valid}")
setattr(self, name, value)
return self
class TransformerMixin:
def fit_transform(self, X: Rows, y: list[float] | None = None) -> Rows:
return self.fit(X, y).transform(X)
class RegressorMixin:
def score(self, X: Rows, y: list[float]) -> float:
return r2_score(y, self.predict(X))
class ClassifierMixin:
def score(self, X: Rows, y: list[Any]) -> float:
return accuracy_score(y, self.predict(X))
Warm-up

The class ChurnRule below flags a customer as at risk (1) when logins_last_30d is 3 or fewer. Write a subclass NewCustomerRule that overrides only predict_one(): a customer is at risk when tenure_months is 6 or fewer. Print both rules’ predictions for X_cust and the number of flagged customers.

Expected output
ChurnRule [0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1] flagged=5
NewCustomerRule [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1] flagged=4
Starter
class ChurnRule:
"""At risk (1) when logins_last_30d <= 3."""
def predict_one(self, row: list[float]) -> int:
return int(row[1] <= 3)
def predict(self, X: Rows) -> list[int]:
return [self.predict_one(row) for row in X]
# TODO: class NewCustomerRule(ChurnRule) that overrides predict_one()
# TODO: print the predictions of both rules and how many customers each flags
Hint 1

tenure_months is row[0]. The new class needs one method only; predict() is inherited.

Hint 2

Override only the method that decides one row. The new rule compares row[0] with 6 and returns int(...) of the comparison.

Solution
class ChurnRule:
"""At risk (1) when logins_last_30d <= 3."""
def predict_one(self, row: list[float]) -> int:
return int(row[1] <= 3)
def predict(self, X: Rows) -> list[int]:
return [self.predict_one(row) for row in X]
class NewCustomerRule(ChurnRule):
"""At risk (1) when tenure_months <= 6."""
def predict_one(self, row: list[float]) -> int:
return int(row[0] <= 6)
for rule in (ChurnRule(), NewCustomerRule()):
preds = rule.predict(X_cust)
print(f"{type(rule).__name__:<16} {preds} flagged={sum(preds)}")
assert NewCustomerRule().predict([[6.0, 50.0], [7.0, 0.0]]) == [1, 0]
assert "predict" not in vars(NewCustomerRule)
Output
ChurnRule [0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1] flagged=5
NewCustomerRule [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1] flagged=4

How it works:

  1. NewCustomerRule.predict() is not defined, so Python finds ChurnRule.predict().
  2. Inside it, self.predict_one(row) starts the search at type(self). For a NewCustomerRule object, the child’s version runs.
  3. The second assert proves that the child holds only its own method.

Alternative: pass the rule as data instead of writing a class per rule: ChurnRule(feature=0, limit=6). That is composition of a setting instead of inheritance, and it suits rules that differ only in numbers. Use a subclass when the logic itself differs.

M19-W02 · Predict the output: which method runs?

Section titled “M19-W02 · Predict the output: which method runs?”
Warm-up

Predict the output: read the code and write down the four lines that it prints.

Starter
class Scaler:
def fit(self) -> str:
return "Scaler.fit"
def transform(self) -> str:
return "Scaler.transform"
def describe(self) -> str:
return f"{self.fit()} then {self.transform()}"
class LogScaler(Scaler):
def transform(self) -> str:
return "LogScaler.transform"
print(Scaler().describe())
print(LogScaler().describe())
print(LogScaler().fit())
print("fit" in vars(LogScaler), "transform" in vars(LogScaler))

Acceptance criteria: write your prediction line by line, then run the code. Your prediction matches the Output in the solution.

Hint 1

describe() is defined only in Scaler. What matters is the class of self when it runs.

Hint 2

vars(LogScaler) contains only the names written inside the LogScaler class body.

Solution
class Scaler:
def fit(self) -> str:
return "Scaler.fit"
def transform(self) -> str:
return "Scaler.transform"
def describe(self) -> str:
return f"{self.fit()} then {self.transform()}"
class LogScaler(Scaler):
def transform(self) -> str:
return "LogScaler.transform"
print(Scaler().describe())
print(LogScaler().describe())
print(LogScaler().fit())
print("fit" in vars(LogScaler), "transform" in vars(LogScaler))
assert LogScaler().describe().endswith("LogScaler.transform")
Output
Scaler.fit then Scaler.transform
Scaler.fit then LogScaler.transform
Scaler.fit
False True

How it works:

  1. Line 1: a Scaler uses its own two methods.
  2. Line 2: describe() is inherited, but self is a LogScaler, so self.transform() finds the override. self.fit() falls back to Scaler.fit.
  3. Line 3: fit() is inherited unchanged.
  4. Line 4: vars() of a class shows only what that class defines, not what it inherits.
Warm-up

LinearModel stores fit_intercept. Write RidgeRegression(LinearModel) with the signature __init__(self, alpha=1.0, fit_intercept=True). It stores alpha and lets the parent store fit_intercept through super().__init__(). Print get_params() of RidgeRegression(alpha=0.5) and the MRO names.

Expected output
{'alpha': 0.5, 'fit_intercept': True}
['RidgeRegression', 'LinearModel', 'BaseEstimator', 'object']
Starter
class LinearModel(BaseEstimator):
def __init__(self, fit_intercept: bool = True) -> None:
self.fit_intercept = fit_intercept
# TODO: class RidgeRegression(LinearModel) with alpha and fit_intercept
# TODO: print get_params() of RidgeRegression(alpha=0.5) and the MRO names
Hint 1

The child accepts both arguments, stores its own and passes the other one to super().__init__(...).

Hint 2

get_params() reads RidgeRegression.__init__, so both names must be parameters of the child’s __init__.

Solution
class LinearModel(BaseEstimator):
def __init__(self, fit_intercept: bool = True) -> None:
self.fit_intercept = fit_intercept
class RidgeRegression(LinearModel):
def __init__(self, alpha: float = 1.0, fit_intercept: bool = True) -> None:
super().__init__(fit_intercept=fit_intercept)
self.alpha = alpha
ridge = RidgeRegression(alpha=0.5)
print(ridge.get_params())
print([cls.__name__ for cls in RidgeRegression.__mro__])
assert ridge.get_params() == {"alpha": 0.5, "fit_intercept": True}
assert RidgeRegression(fit_intercept=False).fit_intercept is False
Output
{'alpha': 0.5, 'fit_intercept': True}
['RidgeRegression', 'LinearModel', 'BaseEstimator', 'object']

How it works:

  1. super().__init__(fit_intercept=fit_intercept) runs LinearModel.__init__ on the same object.
  2. The child sets only the attribute that is new.
  3. get_params() reads the child’s signature, so it lists alpha and fit_intercept in signature order.

M19-W04 · Fix the bug: the parent’s attribute is missing

Section titled “M19-W04 · Fix the bug: the parent’s attribute is missing”
Warm-up

Fix the bug: the code below stops with AttributeError: 'MinMaxScaler' object has no attribute 'clip'. Fix the child class so that MinMaxScaler() works and MinMaxScaler(clip=True) caps the scaled values at the range limits. The script must print the expected output.

Expected output
1.2 0.5
1.0
Starter
class Scaler:
def __init__(self, clip: bool = False) -> None:
self.clip = clip
class MinMaxScaler(Scaler):
def __init__(self, low: float = 0.0, high: float = 1.0) -> None:
self.low = low
self.high = high
def scale(self, value: float, vmin: float, vmax: float) -> float:
scaled = self.low + (value - vmin) / (vmax - vmin) * (self.high - self.low)
if self.clip:
scaled = min(max(scaled, self.low), self.high)
return scaled
scaler = MinMaxScaler()
print(scaler.scale(72.0, 0.0, 60.0), scaler.scale(30.0, 0.0, 60.0))
# TODO: also print MinMaxScaler(clip=True).scale(72.0, 0.0, 60.0)
Hint 1

Two things are missing: the child does not accept clip, and it never runs the parent’s __init__.

Hint 2

Add clip: bool = False to the child’s parameters and call super().__init__(clip=clip).

Solution
class Scaler:
def __init__(self, clip: bool = False) -> None:
self.clip = clip
class MinMaxScaler(Scaler):
def __init__(self, low: float = 0.0, high: float = 1.0, clip: bool = False) -> None:
super().__init__(clip=clip)
self.low = low
self.high = high
def scale(self, value: float, vmin: float, vmax: float) -> float:
scaled = self.low + (value - vmin) / (vmax - vmin) * (self.high - self.low)
if self.clip:
scaled = min(max(scaled, self.low), self.high)
return scaled
scaler = MinMaxScaler()
print(scaler.scale(72.0, 0.0, 60.0), scaler.scale(30.0, 0.0, 60.0))
print(MinMaxScaler(clip=True).scale(72.0, 0.0, 60.0))
assert MinMaxScaler(clip=True).scale(72.0, 0.0, 60.0) == 1.0
assert scaler.clip is False
Output
1.2 0.5
1.0

How it works:

  1. The child’s __init__ replaced the parent’s, and it never called it. So self.clip was never set, and scale() raised the AttributeError.
  2. The child also had no clip parameter: MinMaxScaler(clip=True) would have raised TypeError: MinMaxScaler.__init__() got an unexpected keyword argument 'clip'.
  3. The fixed __init__ accepts clip and hands it to the parent, which stores it. A tenure of 72 months on a 0–60 scale is 1.2; with clip=True it is capped at 1.0.
Warm-up

Use the setup’s BaseEstimator and TransformerMixin. Define OneHotEncoder(TransformerMixin, BaseEstimator) with an empty body (pass) and SparseOneHotEncoder(OneHotEncoder), also empty. Print the MRO names of SparseOneHotEncoder joined by " -> ", then the name of the class where fit_transform and set_params are defined.

Expected output
SparseOneHotEncoder -> OneHotEncoder -> TransformerMixin -> BaseEstimator -> object
fit_transform: TransformerMixin
set_params: BaseEstimator
Starter
# TODO: define OneHotEncoder and SparseOneHotEncoder
# TODO: print the MRO joined by " -> "
# TODO: for "fit_transform" and "set_params", print the defining class
Hint 1

" -> ".join(cls.__name__ for cls in SparseOneHotEncoder.__mro__) builds the first line.

Hint 2

Walk the MRO and stop at the first class whose vars(cls) contains the name: next(cls for cls in mro if name in vars(cls)).

Solution
class OneHotEncoder(TransformerMixin, BaseEstimator):
pass
class SparseOneHotEncoder(OneHotEncoder):
pass
mro = SparseOneHotEncoder.__mro__
print(" -> ".join(cls.__name__ for cls in mro))
for name in ("fit_transform", "set_params"):
owner = next(cls for cls in mro if name in vars(cls))
print(f"{name}: {owner.__name__}")
assert mro[1] is OneHotEncoder and mro[-1] is object
Output
SparseOneHotEncoder -> OneHotEncoder -> TransformerMixin -> BaseEstimator -> object
fit_transform: TransformerMixin
set_params: BaseEstimator

How it works:

  1. The child comes first, then its parent, then the parent’s parents in the order the class statement lists them.
  2. object is always last.
  3. The next(...) search repeats exactly what Python does when it looks up a method.

Alternative: SparseOneHotEncoder.mro() returns the same order as a list.

M19-W06 · Predict the output: isinstance, issubclass and type

Section titled “M19-W06 · Predict the output: isinstance, issubclass and type”
Warm-up

Predict the output: write down the five lines.

Starter
class StandardScaler(TransformerMixin, BaseEstimator):
pass
class KNN(ClassifierMixin, BaseEstimator):
pass
scaler = StandardScaler()
print(isinstance(scaler, BaseEstimator), isinstance(scaler, ClassifierMixin))
print(issubclass(KNN, BaseEstimator), issubclass(BaseEstimator, KNN))
print(type(scaler) is BaseEstimator, type(scaler) is StandardScaler)
print(isinstance(scaler, (ClassifierMixin, TransformerMixin)))
print(issubclass(KNN, object), isinstance(KNN, type))

Acceptance criteria: write your prediction line by line, then run the code. Your prediction matches the Output in the solution.

Hint 1

isinstance() is True for the class and every class in its MRO. type(x) is compares with one exact class.

Hint 2

isinstance() accepts a tuple of classes and returns True if any one matches. A class is itself an object; its type is type.

Solution
class StandardScaler(TransformerMixin, BaseEstimator):
pass
class KNN(ClassifierMixin, BaseEstimator):
pass
scaler = StandardScaler()
print(isinstance(scaler, BaseEstimator), isinstance(scaler, ClassifierMixin))
print(issubclass(KNN, BaseEstimator), issubclass(BaseEstimator, KNN))
print(type(scaler) is BaseEstimator, type(scaler) is StandardScaler)
print(isinstance(scaler, (ClassifierMixin, TransformerMixin)))
print(issubclass(KNN, object), isinstance(KNN, type))
assert isinstance(scaler, TransformerMixin)
Output
True False
True False
False True
True
True True

How it works:

  1. A scaler is a BaseEstimator but not a ClassifierMixin.
  2. issubclass() points one way: from the child to its ancestors.
  3. type(scaler) is exactly StandardScaler. Comparing types with is (or ==) ignores inheritance, which is why isinstance() is the right test for “is this some kind of estimator”.
  4. The tuple form matches on TransformerMixin.
  5. Every class inherits from object, and every class is an instance of type.

M19-W07 · Fix the bug: an abstract method with a typo

Section titled “M19-W07 · Fix the bug: an abstract method with a typo”
Warm-up

Fix the bug: Metric is an ABC with the abstract method compute() and a concrete method report(). Creating MAE() fails with TypeError: Can't instantiate abstract class MAE without an implementation for abstract method 'compute'. Fix MAE so that the script prints the expected output for the true prices [400, 250, 310] (in thousands) and the predictions [380, 260, 300].

Expected output
MAE: 13.33
Starter
class Metric(ABC):
name = "metric"
@abstractmethod
def compute(self, y_true: list[float], y_pred: list[float]) -> float: ...
def report(self, y_true: list[float], y_pred: list[float]) -> str:
return f"{self.name}: {self.compute(y_true, y_pred):.2f}"
class MAE(Metric):
name = "MAE"
def calculate(self, y_true: list[float], y_pred: list[float]) -> float:
return sum(abs(t - p) for t, p in zip(y_true, y_pred)) / len(y_true)
print(MAE().report([400, 250, 310], [380, 260, 300]))
Hint 1

Compare the name of the method in MAE with the name of the abstract method.

Hint 2

MAE.__abstractmethods__ shows the names that are still missing.

Solution
class Metric(ABC):
name = "metric"
@abstractmethod
def compute(self, y_true: list[float], y_pred: list[float]) -> float: ...
def report(self, y_true: list[float], y_pred: list[float]) -> str:
return f"{self.name}: {self.compute(y_true, y_pred):.2f}"
class MAE(Metric):
name = "MAE"
def compute(self, y_true: list[float], y_pred: list[float]) -> float:
errors = [abs(t - p) for t, p in zip(y_true, y_pred, strict=True)]
return sum(errors) / len(errors)
print(MAE().report([400, 250, 310], [380, 260, 300]))
assert not MAE.__abstractmethods__
assert MAE().compute([1.0], [3.0]) == 2.0
Output
MAE: 13.33

How it works:

  1. The ABC refused to create MAE objects because compute was still abstract. calculate was just an extra method.
  2. After the rename, __abstractmethods__ is empty and the class is concrete.
  3. report() is inherited and calls the child’s compute(). The class attribute name is overridden the same way as a method.

M19-W08 · Check an interface with getattr and callable

Section titled “M19-W08 · Check an interface with getattr and callable”
Warm-up

Write describe_api(obj) that returns a line like LinearModel: fit=yes predict=yes, using getattr(obj, name, None) and callable(). Test it on the three objects in the starter.

Expected output
LinearModel: fit=yes predict=yes
Draft: fit=no predict=no
list: fit=no predict=no
Starter
class LinearModel:
def fit(self, X: Rows, y: list[float]) -> Self:
return self
def predict(self, X: Rows) -> list[float]:
return [0.0 for _ in X]
class Draft:
predict = None # placeholder, not a method yet
objects = [LinearModel(), Draft(), [1.0, 2.0]]
# TODO: def describe_api(obj: object) -> str
# TODO: print describe_api() for each object
Hint 1

getattr(obj, "fit", None) returns None when the attribute is missing.

Hint 2

"yes" if callable(...) else "no" turns the test into text. type(obj).__name__ gives the class name.

Solution
class LinearModel:
def fit(self, X: Rows, y: list[float]) -> Self:
return self
def predict(self, X: Rows) -> list[float]:
return [0.0 for _ in X]
class Draft:
predict = None # placeholder, not a method yet
def describe_api(obj: object) -> str:
parts = []
for name in ("fit", "predict"):
ok = callable(getattr(obj, name, None))
parts.append(f"{name}={'yes' if ok else 'no'}")
return f"{type(obj).__name__}: {' '.join(parts)}"
objects = [LinearModel(), Draft(), [1.0, 2.0]]
for obj in objects:
print(describe_api(obj))
assert describe_api(Draft()) == "Draft: fit=no predict=no"
Output
LinearModel: fit=yes predict=yes
Draft: fit=no predict=no
list: fit=no predict=no

How it works:

  1. getattr() with a default never raises, so the check works for any object, even a list.
  2. Draft has an attribute named predict, but None is not callable. hasattr() alone would say True.
  3. This is the LBYL style of duck typing: check first, then call.

M19-W09 · Write a runtime-checkable Protocol

Section titled “M19-W09 · Write a runtime-checkable Protocol”
Warm-up

Write a protocol SupportsTransform with one method, transform(self, X: Rows) -> Rows, and make it usable with isinstance(). Print the result of isinstance() for the three objects in the starter.

Expected output
Doubler True
Mean False
str False
Starter
class Doubler:
def transform(self, X: Rows) -> Rows:
return [[2 * v for v in row] for row in X]
class Mean:
def predict(self, X: Rows) -> list[float]:
return [0.0 for _ in X]
# TODO: the protocol SupportsTransform
# TODO: print isinstance() for Doubler(), Mean() and the string "transform"
Hint 1

A protocol is a class that inherits from Protocol. Its method body is ....

Hint 2

Without the decorator @runtime_checkable, isinstance() raises a TypeError.

Solution
@runtime_checkable
class SupportsTransform(Protocol):
def transform(self, X: Rows) -> Rows: ...
class Doubler:
def transform(self, X: Rows) -> Rows:
return [[2 * v for v in row] for row in X]
class Mean:
def predict(self, X: Rows) -> list[float]:
return [0.0 for _ in X]
for obj in (Doubler(), Mean(), "transform"):
print(f"{type(obj).__name__:<8} {isinstance(obj, SupportsTransform)}")
assert isinstance(Doubler(), SupportsTransform)
assert SupportsTransform not in Doubler.__mro__
Output
Doubler True
Mean False
str False

How it works:

  1. Doubler matches by structure: it has a transform attribute. It does not inherit from the protocol, as the last assert shows.
  2. Mean has no transform, and neither has a string. (A string has translate, not transform.)
  3. The runtime check only tests that the name exists; mypy checks the signature.

M19-C01 · Read hyperparameters with inspect.signature

Section titled “M19-C01 · Read hyperparameters with inspect.signature”
Core

Write two functions without using the setup’s BaseEstimator. param_names(cls) returns the names of the parameters of cls.__init__, without self, *args and **kwargs. get_params(obj) returns a dict of those names and the object’s values. Test them on the two classes in the starter.

Expected output
KNNClassifier ['n_neighbors', 'metric'] {'n_neighbors': 3, 'metric': 'euclidean'}
FlexibleModel ['alpha'] {'alpha': 0.1}
Starter
class KNNClassifier:
def __init__(self, n_neighbors: int = 5, metric: str = "euclidean") -> None:
self.n_neighbors = n_neighbors
self.metric = metric
class FlexibleModel:
def __init__(self, alpha: float = 1.0, *args: Any, **kwargs: Any) -> None:
self.alpha = alpha
self.extra = kwargs
# TODO: def param_names(cls: type) -> list[str]
# TODO: def get_params(obj: object) -> dict[str, Any]
# TODO: print param_names and get_params for KNNClassifier(n_neighbors=3) and
# FlexibleModel(0.1, tol=1e-4)
Hint 1

inspect.signature(cls.__init__).parameters maps each name to a Parameter object with a .kind.

Hint 2

Skip a parameter when its name is "self" or its kind is p.VAR_POSITIONAL or p.VAR_KEYWORD. Read the values with getattr(obj, name).

Solution
class KNNClassifier:
def __init__(self, n_neighbors: int = 5, metric: str = "euclidean") -> None:
self.n_neighbors = n_neighbors
self.metric = metric
class FlexibleModel:
def __init__(self, alpha: float = 1.0, *args: Any, **kwargs: Any) -> None:
self.alpha = alpha
self.extra = kwargs
def param_names(cls: type) -> list[str]:
params = inspect.signature(cls.__init__).parameters.values()
skip = (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD)
return [p.name for p in params if p.name != "self" and p.kind not in skip]
def get_params(obj: object) -> dict[str, Any]:
return {name: getattr(obj, name) for name in param_names(type(obj))}
for obj in (KNNClassifier(n_neighbors=3), FlexibleModel(0.1, tol=1e-4)):
print(type(obj).__name__, param_names(type(obj)), get_params(obj))
assert get_params(FlexibleModel()) == {"alpha": 1.0}
assert param_names(KNNClassifier) == ["n_neighbors", "metric"]
Output
KNNClassifier ['n_neighbors', 'metric'] {'n_neighbors': 3, 'metric': 'euclidean'}
FlexibleModel ['alpha'] {'alpha': 0.1}

How it works:

  1. inspect.signature() returns the parameters in the order they are written.
  2. The filter drops self and the two catch-all parameters.
  3. FlexibleModel received tol=1e-4, but get_params() cannot see it: it has no name in the signature. This is why scikit-learn forbids **kwargs in an estimator’s __init__.

M19-C02 · A small grid search with set_params

Section titled “M19-C02 · A small grid search with set_params”
Core

ThresholdClassifier predicts churn (1) when one feature is at or below a threshold. Inherit from the setup’s ClassifierMixin and BaseEstimator, so that the class gets score() and set_params(). Then use one object and set_params() to try every combination of feature in (0, 1) and threshold in (3.0, 6.0, 9.0) on X_cust, y_cust. Print each accuracy and the best combination.

Expected output
feature=0 threshold=3.0 accuracy=0.90
feature=0 threshold=6.0 accuracy=0.80
feature=0 threshold=9.0 accuracy=0.80
feature=1 threshold=3.0 accuracy=0.65
feature=1 threshold=6.0 accuracy=0.50
feature=1 threshold=9.0 accuracy=0.35
best: {'feature': 0, 'threshold': 3.0} 0.90
Starter
class ThresholdClassifier: # TODO: add the mixin and the base class
def __init__(self, feature: int = 1, threshold: float = 3.0) -> None:
self.feature = feature
self.threshold = threshold
def fit(self, X: Rows, y: list[int]) -> Self:
return self # a fixed rule learns nothing
def predict(self, X: Rows) -> list[int]:
return [int(row[self.feature] <= self.threshold) for row in X]
model = ThresholdClassifier()
# TODO: loop over feature and threshold, call set_params(), print the score
# TODO: print the best combination
Hint 1

class ThresholdClassifier(ClassifierMixin, BaseEstimator): gives the class score(), get_params() and set_params().

Hint 2

model.set_params(feature=f, threshold=t).score(X_cust, y_cust) works in one line, because set_params() returns self. Keep the best (score, params) pair; max() over a list of pairs works too.

Solution
class ThresholdClassifier(ClassifierMixin, BaseEstimator):
def __init__(self, feature: int = 1, threshold: float = 3.0) -> None:
self.feature = feature
self.threshold = threshold
def fit(self, X: Rows, y: list[int]) -> Self:
return self # a fixed rule learns nothing
def predict(self, X: Rows) -> list[int]:
return [int(row[self.feature] <= self.threshold) for row in X]
model = ThresholdClassifier()
results = []
for feature in (0, 1):
for threshold in (3.0, 6.0, 9.0):
model.set_params(feature=feature, threshold=threshold)
acc = model.score(X_cust, y_cust)
results.append((acc, model.get_params()))
print(f"feature={feature} threshold={threshold:<4} accuracy={acc:.2f}")
best_acc, best_params = max(results, key=lambda pair: pair[0])
print("best:", best_params, f"{best_acc:.2f}")
assert best_params == {"feature": 0, "threshold": 3.0}
assert len(results) == 6
Output
feature=0 threshold=3.0 accuracy=0.90
feature=0 threshold=6.0 accuracy=0.80
feature=0 threshold=9.0 accuracy=0.80
feature=1 threshold=3.0 accuracy=0.65
feature=1 threshold=6.0 accuracy=0.50
feature=1 threshold=9.0 accuracy=0.35
best: {'feature': 0, 'threshold': 3.0} 0.90

How it works:

  1. The mixin supplies score(); it calls the class’s own predict().
  2. set_params() changes the object in place. It also returns the object, so model.set_params(...).score(X, y) works as one chained call.
  3. get_params() returns a new dict each time, so each stored result keeps its own values.
  4. max() with a key returns the first pair with the highest accuracy. The best rule, “tenure of 3 months or less”, scores 0.90, against the 0.80 that “nobody churns” gets (exercise C04). On 20 customers, that is two more correct answers: too few to choose a rule with confidence.

Alternative: itertools.product((0, 1), (3.0, 6.0, 9.0)) builds the combinations in one loop. A real grid search would also refit and score on held-out data for each combination.

M19-C03 · A MinMaxScaler with TransformerMixin

Section titled “M19-C03 · A MinMaxScaler with TransformerMixin”
Core

Write MinMaxScaler(TransformerMixin, BaseEstimator) with fit() (learns data_min_ and data_max_ per column) and transform() (maps each column to the range 0 to 1). A constant column must not divide by zero: use a range of 1 for it. Call fit_transform() on the first four customers and print the rounded rows, data_min_, data_max_ and get_params().

Expected output
[[1.0, 1.0], [0.889, 0.0], [0.333, 0.133], [0.0, 0.0]]
[45.0, 2.0] [72.0, 17.0] {'clip': False}
Starter
class MinMaxScaler(TransformerMixin, BaseEstimator):
def __init__(self, clip: bool = False) -> None:
self.clip = clip
def fit(self, X: Rows, y: list[float] | None = None) -> Self:
# TODO: data_min_ and data_max_ per column
return self
def transform(self, X: Rows) -> Rows:
# TODO: (v - min) / (max - min); clip to [0, 1] when self.clip
...
# TODO: fit_transform X_cust[:4], print rounded rows, data_min_, data_max_, params
Hint 1

columns = list(zip(*X)) turns rows into columns. min() and max() of each column give the two lists.

Hint 2

Compute span = (hi - lo) or 1.0 for each column. 0.0 or 1.0 is 1.0.

Solution
class MinMaxScaler(TransformerMixin, BaseEstimator):
def __init__(self, clip: bool = False) -> None:
self.clip = clip
def fit(self, X: Rows, y: list[float] | None = None) -> Self:
columns = list(zip(*X, strict=True))
self.data_min_ = [min(col) for col in columns]
self.data_max_ = [max(col) for col in columns]
return self
def transform(self, X: Rows) -> Rows:
out = []
for row in X:
new_row = []
for v, lo, hi in zip(row, self.data_min_, self.data_max_, strict=True):
scaled = (v - lo) / ((hi - lo) or 1.0)
if self.clip:
scaled = min(max(scaled, 0.0), 1.0)
new_row.append(scaled)
out.append(new_row)
return out
scaler = MinMaxScaler()
rows = scaler.fit_transform(X_cust[:4])
print([[round(v, 3) for v in row] for row in rows])
print(scaler.data_min_, scaler.data_max_, scaler.get_params())
assert rows[0] == [1.0, 1.0] and rows[3] == [0.0, 0.0]
assert MinMaxScaler(clip=True).fit(X_cust[:4]).transform([[90.0, -5.0]]) == [[1.0, 0.0]]
Output
[[1.0, 1.0], [0.889, 0.0], [0.333, 0.133], [0.0, 0.0]]
[45.0, 2.0] [72.0, 17.0] {'clip': False}

How it works:

  1. The class writes only fit() and transform(). fit_transform() comes from the mixin and get_params() from the base.
  2. The learned attributes end with _, as the convention asks, and clip is stored unchanged.
  3. With clip=True, values outside the training range are capped, which the last assert checks.
Core

Write MajorityClassifier(ClassifierMixin, BaseEstimator). fit() stores the most common label in majority_ and the share of each label in class_shares_ (a dict, labels sorted). predict() returns majority_ for every row. Fit it on y_cust, print class_shares_, the predictions for the first three customers and the accuracy. Then answer: what does this accuracy tell you about any churn model you test on these customers?

Expected output
shares: {0: 0.8, 1: 0.2}
first predictions: [0, 0, 0]
accuracy: 0.80
Starter
class MajorityClassifier(ClassifierMixin, BaseEstimator):
def fit(self, X: Rows, y: list[int]) -> Self:
# TODO: majority_ and class_shares_
return self
def predict(self, X: Rows) -> list[int]:
# TODO
...
# TODO: fit on X_cust, y_cust and print the three lines
Hint 1

Counter(y).most_common(1)[0][0] is the most common label.

Hint 2

{label: counts[label] / len(y) for label in sorted(counts)} builds the shares.

Solution
class MajorityClassifier(ClassifierMixin, BaseEstimator):
def fit(self, X: Rows, y: list[int]) -> Self:
counts = Counter(y)
self.majority_ = counts.most_common(1)[0][0]
self.class_shares_ = {label: counts[label] / len(y) for label in sorted(counts)}
return self
def predict(self, X: Rows) -> list[int]:
return [self.majority_ for _ in X]
baseline = MajorityClassifier().fit(X_cust, y_cust)
print("shares:", baseline.class_shares_)
print("first predictions:", baseline.predict(X_cust[:3]))
print(f"accuracy: {baseline.score(X_cust, y_cust):.2f}")
assert baseline.majority_ == 0
assert baseline.score(X_cust, y_cust) == baseline.class_shares_[0]
Output
shares: {0: 0.8, 1: 0.2}
first predictions: [0, 0, 0]
accuracy: 0.80

How it works:

  1. The model has no __init__, so get_params() returns {}: there is nothing to tune.
  2. It never predicts churn, yet it scores 0.80, because 80% of the customers stayed.
  3. Interpretation: 0.80 is the bar. A churn model that scores 0.80 here has learned nothing useful, and accuracy alone hides that it misses every churner. Module 36 adds recall and precision for this reason.

M19-C05 · Predict the output: a cooperative init chain

Section titled “M19-C05 · Predict the output: a cooperative init chain”
Core

Predict the output: every __init__ below prints a line before and after it calls super().__init__(). Write down the eight lines.

Starter
class Step:
def __init__(self) -> None:
print("Step")
class Impute(Step):
def __init__(self) -> None:
print("Impute start")
super().__init__()
print("Impute end")
class Scale(Step):
def __init__(self) -> None:
print("Scale start")
super().__init__()
print("Scale end")
class Prep(Impute, Scale):
def __init__(self) -> None:
print("Prep")
super().__init__()
prep = Prep()
print([cls.__name__ for cls in Prep.__mro__])

Acceptance criteria: write your prediction line by line, then run the code. Your prediction matches the Output in the solution.

Hint 1

Write the MRO of Prep first. Each super().__init__() jumps to the next class in that list.

Hint 2

The “end” lines run when the calls return, in the reverse order of the “start” lines.

Solution
class Step:
def __init__(self) -> None:
print("Step")
class Impute(Step):
def __init__(self) -> None:
print("Impute start")
super().__init__()
print("Impute end")
class Scale(Step):
def __init__(self) -> None:
print("Scale start")
super().__init__()
print("Scale end")
class Prep(Impute, Scale):
def __init__(self) -> None:
print("Prep")
super().__init__()
prep = Prep()
print([cls.__name__ for cls in Prep.__mro__])
assert Prep.__mro__.index(Scale) < Prep.__mro__.index(Step)
Output
Prep
Impute start
Scale start
Step
Scale end
Impute end
['Prep', 'Impute', 'Scale', 'Step', 'object']

How it works:

  1. The MRO is Prep, Impute, Scale, Step, object.
  2. super() in Impute reaches Scale, not Step, because the object is a Prep.
  3. Step prints once, in the middle. Then the calls return: Scale finishes before Impute.

M19-C06 · Fix the bug: a training step that runs twice

Section titled “M19-C06 · Fix the bug: a training step that runs twice”
Core

Fix the bug: TrackedModel.fit() should run each step once, but the counter shows that Model.fit() runs twice. The two middle classes and the child call their parents by name. Rewrite the four fit() methods with super() so that the output matches.

Expected output
TrackedModel.fit
Timed.fit
Logged.fit
Model.fit
Model.fit calls: 1
Starter
class Model:
def fit(self, X: Rows, y: list[float]) -> Self:
self.fit_calls_ = getattr(self, "fit_calls_", 0) + 1
print("Model.fit")
return self
class Timed(Model):
def fit(self, X: Rows, y: list[float]) -> Self:
print("Timed.fit")
return Model.fit(self, X, y)
class Logged(Model):
def fit(self, X: Rows, y: list[float]) -> Self:
print("Logged.fit")
return Model.fit(self, X, y)
class TrackedModel(Timed, Logged):
def fit(self, X: Rows, y: list[float]) -> Self:
Timed.fit(self, X, y)
Logged.fit(self, X, y)
return self
model = TrackedModel().fit(X_houses, y_houses)
print("Model.fit calls:", model.fit_calls_)
Hint 1

Write the MRO of TrackedModel. With super(), one call in TrackedModel is enough to visit every class.

Hint 2

Timed and Logged return super().fit(X, y). TrackedModel.fit can be removed, or it can return super().fit(X, y). Model is the root and does not call super().

Solution
class Model:
def fit(self, X: Rows, y: list[float]) -> Self:
self.fit_calls_ = getattr(self, "fit_calls_", 0) + 1
print("Model.fit")
return self
class Timed(Model):
def fit(self, X: Rows, y: list[float]) -> Self:
print("Timed.fit")
return super().fit(X, y)
class Logged(Model):
def fit(self, X: Rows, y: list[float]) -> Self:
print("Logged.fit")
return super().fit(X, y)
class TrackedModel(Timed, Logged):
def fit(self, X: Rows, y: list[float]) -> Self:
print("TrackedModel.fit")
return super().fit(X, y)
model = TrackedModel().fit(X_houses, y_houses)
print("Model.fit calls:", model.fit_calls_)
assert model.fit_calls_ == 1
Output
TrackedModel.fit
Timed.fit
Logged.fit
Model.fit
Model.fit calls: 1

How it works:

  1. In the buggy code, TrackedModel called both parents, and each parent called Model. Model.fit ran twice, so in a real model the training ran twice.
  2. With super(), the call follows the MRO TrackedModel, Timed, Logged, Model, and each class runs once.
  3. TrackedModel.fit is optional now. Without it, Timed.fit starts the same chain.

M19-C07 · Fix the bug: a mixin on the wrong side

Section titled “M19-C07 · Fix the bug: a mixin on the wrong side”
Core

Fix the bug: VerboseMixin should print a line every time a model is fitted, but LoudScaler().fit(...) prints nothing. Change one line so that the output matches. Then print the MRO names to show why.

Expected output
[verbose] fitting LoudScaler on 20 rows
[24.8, 8.8]
['LoudScaler', 'VerboseMixin', 'StandardScaler', 'TransformerMixin', 'BaseEstimator', 'object']
Starter
class VerboseMixin:
def fit(self, X: Rows, y: list[float] | None = None) -> Self:
print(f"[verbose] fitting {type(self).__name__} on {len(X)} rows")
return super().fit(X, y)
class StandardScaler(TransformerMixin, BaseEstimator):
def fit(self, X: Rows, y: list[float] | None = None) -> Self:
cols = list(zip(*X))
self.mean_ = [sum(c) / len(c) for c in cols]
return self
def transform(self, X: Rows) -> Rows:
return [[v - m for v, m in zip(row, self.mean_)] for row in X]
class LoudScaler(StandardScaler, VerboseMixin):
pass
scaler = LoudScaler().fit(X_cust)
print([round(m, 2) for m in scaler.mean_])
Hint 1

Print LoudScaler.__mro__. Which fit() does Python find first?

Hint 2

StandardScaler.fit does not call super(), so nothing after it in the MRO runs. Put the mixin first.

Solution
class VerboseMixin:
def fit(self, X: Rows, y: list[float] | None = None) -> Self:
print(f"[verbose] fitting {type(self).__name__} on {len(X)} rows")
return super().fit(X, y)
class StandardScaler(TransformerMixin, BaseEstimator):
def fit(self, X: Rows, y: list[float] | None = None) -> Self:
cols = list(zip(*X, strict=True))
self.mean_ = [sum(c) / len(c) for c in cols]
return self
def transform(self, X: Rows) -> Rows:
return [[v - m for v, m in zip(row, self.mean_, strict=True)] for row in X]
class LoudScaler(VerboseMixin, StandardScaler):
pass
scaler = LoudScaler().fit(X_cust)
print([round(m, 2) for m in scaler.mean_])
print([cls.__name__ for cls in LoudScaler.__mro__])
assert LoudScaler.__mro__[1] is VerboseMixin
Output
[verbose] fitting LoudScaler on 20 rows
[24.8, 8.8]
['LoudScaler', 'VerboseMixin', 'StandardScaler', 'TransformerMixin', 'BaseEstimator', 'object']

How it works:

  1. With class LoudScaler(StandardScaler, VerboseMixin), the MRO put StandardScaler before the mixin. Python found StandardScaler.fit first, and it never calls super(), so the mixin’s fit never ran.
  2. With the mixin on the left, VerboseMixin.fit runs first and its super().fit(X, y) reaches StandardScaler.fit.
  3. fit_transform() from TransformerMixin now prints the line too, because it calls self.fit().

M19-C08 · Refactor: from if/elif to polymorphism

Section titled “M19-C08 · Refactor: from if/elif to polymorphism”
Core

Refactor the procedural code below into classes. An abstract base PriceModel declares fit(X, y) and predict(X). ConstantPriceModel(PriceModel) predicts one learned constant through a hook _constant(y), and MeanModel and MedianModel override only the hook. PerSqftModel(PriceModel) learns a rate, so it implements its own fit() and predict(). Keep the output identical. Then add a fourth model, the 75th percentile price, without touching the loop.

Expected output
mean [568167, 568167]
median [515500, 515500]
per_sqft [411106, 423342]
p75 [744250, 744250]
Starter
def fit(kind: str, X: Rows, y: list[float]) -> dict[str, float]:
if kind == "mean":
return {"value": mean(y)}
elif kind == "median":
return {"value": median(y)}
elif kind == "per_sqft":
return {"rate": median(p / row[0] for row, p in zip(X, y))}
raise ValueError(kind)
def predict(kind: str, state: dict[str, float], X: Rows) -> list[float]:
if kind in ("mean", "median"):
return [state["value"] for _ in X]
elif kind == "per_sqft":
return [row[0] * state["rate"] for row in X]
raise ValueError(kind)
for kind in ("mean", "median", "per_sqft"):
state = fit(kind, X_houses[:6], y_houses[:6])
preds = predict(kind, state, X_houses[6:])
print(f"{kind:<9} {[round(p) for p in preds]}")
# TODO: rewrite as classes; add a 75th percentile model
Hint 1

Two kinds of model hide in the if branches: ones that learn a constant and one that learns a rate. Give each kind its own class under the shared base, and put the varying step of the constant models in a hook.

Hint 2

ConstantPriceModel.fit() stores self._constant(y) in value_, and predict() repeats it. statistics.quantiles(y, n=4) returns the three quartiles; the last one is the 75th percentile. The loop becomes for model in models: model.fit(...).predict(...).

Solution
from statistics import quantiles
class PriceModel(ABC):
"""The interface of every price model."""
name = "price"
@abstractmethod
def fit(self, X: Rows, y: list[float]) -> Self: ...
@abstractmethod
def predict(self, X: Rows) -> list[float]: ...
class ConstantPriceModel(PriceModel):
"""Predict one constant; subclasses choose it in the _constant() hook."""
def fit(self, X: Rows, y: list[float]) -> Self:
self.value_ = self._constant(y)
return self
def predict(self, X: Rows) -> list[float]:
return [self.value_ for _ in X]
@abstractmethod
def _constant(self, y: list[float]) -> float: ...
class MeanModel(ConstantPriceModel):
name = "mean"
def _constant(self, y: list[float]) -> float:
return mean(y)
class MedianModel(ConstantPriceModel):
name = "median"
def _constant(self, y: list[float]) -> float:
return median(y)
class PerSqftModel(PriceModel):
name = "per_sqft"
def fit(self, X: Rows, y: list[float]) -> Self:
self.rate_ = median(p / row[0] for row, p in zip(X, y, strict=True))
return self
def predict(self, X: Rows) -> list[float]:
return [row[0] * self.rate_ for row in X]
class UpperQuartileModel(ConstantPriceModel):
name = "p75"
def _constant(self, y: list[float]) -> float:
return quantiles(y, n=4)[2]
models = [MeanModel(), MedianModel(), PerSqftModel(), UpperQuartileModel()]
for model in models:
preds = model.fit(X_houses[:6], y_houses[:6]).predict(X_houses[6:])
print(f"{model.name:<9} {[round(p) for p in preds]}")
assert round(MedianModel().fit([], [1.0, 3.0, 10.0]).value_) == 3
assert all(isinstance(m, PriceModel) for m in models)
assert not isinstance(PerSqftModel(), ConstantPriceModel)
Output
mean [568167, 568167]
median [515500, 515500]
per_sqft [411106, 423342]
p75 [744250, 744250]

How it works:

  1. Each if branch became one class. The kind string became the class itself.
  2. The loop only calls fit() and predict(). Adding UpperQuartileModel needed a new class and one list item, but no change to existing code.
  3. PerSqftModel predicts from a rate, not a constant, so it is not a ConstantPriceModel. It is a PriceModel, so it inherits from that base and implements both methods itself. Each class sits under the parent whose meaning it really shares.
  4. _constant is abstract too, so ConstantPriceModel() itself cannot be instantiated: only its concrete subclasses can.

Alternative: for models that differ only in one function, a dict of functions ({"mean": mean, "median": median}) is simpler than classes. Classes win when each kind needs its own state and several methods.

M19-C09 · Refactor: from inheriting a list to holding one

Section titled “M19-C09 · Refactor: from inheriting a list to holding one”
Core

Refactor: LossHistory below inherits from list to store (epoch, loss) pairs. So it also inherits sort(), clear() and append() of any value, and the “best epoch” breaks after a sort. Rewrite it with composition: hold a private list, offer add(epoch, loss), best_epoch() and a read-only n_epochs property, and reject a loss that is not a number. The script must print the expected output.

Expected output
epochs: 6 best: 5
rejected: loss must be a number, got str
False False
Starter
class LossHistory(list):
def best_epoch(self) -> int:
return min(self, key=lambda pair: pair[1])[0]
history = LossHistory()
for epoch, loss in enumerate([0.92, 0.61, 0.48, 0.51, 0.47, 0.49], start=1):
history.append((epoch, loss))
history.append("oops") # accepted: a list takes anything
# TODO: rewrite LossHistory with composition
# TODO: print n_epochs and best_epoch(); show that add("oops") is rejected
Hint 1

__init__ creates self._pairs = []. add() checks isinstance(loss, (int, float)) and appends the pair.

Hint 2

A @property named n_epochs returns len(self._pairs). Catch the TypeError from add() in a try block to print the message.

Solution
class LossHistory:
"""Training losses by epoch. Holds a list instead of being one."""
def __init__(self) -> None:
self._pairs: list[tuple[int, float]] = []
def add(self, epoch: int, loss: float) -> None:
if not isinstance(loss, (int, float)):
raise TypeError(f"loss must be a number, got {type(loss).__name__}")
self._pairs.append((epoch, float(loss)))
@property
def n_epochs(self) -> int:
return len(self._pairs)
def best_epoch(self) -> int:
return min(self._pairs, key=lambda pair: pair[1])[0]
history = LossHistory()
for epoch, loss in enumerate([0.92, 0.61, 0.48, 0.51, 0.47, 0.49], start=1):
history.add(epoch, loss)
print("epochs:", history.n_epochs, "best:", history.best_epoch())
try:
history.add(7, "oops")
except TypeError as err:
print("rejected:", err)
print(hasattr(history, "sort"), hasattr(history, "clear"))
assert history.best_epoch() == 5 and history.n_epochs == 6
Output
epochs: 6 best: 5
rejected: loss must be a number, got str
False False

How it works:

  1. The new class exposes three operations that make sense for a loss history, and nothing else. sort() and clear() no longer exist.
  2. add() validates every value, which a subclass of list cannot do for append(), extend(), insert(), += and slicing all at once.
  3. The internal list is a detail, marked private with _. Module 20 shows how to add len(history) and iteration with dunder methods.

M19-C10 · Choose and justify: inheritance or composition

Section titled “M19-C10 · Choose and justify: inheritance or composition”
Core

Choose and justify: for each design question, choose inheritance or composition and give one reason. Then implement the first one and print the predictions.

  1. A nearest-neighbor model must work with a Euclidean or a Manhattan distance, chosen by the user.
  2. GradientBoostingRegressor and RandomForestRegressor should both get score() as R².
  3. A report generator should write either Markdown or HTML.

For question 1, write NearestNeighbor with __init__(self, distance), fit(X, y) and predict(X) (1 neighbor). Fit it on the four training customers in the starter, predict for [[10.0, 3.0]], and print the result with math.dist and with a Manhattan function.

Expected output
dist [1]
manhattan [0]
Starter
def manhattan(a: list[float], b: list[float]) -> float:
return sum(abs(x - z) for x, z in zip(a, b))
X_small = [[13.0, 6.0], [15.0, 3.0], [40.0, 20.0], [2.0, 15.0]]
y_small = [1, 0, 0, 1]
# TODO: write your three choices as comments
# TODO: class NearestNeighbor with a distance part
# TODO: print the prediction for [[10.0, 3.0]] with math.dist and with manhattan
Hint 1

Ask “is-a or has-a?” for each question. A model is not a kind of distance; it uses one.

Hint 2

min(range(len(self.X_)), key=lambda i: self.distance(row, self.X_[i])) is the index of the nearest training row.

Solution
# 1. Composition: the model has-a distance, and the user swaps it at run time.
# 2. Inheritance (a mixin): both models are regressors; RegressorMixin adds score().
# 3. Composition: the generator has-a formatter; Markdown and HTML are swappable.
from collections.abc import Callable
def manhattan(a: list[float], b: list[float]) -> float:
return sum(abs(x - z) for x, z in zip(a, b, strict=True))
class NearestNeighbor(ClassifierMixin, BaseEstimator):
def __init__(self, distance: Callable[[list[float], list[float]], float]) -> None:
self.distance = distance # has-a distance function
def fit(self, X: Rows, y: list[int]) -> Self:
self.X_, self.y_ = X, y
return self
def predict(self, X: Rows) -> list[int]:
out = []
for row in X:
i = min(range(len(self.X_)), key=lambda j: self.distance(row, self.X_[j]))
out.append(self.y_[i])
return out
X_small = [[13.0, 6.0], [15.0, 3.0], [40.0, 20.0], [2.0, 15.0]]
y_small = [1, 0, 0, 1]
for distance in (math.dist, manhattan):
model = NearestNeighbor(distance).fit(X_small, y_small)
print(f"{distance.__name__:<9} {model.predict([[10.0, 3.0]])}")
assert NearestNeighbor(manhattan).fit(X_small, y_small).predict([[10.0, 3.0]]) == [0]
Output
dist [1]
manhattan [0]

How it works:

  1. From [10, 3], the row [13, 6] is 3 away on each feature: a straight-line distance of 4.24 and a Manhattan distance of 6. The row [15, 3] is 5 away on one feature: 5 by both measures. So the Euclidean model picks [13, 6] (label 1), and the Manhattan model picks [15, 3] (label 0).
  2. The model class did not change between the two runs. Only the part changed. With inheritance you would need EuclideanNearestNeighbor and ManhattanNearestNeighbor, and one more class per distance.
  3. The distance is an __init__ argument, so get_params() reports it, and set_params(distance=...) swaps it.

Alternative: module 21 turns the distance choice into an Enum, and module 22 names this design the strategy pattern.

M19-C11 · Duck typing with EAFP, done safely

Section titled “M19-C11 · Duck typing with EAFP, done safely”
Core

Write score_all(models, X, y) that returns a dict from class name to score. A model without a score() method gets the text "no score()". Use EAFP, but put only the attribute lookup inside try, so that a real bug inside score() still raises. Test it with the three models in the starter; the last one has a bug.

Expected output
{'MeanModel': 0.0, 'PlainRule': 'no score()'}
real bug surfaced: 'BuggyModel' object has no attribute 'rate_'
Starter
class MeanModel(RegressorMixin, BaseEstimator):
def fit(self, X: Rows, y: list[float]) -> Self:
self.mean_ = mean(y)
return self
def predict(self, X: Rows) -> list[float]:
return [self.mean_ for _ in X]
class PlainRule:
def predict(self, X: Rows) -> list[float]:
return [400_000.0 for _ in X]
class BuggyModel(RegressorMixin, BaseEstimator):
def predict(self, X: Rows) -> list[float]:
return [self.rate_ * row[0] for row in X] # never fitted: no rate_
# TODO: def score_all(models, X, y) -> dict[str, float | str]
# TODO: print score_all for MeanModel().fit(...) and PlainRule()
# TODO: show that BuggyModel's AttributeError is not hidden
Hint 1
try:
method = model.score
except AttributeError:
...
else:
result = method(X, y)
Hint 2

The else block runs only when the try block raised nothing, and errors raised in else are not caught by the except above.

Solution
class MeanModel(RegressorMixin, BaseEstimator):
def fit(self, X: Rows, y: list[float]) -> Self:
self.mean_ = mean(y)
return self
def predict(self, X: Rows) -> list[float]:
return [self.mean_ for _ in X]
class PlainRule:
def predict(self, X: Rows) -> list[float]:
return [400_000.0 for _ in X]
class BuggyModel(RegressorMixin, BaseEstimator):
def predict(self, X: Rows) -> list[float]:
return [self.rate_ * row[0] for row in X] # never fitted: no rate_
def score_all(models: list[Any], X: Rows, y: list[float]) -> dict[str, float | str]:
results: dict[str, float | str] = {}
for model in models:
name = type(model).__name__
try:
method = model.score # only the lookup is guarded
except AttributeError:
results[name] = "no score()"
else:
results[name] = round(method(X, y), 3)
return results
models = [MeanModel().fit(X_houses, y_houses), PlainRule()]
print(score_all(models, X_houses, y_houses))
try:
score_all([BuggyModel()], X_houses, y_houses)
except AttributeError as err:
print("real bug surfaced:", err)
assert score_all([PlainRule()], X_houses, y_houses) == {"PlainRule": "no score()"}
Output
{'MeanModel': 0.0, 'PlainRule': 'no score()'}
real bug surfaced: 'BuggyModel' object has no attribute 'rate_'

How it works:

  1. The mean model scores 0.0: R² compares with the mean, and it predicts the mean.
  2. PlainRule has no score, so the lookup fails and the dict records it.
  3. BuggyModel has score(), so the lookup succeeds. The AttributeError from the missing rate_ happens in the else block and is not swallowed.

M19-C12 · An ABC with a concrete comparison method

Section titled “M19-C12 · An ABC with a concrete comparison method”
Core

Write an ABC Metric with an abstract method compute(y_true, y_pred), a class attribute greater_is_better and a concrete method better(a, b) that returns True when score a is better than score b. Write MAEMetric (lower is better) and AccuracyMetric (higher is better). For each metric, compare two sets of predictions and print which one wins.

Expected output
MAEMetric a=13.33 b=20.00 winner=model_a
AccuracyMetric a=0.75 b=0.50 winner=model_a
Starter
class Metric(ABC):
greater_is_better = True
# TODO: abstract compute(); concrete better(a, b)
# TODO: MAEMetric and AccuracyMetric
y_price = [400.0, 250.0, 310.0]
price_preds = {"model_a": [380.0, 260.0, 300.0], "model_b": [420.0, 230.0, 330.0]}
y_churn = [0, 1, 0, 1]
churn_preds = {"model_a": [0, 1, 1, 1], "model_b": [0, 0, 0, 0]}
# TODO: for each metric, print both scores and the winner
Hint 1

better() uses self.greater_is_better: return a > b when it is True, else a < b. Each subclass overrides the class attribute.

Hint 2

Score both models, then winner = "model_a" if metric.better(score_a, score_b) else "model_b".

Solution
class Metric(ABC):
greater_is_better = True
@abstractmethod
def compute(self, y_true: list[Any], y_pred: list[Any]) -> float: ...
def better(self, a: float, b: float) -> bool:
return a > b if self.greater_is_better else a < b
class MAEMetric(Metric):
greater_is_better = False
def compute(self, y_true: list[Any], y_pred: list[Any]) -> float:
return mae(y_true, y_pred)
class AccuracyMetric(Metric):
def compute(self, y_true: list[Any], y_pred: list[Any]) -> float:
return accuracy_score(y_true, y_pred)
y_price = [400.0, 250.0, 310.0]
price_preds = {"model_a": [380.0, 260.0, 300.0], "model_b": [420.0, 230.0, 330.0]}
y_churn = [0, 1, 0, 1]
churn_preds = {"model_a": [0, 1, 1, 1], "model_b": [0, 0, 0, 0]}
tasks = [(MAEMetric(), y_price, price_preds), (AccuracyMetric(), y_churn, churn_preds)]
for metric, y_true, preds in tasks:
a = metric.compute(y_true, preds["model_a"])
b = metric.compute(y_true, preds["model_b"])
winner = "model_a" if metric.better(a, b) else "model_b"
print(f"{type(metric).__name__:<14} a={a:.2f} b={b:.2f} winner={winner}")
assert MAEMetric().better(1.0, 2.0) and AccuracyMetric().better(0.9, 0.5)
Output
MAEMetric a=13.33 b=20.00 winner=model_a
AccuracyMetric a=0.75 b=0.50 winner=model_a

How it works:

  1. The ABC holds the shared rule (better()), and each subclass supplies the part that differs (compute() and the direction).
  2. The comparison loop is polymorphic: it never checks which metric it has.
  3. scikit-learn’s scorers carry the same idea: for errors such as MAE, a scorer returns the negative value (neg_mean_absolute_error), so that “greater is better” holds for every scorer.

M19-C13 · Interpret: what does a runtime Protocol check prove?

Section titled “M19-C13 · Interpret: what does a runtime Protocol check prove?”
Core

Interpret a result: the code in the starter checks three objects against a runtime protocol and then calls summarize() on each one that passes. Run it, then explain in two sentences why the check passed for an object that crashes, and what would have found the problem earlier. Print the expected output.

Expected output
GoodModel check=True 8 predictions, first 400,000
OneRowModel check=True TypeError: object of type 'float' has no len()
Placeholder check=True TypeError: 'int' object is not callable
Starter
@runtime_checkable
class SupportsPredict(Protocol):
def predict(self, X: Rows) -> list[float]: ...
class GoodModel:
def predict(self, X: Rows) -> list[float]:
return [400_000.0 for _ in X]
class OneRowModel:
def predict(self, row: list[float]) -> float:
return 400_000.0
class Placeholder:
predict = 0
def summarize(model: SupportsPredict) -> str:
preds = model.predict(X_houses)
return f"{len(preds)} predictions, first {preds[0]:,.0f}"
# TODO: for each object, print the isinstance() result and summarize() or the error
Hint 1

Wrap the summarize() call in try and print type(err).__name__ and the message when it fails.

Hint 2

Think about what isinstance() looks at for a protocol: names, signatures or return types?

Solution
@runtime_checkable
class SupportsPredict(Protocol):
def predict(self, X: Rows) -> list[float]: ...
class GoodModel:
def predict(self, X: Rows) -> list[float]:
return [400_000.0 for _ in X]
class OneRowModel:
def predict(self, row: list[float]) -> float:
return 400_000.0
class Placeholder:
predict = 0
def summarize(model: SupportsPredict) -> str:
preds = model.predict(X_houses)
return f"{len(preds)} predictions, first {preds[0]:,.0f}"
passed = []
for obj in (GoodModel(), OneRowModel(), Placeholder()):
ok = isinstance(obj, SupportsPredict)
passed.append(ok)
try:
result = summarize(obj)
except TypeError as err:
result = f"{type(err).__name__}: {err}"
print(f"{type(obj).__name__:<12} check={ok} {result}")
assert passed == [True, True, True]
Output
GoodModel check=True 8 predictions, first 400,000
OneRowModel check=True TypeError: object of type 'float' has no len()
Placeholder check=True TypeError: 'int' object is not callable

How it works:

  1. All three objects pass, because the runtime check only tests that an attribute named predict exists. It ignores the parameters, the return type and even whether the attribute is callable.
  2. OneRowModel.predict() returns one float, so len(preds) fails. Placeholder.predict is the integer 0, so the call fails.
  3. Interpretation: the runtime check is a name filter, not a proof. mypy would have rejected both calls to summarize() before the script ran, because it compares the full signature with the protocol.

M19-C14 · An exception hierarchy with multiple inheritance

Section titled “M19-C14 · An exception hierarchy with multiple inheritance”
Core

Build the error types of minilearn: a base MinilearnError(Exception), a NotFittedError that is also an AttributeError, and a ShapeError that is also a ValueError. Write check_is_fitted(est): it raises NotFittedError when the object has no attribute whose name ends with _ (and does not start with __). Show that one except MinilearnError catches both errors, and that old code with except AttributeError still catches NotFittedError.

Expected output
NotFittedError: This MeanModel is not fitted yet.
ShapeError: X has 8 rows, y has 3
old code catching AttributeError still works
['NotFittedError', 'MinilearnError', 'AttributeError', 'Exception', 'BaseException', 'object']
Starter
# TODO: MinilearnError, NotFittedError, ShapeError
# TODO: def check_is_fitted(est: object) -> None
class MeanModel:
def fit(self, X: Rows, y: list[float]) -> Self:
if len(X) != len(y):
pass # TODO: raise ShapeError
self.mean_ = mean(y)
return self
def predict(self, X: Rows) -> list[float]:
check_is_fitted(self)
return [self.mean_ for _ in X]
# TODO: trigger both errors and catch them as described
Hint 1

class NotFittedError(MinilearnError, AttributeError): pass. The order lists the library’s own base first.

Hint 2

[k for k in vars(est) if k.endswith("_") and not k.startswith("__")] lists the learned attributes.

Solution
class MinilearnError(Exception):
"""Base class for every minilearn error."""
class NotFittedError(MinilearnError, AttributeError):
"""predict() or transform() was called before fit()."""
class ShapeError(MinilearnError, ValueError):
"""X and y do not have the same number of rows."""
def check_is_fitted(est: object) -> None:
learned = [k for k in vars(est) if k.endswith("_") and not k.startswith("__")]
if not learned:
raise NotFittedError(f"This {type(est).__name__} is not fitted yet.")
class MeanModel:
def fit(self, X: Rows, y: list[float]) -> Self:
if len(X) != len(y):
raise ShapeError(f"X has {len(X)} rows, y has {len(y)}")
self.mean_ = mean(y)
return self
def predict(self, X: Rows) -> list[float]:
check_is_fitted(self)
return [self.mean_ for _ in X]
for action in (lambda: MeanModel().predict(X_houses),
lambda: MeanModel().fit(X_houses, y_houses[:3])):
try:
action()
except MinilearnError as err:
print(f"{type(err).__name__}: {err}")
try:
MeanModel().predict(X_houses)
except AttributeError:
print("old code catching AttributeError still works")
print([cls.__name__ for cls in NotFittedError.__mro__])
assert issubclass(ShapeError, ValueError) and not issubclass(ShapeError, AttributeError)
Output
NotFittedError: This MeanModel is not fitted yet.
ShapeError: X has 8 rows, y has 3
old code catching AttributeError still works
['NotFittedError', 'MinilearnError', 'AttributeError', 'Exception', 'BaseException', 'object']

How it works:

  1. Each error has two parents: the library’s base and a built-in type. Callers can catch by library (MinilearnError) or by meaning (AttributeError, ValueError).
  2. scikit-learn’s own NotFittedError inherits from ValueError and AttributeError for the same reason: code written before the class existed keeps working.
  3. The MRO shows the order in which except clauses would match: any class in the list catches the error.

M19-X01 · Nested parameters with double underscores

Section titled “M19-X01 · Nested parameters with double underscores”
Challenge

scikit-learn lets you reach the settings of a part through its owner: model.set_params(scaler__with_mean=False). Write ScaledRegressor(RegressorMixin, BaseEstimator) with the parts scaler and regressor. Override get_params(deep=True) so that it also returns each part’s parameters as part__name, and override set_params() so that a name with __ is passed on to the part. Use the two small part classes in the starter. Print the deep parameters one per line, change two nested values in one call, print the nested values again, and print the shallow parameters.

Expected output
scaler Centerer
regressor Line
scaler__with_mean True
regressor__fit_intercept True
after: {'scaler__with_mean': False, 'regressor__fit_intercept': False}
shallow: {'scaler': 'Centerer', 'regressor': 'Line'}
Starter
class Centerer(TransformerMixin, BaseEstimator):
def __init__(self, with_mean: bool = True) -> None:
self.with_mean = with_mean
def fit(self, X: Rows, y: list[float] | None = None) -> Self:
self.mean_ = mean(row[0] for row in X) if self.with_mean else 0.0
return self
def transform(self, X: Rows) -> Rows:
return [[row[0] - self.mean_] for row in X]
class Line(RegressorMixin, BaseEstimator):
def __init__(self, fit_intercept: bool = True) -> None:
self.fit_intercept = fit_intercept
# fit() and predict() are not needed for this exercise
class ScaledRegressor(RegressorMixin, BaseEstimator):
def __init__(self, scaler: Any, regressor: Any) -> None:
self.scaler = scaler
self.regressor = regressor
# TODO: get_params(self, deep=True) with part__name keys
# TODO: set_params(self, **params) that routes part__name to the part
Hint 1

super().get_params() returns {"scaler": ..., "regressor": ...}. For each value that has a get_params method, add f"{name}__{key}" entries.

Hint 2

name.partition("__") splits "scaler__with_mean" into ("scaler", "__", "with_mean"). Collect the nested values per part, call part.set_params(**values), and pass the plain names to super().set_params(...).

Solution
class Centerer(TransformerMixin, BaseEstimator):
def __init__(self, with_mean: bool = True) -> None:
self.with_mean = with_mean
def fit(self, X: Rows, y: list[float] | None = None) -> Self:
self.mean_ = mean(row[0] for row in X) if self.with_mean else 0.0
return self
def transform(self, X: Rows) -> Rows:
return [[row[0] - self.mean_] for row in X]
class Line(RegressorMixin, BaseEstimator):
def __init__(self, fit_intercept: bool = True) -> None:
self.fit_intercept = fit_intercept
class ScaledRegressor(RegressorMixin, BaseEstimator):
def __init__(self, scaler: Any, regressor: Any) -> None:
self.scaler = scaler
self.regressor = regressor
def get_params(self, deep: bool = True) -> dict[str, Any]:
params = super().get_params()
if deep:
for name, part in list(params.items()):
if hasattr(part, "get_params"):
for key, value in part.get_params().items():
params[f"{name}__{key}"] = value
return params
def set_params(self, **params: Any) -> Self:
nested: dict[str, dict[str, Any]] = {}
plain: dict[str, Any] = {}
for name, value in params.items():
part, sep, key = name.partition("__")
if sep:
nested.setdefault(part, {})[key] = value
else:
plain[name] = value
super().set_params(**plain)
for part, values in nested.items():
getattr(self, part).set_params(**values)
return self
def show(params: dict[str, Any]) -> dict[str, Any]:
"""Show a part by its class name, so that no memory address is printed."""
return {
k: type(v).__name__ if hasattr(v, "get_params") else v
for k, v in params.items()
}
model = ScaledRegressor(Centerer(), Line())
for key, value in show(model.get_params()).items():
print(f"{key:<24} {value}")
model.set_params(scaler__with_mean=False, regressor__fit_intercept=False)
print("after:", {k: v for k, v in model.get_params().items() if "__" in k})
print("shallow:", show(model.get_params(deep=False)))
assert model.scaler.with_mean is False and model.regressor.fit_intercept is False
Output
scaler Centerer
regressor Line
scaler__with_mean True
regressor__fit_intercept True
after: {'scaler__with_mean': False, 'regressor__fit_intercept': False}
shallow: {'scaler': 'Centerer', 'regressor': 'Line'}

How it works:

  1. get_params() calls the inherited version with super() and extends its result: the owner’s two parts, then each part’s parameters with a prefix.
  2. set_params() sorts the names into plain ones (for the owner) and nested ones (for the parts). It passes plain names to the base class, which still validates them, and nested names to each part’s own set_params(), which validates those.
  3. show() prints a part by its class name, so the output holds no memory addresses.
  4. This is how scikit-learn’s grid search tunes a step deep inside a pipeline, for example {"regressor__alpha": [0.1, 1.0]}.

M19-X02 · A plugin registry with init_subclass

Section titled “M19-X02 · A plugin registry with init_subclass”
Challenge

Plugin systems let new code add features without editing the core. Python calls the special class method __init_subclass__ on a parent every time a subclass is created. Write an ABC Exporter that uses it to register each subclass under a format name given in the class statement: class CsvExporter(Exporter, fmt="csv"). Exporter has an abstract method export(rows) -> str and a class method create(fmt) that returns an instance of the registered class. Write CSV and JSON Lines exporters, export two customer records with each, and show the error for an unknown format.

Expected output
['csv', 'jsonl']
--- csv
customer_id,tenure_months,churned
C00001,72,0
C04751,1,1
--- jsonl
{"customer_id": "C00001", "tenure_months": 72, "churned": 0}
{"customer_id": "C04751", "tenure_months": 1, "churned": 1}
error: unknown format 'xml'; known: ['csv', 'jsonl']
Starter
import json
class Exporter(ABC):
registry: dict[str, type["Exporter"]] = {}
# TODO: __init_subclass__(cls, *, fmt: str, **kwargs) that registers cls
# TODO: abstract export(self, rows: list[dict[str, Any]]) -> str
# TODO: classmethod create(cls, fmt: str) -> "Exporter"
# TODO: CsvExporter(Exporter, fmt="csv") and JsonLinesExporter(Exporter, fmt="jsonl")
rows = [
{"customer_id": "C00001", "tenure_months": 72, "churned": 0},
{"customer_id": "C04751", "tenure_months": 1, "churned": 1},
]
Hint 1

__init_subclass__(cls, *, fmt, **kwargs) receives the keywords of the class statement. Store cls in the shared registry under fmt, and pass the rest of kwargs on with super().__init_subclass__(**kwargs).

Hint 2

create() looks up cls.registry[fmt] and calls it with no arguments. Raise a ValueError that lists sorted(cls.registry) when the format is unknown. csv.DictWriter can write into an io.StringIO.

Solution
import json
class Exporter(ABC):
registry: dict[str, type["Exporter"]] = {}
def __init_subclass__(cls, *, fmt: str, **kwargs: Any) -> None:
super().__init_subclass__(**kwargs)
Exporter.registry[fmt] = cls
@abstractmethod
def export(self, rows: list[dict[str, Any]]) -> str: ...
@classmethod
def create(cls, fmt: str) -> "Exporter":
try:
return cls.registry[fmt]()
except KeyError:
known = sorted(cls.registry)
raise ValueError(f"unknown format {fmt!r}; known: {known}") from None
class CsvExporter(Exporter, fmt="csv"):
def export(self, rows: list[dict[str, Any]]) -> str:
buffer = io.StringIO()
writer = csv.DictWriter(buffer, fieldnames=list(rows[0]), lineterminator="\n")
writer.writeheader()
writer.writerows(rows)
return buffer.getvalue()
class JsonLinesExporter(Exporter, fmt="jsonl"):
def export(self, rows: list[dict[str, Any]]) -> str:
return "".join(json.dumps(row) + "\n" for row in rows)
rows = [
{"customer_id": "C00001", "tenure_months": 72, "churned": 0},
{"customer_id": "C04751", "tenure_months": 1, "churned": 1},
]
print(sorted(Exporter.registry))
for fmt in ("csv", "jsonl"):
print(f"--- {fmt}")
print(Exporter.create(fmt).export(rows), end="")
try:
Exporter.create("xml")
except ValueError as err:
print("error:", err)
assert isinstance(Exporter.create("csv"), CsvExporter)
Output
['csv', 'jsonl']
--- csv
customer_id,tenure_months,churned
C00001,72,0
C04751,1,1
--- jsonl
{"customer_id": "C00001", "tenure_months": 72, "churned": 0}
{"customer_id": "C04751", "tenure_months": 1, "churned": 1}
error: unknown format 'xml'; known: ['csv', 'jsonl']

How it works:

  1. When Python runs class CsvExporter(Exporter, fmt="csv"), it passes the keyword fmt to Exporter.__init_subclass__. The method stores the new class in the shared registry. No code outside the subclass has to change.
  2. super().__init_subclass__(**kwargs) keeps the hook cooperative, so other base classes can use the same hook.
  3. create() is a factory: the caller names a format, and the registry finds the class. Module 22 builds the same factory for models: make_model("knn", n_neighbors=3).
  4. The ABC still protects the contract: an exporter without export() registers, but create() for it raises TypeError.

M19-X03 · Fix the bugs: an impossible MRO and a silent mixin

Section titled “M19-X03 · Fix the bugs: an impossible MRO and a silent mixin”
Challenge

Fix the bugs: the code below has two design bugs. First, Python refuses to create ImputingScaler with TypeError: Cannot create a consistent method resolution order (MRO) for bases Estimator, Transformer, ValidationMixin. Once that is fixed, the ValidationMixin check never runs, so a row with a missing value (None) slips through and crashes inside mean() with TypeError: can't convert type 'NoneType' to numerator/denominator. Fix both bugs so that the script prints the expected output.

Expected output
[[-2.0], [0.0], [2.0]]
caught: missing values in rows [1]
['ImputingScaler', 'ValidationMixin', 'Transformer', 'Estimator', 'object']
Starter
class Estimator:
def fit(self, X: list[list[float | None]], y: Any = None) -> Self:
return self
class Transformer(Estimator):
def fit_transform(self, X: list[list[float | None]]) -> Rows:
return self.fit(X).transform(X)
class ValidationMixin:
def fit(self, X: list[list[float | None]], y: Any = None) -> Self:
bad = [i for i, row in enumerate(X) if any(v is None for v in row)]
if bad:
raise ValueError(f"missing values in rows {bad}")
return super().fit(X, y)
class ImputingScaler(Estimator, Transformer, ValidationMixin):
def fit(self, X: list[list[float | None]], y: Any = None) -> Self:
self.mean_ = mean(row[0] for row in X)
return self
def transform(self, X: list[list[float | None]]) -> Rows:
return [[row[0] - self.mean_] for row in X]
clean = [[2.0], [4.0], [6.0]]
print(ImputingScaler().fit_transform(clean))
try:
ImputingScaler().fit_transform([[2.0], [None], [6.0]])
except ValueError as err:
print("caught:", err)
Hint 1

Bug 1: Transformer already inherits from Estimator. Listing Estimator first breaks rule 1 of C3. Drop Estimator from the list.

Hint 2

Bug 2: print the MRO after the first fix. For the mixin’s check to run before the class’s own work, the mixin must come first, and the chain must reach the class’s work only through super(). The class’s own fit() must therefore call super().fit(X, y) before it does its own work, or it must move its work into a hook that the root Estimator.fit calls.

Solution
class Estimator:
def fit(self, X: list[list[float | None]], y: Any = None) -> Self:
self._fit(X)
return self
def _fit(self, X: list[list[float | None]]) -> None:
pass
class Transformer(Estimator):
def fit_transform(self, X: list[list[float | None]]) -> Rows:
return self.fit(X).transform(X)
class ValidationMixin:
def fit(self, X: list[list[float | None]], y: Any = None) -> Self:
bad = [i for i, row in enumerate(X) if any(v is None for v in row)]
if bad:
raise ValueError(f"missing values in rows {bad}")
return super().fit(X, y)
class ImputingScaler(ValidationMixin, Transformer):
def _fit(self, X: list[list[float | None]]) -> None:
self.mean_ = mean(row[0] for row in X)
def transform(self, X: list[list[float | None]]) -> Rows:
return [[row[0] - self.mean_] for row in X]
clean = [[2.0], [4.0], [6.0]]
print(ImputingScaler().fit_transform(clean))
try:
ImputingScaler().fit_transform([[2.0], [None], [6.0]])
except ValueError as err:
print("caught:", err)
print([cls.__name__ for cls in ImputingScaler.__mro__])
assert ImputingScaler.__mro__[1] is ValidationMixin
Output
[[-2.0], [0.0], [2.0]]
caught: missing values in rows [1]
['ImputingScaler', 'ValidationMixin', 'Transformer', 'Estimator', 'object']

How it works:

  1. Bug 1: class ImputingScaler(Estimator, Transformer, ...) asked for Estimator before Transformer, but Transformer is a child of Estimator, which must come first. Listing only Transformer fixes it; Estimator comes along through it.
  2. Bug 2: the class defined fit() itself, so its own fit() was found first and the mixin’s never ran. Now the class overrides only the hook _fit(). The public fit() chain is ValidationMixin.fit then Estimator.fit, and Estimator.fit calls the hook.
  3. The MRO line proves the order: the check runs first, and learning happens last.

Alternative: keep fit() in ImputingScaler, list the mixin first, and make the class’s fit() call super().fit(X, y) before its own work. That works too, but every subclass author must remember the call. The hook design puts the chain in the base class once. Module 22 calls it the template method pattern.

Challenge

Write two mixins with keyword-only settings: VerboseMixin (verbose=False) and SeedMixin (random_state=None). Each one takes its own keyword, passes the rest on with **kwargs and calls super().__init__(). Write SGDTrainer(VerboseMixin, SeedMixin) with its own learning_rate=0.01. Show that every setting lands on the object, that the defaults work, and that a misspelled keyword fails with a clear TypeError from the end of the chain.

Expected output
{'random_state': 42, 'verbose': True, 'learning_rate': 0.1}
{'random_state': None, 'verbose': False, 'learning_rate': 0.01}
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
['SGDTrainer', 'VerboseMixin', 'SeedMixin', 'object']
Starter
class VerboseMixin:
# TODO: __init__(self, *, verbose=False, **kwargs)
...
class SeedMixin:
# TODO: __init__(self, *, random_state=None, **kwargs)
...
class SGDTrainer(VerboseMixin, SeedMixin):
# TODO: __init__(self, *, learning_rate=0.01, **kwargs)
...
# TODO: print vars() for a full call and for SGDTrainer()
# TODO: show the TypeError for SGDTrainer(random_sate=42)
Hint 1

Every __init__ in the chain has the form def __init__(self, *, own=default, **kwargs): super().__init__(**kwargs); self.own = own.

Hint 2

The last class in the MRO is object. If a keyword is left over, object.__init__() receives it and raises TypeError.

Solution
class VerboseMixin:
def __init__(self, *, verbose: bool = False, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.verbose = verbose
class SeedMixin:
def __init__(self, *, random_state: int | None = None, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.random_state = random_state
class SGDTrainer(VerboseMixin, SeedMixin):
def __init__(self, *, learning_rate: float = 0.01, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.learning_rate = learning_rate
full = SGDTrainer(learning_rate=0.1, verbose=True, random_state=42)
print(vars(full))
print(vars(SGDTrainer()))
try:
SGDTrainer(random_sate=42)
except TypeError as err:
print("TypeError:", err)
print([cls.__name__ for cls in SGDTrainer.__mro__])
assert full.random_state == 42 and SGDTrainer().verbose is False
Output
{'random_state': 42, 'verbose': True, 'learning_rate': 0.1}
{'random_state': None, 'verbose': False, 'learning_rate': 0.01}
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
['SGDTrainer', 'VerboseMixin', 'SeedMixin', 'object']

How it works:

  1. Each class removes its own keyword from kwargs by naming it as a parameter, and passes the rest along the MRO.
  2. object.__init__() accepts no extra arguments. A typo such as random_sate reaches it and raises a TypeError, so mistakes do not pass silently.
  3. Keyword-only parameters (after *) make the order of arguments irrelevant, which matters when classes are combined in different orders.
  4. This pattern suits frameworks. A scikit-learn estimator would instead list every parameter explicitly in its own __init__, so that get_params() can read them.

M19-X05 · Refactor: from procedural code to an estimator family

Section titled “M19-X05 · Refactor: from procedural code to an estimator family”
Challenge

Refactor procedural code into OOP: the starter fits and scores two price models on data/houses.csv with separate functions and dicts. Rewrite it as MeanRegressor and LinearRegression classes that inherit score() from the setup’s RegressorMixin and get_params() from BaseEstimator, then loop over the models. Train on the first 2,400 houses and test on the rest. The output must match.

Expected output
MeanRegressor {} R² -0.014 MAE 225,400
LinearRegression {'fit_intercept': True} R² 0.561 MAE 154,798
LinearRegression {'fit_intercept': False} R² 0.531 MAE 153,514
Starter
def load(path: str) -> tuple[Rows, list[float]]:
with open(path, encoding="utf-8", newline="") as f:
records = list(csv.DictReader(f))
return [[float(r["sqft"])] for r in records], [float(r["price"]) for r in records]
def fit_mean(y):
return {"mean": sum(y) / len(y)}
def predict_mean(state, X):
return [state["mean"] for _ in X]
def fit_line(X, y):
x = [row[0] for row in X]
mx, my = sum(x) / len(x), sum(y) / len(y)
slope = sum((a - mx) * (b - my) for a, b in zip(x, y)) / sum((a - mx) ** 2 for a in x)
return {"slope": slope, "intercept": my - slope * mx}
def predict_line(state, X):
return [state["intercept"] + state["slope"] * row[0] for row in X]
X, y = load("data/houses.csv")
X_tr, y_tr, X_te, y_te = X[:2400], y[:2400], X[2400:], y[2400:]
s1 = fit_mean(y_tr)
print("mean", round(r2_score(y_te, predict_mean(s1, X_te)), 3))
s2 = fit_line(X_tr, y_tr)
print("line", round(r2_score(y_te, predict_line(s2, X_te)), 3))
# TODO: classes MeanRegressor and LinearRegression, then one polymorphic loop that
# prints the class name, get_params(), R² and MAE
Hint 1

Each fit_* function becomes a fit() method that stores learned attributes with a trailing _ and returns self. Each predict_* becomes predict().

Hint 2

LinearRegression gets one hyperparameter, fit_intercept=True. When it is False, use 0 for both means. The loop prints model.score(X_te, y_te) and mae(y_te, model.predict(X_te)).

Solution
def load(path: str) -> tuple[Rows, list[float]]:
with open(path, encoding="utf-8", newline="") as f:
records = list(csv.DictReader(f))
return [[float(r["sqft"])] for r in records], [float(r["price"]) for r in records]
class MeanRegressor(RegressorMixin, BaseEstimator):
def fit(self, X: Rows, y: list[float]) -> Self:
self.mean_ = sum(y) / len(y)
return self
def predict(self, X: Rows) -> list[float]:
return [self.mean_ for _ in X]
class LinearRegression(RegressorMixin, BaseEstimator):
def __init__(self, fit_intercept: bool = True) -> None:
self.fit_intercept = fit_intercept
def fit(self, X: Rows, y: list[float]) -> Self:
x = [row[0] for row in X]
mx = sum(x) / len(x) if self.fit_intercept else 0.0
my = sum(y) / len(y) if self.fit_intercept else 0.0
sxy = sum((a - mx) * (b - my) for a, b in zip(x, y, strict=True))
self.coef_ = sxy / sum((a - mx) ** 2 for a in x)
self.intercept_ = my - self.coef_ * mx
return self
def predict(self, X: Rows) -> list[float]:
return [self.intercept_ + self.coef_ * row[0] for row in X]
X, y = load("data/houses.csv")
X_tr, y_tr, X_te, y_te = X[:2400], y[:2400], X[2400:], y[2400:]
models = [MeanRegressor(), LinearRegression(), LinearRegression(fit_intercept=False)]
for model in models:
model.fit(X_tr, y_tr)
r2 = model.score(X_te, y_te)
err = mae(y_te, model.predict(X_te))
print(f"{type(model).__name__:<16} {model.get_params()!s:<24} R² {r2:6.3f} "
f"MAE {err:9,.0f}")
assert round(models[1].score(X_te, y_te), 3) == 0.561
Output
MeanRegressor {} R² -0.014 MAE 225,400
LinearRegression {'fit_intercept': True} R² 0.561 MAE 154,798
LinearRegression {'fit_intercept': False} R² 0.531 MAE 153,514

How it works:

  1. Each pair of functions with a shared state dict became one class. The state became learned attributes on the object (mean_, coef_, intercept_).
  2. score() is written once, in RegressorMixin. The procedural version computed R² by hand twice.
  3. The loop treats the three models the same way. The second LinearRegression differs only in a hyperparameter, which get_params() shows.
  4. The line without an intercept is forced through the origin. Its R² falls from 0.561 to 0.531, while its MAE improves a little. R² squares the errors, so it punishes a few large misses more than the MAE does. Two metrics can rank two models differently.

M19-X06 · Clone and cross-validate any estimator

Section titled “M19-X06 · Clone and cross-validate any estimator”
Challenge

Write clone(est), which builds a new unfitted estimator from type(est) and est.get_params(), and cross_val_scores(est, X, y, k=5). The second function splits the rows into k contiguous folds. For each fold, it fits a fresh clone on the other folds and scores it on the fold, with the estimator’s own score(). Run it on the first 1,000 houses with a mean model and a one-feature line, and print the scores and their mean. Show that the original estimator stays unfitted.

Expected output
MeanRegressor -0.009 -0.005 -0.000 -0.000 -0.014 mean -0.006
LineRegressor 0.576 0.522 0.567 0.563 0.559 mean 0.557
Starter
class MeanRegressor(RegressorMixin, BaseEstimator):
def fit(self, X: Rows, y: list[float]) -> Self:
self.mean_ = mean(y)
return self
def predict(self, X: Rows) -> list[float]:
return [self.mean_ for _ in X]
class LineRegressor(RegressorMixin, BaseEstimator):
def fit(self, X: Rows, y: list[float]) -> Self:
x = [row[0] for row in X]
mx, my = mean(x), mean(y)
sxy = sum((a - mx) * (b - my) for a, b in zip(x, y))
self.coef_ = sxy / sum((a - mx) ** 2 for a in x)
self.intercept_ = my - self.coef_ * mx
return self
def predict(self, X: Rows) -> list[float]:
return [self.intercept_ + self.coef_ * row[0] for row in X]
with open("data/houses.csv", encoding="utf-8", newline="") as f:
records = list(csv.DictReader(f))[:1000]
X = [[float(r["sqft"])] for r in records]
y = [float(r["price"]) for r in records]
# TODO: clone() and cross_val_scores(); print the scores of both models
Hint 1

With size = len(X) // k, fold i holds the rows i * size to (i + 1) * size. The training rows are everything before and after it: X[:start] + X[stop:].

Hint 2

Inside the loop: model = clone(est).fit(X_train, y_train) and scores.append(model.score(X_fold, y_fold)). Never fit est itself.

Solution
class MeanRegressor(RegressorMixin, BaseEstimator):
def fit(self, X: Rows, y: list[float]) -> Self:
self.mean_ = mean(y)
return self
def predict(self, X: Rows) -> list[float]:
return [self.mean_ for _ in X]
class LineRegressor(RegressorMixin, BaseEstimator):
def fit(self, X: Rows, y: list[float]) -> Self:
x = [row[0] for row in X]
mx, my = mean(x), mean(y)
sxy = sum((a - mx) * (b - my) for a, b in zip(x, y, strict=True))
self.coef_ = sxy / sum((a - mx) ** 2 for a in x)
self.intercept_ = my - self.coef_ * mx
return self
def predict(self, X: Rows) -> list[float]:
return [self.intercept_ + self.coef_ * row[0] for row in X]
def clone(est: BaseEstimator) -> BaseEstimator:
return type(est)(**est.get_params())
def cross_val_scores(est: Any, X: Rows, y: list[float], k: int = 5) -> list[float]:
size = len(X) // k
scores = []
for i in range(k):
start, stop = i * size, (i + 1) * size
X_fit, y_fit = X[:start] + X[stop:], y[:start] + y[stop:]
model = clone(est).fit(X_fit, y_fit)
scores.append(model.score(X[start:stop], y[start:stop]))
return scores
with open("data/houses.csv", encoding="utf-8", newline="") as f:
records = list(csv.DictReader(f))[:1000]
X = [[float(r["sqft"])] for r in records]
y = [float(r["price"]) for r in records]
for est in (MeanRegressor(), LineRegressor()):
scores = cross_val_scores(est, X, y)
shown = " ".join(f"{s:6.3f}" for s in scores)
print(f"{type(est).__name__:<13} {shown} mean {mean(scores):.3f}")
assert not hasattr(est, "coef_") and not hasattr(est, "mean_")
Output
MeanRegressor -0.009 -0.005 -0.000 -0.000 -0.014 mean -0.006
LineRegressor 0.576 0.522 0.567 0.563 0.559 mean 0.557

How it works:

  1. clone() is polymorphic through type(est): it rebuilds any estimator class from its own parameters, without an if.
  2. Each fold gets a model that has never seen the fold. Fitting est itself in the loop would leak state from one fold to the next and leave the caller’s object changed.
  3. The mean model scores just below 0 on every fold, because each fold’s mean differs a little from the training mean. The line explains about half the variance.
  4. A score of -0.000 is a tiny negative number that rounds to zero at three decimals.
  5. houses.csv is sorted by sale date, so contiguous folds train on later sales to score earlier ones: they look ahead in time. That is fine for a demo of clone(), but time-ordered data needs forward-only splits, such as scikit-learn’s TimeSeriesSplit (modules 37 and 40).
  6. scikit-learn’s cross_val_score() (module 37) works the same way, with sklearn.base.clone().