Skip to content

21. Dataclasses, enums and slots — Mini-project

minilearn is the small scikit-learn-like library that you build in Part 3. After module 20, it can scale features and fit a KNNClassifier. It cannot yet evaluate a classifier honestly. There is no tool to split the data, the distance metric is fixed, and the only classification metric is accuracy.

In this project you add the module-21 increment:

  1. train_test_split(X, y, *, test_size, random_state, stratify) that returns a frozen dataclass Split. It unpacks like scikit-learn’s four-way result, and no code can edit it after the split.
  2. A Distance enum (EUCLIDEAN, MANHATTAN) that KNNClassifier accepts as its new distance parameter, also as the plain strings "euclidean" and "manhattan". KNNClassifier.kneighbors() returns Neighbor named tuples, so each prediction can be explained.
  3. confusion_matrix(y_true, y_pred) as a list of lists.
  4. classification_report(y_true, y_pred) that returns a dataclass of per-class precision, recall, F1 and support, prints like scikit-learn’s report and converts to JSON with asdict().

Then you use the new tools on the churn data and answer one question: does the KNN churn model really beat a model that always predicts “stays”?

data/customers.csv has 5,000 customers and 15 columns (data dictionary). The project uses two features, tenure_months (0–72) and logins_last_30d (0–60), and the target churned (1 = the customer left in the last month). The churn rate is 19.26%, so the classes are imbalanced, about 1 churner to 4 customers who stay.

The pure-Python KNN compares every test row with every training row. To keep a run near one second, the project uses every 4th customer: 1,250 rows, churn rate 18.1%. The rows of the file are ordered by signup date, so taking every 4th row keeps old and new customers in the sample. Taking the first 1,250 rows would keep only the oldest ones.

Your code must:

  1. Define Split as a frozen dataclass with the fields X_train, X_test, y_train, y_test (tuples) and test_indices (a tuple of row numbers, hidden from the repr). __post_init__ checks that each X part and its y part have the same length and that no part is empty.
  2. Give Split a short __repr__ such as Split(n_train=938, n_test=312), and an __iter__ so that X_train, X_test, y_train, y_test = split works.
  3. Write train_test_split(X, y, *, test_size=0.25, random_state=None, stratify=None). The arguments after * are keyword-only. It rejects mismatched lengths of X, y and stratify, and a test_size outside (0, 1), with a ValueError. The same random_state gives the same split. With stratify=y, each class keeps its share of the rows in both parts.
  4. Define Distance as a StrEnum with EUCLIDEAN and MANHATTAN, a method between(a, b) that uses match, and a __repr__ that returns Distance.EUCLIDEAN, so the repr of a model stays valid Python.
  5. Add the parameter distance: Distance | str = Distance.EUCLIDEAN to KNNClassifier. Store it unchanged in __init__ (the scikit-learn convention). In fit, convert it with Distance(...) into the learned attribute distance_, and raise a ValueError that lists the valid values for an unknown one.
  6. Add KNNClassifier.kneighbors(row), which returns the n_neighbors nearest training rows as Neighbor(index, distance, label) named tuples, sorted by distance, ties broken by the lower index. predict uses it.
  7. Write confusion_matrix(y_true, y_pred, labels=None): rows are the true classes, columns the predicted classes, as in scikit-learn.
  8. Define ClassMetrics(label, precision, recall, f1, support) as a frozen, slotted dataclass and ClassificationReport as a frozen dataclass with the per-class metrics, the accuracy and the macro and weighted averages. str(report) prints a table. A class that is never predicted gets precision 0.0, not a ZeroDivisionError.
  9. Choose the model without looking at the test part. Split the training part again, stratified, into a fit part and a validation part. Fit a scaler on the fit part, try k = 1, 5 and 15 with both distances, and keep the candidate with the best churn F1 on the validation part. Then refit the chosen model and a MajorityClassifier baseline on the whole training part (with a scaler fitted on the training part only), and score both on the test part once.
  10. End with assert checks.

