Skip to content

18. Classes and objects — Mini-project

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.

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_matrix
flowchart 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

You write the first four pieces, as plain classes and functions:

  • Dataset, with the alternative constructor Dataset.from_csv() and the read-only properties n_samples and n_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.
  • LinearRegression for one feature, fitted with the closed-form least squares formula.
  • mean_squared_error and r2_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.

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.

Write a package minilearn/ in your project folder, a script train_houses.py and a test file test_minilearn.py.

  1. minilearn/base.py: a class NotFittedError that subclasses ValueError.
  2. minilearn/datasets.py: a class Dataset.
    • __init__(X, y, feature_names) stores the three values. It raises ValueError for an empty X, for len(X) != len(y) and for a row whose length is not len(feature_names).
    • Read-only properties n_samples and n_features.
    • A class method from_csv(path, target, features, skip_missing=False) that returns an instance built with cls(...). It raises ValueError for an unknown column, for a value that is not a number, and for a blank cell, unless skip_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 method split_at(n_first) that returns two datasets in the original order.
  3. minilearn/preprocessing.py: a class StandardScaler with fit(X) (returns self), transform(X) and inverse_transform(Z). fit learns mean_, scale_ (the population standard deviation, or 1.0 for a constant column) and n_features_in_. transform raises NotFittedError before fit and ValueError for the wrong number of features.
  4. minilearn/linear_model.py: a class LinearRegression(fit_intercept=True). fit(X, y) learns coef_ and intercept_ with least squares and returns self; it raises ValueError when X has more than one feature. predict(X) raises NotFittedError before fit.
  5. minilearn/metrics.py: the functions mean_squared_error(y_true, y_pred) and r2_score(y_true, y_pred), which raise ValueError for lists of different lengths.
  6. minilearn/__init__.py: exports the six public names, so a script can write from minilearn import Dataset.
  7. train_houses.py: loads price and sqft, 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 standardizing sqft changes the coefficient but not the predictions, and shows two protected errors. It ends with assert checks.
  8. test_minilearn.py: at least 8 pytest tests, including an exact line (y = 2x + 1) that LinearRegression must recover, and the error cases.
  9. Type hints on every public method. Use typing.Self for from_csv, fit and split_at.
  10. ruff check passes.

The expected report:

Expected output
Loaded 3000 houses, features ['sqft']
Train: 2400 houses, test: 600 houses
Model: price = 316.29 * sqft - 119,064
Test MSE: 52,870,676,972 RMSE: 229,936 USD
Test R²: 0.561 (baseline that predicts the mean: -0.014)
Scaler: mean_ 1857.2 sqft, scale_ 708.9 sqft
Scaled model: 224,225 USD per standard deviation of sqft
Same predictions after scaling: True
Predicted price for 1,500 sqft: 355,368 USD
Predicted price for 2,500 sqft: 671,656 USD
NotFittedError: LinearRegression is not fitted yet; call fit() first
Rows kept with skip_missing=True: 2910
ValueError: LinearRegression supports exactly 1 feature, got 2
  1. Create the package. Make a folder minilearn/ with an empty __init__.py, and the files base.py, datasets.py, preprocessing.py, linear_model.py and metrics.py. Put train_houses.py and test_minilearn.py next to the folder, not inside it (module 08).

  2. Write NotFittedError. One class with a docstring in base.py. Module 19 adds the base classes to this file.

  3. Write Dataset.__init__ and the properties. Start from Example 4 of the lesson. Add the empty-X check and the row-width check, then n_samples and n_features. Test them in the REPL with a 2-row toy dataset.

  4. Write Dataset.from_csv. Read with csv.DictReader. Check reader.fieldnames for unknown columns before the first row. Use a static method _parse(text, column, line) that returns None for a blank cell and raises ValueError for text that is not a number. Count lines from 2, because line 1 is the header. End with return cls(X, y, features).

  5. Write StandardScaler. For each feature column jj, fit stores the mean μj\mu_j and the population standard deviation σj\sigma_j. transform maps each value to

    z=x−μjσjz = \frac{x - \mu_j}{\sigma_j}

    and inverse_transform maps it back with x=zσj+μjx = z \sigma_j + \mu_j. zip(*X) turns the rows into columns. Use a private _check method for the fitted and width checks.

  6. Write LinearRegression. The least squares line minimizes the mean squared error. For one feature, its slope and intercept have a closed form:

    coef_=∑i(xi−xˉ)(yi−yˉ)∑i(xi−xˉ)2,intercept_=yˉ−coef_⋅xˉ\text{coef\_} = \frac{\sum_i (x_i - \bar{x})(y_i - \bar{y})}{\sum_i (x_i - \bar{x})^2}, \qquad \text{intercept\_} = \bar{y} - \text{coef\_} \cdot \bar{x}

    With fit_intercept=False, use xˉ=yˉ=0\bar{x} = \bar{y} = 0 in the same formulas, so the line goes through the origin. Raise ValueError when every xix_i is equal, because the denominator is then 0.

  7. Write the metrics. With nn samples, true values yiy_i and predictions y^i\hat{y}_i:

    MSE=1n∑i(yi−y^i)2,R2=1−∑i(yi−y^i)2∑i(yi−yˉ)2\text{MSE} = \frac{1}{n} \sum_i (y_i - \hat{y}_i)^2, \qquad R^2 = 1 - \frac{\sum_i (y_i - \hat{y}_i)^2}{\sum_i (y_i - \bar{y})^2}

    R2R^2 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, MSE\sqrt{\text{MSE}}, is in the units of the target (USD), so it is easier to read.

  8. Write the tests. Start with the exact line y=2x+1y = 2x + 1: the model must find coef_ 2 and intercept_ 1. Add one test per error case. Run python -m pytest -q.

  9. 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.

  10. Run and compare. Run python train_houses.py and compare every line with the expected report. Run ruff check ..

