22. Design principles and patterns — Mini-project
This is the last minilearn project. Over modules 18 to 21, the library grew one module at a time: a Dataset, a scaler and a line in module 18; BaseEstimator, the mixins and KNN in module 19; the special methods and the Pipeline in module 20; Split, train_test_split, the Distance enum, kneighbors() and the classification report in module 21. In this project you assemble those parts into one package and organize it by the patterns of the lesson:
- Template method:
BaseEstimator.fit()validates the input, notifies the callbacks and calls the hook_fit().predict()andtransform()work the same way with_predict()and_transform(). - Strategy:
KNNClassifier(distance=...)takes aDistancemember, its name or any function of two rows. - Factory and registry: every estimator class registers itself with
@register("name"), andmake_model("knn", n_neighbors=15)builds it. - Observer:
fit(..., callbacks=[FitLogger()])reports every training step, also inside a pipeline, and an iterative model sendson_epoch_endthrough the same template. - Pipeline and builder:
Pipeline.builder().add("scale", ...).add("model", ...).build(). - Dependency injection: the end-to-end script receives its CSV reader and its logger, so its test runs without the data files.
Then you run the whole library on two real problems: you choose the KNN settings on a validation part, score the test part once, and print the metrics.
Dataset
Section titled “Dataset”The same data and the same row selection as the module 18 and module 21 projects. The data dictionary describes both files.
| Experiment | File | Features | Target | Rows and split |
|---|---|---|---|---|
churn (classification) |
data/customers.csv |
tenure_months, logins_last_30d |
churned (0 or 1) |
every 4th customer (1,250 rows); a stratified 25% test part with random_state=42; a stratified validation part of the training rows with random_state=0 |
houses (regression) |
data/houses.csv |
sqft |
price |
all 3,000 sales; the first 2,400 train and the newest 600 test (Dataset.split_at) |
customers.csv is sorted by signup date, so the sample takes every 4th row to cover old and new customers. houses.csv is sorted by sale date, so a split by position tests on the most recent sales, as a real price model would be used. The tests use small records typed in the test file instead of these files.
Requirements
Section titled “Requirements”Build this package in your project folder, next to data/:
my-course/├── data/ the course datasets├── minilearn/│ ├── __init__.py public names; imports every module, so every model registers│ ├── base.py NotFittedError, check_is_fitted, BaseEstimator, the mixins│ ├── callbacks.py Callback, FitLogger, History, EarlyStopping│ ├── datasets.py Dataset, read_csv_records│ ├── distances.py euclidean, manhattan, Distance, get_distance│ ├── dummy.py MeanRegressor, MajorityClassifier│ ├── linear_model.py LinearRegression, GradientDescentRegressor│ ├── metrics.py MSE, RMSE, R², accuracy, confusion matrix, classification report│ ├── model_selection.py Split, train_test_split (module 21, unchanged)│ ├── neighbors.py Neighbor, KNNClassifier│ ├── pipeline.py check_steps, Pipeline, PipelineBuilder│ ├── preprocessing.py StandardScaler│ └── registry.py MODELS, register, make_model, available_models├── run_minilearn.py the end-to-end run└── test_minilearn.py the pytest suite- Base and template method.
BaseEstimatorkeepsget_params(),set_params(),__repr__and__eq__from modules 19 and 20. Itsfit(X, y=None, *, callbacks=()), marked@typing.final, validates the input (empty X, ragged rows, ayof the wrong length, a missingy), callson_fit_start, calls the abstract hook_fit(), setsn_features_in_, callson_fit_endand returnsself. While_fit()runs, the hook can sendon_epoch_endwithself._notify_epoch(epoch, loss)and read the flagself.stop_training.predict()andtransform()check that the model is fitted and that X has the right number of features, then call_predict()or_transform(). No estimator overridesfit(). - Strategy.
KNNClassifier(n_neighbors=5, distance=Distance.EUCLIDEAN)storesdistanceunchanged and resolves it in_fit(): aDistancemember, its name or any function of two rows. An unknown name raises module 21’sValueError.kneighbors(row)returnsNeighbornamed tuples; ties between neighbors go to the lower row index, ties between votes to the lowest label. - Factory and registry.
@register(name)adds a class toMODELS. It refuses a name that another class holds, but accepts the same class again (a rerun notebook cell).make_model(name, **params)returns a new estimator, or raisesValueErrorwith the list of known names. Registerscaler,linear,gd,knn,meanandmajority. - Observer.
Callbackhas the eventson_fit_start,on_epoch_endandon_fit_endwith empty bodies.FitLogger(log=print)writes one line per fit event to an injected log function and indents nested fits.Historyrecords the events and the losses.EarlyStoppingsetsstop_training. - Pipeline and builder.
Pipeline(steps)subclassesBaseEstimator, storesstepsunchanged and checks them at the start offit()(at least one step, unique names, every step but the last hastransform()), as in module 20. It passes the callbacks on to every step and keeps module 20’slen(), iteration, indexing by position, by name and by slice, andrepr().Pipeline.builder()returns aPipelineBuilder:add(name, step)checks the name at once and returnsself, andbuild()runs the samecheck_steps()before it returns the pipeline. - Dependency injection.
Dataset.from_csv()takes the reader as a keyword argument.run_minilearn.pydescribes both experiments as plain data (names and parameters only, so the list could be a JSON file).main(read=read_csv_records, log=print, experiments=EXPERIMENTS)splits the data, chooses the KNN settings on the validation part by churn F1, refits on the whole training part, scores the test part once against a baseline from the registry, and returns the main score per experiment. - Output.
python run_minilearn.pyprints exactly this report:
== churn ==Dataset(n_samples=1250, features=['tenure_months', 'logins_last_30d'])Split(n_train=938, n_test=312)chosen on validation (234 rows): {'n_neighbors': 1, 'distance': 'manhattan'}, F1 0.368fit Pipeline: 938 rows x 2 features fit StandardScaler: 938 rows x 2 features learned mean_, n_features_in_, scale_ fit KNNClassifier: 938 rows x 2 features learned X_train_, classes_, distance_, n_features_in_, y_train_ learned n_features_in_confusion matrix (rows = true 0/1): [[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 312weighted avg 0.710 0.696 0.702 312baseline: accuracy 0.821, churn recall 0.000== houses ==Dataset(n_samples=3000, features=['sqft'])Split(n_train=2400, n_test=600)fit Pipeline: 2400 rows x 1 features fit StandardScaler: 2400 rows x 1 features learned mean_, n_features_in_, scale_ fit LinearRegression: 2400 rows x 1 features learned coef_, intercept_, n_features_in_ learned n_features_in_R² 0.561 (baseline -0.014)RMSE 229,936 (baseline 349,424)- Tests.
python -m pytest -q test_minilearn.pypasses. The suite covers the factory (a known name, a typo, a taken name, the same class again), the template checks for every registered model,NotFittedError, the three forms ofdistance, the callback events inside a pipeline, early stopping through the template, the stored-unchangedsteps, the builder errors, the container methods, andmain()with a fake reader and a list as the logger.
Changes from modules 18 to 21
Section titled “Changes from modules 18 to 21”The package keeps every public name of modules 18 to 21. These are the changes, and why:
| Change | Before | After | Why |
|---|---|---|---|
fit() |
written in every estimator | one template in BaseEstimator; estimators write _fit() |
the checks and the callbacks exist once (template method) |
Distance.between() |
a match with one case per formula |
a lookup in the dict DISTANCES |
a new distance is a new function, not an edit of a working method (open/closed) |
KNNClassifier(distance=...) |
a Distance member or its name |
also any function of two rows | a caller can pass a distance the library does not know (strategy) |
fit(..., callbacks=()) |
no callbacks | a keyword-only argument | observers without changes to the estimators |
Dataset.from_csv(..., read=...) |
always opens the file | the reader is injected; from_records() holds the parsing |
tests run without files (dependency injection) |
check_X() messages |
each class its own wording | one wording for every model | written once, in the template |
Pipeline.builder() |
none | a builder that checks each step as it arrives | a config loop fails at the bad step |
register / make_model |
none | the registry and the factory | configs choose models by name |
Step plan
Section titled “Step plan”-
Create the package. Make the
minilearn/folder and an empty__init__.py. Copy the metric functions,confusion_matrixandclassification_reportof module 21 intometrics.py. Metrics are plain functions: they keep no state. -
Write
callbacks.pyfirst. It depends on nothing else in the package. GiveCallbackthree methods whose body is only a docstring. -
Write
base.py. MoveNotFittedErrorandcheck_is_fitted()here unchanged. Addcheck_X(). Turnfit()into the template, add_validate(),_check_input()and_notify_epoch(), and declare_fit()with@abstractmethod. GiveTransformerMixinthe class attribute_requires_y = Falseand atransform()that calls_transform(). -
Write
registry.py. It importsBaseEstimatoronly for the type hints. KeepMODELSa plain dict. -
Port the estimators. In each class, rename
fit()to_fit()andpredict()to_predict(), delete the input checks and thereturn self, and add the@register(...)line. Put each family in its own module. Move the formulas ofDistance.between()into functions indistances.py, and letKNNClassifiercallget_distance(). Port the lesson’sGradientDescentRegressorwith_notify_epoch(). -
Write
pipeline.py. Start from your module 20Pipeline. Turn itsfit()into the hook_fit(), move_validate_steps()into the module-levelcheck_steps(), passself._callbackson to every step and add thebuilder()class method. WritePipelineBuilder. -
Copy
model_selection.pyfrom module 21 and add the injectable reader todatasets.py. -
Fill
__init__.py. Import every module and list the public names in__all__. Check in a REPL thatavailable_models()lists all six names afterimport minilearn. -
Write
run_minilearn.py. Keep the experiments as data. Use a dict of split functions and a dict of report functions, one per kind, instead ofifchains. Choose the KNN settings on the validation part only. Run it and compare with the expected output. -
Write
test_minilearn.pyand run it withpython -m pytest -q test_minilearn.py. The-mform puts the project folder on the import path, soimport minilearnworks.
Rubric
Section titled “Rubric”| Criterion | Points | Full points when |
|---|---|---|
| Template method | 3 | fit(), predict() and transform() live only in the base and the mixins; no estimator repeats a check or overrides fit(); epoch events go through the template |
| Strategy | 2 | KNN accepts a member, a name and a function; get_params() shows the setting unchanged |
| Factory and registry | 2 | every model registers itself; a typo lists the valid names; a taken name is an error, the same class again is not |
| Observer | 2 | callbacks reach every step of a pipeline; FitLogger takes an injected log function |
| Pipeline and builder | 2 | steps stored unchanged; step errors appear at build() or at the start of fit(), with the step name |
| Dependency injection | 2 | main() runs in a test with a fake reader and a list as the logger |
| Model selection | 2 | the settings are chosen on the validation part; the test part is scored once |
| Output and tests | 2 | the report equals the expected output; the pytest suite passes; ruff reports no problems |
| No over-engineering | 1 | no class without state or a real second implementation; metrics and distances stay functions |
| Total | 18 | 15 or more: you are ready for the Part 3 checkpoint |
Stretch goals
Section titled “Stretch goals”- Add
Distance.CHEBYSHEVand its function. Count the places you had to change: one enum member and one dict entry. - Read the experiments from a JSON file named on the command line with
argparse(module 08). Nothing inrun_experiment()should change. - Write a
Timercallback that stores the duration of each fit in a dict. Test it with an injected clock function instead oftime.perf_counter, so the test needs no real time. - Add
clone(estimator), which returnstype(estimator)(**estimator.get_params()). It works for aPipelinetoo, becausePipelineis aBaseEstimator, but its steps are shared: makeclone()clone every step insidesteps, as scikit-learn’sclone()does with nested estimators. - Replace the single validation part with 5-fold cross-validation (module 37 does this with scikit-learn), and compare the chosen settings.
- Make a second package,
minilearn_extra, with aMedianRegressorregistered under"median". Advertise it through an entry point in itspyproject.toml(groupminilearn.models) and load it inminilearn/__init__.pywithimportlib.metadata.entry_points(group="minilearn.models"). pytest finds its plugins the same way (grouppytest11).
Reference solution
Section titled “Reference solution”Try the project first. Then compare your package with this one, file by file.
Reference solution
minilearn/metrics.py: plain functions and module 21’s report dataclasses.
"""Metrics: plain functions, because a metric keeps no state.
The functions and the report dataclasses are those of modules 18, 19 and 21.root_mean_squared_error is new."""
import mathfrom collections.abc import Sequencefrom dataclasses import dataclassfrom typing import Any
def _check_lengths(y_true: Sequence[Any], y_pred: Sequence[Any]) -> 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: Sequence[float], y_pred: Sequence[float]) -> float: _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 root_mean_squared_error(y_true: Sequence[float], y_pred: Sequence[float]) -> float: return math.sqrt(mean_squared_error(y_true, y_pred))
def r2_score(y_true: Sequence[float], y_pred: Sequence[float]) -> float: _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: Sequence[Any], y_pred: Sequence[Any]) -> float: _check_lengths(y_true, y_pred) return sum(t == p for t, p in zip(y_true, y_pred, strict=True)) / len(y_true)
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]), )minilearn/callbacks.py: the observer interface and three observers.
"""Observers of training: callbacks that fit() notifies.
A callback overrides only the events it needs. The estimator does not knowwhat its callbacks do: it only calls them."""
import mathfrom collections.abc import Callablefrom typing import Any
type Rows = list[list[float]]
def learned_attributes(estimator: object) -> list[str]: """Names that fit() set: they end with "_" and do not start with "__".""" names = vars(estimator) return sorted(k for k in names if k.endswith("_") and not k.startswith("__"))
class Callback: """Base observer. Every event does nothing until a subclass overrides it."""
def on_fit_start(self, estimator: Any, X: Rows, y: list[Any] | None) -> None: """Called after the input is validated, before the estimator learns."""
def on_epoch_end(self, estimator: Any, epoch: int, loss: float) -> None: """Called by iterative estimators after each pass over the data."""
def on_fit_end(self, estimator: Any) -> None: """Called after the estimator has learned."""
class FitLogger(Callback): """Write one line per event to an injected log function (print by default).
Fits inside fits (the steps of a Pipeline) are indented one level deeper. """
def __init__(self, log: Callable[[str], None] = print) -> None: self.log = log self.depth = 0
def on_fit_start(self, estimator: Any, X: Rows, y: list[Any] | None) -> None: name = type(estimator).__name__ self.log( " " * self.depth + f"fit {name}: {len(X)} rows x {len(X[0])} features" ) self.depth += 1
def on_fit_end(self, estimator: Any) -> None: learned = ", ".join(learned_attributes(estimator)) self.log(" " * self.depth + f"learned {learned}") self.depth -= 1
class History(Callback): """Record every event and every loss, for a test, a report or a chart."""
def __init__(self) -> None: self.events: list[tuple[str, str]] = [] self.losses: list[float] = []
def on_fit_start(self, estimator: Any, X: Rows, y: list[Any] | None) -> None: self.events.append(("start", type(estimator).__name__))
def on_epoch_end(self, estimator: Any, epoch: int, loss: float) -> None: self.losses.append(loss)
def on_fit_end(self, estimator: Any) -> None: self.events.append(("end", type(estimator).__name__))
class EarlyStopping(Callback): """Stop when the loss has not improved by min_delta for `patience` epochs."""
def __init__(self, min_delta: float = 0.0, patience: int = 3) -> None: self.min_delta = min_delta self.patience = patience
def on_fit_start(self, estimator: Any, X: Rows, y: list[Any] | None) -> None: self.best, self.waited = math.inf, 0 # reset, so one object serves many fits
def on_epoch_end(self, estimator: Any, epoch: int, loss: float) -> None: if loss < self.best - self.min_delta: self.best, self.waited = loss, 0 else: self.waited += 1 if self.waited >= self.patience: estimator.stop_training = True # the flag the training loop checksminilearn/base.py: the template methods and the mixins.
"""BaseEstimator and the mixins.
fit(), predict() and transform() are template methods. They run the sharedsteps (validate, notify the callbacks, check that the model is fitted) and callone hook that each subclass writes: _fit(), _predict() or _transform()."""
import inspectfrom abc import ABC, abstractmethodfrom collections.abc import Sequencefrom typing import Any, Self, final
from minilearn.callbacks import Callbackfrom minilearn.metrics import accuracy_score, r2_score
type Rows = list[list[float]]
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")
def check_X(X: Sequence[Sequence[float]], owner: str) -> Rows: """Return X as a list of float rows, or raise ValueError with a clear message.""" if len(X) == 0: raise ValueError(f"{owner}: X is empty") width = len(X[0]) for i, row in enumerate(X): if len(row) != width: message = f"{owner}: row {i} has length {len(row)}, expected {width}" raise ValueError(message) return [[float(v) for v in row] for row in X]
class BaseEstimator(ABC): """Parameters, repr, equality and the fit() template for every estimator."""
_requires_y = True # transformers set this to False
@classmethod def _get_param_names(cls) -> 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(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 return type(self) is type(other) and self.get_params() == other.get_params()
@final # a type checker reports any subclass that overrides the template def fit( self, X: Sequence[Sequence[float]], y: Sequence[Any] | None = None, *, callbacks: Sequence[Callback] = (), ) -> Self: """Template method: validate, notify, learn (_fit), notify, return self.""" rows, labels = self._validate(X, y) self._callbacks = tuple(callbacks) # the hook can send epoch events self.stop_training = False # an observer may set this to True try: for callback in self._callbacks: callback.on_fit_start(self, rows, labels) self._fit(rows, labels) self.n_features_in_ = len(rows[0]) for callback in self._callbacks: callback.on_fit_end(self) finally: self._callbacks = () # do not keep the observers after fit() return self
def _notify_epoch(self, epoch: int, loss: float) -> None: """For iterative hooks: send on_epoch_end to the callbacks of this fit().""" for callback in self._callbacks: callback.on_epoch_end(self, epoch, loss)
def _validate( self, X: Sequence[Sequence[float]], y: Sequence[Any] | None ) -> tuple[Rows, list[Any] | None]: name = type(self).__name__ rows = check_X(X, name) if y is None: if self._requires_y: raise ValueError(f"{name}.fit() needs y") return rows, None labels = list(y) if len(labels) != len(rows): raise ValueError(f"{name}: X has {len(rows)} rows but y has {len(labels)}") return rows, labels
def _check_input(self, X: Sequence[Sequence[float]]) -> Rows: """Shared checks of predict() and transform().""" check_is_fitted(self) name = type(self).__name__ rows = check_X(X, name) if len(rows[0]) != self.n_features_in_: raise ValueError( f"{name}: X has {len(rows[0])} features, " f"but fit() saw {self.n_features_in_}" ) return rows
@abstractmethod def _fit(self, X: Rows, y: list[Any] | None) -> None: """The hook: learn from validated data and set attributes ending in _."""
class TransformerMixin: """transform() and fit_transform() for transformers."""
_requires_y = False
def transform(self, X: Sequence[Sequence[float]]) -> Rows: return self._transform(self._check_input(X))
def fit_transform( self, X: Sequence[Sequence[float]], y: Sequence[Any] | None = None, *, callbacks: Sequence[Callback] = (), ) -> Rows: return self.fit(X, y, callbacks=callbacks).transform(X)
class PredictorMixin: """predict() for regressors and classifiers."""
def predict(self, X: Sequence[Sequence[float]]) -> list[Any]: return self._predict(self._check_input(X))
class RegressorMixin(PredictorMixin): def score(self, X: Sequence[Sequence[float]], y: Sequence[float]) -> float: """R²: higher is better, 1.0 is perfect.""" return r2_score(list(y), self.predict(X))
class ClassifierMixin(PredictorMixin): def score(self, X: Sequence[Sequence[float]], y: Sequence[Any]) -> float: """Accuracy: higher is better, 1.0 is perfect.""" return accuracy_score(list(y), self.predict(X))minilearn/registry.py: the factory and the registry.
"""The model registry: a factory that builds estimators by name.
Each estimator class registers itself with @register("name"). Code that reads aconfig file calls make_model("knn", n_neighbors=15) and never imports the class."""
from collections.abc import Callablefrom typing import Any
from minilearn.base import BaseEstimator
MODELS: dict[str, type[BaseEstimator]] = {}
def _same_class(a: type, b: type) -> bool: """True for one class defined twice: a reloaded module or a rerun notebook cell.""" return (a.__module__, a.__qualname__) == (b.__module__, b.__qualname__)
def register[E: type[BaseEstimator]](name: str) -> Callable[[E], E]: """Class decorator: add the class to MODELS under name."""
def decorator(cls: E) -> E: if name in MODELS and not _same_class(MODELS[name], cls): taken = MODELS[name].__name__ raise ValueError(f"model name {name!r} is already used by {taken}") MODELS[name] = cls return cls
return decorator
def make_model(name: str, **params: Any) -> BaseEstimator: """Factory: build a new estimator registered under name.""" try: cls = MODELS[name] except KeyError: known = ", ".join(sorted(MODELS)) raise ValueError(f"unknown model {name!r}; choose from: {known}") from None return cls(**params)
def available_models() -> list[str]: return sorted(MODELS)minilearn/distances.py: module 21’s Distance, with the formulas moved into a strategy dict.
"""Distance strategies for KNNClassifier.
Module 21 put both formulas in one `match` inside Distance.between(): every newdistance meant editing that method. Here each formula is a plain function, and adict maps the Distance members to them (open/closed). KNNClassifier also acceptsany function of two rows."""
import mathfrom collections.abc import Callable, Sequencefrom enum import StrEnum, auto
type Row = Sequence[float]type DistanceFunc = Callable[[Row, Row], float]
def euclidean(a: Row, b: Row) -> float: return math.dist(a, b)
def manhattan(a: Row, b: Row) -> float: return sum(abs(x - y) for x, y in zip(a, b, strict=True))
class Distance(StrEnum): """The named distances (module 21). The values are "euclidean", "manhattan"."""
EUCLIDEAN = auto() MANHATTAN = auto()
def __repr__(self) -> str: return f"{type(self).__name__}.{self.name}" # valid Python, for model reprs
def between(self, a: Row, b: Row) -> float: return DISTANCES[self](a, b) # module 21's API, now a dict lookup
DISTANCES: dict[Distance, DistanceFunc] = { Distance.EUCLIDEAN: euclidean, Distance.MANHATTAN: manhattan,}
def get_distance(distance: Distance | str | DistanceFunc) -> DistanceFunc: """Accept a Distance member, its name ("manhattan") or any distance function.""" if callable(distance): return distance try: return DISTANCES[Distance(distance)] except ValueError: valid = ", ".join(d.value for d in Distance) msg = f"unknown distance {distance!r}; use one of: {valid}" raise ValueError(msg) from Noneminilearn/preprocessing.py, linear_model.py, neighbors.py and dummy.py: the estimators write hooks only.
"""StandardScaler: rescale each feature to mean 0 and standard deviation 1."""
import math
from minilearn.base import BaseEstimator, Rows, TransformerMixinfrom minilearn.registry import register
@register("scaler")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: Rows, y: object = None) -> None: columns = list(zip(*X, strict=True)) n = len(X) means = [sum(col) / n for col in columns] stds = [ math.sqrt(sum((v - m) ** 2 for v in col) / n) for col, m in zip(columns, means, strict=True) ] self.mean_ = means if self.with_mean else [0.0] * len(columns) self.scale_ = [s or 1.0 for s in stds] if self.with_std else [1.0] * len(stds)
def _transform(self, X: Rows) -> Rows: 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, X: Rows) -> Rows: rows = self._check_input(X) 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 rows ]"""Linear models for one feature: closed-form least squares and gradient descent."""
from minilearn.base import BaseEstimator, RegressorMixin, Rowsfrom minilearn.registry import register
def _single_column(X: Rows, owner: str) -> list[float]: if len(X[0]) != 1: raise ValueError(f"{owner} supports exactly 1 feature, got {len(X[0])}") return [row[0] for row in X]
@register("linear")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
def _fit(self, X: Rows, y: list[float]) -> None: x = _single_column(X, "LinearRegression") if len(x) < 2: raise ValueError("LinearRegression needs at least 2 samples") mean_x = sum(x) / len(x) if self.fit_intercept else 0.0 mean_y = sum(y) / len(y) if self.fit_intercept else 0.0 sxy = sum((a - mean_x) * (b - mean_y) for a, b in zip(x, y, strict=True)) sxx = sum((a - mean_x) ** 2 for a in x) if sxx == 0: raise ValueError("cannot fit a line: all x values are equal") self.coef_ = sxy / sxx self.intercept_ = mean_y - self.coef_ * mean_x
def _predict(self, X: Rows) -> list[float]: return [self.intercept_ + self.coef_ * row[0] for row in X]
@register("gd")class GradientDescentRegressor(RegressorMixin, BaseEstimator): """A line fitted step by step; sends on_epoch_end to the callbacks of fit()."""
def __init__(self, learning_rate: float = 0.1, max_epochs: int = 200) -> None: self.learning_rate = learning_rate self.max_epochs = max_epochs
def _fit(self, X: Rows, y: list[float]) -> None: x = _single_column(X, "GradientDescentRegressor") n, lr = len(x), self.learning_rate self.coef_, self.intercept_ = 0.0, 0.0 for epoch in range(1, self.max_epochs + 1): errors = [ self.intercept_ + self.coef_ * a - b for a, b in zip(x, y, strict=True) ] self.coef_ -= ( lr * 2 / n * sum(e * a for e, a in zip(errors, x, strict=True)) ) self.intercept_ -= lr * 2 / n * sum(errors) self._notify_epoch(epoch, sum(e * e for e in errors) / n) if self.stop_training: # set by an observer such as EarlyStopping break self.n_epochs_ = epoch
def _predict(self, X: Rows) -> list[float]: return [self.intercept_ + self.coef_ * row[0] for row in X]"""KNNClassifier: majority vote of the k nearest training rows."""
from collections import Counterfrom typing import Any, NamedTuple
from minilearn.base import BaseEstimator, ClassifierMixin, Rows, check_is_fittedfrom minilearn.distances import Distance, DistanceFunc, Row, get_distancefrom minilearn.registry import register
class Neighbor(NamedTuple): index: int # row number in the training data distance: float label: Any
@register("knn")class KNNClassifier(ClassifierMixin, BaseEstimator): """Majority vote of the k nearest training rows, with a distance strategy."""
def __init__( self, n_neighbors: int = 5, distance: Distance | str | DistanceFunc = Distance.EUCLIDEAN, ) -> None: self.n_neighbors = n_neighbors self.distance = distance # stored unchanged; resolved in fit()
def _fit(self, X: Rows, y: list[Any]) -> None: if self.n_neighbors < 1: raise ValueError(f"n_neighbors must be >= 1, got {self.n_neighbors}") self.distance_ = get_distance(self.distance) # the strategy self.X_train_ = X self.y_train_ = y self.classes_ = sorted(set(y))
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_(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: Rows) -> list[Any]: 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"""Baselines: every real model must beat them."""
from collections import Counterfrom typing import Any
from minilearn.base import BaseEstimator, ClassifierMixin, RegressorMixin, Rowsfrom minilearn.registry import register
@register("mean")class MeanRegressor(RegressorMixin, BaseEstimator): """Predict the training mean for every row."""
def _fit(self, X: Rows, y: list[float]) -> None: self.mean_ = sum(y) / len(y)
def _predict(self, X: Rows) -> list[float]: return [self.mean_ for _ in X]
@register("majority")class MajorityClassifier(ClassifierMixin, BaseEstimator): """Predict the most common training label (the smaller one on a tie)."""
def _fit(self, X: Rows, y: list[Any]) -> None: counts = Counter(y) top = max(counts.values()) self.majority_ = min(label for label, n in counts.items() if n == top)
def _predict(self, X: Rows) -> list[Any]: return [self.majority_ for _ in X]minilearn/pipeline.py: module 20’s pipeline on the template, and its builder.
"""Pipeline (module 20) and PipelineBuilder (new in module 22).
Pipeline stores `steps` unchanged and validates them in fit(), as scikit-learndoes. PipelineBuilder runs the same check_steps() in build(), so a mistakefails before any training starts."""
from collections.abc import Iterator, Sequencefrom typing import Any, Self
from minilearn.base import BaseEstimator, Rows
type Step = tuple[str, Any]
def check_steps(steps: Sequence[Step]) -> None: if not steps: raise ValueError("a Pipeline needs at least one step") names = [name for name, _ in steps] if len(set(names)) != len(names): raise ValueError(f"step names must be unique, got {names}") for name, step in steps[:-1]: if not hasattr(step, "transform"): raise TypeError(f"step {name!r} must have a transform() method")
class Pipeline(BaseEstimator): """Named steps: transformers first, a model last. Indexable like a list."""
_requires_y = False # the last step decides whether it needs y
def __init__(self, steps: list[Step]) -> None: self.steps = steps # stored unchanged, scikit-learn style; fit() validates
@classmethod def builder(cls) -> "PipelineBuilder": return PipelineBuilder()
# --- container methods (module 20) --------------------------------- def __repr__(self) -> str: lines = [f" ({name!r}, {step!r})," for name, step in self.steps] return "Pipeline([\n" + "\n".join(lines) + "\n])"
def __len__(self) -> int: return len(self.steps)
def __getitem__(self, key: int | slice | str) -> Any: if isinstance(key, str): for name, step in self.steps: if name == key: return step raise KeyError(key) if isinstance(key, slice): return Pipeline(self.steps[key]) if isinstance(key, int): return self.steps[key][1] kind = type(key).__name__ raise TypeError(f"Pipeline indices must be int, slice or str, not {kind}")
def __iter__(self) -> Iterator[Step]: return iter(self.steps)
# --- estimator methods: the template fit() calls this hook --------- def _fit(self, X: Rows, y: list[Any] | None) -> None: check_steps(self.steps) # validation at the start of fit() for _, step in self.steps[:-1]: X = step.fit(X, y, callbacks=self._callbacks).transform(X) self[-1].fit(X, y, callbacks=self._callbacks) # the same observers
def _transform(self, X: Sequence[Sequence[float]]) -> Any: for _, step in self.steps[:-1]: X = step.transform(X) # transform only: no refit on new data return X
def predict(self, X: Sequence[Sequence[float]]) -> list[Any]: return self[-1].predict(self._transform(X))
def score(self, X: Sequence[Sequence[float]], y: Sequence[Any]) -> float: return self[-1].score(self._transform(X), y)
class PipelineBuilder: """Build a Pipeline one named step at a time: .add(...).add(...).build()."""
def __init__(self) -> None: self._steps: list[Step] = []
def add(self, name: str, step: Any) -> Self: if not name.isidentifier(): raise ValueError(f"step name {name!r} is not a valid identifier") if any(existing == name for existing, _ in self._steps): raise ValueError(f"step {name!r} was already added") self._steps.append((name, step)) return self # returning self makes the calls chainable
def build(self) -> Pipeline: check_steps(self._steps) # fail now, not later inside fit() return Pipeline(list(self._steps))minilearn/model_selection.py (module 21, unchanged) and minilearn/datasets.py (modules 18 and 20, with an injectable reader).
"""Split and train_test_split, unchanged from module 21."""
import randomfrom collections.abc import Iterator, Sequencefrom dataclasses import dataclass, fieldfrom typing import Any
type Row = Sequence[float]
@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), )"""Dataset (modules 18 and 20) and the default CSV reader that callers can replace.
New in module 22: from_records() holds the parsing, and from_csv() takes thereader as an injected keyword argument, so a test can pass records in memory."""
import csvfrom collections.abc import Callable, Iteratorfrom typing import Any, Self
type Records = list[dict[str, str]]
def read_csv_records(path: str) -> Records: with open(path, encoding="utf-8", newline="") as f: return list(csv.DictReader(f))
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[Any], 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_records( cls, records: Records, target: str, features: list[str], skip_missing: bool = False, ) -> Self: """Build a Dataset from dicts, such as the rows of csv.DictReader.""" header = list(records[0]) if records else [] missing = [name for name in [*features, target] if name not in header] if missing: raise ValueError(f"unknown columns {missing}") X: list[list[float]] = [] y: list[Any] = [] for line, row in enumerate(records, 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)
@classmethod def from_csv( cls, path: str, target: str, features: list[str], skip_missing: bool = False, *, read: Callable[[str], Records] = read_csv_records, ) -> Self: """Load the feature and target columns of a CSV file with an injected reader.""" return cls.from_records(read(path), target, features, skip_missing)
def column(self, name: str) -> list[float]: 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], Any]]: yield from zip(self.X, self.y, strict=True)minilearn/__init__.py: importing the package registers every model.
"""minilearn: a tiny scikit-learn-like library in pure Python (module 22).
Importing the package imports every estimator module, and each moduleregisters its classes. So make_model() knows every model after`import minilearn`."""
from minilearn.base import ( BaseEstimator, ClassifierMixin, NotFittedError, RegressorMixin, TransformerMixin, check_is_fitted,)from minilearn.callbacks import Callback, EarlyStopping, FitLogger, Historyfrom minilearn.datasets import Dataset, read_csv_recordsfrom minilearn.distances import Distance, euclidean, get_distance, manhattanfrom minilearn.dummy import MajorityClassifier, MeanRegressorfrom minilearn.linear_model import GradientDescentRegressor, LinearRegressionfrom minilearn.metrics import ( ClassificationReport, ClassMetrics, accuracy_score, classification_report, confusion_matrix, mean_squared_error, r2_score, root_mean_squared_error,)from minilearn.model_selection import Split, train_test_splitfrom minilearn.neighbors import KNNClassifier, Neighborfrom minilearn.pipeline import Pipeline, PipelineBuilder, check_stepsfrom minilearn.preprocessing import StandardScalerfrom minilearn.registry import available_models, make_model, register
__all__ = [ "BaseEstimator", "Callback", "ClassMetrics", "ClassificationReport", "ClassifierMixin", "Dataset", "Distance", "EarlyStopping", "FitLogger", "GradientDescentRegressor", "History", "KNNClassifier", "LinearRegression", "MajorityClassifier", "MeanRegressor", "Neighbor", "NotFittedError", "Pipeline", "PipelineBuilder", "RegressorMixin", "Split", "StandardScaler", "TransformerMixin", "accuracy_score", "available_models", "check_is_fitted", "check_steps", "classification_report", "confusion_matrix", "euclidean", "get_distance", "make_model", "manhattan", "mean_squared_error", "r2_score", "read_csv_records", "register", "root_mean_squared_error", "train_test_split",]run_minilearn.py: the experiments as data, and main() as the composition root.
"""End-to-end minilearn run on customer churn and house prices.
Each experiment is plain data (it could live in a JSON file). The factorybuilds the models by name, the builder assembles the pipeline, a callbacklogs every training step, and the reader and the logger are injected.Hyperparameters are chosen on a validation part of the training rows; thetest rows are scored once, at the end."""
import itertoolsfrom collections.abc import Callablefrom typing import Any
from minilearn import ( Dataset, FitLogger, Pipeline, Split, classification_report, confusion_matrix, make_model, r2_score, read_csv_records, root_mean_squared_error, train_test_split,)
type Log = Callable[[str], None]type Reader = Callable[[str], list[dict[str, str]]]
EXPERIMENTS: list[dict[str, Any]] = [ { "name": "churn", "task": "classification", "path": "data/customers.csv", "target": "churned", "features": ["tenure_months", "logins_last_30d"], "every": 4, # every 4th customer: 1,250 rows, as in module 21 "split": {"kind": "random", "test_size": 0.25, "random_state": 42}, "steps": [["scale", "scaler", {}], ["model", "knn", {}]], "search": {"n_neighbors": [1, 5, 15], "distance": ["euclidean", "manhattan"]}, "baseline": "majority", }, { "name": "houses", "task": "regression", "path": "data/houses.csv", "target": "price", "features": ["sqft"], "every": 1, "split": {"kind": "time", "n_train": 2400}, # test on the newest sales "steps": [["scale", "scaler", {}], ["model", "linear", {}]], "search": {}, "baseline": "mean", },]
# --- splits: a strategy dict, one function per kind ------------------------def random_split(data: Dataset, cfg: dict[str, Any]) -> Split: return train_test_split( data.X, data.y, test_size=cfg["test_size"], random_state=cfg["random_state"], stratify=data.y, )
def time_split(data: Dataset, cfg: dict[str, Any]) -> Split: old, new = data.split_at(cfg["n_train"]) # module 18: keeps the order return Split( X_train=tuple(map(tuple, old.X)), X_test=tuple(map(tuple, new.X)), y_train=tuple(old.y), y_test=tuple(new.y), )
SPLITS = {"random": random_split, "time": time_split}
# --- building and choosing a pipeline --------------------------------------def build_pipeline(steps: list[list[Any]], **model_params: Any) -> Pipeline: builder = Pipeline.builder() for name, model_name, params in steps: if name == "model": params = params | model_params builder.add(name, make_model(model_name, **params)) return builder.build()
def churn_f1(y_true: list[Any], y_pred: list[Any]) -> float: return classification_report(y_true, y_pred).classes[-1].f1 # the class 1
def choose_params(cfg: dict[str, Any], split: Split, log: Log) -> dict[str, Any]: """Grid search on a validation part carved out of the training part.""" grid = cfg["search"] if not grid: return {} X, _, y, _ = split X_fit, X_val, y_fit, y_val = train_test_split( X, y, test_size=0.25, random_state=0, stratify=y ) scores = {} for values in itertools.product(*grid.values()): params = dict(zip(grid, values, strict=True)) pipe = build_pipeline(cfg["steps"], **params).fit(X_fit, y_fit) scores[tuple(values)] = churn_f1(list(y_val), pipe.predict(X_val)) best = max(scores, key=scores.get) # ties: the first candidate chosen = dict(zip(grid, best, strict=True)) log(f"chosen on validation ({len(X_val)} rows): {chosen}, F1 {scores[best]:.3f}") return chosen
# --- reports: a strategy dict, one function per task -----------------------def report_classification( y_true: list[Any], pred: list[Any], base: list[Any], log: Log) -> float: log(f"confusion matrix (rows = true 0/1): {confusion_matrix(y_true, pred)}") log(str(classification_report(y_true, pred))) base_report = classification_report(y_true, base) churners = base_report.classes[-1] accuracy = base_report.accuracy log(f"baseline: accuracy {accuracy:.3f}, churn recall {churners.recall:.3f}") return churn_f1(y_true, pred)
def report_regression( y_true: list[float], pred: list[float], base: list[float], log: Log) -> float: log(f"R² {r2_score(y_true, pred):.3f} (baseline {r2_score(y_true, base):.3f})") rmse = root_mean_squared_error(y_true, pred) rmse_base = root_mean_squared_error(y_true, base) log(f"RMSE {rmse:,.0f} (baseline {rmse_base:,.0f})") return r2_score(y_true, pred)
REPORTS = {"classification": report_classification, "regression": report_regression}
def run_experiment(cfg: dict[str, Any], read: Reader, log: Log) -> float: raw = Dataset.from_csv(cfg["path"], cfg["target"], cfg["features"], read=read) if cfg["task"] == "classification": raw = Dataset(raw.X, [int(v) for v in raw.y], raw.feature_names) # 0/1 data = raw[:: cfg["every"]] split = SPLITS[cfg["split"]["kind"]](data, cfg["split"]) log(f"== {cfg['name']} ==") log(f"{data!r}") log(f"{split!r}")
params = choose_params(cfg, split, log) pipeline = build_pipeline(cfg["steps"], **params) pipeline.fit(split.X_train, split.y_train, callbacks=[FitLogger(log)]) baseline = make_model(cfg["baseline"]).fit(split.X_train, split.y_train)
y_test = list(split.y_test) pred = pipeline.predict(split.X_test) # the test rows, scored once return REPORTS[cfg["task"]](y_test, pred, baseline.predict(split.X_test), log)
def main( read: Reader = read_csv_records, log: Log = print, experiments: list[dict[str, Any]] = EXPERIMENTS,) -> dict[str, float]: return {cfg["name"]: run_experiment(cfg, read, log) for cfg in experiments}
if __name__ == "__main__": main()Run it from the project folder:
python run_minilearn.py== churn ==Dataset(n_samples=1250, features=['tenure_months', 'logins_last_30d'])Split(n_train=938, n_test=312)chosen on validation (234 rows): {'n_neighbors': 1, 'distance': 'manhattan'}, F1 0.368fit Pipeline: 938 rows x 2 features fit StandardScaler: 938 rows x 2 features learned mean_, n_features_in_, scale_ fit KNNClassifier: 938 rows x 2 features learned X_train_, classes_, distance_, n_features_in_, y_train_ learned n_features_in_confusion matrix (rows = true 0/1): [[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 312weighted avg 0.710 0.696 0.702 312baseline: accuracy 0.821, churn recall 0.000== houses ==Dataset(n_samples=3000, features=['sqft'])Split(n_train=2400, n_test=600)fit Pipeline: 2400 rows x 1 features fit StandardScaler: 2400 rows x 1 features learned mean_, n_features_in_, scale_ fit LinearRegression: 2400 rows x 1 features learned coef_, intercept_, n_features_in_ learned n_features_in_R² 0.561 (baseline -0.014)RMSE 229,936 (baseline 349,424)test_minilearn.py: the suite. It passes fakes to main(), so it never opens a data file.
"""Tests for the assembled minilearn. Run: python -m pytest -q test_minilearn.py"""
import copy
import pytest
from minilearn import ( Distance, EarlyStopping, GradientDescentRegressor, History, KNNClassifier, LinearRegression, NotFittedError, Pipeline, StandardScaler, available_models, make_model, register,)from minilearn.dummy import MeanRegressorfrom run_minilearn import EXPERIMENTS, main
X_SMALL = [[0.0], [1.0], [2.0], [10.0], [11.0], [12.0]]Y_SMALL = [0, 0, 0, 1, 1, 1]
def test_factory_builds_registered_models_by_name(): assert make_model("knn", n_neighbors=3) == KNNClassifier(n_neighbors=3) assert available_models() == ["gd", "knn", "linear", "majority", "mean", "scaler"]
def test_factory_lists_the_known_names_for_a_typo(): with pytest.raises(ValueError, match="unknown model 'kn'; choose from: gd, knn"): make_model("kn")
def test_register_rejects_another_class_under_a_taken_name(): with pytest.raises(ValueError, match="'mean' is already used by MeanRegressor"): register("mean")(StandardScaler)
def test_register_accepts_the_same_class_again(): # a rerun notebook cell or importlib.reload() defines the class a second time assert register("mean")(MeanRegressor) is MeanRegressor
@pytest.mark.parametrize("name", available_models())def test_template_method_validates_input_for_every_model(name): with pytest.raises(ValueError, match="row 1 has length 2, expected 1"): make_model(name).fit([[1.0], [2.0, 3.0]], [0, 1])
@pytest.mark.parametrize("name", ["gd", "knn", "linear", "majority", "mean"])def test_predict_before_fit_raises_not_fitted(name): with pytest.raises(NotFittedError, match="is not fitted yet; call fit"): make_model(name).predict([[1.0]])
def test_knn_accepts_a_name_a_member_or_any_function(): calls = []
def recorded(a, b): calls.append(1) return abs(a[0] - b[0])
knn = KNNClassifier(n_neighbors=3, distance=recorded).fit(X_SMALL, Y_SMALL) assert knn.predict([[1.5], [10.5]]) == [0, 1] assert len(calls) == 2 * len(X_SMALL) by_name = KNNClassifier(distance="manhattan").fit(X_SMALL, Y_SMALL) assert by_name.get_params()["distance"] == "manhattan" assert by_name.kneighbors([0.4])[0].index == 0 assert Distance.MANHATTAN.between([0, 0], [3, 4]) == 7 with pytest.raises(ValueError, match="unknown distance 'cosine'"): KNNClassifier(distance="cosine").fit(X_SMALL, Y_SMALL)
def test_callbacks_observe_the_pipeline_and_every_step_in_order(): history = History() pipe = Pipeline([("scale", StandardScaler()), ("model", KNNClassifier(3))]) pipe.fit(X_SMALL, Y_SMALL, callbacks=[history]) names = [f"{event} {name}" for event, name in history.events] assert names == [ "start Pipeline", "start StandardScaler", "end StandardScaler", "start KNNClassifier", "end KNNClassifier", "end Pipeline", ]
def test_early_stopping_works_through_the_template(): x = [[v] for v in (-1.5, -0.5, 0.5, 1.5)] y = [1.0, 2.0, 3.0, 4.0] history, stop = History(), EarlyStopping(min_delta=1e-6, patience=2) gd = GradientDescentRegressor(learning_rate=0.1, max_epochs=1000) gd.fit(x, y, callbacks=[history, stop]) assert gd.n_epochs_ < 1000 and len(history.losses) == gd.n_epochs_ assert gd.coef_ == pytest.approx(1.0, abs=1e-3)
def test_pipeline_stores_steps_unchanged_and_validates_in_fit(): steps = [("model", LinearRegression()), ("scale", StandardScaler())] pipe = Pipeline(steps) # no error yet: scikit-learn style assert pipe.steps is steps and pipe.get_params() == {"steps": steps} with pytest.raises(TypeError, match="step 'model' must have a transform"): pipe.fit([[1.0], [2.0]], [1.0, 2.0])
def test_builder_checks_each_step_early(): builder = Pipeline.builder().add("scale", StandardScaler()) with pytest.raises(ValueError, match="already added"): builder.add("scale", StandardScaler()) builder.add("model", LinearRegression()).add("again", StandardScaler()) with pytest.raises(TypeError, match="step 'model' must have a transform"): builder.build()
def test_pipeline_behaves_like_a_container(): pipe = ( Pipeline.builder() .add("scale", StandardScaler()) .add("model", LinearRegression()) .build() ) assert len(pipe) == 2 assert [name for name, _ in pipe] == ["scale", "model"] assert pipe["model"] is pipe[-1] assert len(pipe[:1]) == 1 assert repr(pipe).startswith("Pipeline([\n ('scale', StandardScaler(")
def test_main_runs_with_an_injected_reader_and_logger(): customers = [ {"tenure_months": str(t), "logins_last_30d": str(t % 7), "churned": str(t % 2)} for t in range(80) ] houses = [{"sqft": str(1000 + 10 * i), "price": str(200 + i)} for i in range(20)]
def fake_read(path): return customers if path.endswith("customers.csv") else houses
experiments = copy.deepcopy(EXPERIMENTS) experiments[1]["split"]["n_train"] = 15 # 20 fake houses, not 3,000 lines = [] scores = main(read=fake_read, log=lines.append, experiments=experiments) assert set(scores) == {"churn", "houses"} assert scores["houses"] == pytest.approx(1.0) # price is exactly linear in sqft assert lines[:3] == [ "== churn ==", "Dataset(n_samples=20, features=['tenure_months', 'logins_last_30d'])", "Split(n_train=15, n_test=5)", ] assert sum(line.lstrip().startswith("fit ") for line in lines) == 6python -m pytest -q test_minilearn.pypython -c "import minilearn; print(minilearn.available_models())"...................... [100%]22 passed in 0.03s['gd', 'knn', 'linear', 'majority', 'mean', 'scaler']How it works:
- One template, many hooks.
BaseEstimator.fit()is the onlyfit()in the package, and@finallets a type checker report any override. Each estimator writes_fit()and_predict()or_transform(), so the input checks and the callbacks behave the same for every model. The parametrized test proves it for every name in the registry.GradientDescentRegressor._fit()sends its epoch events with_notify_epoch(), soEarlyStoppingworks without an override. - The registry fills itself.
import minilearnruns__init__.py, which importspreprocessing,linear_model,neighborsanddummy. Each@registerline runs with itsclassstatement.run_minilearn.pynever imports a model class: it only knows names. - Strategies are functions.
distances.pyholds two functions and a dict. Module 21’smatchinbetween()became one dict lookup, sobetween()still works. The test passes a function that counts its calls: 2 test rows × 6 training rows = 12 distance calls. - The pipeline is an estimator.
Pipelinestoresstepsunchanged and checks them infit(), as scikit-learn and module 20 do, soget_params(),==andclone()work on it. The builder runs the samecheck_steps()earlier, inbuild().FitLoggershows the nesting: the pipeline’s fit contains its steps’ fits. - Selection on validation, test once.
choose_params()carves a validation part out of the training rows (module 21’s second split) and tries the six KNN settings there. Only the chosen settings are refitted on all 938 training rows and scored on the 312 test rows. The test rows play no part in the choice, so their score is an honest estimate. - Injection makes
main()testable. The test’s fake reader returns 80 customer records and 20 houses whose price is exactly linear insqft, so the regression must score R² = 1.0. The logger islines.append, and the test counts thefitlines: two experiments × (one pipeline + two steps). - Interpretation. These are the numbers of the module 21 project: the same rows, the same seeds and the same choice (k = 1, Manhattan, churn F1 0.368 on validation). The refactoring changed the design, not the results. On the test part, KNN finds 12 of the 56 churners (recall 0.214, F1 0.202), while the majority baseline has the higher accuracy (0.821) and finds none. On the house data, the line explains 56% of the price variance (R² 0.561) and cuts the RMSE from about 349,000 to 230,000 USD. Two churn features are not enough: module 33 builds better features, and module 36 chooses a decision threshold.
Alternative: you could keep one file, minilearn.py, with all classes in it, and the patterns would work the same. The package wins once the code is too long to read in one sitting, or once other projects import parts of it. A different split is fine too, as long as each module has one job and __init__.py imports every module that registers a model.