Skip to content

20. The Python data model — Mini-project

minilearn is the small scikit-learn-like library that you build across Part 3. After modules 18 and 19, it has a Dataset, metric functions, a BaseEstimator with get_params() and set_params(), the mixins, a StandardScaler, a one-feature LinearRegression and a KNNClassifier. The lesson of this module added __repr__ and __eq__ to BaseEstimator and container methods to Dataset.

This increment adds two classes that make minilearn feel like a real library:

  1. Vector: an immutable vector with +, -, * (by a number, on either side), abs() and @. KNNClassifier measures its distances with it: abs(a - b).
  2. Pipeline: a chain of named steps, such as a scaler and then a model, that you fit and score as one model. It behaves like a list of steps: len(pipe), pipe[0], pipe[-1], pipe["knn"], pipe[:1], for name, step in pipe and a readable print(pipe).

scikit-learn’s Pipeline supports the same indexing: pipe[0], pipe["scaler"] and pipe[:-1]. Module 34 uses it.

The page runs on its own. The block below restates the minilearn code that this project needs, copied unchanged from modules 18 and 19, plus the __repr__ and __eq__ of BaseEstimator and the container methods of Dataset from this module’s lesson. It leaves out MeanRegressor and MajorityClassifier, which the project does not use, and KNNClassifier, which the project rewrites. Paste it at the top of your script, or into a file minilearn_base.py that you import.

minilearn so far: metrics, base classes, StandardScaler, LinearRegression and Dataset
minilearn_base.py
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)

Two course files, the same ones that modules 18 and 19 use:

File Features Target Split
data/customers.csv tenure_months, logins_last_30d churned (0 or 1) train: every 5th customer (1,000 rows); test: every 25th customer, starting at row 2 (200 rows)
data/houses.csv sqft price train: the first 2,400 sales; test: the last 600 sales (the file is sorted by date)

The churn rate is 18.7% in the training slice and 18.0% in the test slice, close to the 19.3% of the whole file. Tenure (0 to 72 months) and logins (0 to 60) have different spreads, so the KNN model needs a scaler in front of it. That makes the scaler and the model a natural pipeline.

Vector must:

  1. Store its components as a tuple of floats, so a vector never changes. An empty vector raises ValueError.
  2. Have __repr__ (Vector([3.0, 4.0])), __len__, __iter__, __getitem__, __eq__ and __hash__.
  3. Support u + v and u - v for vectors of the same length (ValueError otherwise), v * 2, 2 * v, v / 2, abs(v) (the Euclidean norm) and u @ v (the dot product).
  4. Return NotImplemented for operands it does not support, so Python raises the usual TypeError.
  5. Support sum(vectors).

KNNClassifier must store the training rows as Vector objects and compute each distance as abs(train_row - query). Its predictions must not change.

Pipeline must:

  1. Inherit from BaseEstimator and take one argument, steps: a list of (name, estimator) pairs.
  2. Store steps unchanged in __init__, as every minilearn estimator stores its arguments. The checks run at the start of fit(), as in scikit-learn: an empty list or duplicate names raise ValueError, and a non-last step without transform() raises TypeError.
  3. Have fit(X, y) (fit-transform each transformer, then fit the last step, return self), predict(X) and score(X, y).
  4. Support len(pipe); pipe[i] for an integer, negative ones too, returning the estimator; pipe["name"] returning the estimator or raising KeyError; pipe[a:b] returning a new Pipeline; any other key type raises TypeError.
  5. Support for name, step in pipe.
  6. Print as valid Python, one step per line, so a long pipeline stays readable.
  1. Paste the base code. Copy the collapsed block above into your script and run it. It prints nothing.

  2. Write Vector storage and display. Store tuple(float(c) for c in components). Write __repr__, __len__, __iter__ and __getitem__. Check print(Vector([3, 4])).

  3. Add equality and hashing. Compare and hash the tuple. Check len({Vector([1, 2]), Vector([1, 2])}) == 1.

  4. Add the operators. Write one helper that checks the lengths and pairs the components. Then __add__, __sub__, __mul__, __rmul__ = __mul__, __truediv__, __matmul__ and __abs__. Add __radd__ for sum(). Check abs(Vector([3, 4])) == 5.0 and 2 * Vector([1, 1]).

  5. Switch KNN to vectors. In fit(), store [Vector(row) for row in X]. In _predict_one(), build query = Vector(row) and sort by abs(self.X_train_[i] - query). Keep the index as the tie breaker.

  6. Write Pipeline.__init__ and _validate_steps(). __init__ only stores self.steps = steps. _validate_steps() raises the errors of requirement 2, and fit() calls it first. Then set_params(steps=[]) cannot slip past the checks either.

  7. Write the container methods. __len__ and __iter__ delegate to self.steps. __getitem__ tests str, then slice, then int, then raises TypeError.

  8. Write fit, predict and score. In fit, pass the output of each fit_transform on to the next step. predict and score run transform (not fit_transform!) on every step but the last.

  9. Write __repr__. Build one line per step with f" ({name!r}, {step!r}),", then wrap the lines in Pipeline([ and ]).

  10. Run the demo in the reference solution and compare your output.