A skeleton to start from:

minilearn/linear_model.py (starter)
"""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
...
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
  1. Add fit_transform(X) to StandardScaler: it calls fit(X) and returns transform(X). Module 19 moves this method into a TransformerMixin, so that every transformer gets it for free.
  2. Add root_mean_squared_error and mean_absolute_error (the mean of ∣yi−y^i∣|y_i - \hat{y}_i|) to metrics.py, with tests. Which one is less sensitive to the 8 price outliers in data/houses.csv?
  3. Compare with scikit-learn: fit sklearn.linear_model.LinearRegression on the same training data (as a NumPy array, np.array(train.X)) and check that coef_[0] and intercept_ agree with yours to 6 significant digits.
  4. Predict log(price) instead of price (use math.log on y and math.exp on the predictions). Compute the R² of the predictions in USD. Does the log help a one-feature model?
  5. Add a class method Dataset.from_rows(rows, target, features) that builds a dataset from a list of dicts, and rewrite from_csv so that it reads the rows and calls from_rows. Now the parsing logic exists once.

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.py

minilearn/base.py holds the exception. Module 19 adds the base classes here.

minilearn/base.py
"""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.

minilearn/datasets.py
"""Dataset: the features X and the target y of a supervised learning problem."""
import csv
from 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, rest

minilearn/preprocessing.py holds StandardScaler. It has no __init__, because it has no settings yet; Python then uses the default initializer, which does nothing.

minilearn/preprocessing.py
"""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.

minilearn/linear_model.py
"""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.

minilearn/metrics.py
"""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_tot

minilearn/__init__.py exports the public names.

minilearn/__init__.py
"""minilearn: a tiny scikit-learn-like library in pure Python (module 18 version)."""
from minilearn.base import NotFittedError
from minilearn.datasets import Dataset
from minilearn.linear_model import LinearRegression
from minilearn.metrics import mean_squared_error, r2_score
from minilearn.preprocessing import StandardScaler
__all__ = [
"Dataset",
"LinearRegression",
"NotFittedError",
"StandardScaler",
"mean_squared_error",
"r2_score",
]

The training script runs the whole workflow:

train_houses.py
"""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_samples
baseline = [mean_price] * test.n_samples
print(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-checks
assert data.n_samples == 3000 and two.n_samples == 2910
assert 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 < 1
Output
Loaded 3000 houses, features ['sqft']
Train: 2400 houses, test: 600 houses
Model: price = 316.29 * sqft - 119,064
Test MSE: 52,870,676,972 RMSE: 229,936 USD
Test R²: 0.561 (baseline that predicts the mean: -0.014)
Scaler: mean_ 1857.2 sqft, scale_ 708.9 sqft
Scaled model: 224,225 USD per standard deviation of sqft
Same predictions after scaling: True
Predicted price for 1,500 sqft: 355,368 USD
Predicted price for 2,500 sqft: 671,656 USD
NotFittedError: LinearRegression is not fitted yet; call fit() first
Rows kept with skip_missing=True: 2910
ValueError: LinearRegression supports exactly 1 feature, got 2

The tests check each class on tiny data whose answer you can compute by hand:

test_minilearn.py
"""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.fixture
def 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)
Terminal
python -m pytest -q test_minilearn.py
Output
............... [100%]
15 passed in 0.01s

How it works:

  1. The data. Dataset.from_csv is an alternative constructor: it turns a CSV file into clean lists and ends with cls(X, y, features). The __init__ checks therefore run for every dataset, from a file or from lists in a test. n_samples and n_features are read-only properties, so they always agree with X.
  2. The split. split_at(2400) keeps the time order: the model learns from older sales and is judged on the 600 newest ones. It uses type(self) to build the two parts, so a subclass of Dataset gets two instances of the subclass.
  3. The model. LinearRegression.fit computes 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.
  4. 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.
  5. Scaling. After StandardScaler, the coefficient is 224,225 USD per standard deviation (708.9 sqft) of area: the old coef_ times scale_, 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.
  6. No leakage. The scaler and the model see the training set only. The test set is transformed with the training mean_ and scale_.
  7. The guards. predict before fit raises NotFittedError with a clear message. skip_missing=True keeps the 2,910 rows with a school rating, and LinearRegression refuses the two-feature dataset instead of silently using only one column.
  8. Method design. Each kind of method appears where it fits: from_csv is a class method; _parse, _single_column and _population_std are static helpers that need no instance; fit, transform and predict are 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.