smartyfy.mrindigi.com

Python Master Course V2 — 133. Linear Regression and Regularized Prediction

Purpose and learning outcomes

Predicting a number requires more than reporting a single score. We will compare a mean prediction with linear, ridge, and lasso models, then inspect the pattern of their errors. The synthetic target is deliberately continuous and partially noisy, so even a sensible model has residual error. Its known construction helps us separate useful predictive behavior from unsupported causal interpretation.

  • Interpret residuals and regression metrics
  • Fit linear, ridge and lasso models through pipelines
  • Explain regularization, feature scale and coefficient limitations

Prerequisites: 122: linear algebra; 129: optimization; 131–132: splits and pipelines.

Environment and run order

Use a dedicated Python 3.11 or 3.12 virtual environment. These exercises use local synthetic or bundled data; no account, API key, or dataset download is needed. The shell commands install free packages. Run the Python blocks in order in one lesson file; worked solutions continue from that file unless stated otherwise.

Shell

python -m venv .venv
# macOS/Linux: source .venv/bin/activate
# Windows PowerShell: .venv\Scripts\Activate.ps1
python -m pip install numpy pandas scikit-learn matplotlib joblib
python -m pip freeze > requirements-observed.txt

Understand the model and the evidence

A linear predictor and its residual

A linear model predicts an intercept plus a weighted sum of features. A residual here is observed minus predicted. Positive residuals mean underprediction; negative residuals mean overprediction. Least squares selects coefficients to reduce squared residuals on training rows. It does not promise that the underlying process is linear, that residuals are independent, or that a coefficient measures what would happen if you intervened on a feature.

Different errors answer different questions

Mean absolute error averages absolute residual magnitudes and has the target’s units. Root mean squared error also has those units but emphasizes large errors more strongly. R-squared compares squared error with a constant mean reference for the evaluated observations; it can be negative when predictions are worse than that reference. Report the metric and units, and decide the primary criterion before examining candidate validation results.

Shrinkage trades fit for stability

Ridge adds a penalty based on squared coefficient magnitude; lasso uses absolute magnitude and may set some coefficients exactly to zero. Their alpha parameter controls penalty strength within that estimator. Larger alpha usually means stronger shrinkage, not universally better generalization. Numeric feature scale matters because a coefficient’s size depends on its input unit. Standardizing inside the training pipeline makes the penalty’s treatment of features more comparable.

Correlation complicates interpretation

If two columns contain nearly the same information, many coefficient combinations can produce similar predictions. Lasso may keep one and drop the other, while ridge may share weight. That does not prove the dropped measurement is irrelevant in the real world. Predictive coefficients depend on all included variables, regularization, scaling, and sample variation. Confounding and selection effects remain even if residual metrics look excellent.

Incremental worked example

1. Create data with redundant information

The last feature closely repeats the first. This makes coefficient instability visible without external files. Test rows are reserved before any scaling. The continuous outcome includes irreducible noise; no metric value is specified in advance.

Python

import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.dummy import DummyRegressor
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score

rng = np.random.default_rng(33)
X = rng.normal(size=(480, 6))
X[:, 5] = X[:, 0] + rng.normal(0, 0.03, len(X))
y = 10 + 4 * X[:, 0] - 2 * X[:, 1] + rng.normal(0, 2, len(X))
X_dev, X_test, y_dev, y_test = train_test_split(X, y, test_size=0.20, random_state=33)
X_train, X_valid, y_train, y_valid = train_test_split(
    X_dev, y_dev, test_size=0.25, random_state=34)
models = {
    "mean": DummyRegressor(strategy="mean"),
    "linear": make_pipeline(StandardScaler(), LinearRegression()),
    "ridge": make_pipeline(StandardScaler(), Ridge(alpha=10.0)),
    "lasso": make_pipeline(StandardScaler(), Lasso(alpha=0.1, max_iter=5000))}

2. Compare validation errors and inspect residuals

All candidates receive the same rows. Choose by validation MAE, then refit that declared model on the development partition before one final test evaluation. The residual summary is descriptive; a later decision to change features after inspecting test errors would require a new honest evaluation.

Python

scores = {}
for name, model in models.items():
    model.fit(X_train, y_train)
    pred = model.predict(X_valid)
    scores[name] = mean_absolute_error(y_valid, pred)
    print(name, "validation MAE", round(scores[name], 3),
          "RMSE", round(np.sqrt(mean_squared_error(y_valid, pred)), 3))
chosen_name = min(scores, key=scores.get)
chosen = models[chosen_name]
chosen.fit(X_dev, y_dev)
test_pred = chosen.predict(X_test)
residual = y_test - test_pred
print("chosen", chosen_name)
print("test MAE", mean_absolute_error(y_test, test_pred))
print("test R2", r2_score(y_test, test_pred))
print("residual quantiles", np.quantile(residual, [0.1, 0.5, 0.9]))

