02 - Linear Regression and Evaluation (revised)

📚 02 - Linear Regression and Evaluation (revised).pdf

Brief overview

This document introduces the fundamental concepts of linear regression for predictive modeling and details essential methods for evaluating model performance. Understanding these topics is crucial for building accurate and reliable predictive systems.

Key points

  • Understanding the identification of regression tasks and the construction of simple prediction rules.
  • Learning how to build and interpret straight-line linear models, including slope and intercept.
  • Calculating residuals and mean squared error (MSE) to measure prediction errors.
  • Differentiating between training and new-data performance, and understanding underfitting and overfitting.
  • Exploring the roles of training, validation, and test data in honest model evaluation.

1. Understanding linear regression

1.1 Regression tasks and prediction rules

  • Regression task: Predicts a numerical, measurable quantity.
  • Example: Predicting delivery time in minutes.
  • Test: Does a value between two possible targets make sense? (e.g., 27.5 degrees Celsius is meaningful).
  • Classification task: Predicts a category.
  • Example: Predicting if a message is spam.
  • Test: A value halfway between two categories is not meaningful (e.g., halfway between "tuna" and "salmon").
  • Identifiers: Numbers that are labels, not quantities (e.g., phone numbers, postal codes). Averaging them doesn't make sense.

Regression tasks predict measurable quantities.

  • Prediction rule: A simple rule to estimate an output.
  • Example: predicted time = 5 minutes (prep) + 3 minutes * distance (km).
  • Features (x): The input variable used for prediction (e.g., distance).
  • Predicted output (ŷ): The estimated output value. The hat (^) signifies a prediction.
Input (x)Preparation (5 min)Travel allowance (3x)Predicted Time (ŷ)
0 km5 min0 min5 min
1 km5 min3 min8 min
2 km5 min6 min11 min
3 km5 min9 min14 min

1## 1.2 The straight-line model

  • General straight-line model: ŷ = α + βx.
  • x: Input or feature.
  • ŷ: Predicted output.
  • α (alpha): The intercept. It's the predicted value when x = 0.
  • β (beta): The slope. It's the predicted change in ŷ when x increases by 1.
  • Units of slope: output-unit per input-unit (e.g., minutes per kilometer).
  • Parameter interpretation:
  • Slope: Controls how steeply the line rises or falls.
  • Intercept: Slides the entire line up or down.

The slope tells you how much the prediction changes for each unit increase in the input.

1.2.1 Making predictions with the model

  • Prediction example: For ŷ = 5 + 3x, predict time at 6 km.
  • Substitute x = 6: ŷ = 5 + 3 .
  • Calculate: ŷ = 5 + 18 = 23 minutes 2 3.

1.3 Understanding prediction errors

  • Actual value (y): The true observed output.
  • Residual: The difference between the actual value and the predicted value.
  • Formula: r = y - ŷ.
  • Residual interpretation:
  • r > 0: The model predicted too low; actual is higher than predicted.
  • r < 0: The model predicted too high; actual is lower than predicted.
  • r = 0: The prediction was exact for that observation.

A positive residual means your model underestimated the true value.

  • Problem with adding residuals: Positive and negative residuals can cancel each other out, hiding errors.
  • Mean Squared Error (MSE): Combines errors by squaring them to prevent cancellation and then averaging.
  • Formula: MSE = (1/n) * Σ(yi - ŷi)².
  • n: Number of observations.
  • yi: Actual value for observation i.
  • ŷi: Predicted value for observation i.
  • Σ: Summation symbol.
  • MSE unit: Squared units of the target variable (e.g., minutes²).
  • MSE interpretation: A lower MSE indicates a model with closer predictions on the same data.

MSE punishes larger errors much more severely than smaller ones.

1.3.1 Calculating model performance

  • Example Calculation: Scoring the rule ŷ = 5 + 3x on three deliveries.
x (km)y (min)ŷ = 5 + 3xr = y - ŷr²
198+11
2111100
31614+24
  • MSE Calculation: MSE=5/3≈1.667MSE = 5 / 3 ≈ 1.667.
  • This MSE shows the company's rule is not perfect, as it underestimates some deliveries 4 5.

1.4 Fitting the best straight line

  • Best line: The line that results in the smallest Mean Squared Error (MSE) on the data.
  • Loss function: A measure of how poor the predictions are (MSE is a loss function).
  • Fitting/Training: Choosing the model parameters (α and β) to minimize the loss function.

