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:
Vector: an immutable vector with+,-,*(by a number, on either side),abs()and@.KNNClassifiermeasures its distances with it:abs(a - b).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 pipeand a readableprint(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
import csvimport inspectimport mathfrom collections import Counterfrom collections.abc import Iterable, Iteratorfrom 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)Dataset
Section titled “Dataset”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.
Requirements
Section titled “Requirements”Vector must:
- Store its components as a tuple of floats, so a vector never changes. An empty vector raises
ValueError. - Have
__repr__(Vector([3.0, 4.0])),__len__,__iter__,__getitem__,__eq__and__hash__. - Support
u + vandu - vfor vectors of the same length (ValueErrorotherwise),v * 2,2 * v,v / 2,abs(v)(the Euclidean norm) andu @ v(the dot product). - Return
NotImplementedfor operands it does not support, so Python raises the usualTypeError. - 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:
- Inherit from
BaseEstimatorand take one argument,steps: a list of(name, estimator)pairs. - Store
stepsunchanged in__init__, as everyminilearnestimator stores its arguments. The checks run at the start offit(), as in scikit-learn: an empty list or duplicate names raiseValueError, and a non-last step withouttransform()raisesTypeError. - Have
fit(X, y)(fit-transform each transformer, then fit the last step, returnself),predict(X)andscore(X, y). - Support
len(pipe);pipe[i]for an integer, negative ones too, returning the estimator;pipe["name"]returning the estimator or raisingKeyError;pipe[a:b]returning a newPipeline; any other key type raisesTypeError. - Support
for name, step in pipe. - Print as valid Python, one step per line, so a long pipeline stays readable.
Step plan
Section titled “Step plan”-
Paste the base code. Copy the collapsed block above into your script and run it. It prints nothing.
-
Write
Vectorstorage and display. Storetuple(float(c) for c in components). Write__repr__,__len__,__iter__and__getitem__. Checkprint(Vector([3, 4])). -
Add equality and hashing. Compare and hash the tuple. Check
len({Vector([1, 2]), Vector([1, 2])}) == 1. -
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__forsum(). Checkabs(Vector([3, 4])) == 5.0and2 * Vector([1, 1]). -
Switch KNN to vectors. In
fit(), store[Vector(row) for row in X]. In_predict_one(), buildquery = Vector(row)and sort byabs(self.X_train_[i] - query). Keep the index as the tie breaker. -
Write
Pipeline.__init__and_validate_steps().__init__only storesself.steps = steps._validate_steps()raises the errors of requirement 2, andfit()calls it first. Thenset_params(steps=[])cannot slip past the checks either. -
Write the container methods.
__len__and__iter__delegate toself.steps.__getitem__testsstr, thenslice, thenint, then raisesTypeError. -
Write
fit,predictandscore. Infit, pass the output of eachfit_transformon to the next step.predictandscoreruntransform(notfit_transform!) on every step but the last. -
Write
__repr__. Build one line per step withf" ({name!r}, {step!r}),", then wrap the lines inPipeline([and]). -
Run the demo in the reference solution and compare your output.
A skeleton to start from:
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, scoreRubric
Section titled “Rubric”| 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 |
Stretch goals
Section titled “Stretch goals”- Add
__contains__toPipeline, so that"scale" in pipechecks 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). - Support nested parameters, as scikit-learn does:
pipe.get_params()also returns"knn__n_neighbors": 15, andpipe.set_params(knn__n_neighbors=5)changes the step. - Give
Pipelinea__call__that meanspredict, like the lesson’sCallableMixin. - Add
Vector.__neg__andVector.__rmatmul__, and explain why__rmatmul__is never called when both operands are vectors. - Time
KNNClassifier.predictwithmath.distand withVector(module 15’stimeit). TheVectorversion is slower: everya - bbuilds a new object. Module 23 shows how NumPy removes that cost.
Reference solution
Section titled “Reference solution”Try the project yourself first. Then compare with this solution. Your names can differ; your output must not.
Reference solution
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}")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]) TrueValueError: vector lengths differ: 2 and 3TypeError: unsupported operand type(s) for *: 'Vector' and 'Vector'ValueError: a Vector needs at least one componentBuild 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/1train, 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])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 -> KNNClassifierPipeline([ ('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())]))accuracy 0.845scaler means: [23.107, 11.552][1, 0]R2 0.561 224225TrueWrong 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.stepsassert 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 pipeKeyError: 'svm'IndexError: list index out of rangeTypeError: Pipeline indices must be int, slice or str, not floatValueError: a Pipeline needs at least one stepValueError: step names must be unique, got ['knn', 'knn']TypeError: step 'model' must have a transform() methodHow it works:
- Vector. The components live in a tuple, so
__hash__is safe._pairs()is the single place that checks the lengths. Every operator returns a newVectororNotImplemented.isinstance(scalar, bool)rejectsv * True, which Python would otherwise treat asv * 1. - Reflected operators.
2 * vreaches__rmul__, which is the same function as__mul__.sum([u, v, v])starts with0 + u, which reaches__radd__. - KNN.
abs(self.X_train_[i] - query)reads like the formula . The predictions and the accuracy (0.845) are the same as withmath.distin the lesson. - Pipeline as a container.
__getitem__checksstr,sliceandintin turn. An integer past the end raisesIndexErrorfrom the list itself. A slice returns a newPipelinethat holds the same estimator objects, sopipe[:1]afterfitholds the fitted scaler. - Pipeline as a model.
__init__stores the list unchanged, soget_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 offit(). The error demo shows thatPipeline([])builds fine and fails only when you fit it.fitthen passes the output of eachfit_transformto the next step.predictandscoreonly calltransform, so the scaler keeps the training means 23.107 and 11.552 that it learned infit. - Equality for free.
Pipelineinherits__eq__fromBaseEstimator. Its only parameter issteps, a list of pairs, and lists compare item by item, so two pipelines with equal steps are equal. The fittedregequals an unfitted copy, because__eq__compares parameters, not learned attributes. - 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.