Expected output / interpretation

Four validation rows are printed, followed by the selected model and test metrics.
Scores depend on the installed numerical stack and are not target values.
The useful comparison is each fitted model against the mean baseline on identical rows.

Guided lab and acceptance criteria

  1. Before fitting, write why MAE is the primary choice for this artificial continuous target. Then calculate RMSE too and explain why occasional large errors can move it more strongly.
  2. Plot validation predictions against validation residuals for each candidate before the final evaluation. Look for curvature, widening spread, or systematic bias. A roughly centered cloud is reassuring but does not prove all modeling assumptions.
  3. Compare the fitted coefficients of the three linear-family models and mark the near-duplicate columns. Repeat the development experiment on two prespecified seeds, keeping each test partition sealed until its choices are complete. Report variation rather than choosing the most attractive run.
  4. Submit one comparison, a residual plot with labeled axes, the exact candidate settings, and a short limitations note. Passing work states that synthetic feature associations are not evidence for real interventions and records which observations influenced selection.

Common mistakes and repairs

  • Reporting mean squared error as though it has target units: squared error is in squared units; take the square root when communicating RMSE.
  • Comparing raw coefficient magnitudes across unscaled measurements: a kilometer and a meter produce different coefficients for the same relationship.
  • Trying more alpha values after seeing test performance: use a validation or cross-validation search and keep test data outside it.

Questions that test understanding

Why can a linear model have negative R-squared?

R-squared is one minus model squared error divided by the evaluated target’s total squared variation around its mean. If the numerator exceeds that reference variation, the result is negative. This is possible on unseen rows and does not imply a metric implementation bug.

Does a lasso coefficient of zero prove no relationship exists?

No. The penalty can remove a weak, redundant, or unstable contribution at a chosen alpha. A correlated feature may substitute for it. Zero is a property of this fitted predictive model, not a causal conclusion about the data-generating process.

Why scale before ridge but not before the mean baseline?

The ridge penalty operates on coefficients whose numeric magnitude depends on feature units. Scaling changes that geometry in an intentional way. A mean baseline ignores the features entirely, so scaling them would add work without changing its prediction.

Should training residuals always average exactly zero?

An ordinary least-squares model with a fitted intercept has a training residual-sum property up to numerical error. That property need not hold on validation or test data, and different losses, constraints, or fitting procedures may change it. Do not demand it as a universal regression test.

Is the lowest RMSE always the best deployment choice?

Only if squared-error consequences match the intended use closely enough. A task may care about absolute error, underprediction costs, tail errors, or an operational tolerance. Choose the evaluation question first and use multiple summaries to understand the chosen model’s limitations.

Why refit on development data after selection?

Once the configuration is frozen, training on all non-test data can use the available learning information more efficiently. The test set remains independent of that selection and refit. Document that the final fitted parameters differ from those used for the validation comparison.

Exercises with worked solutions

Exercise 1: Make the metric calculation transparent

Reveal the worked solution and reasoning

Manual formulas are a useful test of metric meaning. The tolerances compare floating-point calculations, not exact string representations. The residual is observed minus predicted, but its sign disappears in MAE and RMSE.

Python

manual_mae = np.mean(np.abs(y_test - test_pred))
manual_rmse = np.sqrt(np.mean((y_test - test_pred) ** 2))
assert np.isclose(manual_mae, mean_absolute_error(y_test, test_pred))
print(manual_mae, manual_rmse)

Exercise 2: Diagnose a unit change

Reveal the worked solution and reasoning

Multiply one feature by 1000 and refit both the scaled ridge pipeline and an unscaled Ridge on training only. The standardized pipeline should be largely insensitive apart from floating-point and solver variation; the raw ridge penalty will treat that feature differently. The correct explanation concerns coefficient units and penalty geometry, not a claim that scaling creates new information.

Python

scaled_X = X_train.copy()
scaled_X[:, 0] *= 1000
unit_model = make_pipeline(StandardScaler(), Ridge(alpha=10.0))
unit_model.fit(scaled_X, y_train)
valid_units = X_valid.copy()
valid_units[:, 0] *= 1000
print("changed-unit validation MAE", mean_absolute_error(
    y_valid, unit_model.predict(valid_units)))

Recap and next step

Useful regression evidence combines an appropriate baseline, honest held-out errors, and inspection of residual structure. Regularization can stabilize prediction but changes coefficient interpretation. The next lesson returns to categories and separates a model’s score from the decision rule that turns that score into an action.

Official references

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.