Fitting a model means finding the parameters that minimize its prediction errors.

1.4.1 Finding the best constant (zero slope)

  • If a model predicts a single constant value for all inputs, the best constant is the mean of the actual values.
  • Example: For actual times (9, 11, 16 min), the mean is (9+11+16)/3 = 12 minutes.
  • This minimizes the sum of squared errors for a flat line 6.

The best constant prediction is the mean of the actual target values.

1.4.2 Finding the best slope and intercept

  • Key property of least squares: The best-fit line always passes through the point of means (x̄, ȳ).
  • x̄ (x-bar): Mean of the input feature x.
  • ȳ (y-bar): Mean of the actual target y.
  • This allows us to fix one point and only search for the best slope (β). The intercept (α) can then be calculated.
  • Formula: α = ȳ - βx̄.

The fitted line balances the errors and passes through the average input and average output.

  • MSE curve: Plotting MSE against different slopes shows a U-shaped curve.
  • The lowest point on the curve represents the minimum MSE and thus the best slope.

The goal of training is to find the bottom of the MSE curve.

1.4.3 Shortcut formula for the least-squares slope

  • The slope β can be calculated directly using the following formula:
  • β = Σ((xi - x̄)(yi - ȳ)) / Σ((xi - x̄)²).
  • Σ((xi - x̄)(yi - ȳ)): Sum of the products of deviations from the means (this is the "vote" sum).
  • Σ((xi - x̄)²) : Sum of squared deviations of the input from its mean (measures horizontal spread).

The slope formula balances the tendency for the line to rise or fall based on how input and output deviations align.

1.4.4 Applying the formulas

  • Example Data: | x | y | |:- |:---- | | 1 | 9 | | 2 | 11 | | 3 | 16 |
  • Means: x̄ = 2, ȳ = 12.
  • Vote table:
xiyixi - x̄yi - ȳProduct (xi - x̄)(yi - ȳ)(xi - x̄)²
19-1-3+31
2110-100
316+1+4+41
  • Slope calculation: β = 7 / 2 = 3.5.
  • Intercept calculation: α = 12 - (3.5 * 2) = 12 - 7 = 5.
  • Best-fit line: ŷ = 5 + 3.5x.
  • MSE for best line: 0.500 (significantly lower than the company's guess) 7 8 9.

Rounding intermediate calculations can lead to a less optimal final answer.

1.5 Evaluating a given model and fitting the best line

  • Model evaluation: Calculating the loss function (e.g., MSE) for a given set of parameters (α, β) and data.
  • Fitting: Using formulas to find the α and β that minimize the loss function.

1.5.1 Example: Mathematics and UTBK scores

  • Data: | Student | Math Score (M) | UTBK Score (y) | |:------ |:------------- |:------------- | | 1 | 95 | 785 | | 2 | 86 | 790 | | 3 | 68 | 600 |
  • Model: ŷ = α + βM.
  • Loss function: L(α, β) = (1/n) * Σ(yi - (α + βMi))².

1.5.1.1 Evaluating a given model

  • Evaluate for: α = 227, β = 6.0.
  • Predictions:
  • Student 1: ŷ = 227 + 6 = 797 .
  • Student 2: ŷ = 227 + 6 = 743 .
  • Student 3: ŷ = 227 + 6 = 635 .
  • Residuals and Squares:
MᵢyᵢŷᵢResidual (yi - ŷᵢ)Squared Residual
95785797-12144
86790743+472209
68600635-351225
  • Loss (MSE): L(227,6.0)=(144+2209+1225)/3=3578/3≈1192.7L(227, 6.0) = (144 + 2209 + 1225) / 3 = 3578 / 3 ≈ 1192.7.

1.5.1.2 Fitting the best line

  • Step 1: Calculate means:
  • M̄ = (95 + 86 + 68) / 3 = 83.
  • ȳ = (785 + 790 + 600) / 3 = 725.
  • Step 2: Vote table:
MᵢyᵢMᵢ - M̄yᵢ - ȳProduct (Mᵢ - M̄)(yᵢ - ȳ)(Mᵢ - M̄)²
95785+12+60+720144
86790+3+65+1959
68600-15-125+1875225
  • Step 3: Calculate slope: β=2790/378≈7.38β = 2790 / 378 ≈ 7.38.
  • Step 4: Calculate intercept: α=725−(7.38∗83)≈725−612.54≈112.46α = 725 - (7.38 * 83) ≈ 725 - 612.54 ≈ 112.46.
  • Rounded parameters: α = 112.4, β = 7.4.

Rounding parameters at the very end preserves accuracy.

1.5.2 Common misconceptions

  • Hat on ŷ: Distinguishes prediction from actual value.
  • Slope units: Output-unit per input-unit.
  • Intercept realism: It's the prediction at x=0, which might not be a realistic scenario.
  • Negative residual: Actual value is below the prediction.
  • Adding residuals: They cancel; squares are needed.
  • MSE units: Squared units of the target variable.
  • Fitted line through points: Least squares minimizes total error, not necessarily passing through every point.
  • Rounding: Round only final answers as requested; intermediate rounding changes results 10 11 12.

The best-fit line minimizes the total squared difference between predicted and actual values.

🔑 Important: Linear regression fits a straight line to data by minimizing the mean squared error, providing a way to predict numerical outcomes based on input features.

2. Evaluating model performance honestly

To assess a model effectively, it's crucial to understand how well it performs on data it hasn't seen before. Simply checking how well a model fits the data used to create it (training data) can be misleading.

2.1 Understanding model errors

Models can be wrong in a few key ways:

  • Underfitting: The model is too simple to capture the real pattern in the data. This leads to poor performance on both the training data and new, unseen data.
  • Overfitting: The model is too complex and learns the noise in the training data too closely. This makes the model look great on the training data but perform poorly on new data.

The real goal is predicting new data, not just fitting existing data.

A perfect score on training data can be a red flag, suggesting the model might be too flexible and is essentially memorizing the noise.

Training error vs. New-data error

Model PerformanceTraining ErrorNew-data Error
UnderfittingHighHigh
Good FitLowLow
OverfittingVery LowHigh

The key takeaway is that low training error alone doesn't guarantee a good model.

Low training error can mean a good model or a disastrous one.

2.2 Splitting data for honest evaluation

To avoid being fooled by training performance, you must evaluate your model on data it has not seen during training.

  • Training set: Used to fit the model parameters (like the slope and intercept of a line). This is like practicing questions for a test.
  • Validation set: Used to compare different model choices during development and select the best one. This is like taking a rehearsal quiz.
  • Test set: Used only once at the very end to estimate the final performance on completely new data. This is like the final exam.

Each data portion has one job and these jobs must not overlap.

If a large gap exists between training performance and validation performance, it's a strong warning sign of overfitting. However, it's not definitive proof.

Data roles

PortionJobAnalogy
Training setFit the model parametersWorked practice
Validation setCompare choices during developmentA rehearsal quiz
Test setEstimate final performance on unseen dataThe final exam

The test set must remain untouched until the very end. If you use it to make adjustments, it effectively becomes part of the development process, and its score is no longer an honest estimate of future performance.

The test set is consulted once; the validation set is consulted many times.

2.3 Limitations of simple models

Even when used honestly, simple models like straight lines have limitations:

  • Missing curvature: A straight line cannot capture patterns where the output first increases and then decreases, or vice versa. This leads to underfitting.
  • Large errors dominate: Mean Squared Error (MSE) squares errors. A large error, even if rare, can heavily influence the model's fit, pulling the line away from other data points. This is especially true if the large error is a mistake.

Large errors are squared, meaning a doubling of error quadruples its contribution to MSE.

  • Extrapolation is risky: Predicting values outside the range of the observed input data is dangerous. The model assumes the pattern continues linearly, which is often not true in reality.

Interpolation is predicting within the observed range; extrapolation is predicting outside it.

  • Association is not causation: A model showing that two variables move together doesn't mean one causes the other. It only shows an association in the observed data.

🔑 Important: Always separate prediction from proof of causation.

2.4 Advanced evaluation techniques

Two important concepts for more robust model evaluation are:

  • Cross-validation: The data is split into several parts (folds). Each fold takes turns being the validation set while the rest train the model. The scores are averaged, providing a more stable estimate than a single validation split.
  • Data leakage: This occurs when information that should not be available during training accidentally reaches the model. A common cause is preprocessing data incorrectly, such as calculating means or scaling factors over the entire dataset before splitting it 13.

🔑 Important: Always split your data before any preprocessing that learns from the data.

© 2026 Maeve. All rights reserved. This content is protected by copyright.

See also