Definitions you need for requirement 8. For one class, a true positive (TP) is a row of that class that the model predicted as that class:

  • Precision = TP / (rows predicted as the class). Of the customers flagged as churners, how many churned?
  • Recall = TP / (rows that really are the class). Of the churners, how many were flagged?
  • F1 = 2 × precision × recall / (precision + recall), the harmonic mean of the two.
  • Support = the number of rows that really are the class.
  • Macro average: the plain mean over the classes. Weighted average: the mean weighted by support.

Start from the minilearn code of modules 18 to 20. The block below is the base block of the module 20 project, copied unchanged, plus MajorityClassifier from the module 19 project. It leaves out Vector, Pipeline and module 20’s KNNClassifier: this project rewrites KNNClassifier, and its new Distance enum replaces the Vector distance. Open the block, copy it to the top of a file minilearn_21.py and add your code below it.

minilearn so far: metrics, base classes, StandardScaler, LinearRegression, Dataset and MajorityClassifier
minilearn_21.py (the start)
import csv
import inspect
import math
from collections import Counter
from collections.abc import Iterable, Iterator
from typing import Any, Self
# --- metrics.py (modules 18 and 19) ---------------------------------------
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
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 (module 19; __repr__ and __eq__ from the module 20 lesson) ----
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")
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
def __repr__(self) -> str:
args = ", ".join(f"{k}={v!r}" for k, v in self.get_params().items())
return f"{type(self).__name__}({args})"
def __eq__(self, other: object) -> bool:
if not isinstance(other, BaseEstimator):
return NotImplemented
same_type = type(self) is type(other)
return same_type and self.get_params() == other.get_params()
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 and linear_model.py (module 19) ----------------------
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_}"
)
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)]
# --- datasets.py (module 18; container methods from the module 20 lesson) ---
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
def __repr__(self) -> str:
return f"Dataset(n_samples={len(self)}, features={self.feature_names!r})"
def __len__(self) -> int:
return len(self.X)
def __getitem__(self, key: int | slice | str) -> Any:
if isinstance(key, int): # one sample: (features, target)
return self.X[key], self.y[key]
if isinstance(key, slice): # a smaller Dataset
return type(self)(self.X[key], self.y[key], self.feature_names)
if isinstance(key, str): # one feature column, by name
if key not in self.feature_names:
raise KeyError(key)
return self.column(key)
kind = type(key).__name__
raise TypeError(f"Dataset indices must be int, slice or str, not {kind}")
def __iter__(self) -> Iterator[tuple[list[float], float]]:
yield from zip(self.X, self.y, strict=True)
# --- MajorityClassifier (module 19 project) ---------------------------------
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]
  1. Write Split. A frozen dataclass with the four data fields and test_indices: tuple[int, ...] = field(default=(), repr=False). Add the checks to __post_init__. Write __repr__ yourself: @dataclass keeps a __repr__ that the class defines. Make __iter__ a generator that yields the four parts.

  2. Write train_test_split. Validate the inputs. Group the row numbers by class when stratify is given, otherwise use one group of all rows. Shuffle each group with one random.Random(random_state), put the first round(len(group) * test_size) rows of each group in the test part, and sort the test row numbers. Build tuples of tuples, so the frozen Split is immutable all the way down.

  3. Test the split. Check the sizes, the churn rate of both parts and that the same seed gives an equal Split. Try split.X_test = () and see FrozenInstanceError.

  4. Write Distance. Use StrEnum with auto(): the values become "euclidean" and "manhattan". Add between(a, b) with a match on self, and __repr__.

  5. Upgrade KNNClassifier. Add distance to __init__. In fit, keep the n_neighbors check of modules 19 and 20 and add the distance check: convert distance into distance_. Write kneighbors(row) with a Neighbor named tuple. Rewrite predict to vote over kneighbors.

  6. Write the metrics. confusion_matrix first. Then classification_report reads TP, the predicted count and the actual count of each class from the matrix: TP is on the diagonal, the predicted count is a column sum and the actual count is a row sum.

  7. Run the evaluation. Load the data with Dataset.from_csv, convert y to int, take every 4th row with customers[::4] and split with stratify=y. Split the training part again into fit and validation parts, choose the model on the validation part, refit it on the whole training part, and score it and the baseline on the test part once.

  8. Add the asserts and read the report: which number tells you how many churners the model finds?

A skeleton to start from, below the code of the block above:

minilearn_21.py (starter)
import json
import random
from collections.abc import Iterator, Sequence
from dataclasses import asdict, dataclass, field
from enum import StrEnum, auto
from typing import NamedTuple
Row = Sequence[float] # one row of features: a list or a tuple
@dataclass(frozen=True)
class Split:
X_train: tuple[tuple[float, ...], ...]
# TODO: X_test, y_train, y_test, test_indices
# TODO: __post_init__, __repr__, __iter__
def train_test_split(
X, y, *, test_size=0.25, random_state=None, stratify=None
) -> Split:
... # TODO
class Distance(StrEnum):
EUCLIDEAN = auto()
# TODO: MANHATTAN, __repr__, between()
class Neighbor(NamedTuple):
index: int
# TODO: distance, label
# TODO: KNNClassifier with a distance parameter (module 20's class, rewritten)
# TODO: confusion_matrix, ClassMetrics, ClassificationReport, classification_report
# TODO: the evaluation and the asserts
Criterion Points Full points when
Frozen Split 3 frozen dataclass of tuples; checks in __post_init__; short repr; unpacks into four parts
train_test_split 3 keyword-only options; input checks; reproducible with random_state; stratification keeps the class shares
Distance enum 2 StrEnum, match in between(), repr that is valid Python
KNNClassifier upgrade 3 distance stored unchanged and validated in fit; kneighbors() returns sorted Neighbor tuples; deterministic ties
Metrics 3 correct confusion matrix orientation; no division by zero; macro and weighted averages
Report dataclasses 2 frozen ClassMetrics with slots=True; readable __str__; asdict() gives JSON
No leakage 2 scalers are fitted on training rows only; k and the distance are chosen on the validation part; the test part is scored once
Interpretation 1 you compare with the baseline and name recall as the number that matters for churn
Self-checks 2 asserts for the split, the matrix and the report
Total 21 17 or more: you are ready for module 22
  1. Add Distance.CHEBYSHEV (the largest difference over the features). Add the member first and run predict: the final raise in between() fails loudly until you add the formula.
  2. Add a Task enum (REGRESSION, CLASSIFICATION) as a class attribute _task of each estimator, and make a generic evaluate(model, split) that returns R² for regressors and a ClassificationReport for classifiers.
  3. Add a FitReport frozen dataclass (model, n_train, n_test, train_accuracy, test_accuracy) and collect one per model in a list. Sort the list with a rank_key field and order=True.
  4. Make train_test_split accept an int test_size (a number of rows), as scikit-learn does.
  5. Run the evaluation on all 5,000 customers with heapq.nsmallest in kneighbors instead of a full sort. Measure the speed-up with time.perf_counter().

Try the project yourself first. Then compare. Your names can differ; your numbers must not.

Reference solution

The solution runs below the code of the “minilearn so far” block.