A skeleton to start from:

minilearn_m20.py (starter)
class Vector:
"""An immutable vector of floats: +, -, * (by a number), abs() and @."""
def __init__(self, components: Iterable[float]) -> None:
... # TODO: store a tuple of floats; reject an empty vector
# TODO: __repr__, __len__, __iter__, __getitem__, __eq__, __hash__
# TODO: __add__, __radd__, __sub__, __mul__, __rmul__, __truediv__, __matmul__, __abs__
class KNNClassifier(ClassifierMixin, BaseEstimator):
... # TODO: the module 19 class, with Vector distances
class Pipeline(BaseEstimator):
def __init__(self, steps: list[tuple[str, Any]]) -> None:
self.steps = steps # stored unchanged; fit() validates
# TODO: _validate_steps (empty, duplicate names, missing transform())
# TODO: __repr__, __len__, __getitem__, __iter__
# TODO: fit (validate first), predict, score
Criterion Points Full points when
Vector display and equality 2 repr rebuilds the vector; equal vectors are equal and hash alike
Vector arithmetic 3 +, -, * on both sides, /, @, abs() and sum() give the right results
Operator errors 2 different lengths raise ValueError; unsupported operands return NotImplemented
KNN with vectors 2 distances use abs(a - b); accuracy on the test slice is 0.845
Pipeline container 3 len, positive and negative indexes, names, slices and iteration work; wrong keys raise KeyError, IndexError or TypeError
Pipeline model 3 fit returns self; predict and score use transform only; the house pipeline gives R² 0.561
Validation 1 __init__ stores steps unchanged; fit() rejects empty, duplicate and non-transformer steps with a clear message
Readability 2 type hints, docstrings, a multi-line repr that is valid Python
Total 18 15 or more: you are ready for module 21
  1. Add __contains__ to Pipeline, so that "scale" in pipe checks the step names. Note that it then disagrees with __iter__, which yields pairs; decide whether that is acceptable and write down why (a dict makes the same choice for its keys).
  2. Support nested parameters, as scikit-learn does: pipe.get_params() also returns "knn__n_neighbors": 15, and pipe.set_params(knn__n_neighbors=5) changes the step.
  3. Give Pipeline a __call__ that means predict, like the lesson’s CallableMixin.
  4. Add Vector.__neg__ and Vector.__rmatmul__, and explain why __rmatmul__ is never called when both operands are vectors.
  5. Time KNNClassifier.predict with math.dist and with Vector (module 15’s timeit). The Vector version is slower: every a - b builds a new object. Module 23 shows how NumPy removes that cost.

Try the project yourself first. Then compare with this solution. Your names can differ; your output must not.

