18. Classes and objects — Mini-project
What minilearn is
Section titled “What minilearn is”minilearn is a tiny machine learning library in the style of scikit-learn, written in pure Python: no NumPy, no pandas. You build it yourself, one module at a time, through Part 3. Each mini-project of modules 18 to 22 adds one piece.
Why build a library that already exists? Because scikit-learn, PyTorch and pandas are object-oriented libraries. Every fit, transform and predict that you call later in the course is a method of a class that follows a few design rules. When you have written those classes yourself, the real libraries stop being magic. In module 34, you rebuild the same classes with NumPy on top of scikit-learn’s own base classes.
minilearn uses the data layout of scikit-learn. X is a list of rows (a list of lists of floats), one row per sample and one value per feature. y is a list with one target value per sample.
The final shape (after module 22)
Section titled “The final shape (after module 22)”minilearn/ base.py BaseEstimator, TransformerMixin, RegressorMixin, ClassifierMixin, NotFittedError, check_is_fitted datasets.py Dataset (from_csv, n_samples, n_features) preprocessing.py StandardScaler (fit, transform, inverse_transform, mean_, scale_) linear_model.py LinearRegression (one feature: coef_, intercept_) neighbors.py KNNClassifier (n_neighbors, distance strategy, majority vote) pipeline.py Pipeline (named steps, fit/predict, len, indexing, iteration) metrics.py mean_squared_error, r2_score, accuracy_score, confusion_matrixflowchart LR
M18["18 Classes<br/>Dataset, StandardScaler,<br/>LinearRegression, metrics"] --> M19["19 Inheritance<br/>BaseEstimator, mixins,<br/>KNNClassifier"]
M19 --> M20["20 Data model<br/>Pipeline, Vector,<br/>__repr__, __len__"]
M20 --> M21["21 Dataclasses<br/>Split, Distance enum,<br/>classification report"]
M21 --> M22["22 Patterns<br/>factory, callbacks,<br/>end-to-end run"]
Four rules, borrowed from scikit-learn, hold for every class:
| Rule | Example | Why |
|---|---|---|
| Constructor arguments are stored unchanged as attributes | LinearRegression(fit_intercept=False).fit_intercept is False |
settings are easy to read, copy and compare |
Learned attributes end with _ and exist only after fit |
coef_, intercept_, mean_, scale_ |
hasattr(model, "coef_") tells you if the model is fitted |
fit returns self |
LinearRegression().fit(X, y).predict(X_new) |
one-line chains |
Using a model before fit raises NotFittedError |
LinearRegression().predict(X) |
a clear message instead of an AttributeError |
What this module adds
Section titled “What this module adds”You write the first four pieces, as plain classes and functions:
Dataset, with the alternative constructorDataset.from_csv()and the read-only propertiesn_samplesandn_features. You started it in Example 4 of the lesson; here you finish it.StandardScaler, which learns the mean and the standard deviation of each feature.LinearRegressionfor one feature, fitted with the closed-form least squares formula.mean_squared_errorandr2_score.
Then you use them to answer one question: how well does the living area of a house predict its price? The script must run with one command, python train_houses.py, and its tests with python -m pytest -q.
Module 19 moves the shared code into BaseEstimator and mixin classes. Keep your names and attributes exactly as specified, so that the next module can build on them.
Dataset
Section titled “Dataset”data/houses.csv has 3,000 house sales from 2022 to 2024, sorted by sold_date. The project uses three of its columns:
| Column | Meaning | Notes |
|---|---|---|
sqft |
living area in square feet | 550 to 5,710 |
price |
sale price in USD | the target; 117,500 to 3,730,500 |
school_rating |
rating of the local school, 1 to 10 | 90 blank cells |
The rows are in time order, so the project splits them in time order too: the first 2,400 sales are the training set (the data the model learns from), and the last 600 sales are the test set (new data that measures how well the model generalizes). This mimics real use: you train on past sales and predict future ones. Module 21 adds a random train_test_split.
Requirements
Section titled “Requirements”Write a package minilearn/ in your project folder, a script train_houses.py and a test file test_minilearn.py.
minilearn/base.py: a classNotFittedErrorthat subclassesValueError.minilearn/datasets.py: a classDataset.__init__(X, y, feature_names)stores the three values. It raisesValueErrorfor an emptyX, forlen(X) != len(y)and for a row whose length is notlen(feature_names).- Read-only properties
n_samplesandn_features. - A class method
from_csv(path, target, features, skip_missing=False)that returns an instance built withcls(...). It raisesValueErrorfor an unknown column, for a value that is not a number, and for a blank cell, unlessskip_missing=True, which skips that row. Error messages name the line of the file. - A method
column(name)that returns the values of one feature, and a methodsplit_at(n_first)that returns two datasets in the original order.
minilearn/preprocessing.py: a classStandardScalerwithfit(X)(returnsself),transform(X)andinverse_transform(Z).fitlearnsmean_,scale_(the population standard deviation, or 1.0 for a constant column) andn_features_in_.transformraisesNotFittedErrorbeforefitandValueErrorfor the wrong number of features.minilearn/linear_model.py: a classLinearRegression(fit_intercept=True).fit(X, y)learnscoef_andintercept_with least squares and returnsself; it raisesValueErrorwhenXhas more than one feature.predict(X)raisesNotFittedErrorbeforefit.minilearn/metrics.py: the functionsmean_squared_error(y_true, y_pred)andr2_score(y_true, y_pred), which raiseValueErrorfor lists of different lengths.minilearn/__init__.py: exports the six public names, so a script can writefrom minilearn import Dataset.train_houses.py: loadspriceandsqft, splits at 2,400, fits the model on the training set, and prints the report below. It compares the model with a baseline that always predicts the mean training price, shows that standardizingsqftchanges the coefficient but not the predictions, and shows two protected errors. It ends withassertchecks.test_minilearn.py: at least 8 pytest tests, including an exact line (y = 2x + 1) thatLinearRegressionmust recover, and the error cases.- Type hints on every public method. Use
typing.Selfforfrom_csv,fitandsplit_at. ruff checkpasses.
The expected report:
Loaded 3000 houses, features ['sqft']Train: 2400 houses, test: 600 housesModel: price = 316.29 * sqft - 119,064Test MSE: 52,870,676,972 RMSE: 229,936 USDTest R²: 0.561 (baseline that predicts the mean: -0.014)Scaler: mean_ 1857.2 sqft, scale_ 708.9 sqftScaled model: 224,225 USD per standard deviation of sqftSame predictions after scaling: TruePredicted price for 1,500 sqft: 355,368 USDPredicted price for 2,500 sqft: 671,656 USDNotFittedError: LinearRegression is not fitted yet; call fit() firstRows kept with skip_missing=True: 2910ValueError: LinearRegression supports exactly 1 feature, got 2Step plan
Section titled “Step plan”-
Create the package. Make a folder
minilearn/with an empty__init__.py, and the filesbase.py,datasets.py,preprocessing.py,linear_model.pyandmetrics.py. Puttrain_houses.pyandtest_minilearn.pynext to the folder, not inside it (module 08). -
Write
NotFittedError. One class with a docstring inbase.py. Module 19 adds the base classes to this file. -
Write
Dataset.__init__and the properties. Start from Example 4 of the lesson. Add the empty-Xcheck and the row-width check, thenn_samplesandn_features. Test them in the REPL with a 2-row toy dataset. -
Write
Dataset.from_csv. Read withcsv.DictReader. Checkreader.fieldnamesfor unknown columns before the first row. Use a static method_parse(text, column, line)that returnsNonefor a blank cell and raisesValueErrorfor text that is not a number. Count lines from 2, because line 1 is the header. End withreturn cls(X, y, features). -
Write
StandardScaler. For each feature column ,fitstores the mean and the population standard deviation .transformmaps each value toand
inverse_transformmaps it back with .zip(*X)turns the rows into columns. Use a private_checkmethod for the fitted and width checks. -
Write
LinearRegression. The least squares line minimizes the mean squared error. For one feature, its slope and intercept have a closed form:With
fit_intercept=False, use in the same formulas, so the line goes through the origin. RaiseValueErrorwhen every is equal, because the denominator is then 0. -
Write the metrics. With samples, true values and predictions :
is 1 for perfect predictions and 0 for a model that always predicts the mean. It is negative for a model that is worse than the mean. The RMSE, , is in the units of the target (USD), so it is easier to read.
-
Write the tests. Start with the exact line : the model must find
coef_2 andintercept_1. Add one test per error case. Runpython -m pytest -q. -
Write
train_houses.py. Follow the expected report from top to bottom. Fit the scaler on the training set only, then transform both sets with it. -
Run and compare. Run
python train_houses.pyand compare every line with the expected report. Runruff check ..
A skeleton to start from:
"""LinearRegression for one feature, fitted with closed-form least squares."""
from typing import Self
from minilearn.base import NotFittedError
class LinearRegression: def __init__(self, fit_intercept: bool = True): self.fit_intercept = fit_intercept # store constructor arguments unchanged
def fit(self, X: list[list[float]], y: list[float]) -> Self: # TODO: check that X has exactly 1 feature and the same length as y # TODO: compute coef_ and intercept_ with the least squares formulas return self
def predict(self, X: list[list[float]]) -> list[float]: # TODO: raise NotFittedError before fit, then apply the line to each row ...Rubric
Section titled “Rubric”| Criterion | Points | Full points when |
|---|---|---|
| Runs | 2 | python train_houses.py prints the expected report; python -m pytest -q passes |
Dataset |
3 | from_csv is a class method that returns cls(...); the properties are read-only; every error names the problem and the line |
StandardScaler |
3 | learned attributes end with _ and exist only after fit; fit returns self; inverse_transform undoes transform |
LinearRegression |
3 | matches the closed-form formulas; supports fit_intercept=False; rejects 2 features; NotFittedError before fit |
| Metrics | 2 | MSE and R² match the formulas; R² is 0 for the mean and 1 for perfect predictions |
| Method design | 2 | instance, class and static methods are each used where they fit; internal helpers start with _ |
| No leakage | 1 | the scaler and the model are fitted on the training set only |
| Tests | 2 | at least 8 tests, with an exact-line test and the error cases |
| Readability | 2 | type hints, docstrings, Self for methods that return the instance, ruff-clean |
| Total | 20 | 16 or more: you are ready for module 19 |
Stretch goals
Section titled “Stretch goals”- Add
fit_transform(X)toStandardScaler: it callsfit(X)and returnstransform(X). Module 19 moves this method into aTransformerMixin, so that every transformer gets it for free. - Add
root_mean_squared_errorandmean_absolute_error(the mean of ) tometrics.py, with tests. Which one is less sensitive to the 8 price outliers indata/houses.csv? - Compare with scikit-learn: fit
sklearn.linear_model.LinearRegressionon the same training data (as a NumPy array,np.array(train.X)) and check thatcoef_[0]andintercept_agree with yours to 6 significant digits. - Predict
log(price)instead ofprice(usemath.logonyandmath.expon the predictions). Compute the R² of the predictions in USD. Does the log help a one-feature model? - Add a class method
Dataset.from_rows(rows, target, features)that builds a dataset from a list of dicts, and rewritefrom_csvso that it reads the rows and callsfrom_rows. Now the parsing logic exists once.
Reference solution
Section titled “Reference solution”Try the project yourself first. Then compare your files with these. Your names of internal helpers and your messages can differ; the public names and the report must not.
Reference solution
The project folder:
your-project/ data/houses.csv minilearn/ __init__.py base.py datasets.py linear_model.py metrics.py preprocessing.py test_minilearn.py train_houses.pyminilearn/base.py holds the exception. Module 19 adds the base classes here.
"""Shared building blocks. Module 19 adds BaseEstimator and the mixins here."""
class NotFittedError(ValueError): """Raised when a model or transformer is used before fit()."""minilearn/datasets.py holds Dataset. from_csv parses and validates the file, then calls cls(...), so __init__ checks every dataset, whatever its source.
"""Dataset: the features X and the target y of a supervised learning problem."""
import csvfrom typing import Self
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, restminilearn/preprocessing.py holds StandardScaler. It has no __init__, because it has no settings yet; Python then uses the default initializer, which does nothing.
"""StandardScaler: rescale each feature to mean 0 and standard deviation 1."""
from typing import Self
from minilearn.base import NotFittedError
class StandardScaler: """Standardize features: z = (x - mean_) / scale_, column by column."""
def fit(self, X: list[list[float]]) -> Self: if not X: raise ValueError("cannot fit on an empty X") n = len(X) columns = list(zip(*X, strict=True)) # one tuple per feature self.mean_ = [sum(col) / n for col in columns] self.scale_ = [ self._population_std(col, mean) for col, mean in zip(columns, self.mean_, strict=True) ] 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: if not hasattr(self, "mean_"): raise NotFittedError("StandardScaler is not fitted yet; call fit() first") 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_}" )minilearn/linear_model.py holds LinearRegression.
"""LinearRegression for one feature, fitted with closed-form least squares."""
from typing import Self
from minilearn.base import NotFittedError
class LinearRegression: """Fit y = coef_ * x + intercept_ for a single feature x."""
def __init__(self, fit_intercept: bool = True): self.fit_intercept = fit_intercept # stored unchanged, scikit-learn style
@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 # no intercept: the line goes through (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]: if not hasattr(self, "coef_"): raise NotFittedError("LinearRegression is not fitted yet; call fit() first") return [self.coef_ * x + self.intercept_ for x in self._single_column(X)]minilearn/metrics.py holds two plain functions. A metric has no state, so it needs no class.
"""Regression metrics: mean squared error and the coefficient of determination."""
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_totminilearn/__init__.py exports the public names.
"""minilearn: a tiny scikit-learn-like library in pure Python (module 18 version)."""
from minilearn.base import NotFittedErrorfrom minilearn.datasets import Datasetfrom minilearn.linear_model import LinearRegressionfrom minilearn.metrics import mean_squared_error, r2_scorefrom minilearn.preprocessing import StandardScaler
__all__ = [ "Dataset", "LinearRegression", "NotFittedError", "StandardScaler", "mean_squared_error", "r2_score",]The training script runs the whole workflow:
"""Predict house prices from living area with minilearn (module 18)."""
import math
from minilearn import ( Dataset, LinearRegression, NotFittedError, StandardScaler, mean_squared_error, r2_score,)
# 1. Load the data. The houses are sorted by sale date, so the first 2,400# sales train the model and the last 600 (the newest) test it.data = Dataset.from_csv("data/houses.csv", target="price", features=["sqft"])train, test = data.split_at(2400)print(f"Loaded {data.n_samples} houses, features {data.feature_names}")print(f"Train: {train.n_samples} houses, test: {test.n_samples} houses")
# 2. Fit the line on the training set only.model = LinearRegression().fit(train.X, train.y)sign = "+" if model.intercept_ >= 0 else "-"print(f"Model: price = {model.coef_:.2f} * sqft {sign} {abs(model.intercept_):,.0f}")
# 3. Evaluate on the test set and against a baseline that always predicts# the mean training price.pred = model.predict(test.X)mse = mean_squared_error(test.y, pred)mean_price = sum(train.y) / train.n_samplesbaseline = [mean_price] * test.n_samplesprint(f"Test MSE: {mse:,.0f} RMSE: {math.sqrt(mse):,.0f} USD")r2, r2_baseline = r2_score(test.y, pred), r2_score(test.y, baseline)print(f"Test R²: {r2:.3f} (baseline that predicts the mean: {r2_baseline:.3f})")
# 4. Standardize the feature. The fitted line changes its units, not its predictions.scaler = StandardScaler().fit(train.X)scaled_model = LinearRegression().fit(scaler.transform(train.X), train.y)scaled_pred = scaled_model.predict(scaler.transform(test.X))print(f"Scaler: mean_ {scaler.mean_[0]:.1f} sqft, scale_ {scaler.scale_[0]:.1f} sqft")print(f"Scaled model: {scaled_model.coef_:,.0f} USD per standard deviation of sqft")same = all(math.isclose(a, b) for a, b in zip(pred, scaled_pred, strict=True))print("Same predictions after scaling:", same)
# 5. Use the model and see the errors that protect it.for sqft, price in zip([1500, 2500], model.predict([[1500.0], [2500.0]]), strict=True): print(f"Predicted price for {sqft:,} sqft: {price:,.0f} USD")try: LinearRegression().predict(test.X)except NotFittedError as exc: print("NotFittedError:", exc)two = Dataset.from_csv("data/houses.csv", "price", ["sqft", "school_rating"], True)print(f"Rows kept with skip_missing=True: {two.n_samples}")try: LinearRegression().fit(two.X, two.y)except ValueError as exc: print("ValueError:", exc)
# Self-checksassert data.n_samples == 3000 and two.n_samples == 2910assert math.isclose(scaled_model.coef_, model.coef_ * scaler.scale_[0])round_trip = scaler.inverse_transform(scaler.transform(test.X))assert all(math.isclose(a[0], b[0]) for a, b in zip(round_trip, test.X, strict=True))assert r2_baseline < 0 < r2 < 1Loaded 3000 houses, features ['sqft']Train: 2400 houses, test: 600 housesModel: price = 316.29 * sqft - 119,064Test MSE: 52,870,676,972 RMSE: 229,936 USDTest R²: 0.561 (baseline that predicts the mean: -0.014)Scaler: mean_ 1857.2 sqft, scale_ 708.9 sqftScaled model: 224,225 USD per standard deviation of sqftSame predictions after scaling: TruePredicted price for 1,500 sqft: 355,368 USDPredicted price for 2,500 sqft: 671,656 USDNotFittedError: LinearRegression is not fitted yet; call fit() firstRows kept with skip_missing=True: 2910ValueError: LinearRegression supports exactly 1 feature, got 2The tests check each class on tiny data whose answer you can compute by hand:
"""Unit tests for the module 18 version of minilearn. Run: python -m pytest -q"""
import math
import pytest
from minilearn import ( Dataset, LinearRegression, NotFittedError, StandardScaler, mean_squared_error, r2_score,)
@pytest.fixturedef small_csv(tmp_path): path = tmp_path / "small.csv" path.write_text("sqft,rating,price\n1000,5,200\n2000,,350\n1500,7,300\n") return str(path)
def test_dataset_counts_samples_and_features(): data = Dataset([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], [1.0, 2.0, 3.0], ["a", "b"]) assert (data.n_samples, data.n_features) == (3, 2) assert data.column("b") == [2.0, 4.0, 6.0]
def test_dataset_rejects_mismatched_lengths(): with pytest.raises(ValueError, match="2 rows but y has 1"): Dataset([[1.0], [2.0]], [1.0], ["a"])
def test_from_csv_reads_the_requested_columns(small_csv): data = Dataset.from_csv(small_csv, target="price", features=["sqft"]) assert data.X == [[1000.0], [2000.0], [1500.0]] assert data.y == [200.0, 350.0, 300.0]
def test_from_csv_blank_cell_raises_or_is_skipped(small_csv): with pytest.raises(ValueError, match="line 3"): Dataset.from_csv(small_csv, "price", ["sqft", "rating"]) data = Dataset.from_csv(small_csv, "price", ["sqft", "rating"], skip_missing=True) assert data.n_samples == 2
def test_from_csv_unknown_column(small_csv): with pytest.raises(ValueError, match="unknown columns"): Dataset.from_csv(small_csv, target="price", features=["area"])
def test_split_at_keeps_the_order(): data = Dataset([[float(i)] for i in range(5)], [0.0] * 5, ["x"]) first, rest = data.split_at(3) assert first.X == [[0.0], [1.0], [2.0]] and rest.X == [[3.0], [4.0]]
def test_scaler_learns_mean_and_population_std(): scaler = StandardScaler().fit([[1.0, 10.0], [2.0, 10.0], [3.0, 10.0]]) assert scaler.mean_ == [2.0, 10.0] assert scaler.scale_[0] == pytest.approx(math.sqrt(2 / 3)) assert scaler.scale_[1] == 1.0 # constant column
def test_scaler_round_trip(): X = [[1500.0], [2420.0], [980.0]] scaler = StandardScaler().fit(X) Z = scaler.transform(X) assert sum(row[0] for row in Z) == pytest.approx(0.0) assert scaler.inverse_transform(Z) == [[pytest.approx(row[0])] for row in X]
def test_not_fitted_errors(): with pytest.raises(NotFittedError): StandardScaler().transform([[1.0]]) with pytest.raises(NotFittedError): LinearRegression().predict([[1.0]])
def test_linear_regression_recovers_an_exact_line(): X = [[0.0], [1.0], [2.0], [3.0]] y = [1.0, 3.0, 5.0, 7.0] # y = 2x + 1 model = LinearRegression().fit(X, y) assert model.coef_ == pytest.approx(2.0) assert model.intercept_ == pytest.approx(1.0) assert model.predict([[10.0]]) == [pytest.approx(21.0)]
def test_linear_regression_without_intercept(): model = LinearRegression(fit_intercept=False).fit([[1.0], [2.0]], [2.0, 4.0]) assert (model.coef_, model.intercept_) == (pytest.approx(2.0), 0.0)
def test_linear_regression_needs_one_feature(): with pytest.raises(ValueError, match="exactly 1 feature"): LinearRegression().fit([[1.0, 2.0], [3.0, 4.0]], [1.0, 2.0])
@pytest.mark.parametrize( ("y_pred", "mse", "r2"), [ ([1.0, 2.0, 3.0], 0.0, 1.0), # perfect predictions ([2.0, 2.0, 2.0], 2 / 3, 0.0), # always the mean ([1.0, 2.0, 5.0], 4 / 3, -1.0), # worse than the mean ],)def test_metrics(y_pred, mse, r2): y_true = [1.0, 2.0, 3.0] assert mean_squared_error(y_true, y_pred) == pytest.approx(mse) assert r2_score(y_true, y_pred) == pytest.approx(r2)python -m pytest -q test_minilearn.py............... [100%]15 passed in 0.01sHow it works:
- The data.
Dataset.from_csvis an alternative constructor: it turns a CSV file into clean lists and ends withcls(X, y, features). The__init__checks therefore run for every dataset, from a file or from lists in a test.n_samplesandn_featuresare read-only properties, so they always agree withX. - The split.
split_at(2400)keeps the time order: the model learns from older sales and is judged on the 600 newest ones. It usestype(self)to build the two parts, so a subclass ofDatasetgets two instances of the subclass. - The model.
LinearRegression.fitcomputes the least squares slope and intercept. The line is price = 316.29 × sqft − 119,064: each extra square foot adds about 316 USD. The negative intercept only means that the line is not valid near 0 sqft; no house in the data is that small. - The evaluation. The test R² is 0.561: living area alone explains a bit more than half of the variance of the price. The RMSE is about 230,000 USD, large next to a median price of 376,000 USD, because the neighborhood, the condition and other features matter too. The baseline that always predicts the mean training price has an R² slightly below 0. It is worse than useless on the test set, because prices rose over time and the test houses are newer sales.
- Scaling. After
StandardScaler, the coefficient is 224,225 USD per standard deviation (708.9 sqft) of area: the oldcoef_timesscale_, as the script asserts. The predictions stay the same, as the script checks. Scaling changes the units of a linear model, not its fit. It matters for models that compare distances, such as the KNN classifier of module 19, and for gradient descent. - No leakage. The scaler and the model see the training set only. The test set is transformed with the training
mean_andscale_. - The guards.
predictbeforefitraisesNotFittedErrorwith a clear message.skip_missing=Truekeeps the 2,910 rows with a school rating, andLinearRegressionrefuses the two-feature dataset instead of silently using only one column. - Method design. Each kind of method appears where it fits:
from_csvis a class method;_parse,_single_columnand_population_stdare static helpers that need no instance;fit,transformandpredictare instance methods that read and write the learned state. The metrics are plain functions, because they keep no state.
Alternative: with NumPy, the whole of LinearRegression.fit is one call to np.polyfit(x, y, 1), and StandardScaler is two lines with X.mean(axis=0) and X.std(axis=0) (module 23). scikit-learn’s LinearRegression handles any number of features with linear algebra (module 35). The pure-Python classes here show the design that those libraries share: settings in __init__, learning in fit, learned attributes with _, and fit returning self.