minilearn_21.py (part 1: the split)
import json
import random
from collections.abc import Iterator, Sequence
from dataclasses import FrozenInstanceError, asdict, dataclass, field
from enum import StrEnum, auto
from typing import NamedTuple
Row = Sequence[float] # one row of features: a list or a tuple
@dataclass(frozen=True)
class Split:
"""The result of train_test_split: four read-only parts."""
X_train: tuple[tuple[float, ...], ...]
X_test: tuple[tuple[float, ...], ...]
y_train: tuple[Any, ...]
y_test: tuple[Any, ...]
test_indices: tuple[int, ...] = field(default=(), repr=False)
def __post_init__(self) -> None:
if len(self.X_train) != len(self.y_train):
raise ValueError("X_train and y_train have different lengths")
if len(self.X_test) != len(self.y_test):
raise ValueError("X_test and y_test have different lengths")
if not self.X_train or not self.X_test:
raise ValueError("both parts of a split need at least one row")
def __repr__(self) -> str:
return f"Split(n_train={len(self.X_train)}, n_test={len(self.X_test)})"
def __iter__(self) -> Iterator[tuple[Any, ...]]:
yield from (self.X_train, self.X_test, self.y_train, self.y_test)
def train_test_split(
X: Sequence[Row],
y: Sequence[Any],
*,
test_size: float = 0.25,
random_state: int | None = None,
stratify: Sequence[Any] | None = None,
) -> Split:
"""Shuffle the rows and split them into a training part and a test part."""
if len(X) != len(y):
raise ValueError(f"X has {len(X)} rows but y has {len(y)}")
if stratify is not None and len(stratify) != len(y):
raise ValueError(f"stratify has {len(stratify)} labels but y has {len(y)}")
if not 0 < test_size < 1:
raise ValueError(f"test_size must be in (0, 1), got {test_size}")
groups: dict[Any, list[int]] = {}
for i in range(len(y)):
key = None if stratify is None else stratify[i]
groups.setdefault(key, []).append(i)
rng = random.Random(random_state)
test_idx: list[int] = []
for key in sorted(groups, key=repr): # a fixed order, so the seed works
rows = groups[key]
rng.shuffle(rows)
test_idx.extend(rows[: round(len(rows) * test_size)])
test_idx.sort()
in_test = set(test_idx)
train_idx = [i for i in range(len(y)) if i not in in_test]
return Split(
X_train=tuple(tuple(X[i]) for i in train_idx),
X_test=tuple(tuple(X[i]) for i in test_idx),
y_train=tuple(y[i] for i in train_idx),
y_test=tuple(y[i] for i in test_idx),
test_indices=tuple(test_idx),
)
features = ["tenure_months", "logins_last_30d"]
raw = Dataset.from_csv("data/customers.csv", target="churned", features=features)
customers = Dataset(raw.X, [int(v) for v in raw.y], raw.feature_names) # 0/1 labels
sample = customers[::4] # every 4th customer: 1,250 rows
X, y = sample.X, sample.y
split = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
X_train, X_test, y_train, y_test = split
print(raw)
print(sample)
print(split, split.test_indices[:5])
print(f"churn rate: all {sum(y) / len(y):.3f}, ", end="")
print(f"train {sum(y_train) / len(y_train):.3f}, test {sum(y_test) / len(y_test):.3f}")
same = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
print(same == split, same is split)
try:
split.X_test = ()
except FrozenInstanceError as exc:
print("FrozenInstanceError:", exc)
for bad in [{"test_size": 25}, {"test_size": 0.0}, {"stratify": y[:10]}]:
try:
train_test_split(X, y, **bad)
except ValueError as exc:
print("ValueError:", exc)
Output
Dataset(n_samples=5000, features=['tenure_months', 'logins_last_30d'])
Dataset(n_samples=1250, features=['tenure_months', 'logins_last_30d'])
Split(n_train=938, n_test=312) (1, 4, 5, 16, 17)
churn rate: all 0.181, train 0.181, test 0.179
True False
FrozenInstanceError: cannot assign to field 'X_test'
ValueError: test_size must be in (0, 1), got 25
ValueError: test_size must be in (0, 1), got 0.0
ValueError: stratify has 10 labels but y has 1250
minilearn_21.py (part 2: Distance and KNNClassifier)
class Distance(StrEnum):
"""How KNNClassifier measures the distance between two rows."""
EUCLIDEAN = auto() # "euclidean": straight-line distance
MANHATTAN = auto() # "manhattan": sum of the absolute differences
def __repr__(self) -> str:
return f"{type(self).__name__}.{self.name}" # valid Python, for model reprs
def between(self, a: Row, b: Row) -> float:
match self:
case Distance.EUCLIDEAN:
return math.dist(a, b)
case Distance.MANHATTAN:
return sum(abs(x - y) for x, y in zip(a, b, strict=True))
raise AssertionError(f"no formula for {self!r}")
class Neighbor(NamedTuple):
index: int # row number in the training data
distance: float
label: Any
class KNNClassifier(ClassifierMixin, BaseEstimator):
"""Majority vote of the k nearest training rows, with a choice of distance."""
def __init__(
self, n_neighbors: int = 5, distance: Distance | str = Distance.EUCLIDEAN
) -> None:
self.n_neighbors = n_neighbors
self.distance = distance # stored unchanged; validated in fit()
def fit(self, X: Sequence[Row], y: Sequence[Any]) -> Self:
if self.n_neighbors < 1:
raise ValueError(f"n_neighbors must be >= 1, got {self.n_neighbors}")
try:
self.distance_ = Distance(self.distance)
except ValueError:
valid = ", ".join(d.value for d in Distance)
msg = f"unknown distance {self.distance!r}; use one of: {valid}"
raise ValueError(msg) from None
self.X_train_ = [list(row) for row in X]
self.y_train_ = list(y)
self.classes_ = sorted(set(y))
return self
def kneighbors(self, row: Row) -> list[Neighbor]:
check_is_fitted(self)
pairs = zip(self.X_train_, self.y_train_, strict=True)
found = [
Neighbor(i, self.distance_.between(row, x), label)
for i, (x, label) in enumerate(pairs)
]
found.sort(key=lambda n: (n.distance, n.index)) # ties: lower row number
return found[: self.n_neighbors]
def predict(self, X: Sequence[Row]) -> list[Any]:
check_is_fitted(self)
predictions = []
for row in X:
votes = Counter(n.label for n in self.kneighbors(row))
predictions.append(max(self.classes_, key=lambda label: votes[label]))
return predictions
scaler = StandardScaler().fit(X_train) # learn from the training part only
Xs_train, Xs_test = scaler.transform(X_train), scaler.transform(X_test)
knn = KNNClassifier(n_neighbors=3, distance="manhattan").fit(Xs_train, y_train)
print(knn, "->", repr(knn.distance_))
print(KNNClassifier(15, Distance.MANHATTAN))
print("customer", X_test[0], "true label", y_test[0])
for n in knn.kneighbors(Xs_test[0]):
row = X_train[n.index]
print(f" train row {n.index:>3}: {row} distance {n.distance:.3f} label {n.label}")
try:
KNNClassifier(distance="cosine").fit(Xs_train, y_train)
except ValueError as exc:
print("ValueError:", exc)
Output
KNNClassifier(n_neighbors=3, distance='manhattan') -> Distance.MANHATTAN
KNNClassifier(n_neighbors=15, distance=Distance.MANHATTAN)
customer (72.0, 25.0) true label 0
train row 4: (72.0, 25.0) distance 0.000 label 0
train row 26: (72.0, 24.0) distance 0.116 label 0
train row 18: (72.0, 23.0) distance 0.233 label 0
ValueError: unknown distance 'cosine'; use one of: euclidean, manhattan
minilearn_21.py (part 3: the metrics)
def confusion_matrix(
y_true: Sequence[Any], y_pred: Sequence[Any], labels: Sequence[Any] | None = None
) -> list[list[int]]:
"""Rows are true classes, columns are predicted classes."""
if labels is None:
labels = sorted(set(y_true) | set(y_pred))
position = {label: j for j, label in enumerate(labels)}
matrix = [[0] * len(labels) for _ in labels]
for t, p in zip(y_true, y_pred, strict=True):
matrix[position[t]][position[p]] += 1
return matrix
@dataclass(frozen=True, slots=True)
class ClassMetrics:
label: str
precision: float
recall: float
f1: float
support: int
@dataclass(frozen=True)
class ClassificationReport:
classes: tuple[ClassMetrics, ...]
accuracy: float
macro_avg: ClassMetrics
weighted_avg: ClassMetrics
def __str__(self) -> str:
def line(m: ClassMetrics) -> str:
scores = f"{m.precision:>9.3f} {m.recall:>6.3f} {m.f1:>5.3f}"
return f"{m.label:>12} {scores} {m.support:>7}"
n = self.macro_avg.support
lines = [f"{'':>12} {'precision':>9} {'recall':>6} {'f1':>5} {'support':>7}"]
lines += [line(m) for m in self.classes]
lines.append(f"{'accuracy':>12} {'':>9} {'':>6} {self.accuracy:>5.3f} {n:>7}")
lines += [line(self.macro_avg), line(self.weighted_avg)]
return "\n".join(lines)
def _safe_ratio(numerator: float, denominator: float) -> float:
return numerator / denominator if denominator else 0.0
def classification_report(
y_true: Sequence[Any], y_pred: Sequence[Any]
) -> ClassificationReport:
labels = sorted(set(y_true) | set(y_pred))
matrix = confusion_matrix(y_true, y_pred, labels)
per_class = []
for j, label in enumerate(labels):
tp = matrix[j][j]
precision = _safe_ratio(tp, sum(row[j] for row in matrix)) # column sum
recall = _safe_ratio(tp, sum(matrix[j])) # row sum
f1 = _safe_ratio(2 * precision * recall, precision + recall)
support = sum(matrix[j])
per_class.append(ClassMetrics(str(label), precision, recall, f1, support))
def average(name: str, weights: list[int]) -> ClassMetrics:
def mean_of(attr: str) -> float:
pairs = zip(per_class, weights, strict=True)
return sum(getattr(m, attr) * w for m, w in pairs) / sum(weights)
precision, recall, f1 = mean_of("precision"), mean_of("recall"), mean_of("f1")
return ClassMetrics(name, precision, recall, f1, len(y_true))
return ClassificationReport(
classes=tuple(per_class),
accuracy=accuracy_score(list(y_true), list(y_pred)),
macro_avg=average("macro avg", [1] * len(per_class)),
weighted_avg=average("weighted avg", [m.support for m in per_class]),
)
toy_true = ["stay", "stay", "stay", "churn", "churn"]
toy_pred = ["stay", "churn", "stay", "churn", "stay"]
print(confusion_matrix(toy_true, toy_pred))
print(classification_report(toy_true, toy_pred))
print(classification_report(toy_true, ["stay"] * 5).classes[0]) # never predicts churn
Output
[[1, 1], [1, 2]]
precision recall f1 support
churn 0.500 0.500 0.500 2
stay 0.667 0.667 0.667 3
accuracy 0.600 5
macro avg 0.583 0.583 0.583 5
weighted avg 0.600 0.600 0.600 5
ClassMetrics(label='churn', precision=0.0, recall=0.0, f1=0.0, support=2)
minilearn_21.py (part 4: the evaluation)
# 1. Choose the model on a validation part carved out of the training part.
inner = train_test_split(
X_train, y_train, test_size=0.25, random_state=0, stratify=y_train
)
X_fit, X_val, y_fit, y_val = inner
inner_scaler = StandardScaler().fit(X_fit)
Xs_fit, Xs_val = inner_scaler.transform(X_fit), inner_scaler.transform(X_val)
candidates = [KNNClassifier(k, d) for d in Distance for k in (1, 5, 15)]
val_f1 = {}
print("fit/validation:", inner)
print(f"{'candidate':<58} {'recall(1)':>9} {'f1(1)':>6}")
for model in candidates:
report = classification_report(y_val, model.fit(Xs_fit, y_fit).predict(Xs_val))
churners = report.classes[1]
val_f1[repr(model)] = churners.f1
print(f"{model!r:<58} {churners.recall:>9.3f} {churners.f1:>6.3f}")
chosen = max(candidates, key=lambda m: val_f1[repr(m)])
# 2. Refit the chosen settings and the baseline on the whole training part.
final = KNNClassifier(**chosen.get_params()).fit(Xs_train, y_train)
baseline = MajorityClassifier().fit(Xs_train, y_train)
# 3. Score the test part once.
print()
for model in (baseline, final):
y_pred = model.predict(Xs_test)
report = classification_report(y_test, y_pred)
print(model, "on the test part:", confusion_matrix(y_test, y_pred))
print(report)
churn_row = asdict(report)["classes"][1] # a plain dict, ready for JSON
rounded = {k: round(v, 3) if isinstance(v, float) else v for k, v in churn_row.items()}
print(json.dumps(rounded))
assert split.test_indices == tuple(sorted(split.test_indices))
assert len(split.X_train) + len(split.X_test) == len(X)
assert len(X_fit) + len(X_val) == len(X_train)
assert sum(sum(row) for row in confusion_matrix(y_test, y_pred)) == len(y_test)
assert report.classes[1].support == sum(y_test)
assert math.isclose(report.accuracy, final.score(Xs_test, y_test))
assert final == chosen # same class and parameters: get_params() rebuilt it
Output
fit/validation: Split(n_train=704, n_test=234)
candidate recall(1) f1(1)
KNNClassifier(n_neighbors=1, distance=Distance.EUCLIDEAN) 0.381 0.360
KNNClassifier(n_neighbors=5, distance=Distance.EUCLIDEAN) 0.238 0.333
KNNClassifier(n_neighbors=15, distance=Distance.EUCLIDEAN) 0.095 0.167
KNNClassifier(n_neighbors=1, distance=Distance.MANHATTAN) 0.381 0.368
KNNClassifier(n_neighbors=5, distance=Distance.MANHATTAN) 0.214 0.310
KNNClassifier(n_neighbors=15, distance=Distance.MANHATTAN) 0.024 0.044
MajorityClassifier() on the test part: [[256, 0], [56, 0]]
precision recall f1 support
0 0.821 1.000 0.901 256
1 0.000 0.000 0.000 56
accuracy 0.821 312
macro avg 0.410 0.500 0.451 312
weighted avg 0.673 0.821 0.740 312
KNNClassifier(n_neighbors=1, distance=Distance.MANHATTAN) on the test part: [[205, 51], [44, 12]]
precision recall f1 support
0 0.823 0.801 0.812 256
1 0.190 0.214 0.202 56
accuracy 0.696 312
macro avg 0.507 0.508 0.507 312
weighted avg 0.710 0.696 0.702 312
{"label": "1", "precision": 0.19, "recall": 0.214, "f1": 0.202, "support": 56}