Reference solution
minilearn_m20.py
class Vector:
"""An immutable vector of floats: +, -, * (by a number), abs() and @."""
def __init__(self, components: Iterable[float]) -> None:
self._components = tuple(float(c) for c in components)
if not self._components:
raise ValueError("a Vector needs at least one component")
def __repr__(self) -> str:
return f"Vector({list(self._components)!r})"
def __len__(self) -> int:
return len(self._components)
def __iter__(self) -> Iterator[float]:
return iter(self._components)
def __getitem__(self, index: int) -> float:
return self._components[index]
def __eq__(self, other: object) -> bool:
if not isinstance(other, Vector):
return NotImplemented
return self._components == other._components
def __hash__(self) -> int:
return hash(self._components)
def _pairs(self, other: "Vector") -> Iterator[tuple[float, float]]:
if len(self) != len(other):
raise ValueError(f"vector lengths differ: {len(self)} and {len(other)}")
return zip(self, other)
def __add__(self, other: object) -> "Vector":
if not isinstance(other, Vector):
return NotImplemented
return Vector(a + b for a, b in self._pairs(other))
def __radd__(self, other: object) -> "Vector":
return self if other == 0 else NotImplemented # the start value of sum()
def __sub__(self, other: object) -> "Vector":
if not isinstance(other, Vector):
return NotImplemented
return Vector(a - b for a, b in self._pairs(other))
def __mul__(self, scalar: object) -> "Vector":
if isinstance(scalar, bool) or not isinstance(scalar, int | float):
return NotImplemented
return Vector(a * scalar for a in self)
__rmul__ = __mul__ # 2 * v is the same as v * 2
def __truediv__(self, scalar: object) -> "Vector":
if isinstance(scalar, bool) or not isinstance(scalar, int | float):
return NotImplemented
return Vector(a / scalar for a in self)
def __matmul__(self, other: object) -> float:
if not isinstance(other, Vector):
return NotImplemented
return sum(a * b for a, b in self._pairs(other))
def __abs__(self) -> float:
return math.sqrt(self @ self)
class KNNClassifier(ClassifierMixin, BaseEstimator):
"""Majority vote of the k nearest training rows, with Vector distances."""
def __init__(self, n_neighbors: int = 5) -> None:
self.n_neighbors = n_neighbors
def fit(self, X: list[list[float]], y: list[Any]) -> Self:
if self.n_neighbors < 1:
raise ValueError(f"n_neighbors must be >= 1, got {self.n_neighbors}")
self.X_train_ = [Vector(row) for row in X]
self.y_train_ = list(y)
self.classes_ = sorted(set(y))
return self
def _predict_one(self, row: list[float]) -> Any:
query = Vector(row)
def distance(i: int) -> tuple[float, int]:
return abs(self.X_train_[i] - query), i # ties: lower index first
nearest = sorted(range(len(self.X_train_)), key=distance)
votes = Counter(self.y_train_[i] for i in nearest[: self.n_neighbors])
return max(self.classes_, key=lambda label: votes[label])
def predict(self, X: list[list[float]]) -> list[Any]:
check_is_fitted(self)
return [self._predict_one(row) for row in X]
class Pipeline(BaseEstimator):
"""Named steps: transformers first, a model last. Indexable like a list."""
def __init__(self, steps: list[tuple[str, Any]]) -> None:
self.steps = steps # stored unchanged, scikit-learn style; fit() validates
def _validate_steps(self) -> None:
if not self.steps:
raise ValueError("a Pipeline needs at least one step")
names = [name for name, _ in self.steps]
if len(set(names)) != len(names):
raise ValueError(f"step names must be unique, got {names}")
for name, step in self.steps[:-1]:
if not hasattr(step, "transform"):
raise TypeError(f"step {name!r} must have a transform() method")
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] # IndexError past the end, from the list
kind = type(key).__name__
raise TypeError(f"Pipeline indices must be int, slice or str, not {kind}")
def __iter__(self) -> Iterator[tuple[str, Any]]:
return iter(self.steps)
def _transform(self, X: list[list[float]]) -> list[list[float]]:
for _, step in self.steps[:-1]:
X = step.transform(X) # transform only: no refit on new data
return X
def fit(self, X: list[list[float]], y: list[Any]) -> Self:
self._validate_steps() # checks at the start of fit(), as in module 19
for _, step in self.steps[:-1]:
X = step.fit_transform(X, y)
self[-1].fit(X, y)
return self
def predict(self, X: list[list[float]]) -> list[Any]:
return self[-1].predict(self._transform(X))
def score(self, X: list[list[float]], y: list[Any]) -> float:
return self[-1].score(self._transform(X), y)

Check the vector arithmetic first:

u, v = Vector([3, 4]), Vector([1, 1])
print(u + v, u - v, 2 * v, u * 0.5, u / 2)
print(abs(u), u @ v, sum([u, v, v]), u == Vector([3.0, 4.0]))
for bad in (lambda: u + Vector([1, 2, 3]), lambda: u * v, lambda: Vector([])):
try:
bad()
except (ValueError, TypeError) as error:
print(f"{type(error).__name__}: {error}")
Output
Vector([4.0, 5.0]) Vector([2.0, 3.0]) Vector([2.0, 2.0]) Vector([1.5, 2.0]) Vector([1.5, 2.0])
5.0 7.0 Vector([5.0, 6.0]) True
ValueError: vector lengths differ: 2 and 3
TypeError: unsupported operand type(s) for *: 'Vector' and 'Vector'
ValueError: a Vector needs at least one component

Build the churn pipeline and use it like a list:

raw = Dataset.from_csv(
"data/customers.csv",
target="churned",
features=["tenure_months", "logins_last_30d"],
)
customers = Dataset(raw.X, [int(v) for v in raw.y], raw.feature_names) # 0/1
train, test = customers[::5], customers[2::25]
pipe = Pipeline([("scale", StandardScaler()), ("knn", KNNClassifier(n_neighbors=15))])
print(pipe)
print(len(pipe), pipe[0], pipe[-1], pipe["knn"] is pipe[1])
for name, step in pipe:
print(f"{name:>6} -> {type(step).__name__}")
print(pipe[:1])
Output
Pipeline([
('scale', StandardScaler(with_mean=True, with_std=True)),
('knn', KNNClassifier(n_neighbors=15)),
])
2 StandardScaler(with_mean=True, with_std=True) KNNClassifier(n_neighbors=15) True
scale -> StandardScaler
knn -> KNNClassifier
Pipeline([
('scale', StandardScaler(with_mean=True, with_std=True)),
])

Fit, score and predict:

pipe.fit(train.X, train.y)
print(f"accuracy {pipe.score(test.X, test.y):.3f}")
print("scaler means:", pipe["scale"].mean_)
print(pipe.predict([[4, 2], [48, 20]]))
houses = Dataset.from_csv("data/houses.csv", target="price", features=["sqft"])
h_train, h_test = houses[:2400], houses[2400:]
reg = Pipeline([("scale", StandardScaler()), ("linear", LinearRegression())])
reg.fit(h_train.X, h_train.y)
print(f"R2 {reg.score(h_test.X, h_test.y):.3f}", round(reg["linear"].coef_))
print(reg == Pipeline([("scale", StandardScaler()), ("linear", LinearRegression())]))
Output
accuracy 0.845
scaler means: [23.107, 11.552]
[1, 0]
R2 0.561 224225
True

Wrong keys and wrong steps:

for key in ("svm", 2, 1.5):
try:
print(pipe[key])
except (KeyError, IndexError, TypeError) as error:
print(f"{type(error).__name__}: {error}")
bad_steps = [
[],
[("knn", KNNClassifier()), ("knn", KNNClassifier())],
[("model", LinearRegression()), ("knn", KNNClassifier())],
]
for steps in bad_steps:
unchecked = Pipeline(steps) # __init__ only stores the list
try:
unchecked.fit(train.X, train.y)
except (ValueError, TypeError) as error:
print(f"{type(error).__name__}: {error}")
assert pipe.get_params()["steps"] is pipe.steps
assert abs(Vector([3, 4])) == 5.0 and 2 * Vector([1, 1]) == Vector([2, 2])
assert len(pipe[1:]) == 1 and isinstance(pipe[1:], Pipeline)
assert pipe.fit(train.X, train.y) is pipe
Output
KeyError: 'svm'
IndexError: list index out of range
TypeError: Pipeline indices must be int, slice or str, not float
ValueError: a Pipeline needs at least one step
ValueError: step names must be unique, got ['knn', 'knn']
TypeError: step 'model' must have a transform() method

How it works:

  1. Vector. The components live in a tuple, so __hash__ is safe. _pairs() is the single place that checks the lengths. Every operator returns a new Vector or NotImplemented. isinstance(scalar, bool) rejects v * True, which Python would otherwise treat as v * 1.
  2. Reflected operators. 2 * v reaches __rmul__, which is the same function as __mul__. sum([u, v, v]) starts with 0 + u, which reaches __radd__.
  3. KNN. abs(self.X_train_[i] - query) reads like the formula ∥xi−q∥\lVert x_i - q \rVert. The predictions and the accuracy (0.845) are the same as with math.dist in the lesson.
  4. Pipeline as a container. __getitem__ checks str, slice and int in turn. An integer past the end raises IndexError from the list itself. A slice returns a new Pipeline that holds the same estimator objects, so pipe[:1] after fit holds the fitted scaler.
  5. Pipeline as a model. __init__ stores the list unchanged, so get_params()["steps"] is the very list you passed, as in scikit-learn. fit() first runs _validate_steps(), the convention of modules 18 and 19: checks at the start of fit(). The error demo shows that Pipeline([]) builds fine and fails only when you fit it. fit then passes the output of each fit_transform to the next step. predict and score only call transform, so the scaler keeps the training means 23.107 and 11.552 that it learned in fit.
  6. Equality for free. Pipeline inherits __eq__ from BaseEstimator. Its only parameter is steps, a list of pairs, and lists compare item by item, so two pipelines with equal steps are equal. The fitted reg equals an unfitted copy, because __eq__ compares parameters, not learned attributes.
  7. Repr. {step!r} reuses the estimator reprs. The multi-line form is valid Python, so you could paste it back into a script.

Alternative: store the steps in a dict instead of a list of pairs. Lookup by name becomes one line, self._steps[key], but lookup by position needs list(self._steps.values())[key]. scikit-learn keeps the list of pairs (pipe.steps) and adds a dict view, pipe.named_steps.