How it works:

  1. Split. The frozen dataclass stores tuples of tuples, so neither the fields nor the rows inside them can change. __post_init__ refuses inconsistent parts. @dataclass keeps the __repr__ that the class defines, so the repr shows sizes instead of 1,250 rows. __iter__ yields the four parts, so the result unpacks like scikit-learn’s. Two splits with the same seed are equal objects, because the generated __eq__ compares the fields.
  2. Stratification. The function groups the row numbers by class and takes the same fraction of each group. Both parts keep a churn rate close to 18.1%. Sorting the groups by repr gives a fixed order, so one seed always gives the same split.
  3. Distance. StrEnum with auto() produces the values "euclidean" and "manhattan", so Distance("manhattan") accepts the plain string that a user or a config file gives. The custom __repr__ keeps repr(model) valid Python. The match in between() holds both formulas, and the final raise catches a member without one.
  4. KNNClassifier. __init__ stores distance unchanged, so get_params() and the repr show what the user passed. fit validates it and stores the member in distance_. kneighbors() returns Neighbor named tuples; the sort key (distance, index) makes ties deterministic. The printout shows why the first test customer got its label.
  5. Metrics. The confusion matrix has true classes in rows and predicted classes in columns. Precision divides TP by a column sum, recall by a row sum. _safe_ratio returns 0.0 for a class that is never predicted, as scikit-learn does (scikit-learn also prints a warning).
  6. Report dataclasses. ClassMetrics is frozen and slotted: a small, immutable value. ClassificationReport holds them in a tuple. __str__ prints a table, and asdict() converts the whole report, recursively, into dicts for JSON.
  7. Model selection without the test part. The second split carves a validation part (234 rows, 42 churners) out of the training part. The six candidates are compared there, by churn F1 and not by accuracy. The test part plays no role in the choice, so its score is an honest estimate. KNNClassifier(**chosen.get_params()) rebuilds the chosen settings as a new, unfitted model, which is then fitted on the whole training part.
  8. Interpretation. The validation part chose k = 1 with the Manhattan distance (churn F1 0.368). On the test part, the same model reaches F1 0.202 and recall 0.214: it finds about 1 churner in 5. The drop from 0.368 shows how noisy a score on 42 churners is; module 37 replaces the single validation split with cross-validation. The baseline that always predicts “stays” has the higher accuracy (0.821 against 0.696), because 82% of the test customers stay, but it finds no churner at all. Accuracy hides this; the report shows it. Two features are not enough to find churners well; module 36 builds better models and chooses a decision threshold.

Alternative: Split could be a NamedTuple with five fields, which unpacks for free. You would lose the checks, the short repr and the type-safe equality (see the tip above). For the report, a plain dict of dicts, as scikit-learn returns with output_dict=True, is fine for JSON, but the dataclasses give you attribute access (report.classes[1].recall), a __str__ and immutability.