Part 3 — Supervised Learning Lesson 13 / 56
Estimated Reading: 15–18 mins Level: Intermediate

Linear Regression: From Theory to Practice

Mathematical Foundations, Ordinary Least Squares Optimization, Residual Geometry, and Python Implementation

Core Learning Objectives

Master the mathematical formulation of Simple and Multiple Linear Regression; explore how Ordinary Least Squares (OLS) minimizes the Residual Sum of Squares (RSS); quantify prediction errors using MAE, MSE, RMSE, and $R^2$; build production regression pipelines with Scikit-Learn; and audit the five classical assumptions of linear modeling.

1. Introduction: The Supervised Prediction Problem

In previous lessons, we mastered dataset creation, exploratory data analysis (EDA), data cleaning, feature transformation, train-validation-test splitting, and preprocessing pipelines. With a pristine, leakage-free feature matrix in hand, our next objective is to train algorithms that extract generalizable patterns from data.

The foundational starting point for supervised machine learning is Linear Regression.

Suppose you are developing an intelligent appraisal engine for Byteion Real Estate. Your task is to estimate the market valuation of residential properties based on structural attributes. Consider historical sales data from recent urban transactions:

Floor Area ($x$) Observed Selling Price ($y$) Implied Unit Rate
800 sq ftBDT 40 LakhBDT 5,000 / sq ft
1,000 sq ftBDT 50 LakhBDT 5,000 / sq ft
1,200 sq ftBDT 60 LakhBDT 5,000 / sq ft
1,500 sq ftBDT 75 LakhBDT 5,000 / sq ft
2,000 sq ftBDT 100 LakhBDT 5,000 / sq ft

An immediate trend emerges: as square footage expands, selling price increases in a steady, linear proportion.

By capturing this relationship as a rigorous mathematical equation, our model can infer the fair market price for any unseen home—such as a 1,750 sq ft property—with empirical confidence.

Formal Definition: Linear Regression is a supervised machine learning algorithm that estimates a continuous numerical target variable ($y$) by modeling an optimal linear relationship between one or more independent feature attributes ($X$) and the target.

2. Practical Real-World Applications

Wherever systems require continuous numeric forecasting rather than discrete category assignment, Linear Regression serves as a rapid, interpretable baseline:

Application Domain Input Attributes ($X$) Continuous Target ($y$)
Real Estate Appraisal Area, bedroom count, building age, location score Property Price (Currency)
E-Commerce Sales Forecasting Ad spend, discount %, trailing 30-day velocity Gross Monthly Revenue ($)
Power Grid Demand Forecasting Ambient temperature, industrial active loads, humidity Load Consumption (Megawatts)
Software Engineer Salary Model Years of experience, degree level, public contributions Annual Base Compensation ($)

3. Regression vs. Classification: Fundamental Dichotomy

Supervised learning divides into two core problem types based on the target variable's mathematical domain:

Dimension Regression Classification
Primary Objective Predict a continuous quantity along the real number line. Assign a sample into one of several discrete classes or categories.
Target Space Continuous Real Numbers $\mathbb{R}$ (e.g. 52.5 Lakh, 98.6°F) Discrete Labels (e.g. "Spam", "Legit", "Class 0 / 1")
Real Estate Case What will this home sell for? ($750,000) Will this home sell within 30 days? (Yes / No)
Evaluation Metrics MAE, MSE, RMSE, $R^2$ Accuracy, Precision, Recall, F1-Score, ROC-AUC

4. Simple Linear Regression: Mathematical Formulation

When estimating a continuous target ($y$) from exactly one scalar predictor ($x$), the framework is termed Simple Linear Regression.

In elementary geometry, straight lines are expressed as $y = mx + c$. In statistical machine learning, standard parameter notation is adopted:

$$\hat{y} = wx + b$$
Weight or Slope ($w$) Quantifies the expected marginal change in the predicted target $\hat{y}$ per single-unit increment in the input feature $x$.
Bias or Intercept ($b$) Represents the baseline output when the input feature is zero ($x = 0 \implies \hat{y} = b$).

Concrete Parameter Interpretation

Suppose our trained model yields: $\hat{y} = 0.05x + 10$ (where $x$ is square feet and $\hat{y}$ is price in Lakh BDT).

  • Slope ($w = 0.05$): Each additional square foot of floor space increases the estimated price by $0.05$ Lakh BDT (BDT 5,000).
  • Intercept ($b = 10$): At zero square feet, $\hat{y} = 10$ Lakh BDT. Since a zero-sq-ft home is a physical impossibility, the intercept functions as an anchor baseline to center the linear hyperplane across the observed data range.

For an apartment measuring 1,200 sq ft, the model's prediction is computed directly:

$$\hat{y} = 0.05(1200) + 10 = 60 + 10 = 70 \text{ Lakh BDT}$$

5. Residuals & Prediction Errors

No empirical dataset falls perfectly onto a 1-dimensional line. The vertical deviation between an actual observed target point and the model's predicted line is the Residual ($e_i$):

$$e_i = y_i - \hat{y}_i$$

Where $y_i$ is the ground-truth target recorded in our dataset, and $\hat{y}_i = wx_i + b$ is the model's estimate.

Positive Residual ($e_i > 0$) Observed price exceeds estimate ($y_i > \hat{y}_i$). The model under-predicted.
Negative Residual ($e_i \lt 0$) Observed price is below estimate ($y_i \lt \hat{y}_i$). The model over-predicted.
Zero Residual ($e_i = 0$) Exact prediction. The observed point lies directly on the regression line.

6. Multiple Linear Regression: Multivariable Prediction

In realistic deployments, property valuation relies on multiple simultaneous features: floor area, bedroom count, age, proximity to transit, and neighborhood metrics.

When $n$ feature attributes ($x_1, x_2, \dots, x_n$) are jointly modeled, the architecture becomes Multiple Linear Regression:

$$\hat{y} = b + w_1 x_1 + w_2 x_2 + w_3 x_3 + \dots + w_n x_n$$

Expressed in compact linear algebra notation: $\hat{y} = Xw + b$, where $X \in \mathbb{R}^{m \times n}$ and $w \in \mathbb{R}^{n \times 1}$.

Partial Derivative Interpretation (Ceteris Paribus):

Suppose our multivariable model is $\hat{y} = 15 + 0.04(\text{Area}) + 5.0(\text{Bedrooms}) - 0.5(\text{Age})$. Here, $w_2 = 5.0$ signifies: holding floor area and building age strictly constant, each additional bedroom increases the expected valuation by 5.0 Lakh BDT. The negative coefficient $w_3 = -0.5$ indicates that each year of age depreciates property value by 0.5 Lakh BDT (BDT 50,000).

7. How Linear Regression Learns: OLS Optimization

The central optimization task is identifying the unique parameter vector ($w^*, b^*$) that minimizes the total aggregate prediction error across all $n$ training records.

The standard closed-form optimization criterion is Ordinary Least Squares (OLS).

Residual Sum of Squares (RSS)

OLS formulates an explicit loss objective by summing the squared residuals of all training points:

$$\text{RSS}(w, b) = \sum_{i=1}^n (y_i - \hat{y}_i)^2 = \sum_{i=1}^n (y_i - (w x_i + b))^2$$
Why square the residuals rather than taking absolute values?
  1. Positive and negative deviations cannot cancel each other out.
  2. Squaring produces a smooth, continuous convex paraboloid loss surface with continuous derivatives ($\frac{\partial \text{RSS}}{\partial w}$), enabling exact closed-form calculus solutions.
  3. Large errors receive quadratic penalties (an error of 10 units has a squared cost of 100, twenty-five times larger than an error of 2 units).

Two Methods of Parameter Optimization

1. Analytical Normal Equation Setting vector derivatives to zero yields an exact closed-form linear algebra solution:
$$w = (X^T X)^{-1} X^T y$$
Scikit-Learn's LinearRegression solves this using Singular Value Decomposition (SVD) and QR factorizations, ensuring numerical stability even when $X^T X$ is singular.
2. Iterative Gradient Descent For massive web-scale datasets where computing $(X^T X)^{-1}$ exceeds RAM bounds, parameters step iteratively down the loss gradient:
$$w \leftarrow w - \alpha \frac{\partial J}{\partial w}$$
Implemented in Scikit-Learn as SGDRegressor.

8. Regression Performance Evaluation Metrics

To validate generalization accuracy on unseen test partitions, practitioners utilize four complementary statistical metrics:

1. Mean Absolute Error (MAE) Unit: Target Unit
$$\text{MAE} = \frac{1}{n}\sum_{i=1}^n |y_i - \hat{y}_i|$$

The arithmetic mean of absolute errors. Highly intuitive for business communication: an MAE of 3.5 Lakh means the model is off by 3.5 Lakh BDT on average. Robust against extreme outliers.

2. Mean Squared Error (MSE) Unit: Squared Target Unit
$$\text{MSE} = \frac{1}{n}\sum_{i=1}^n (y_i - \hat{y}_i)^2$$

The average squared prediction error. Heavily penalizes catastrophic outliers. Because it is denominated in squared units (e.g. $\text{BDT}^2$), direct real-world interpretation is challenging.

3. Root Mean Squared Error (RMSE) Unit: Target Unit
$$\text{RMSE} = \sqrt{\text{MSE}} = \sqrt{\frac{1}{n}\sum_{i=1}^n (y_i - \hat{y}_i)^2}$$

The square root of MSE restores the metric to the target's original dimensions. Unlike MAE, RMSE retains high sensitivity to large outlier prediction failures.

4. Coefficient of Determination ($R^2$) Dimensionless ($-\infty$ to 1.0)
$$R^2 = 1 - \frac{\text{SS}_{\text{res}}}{\text{SS}_{\text{tot}}} = 1 - \frac{\sum (y_i - \hat{y}_i)^2}{\sum (y_i - \bar{y})^2}$$

Quantifies the proportion of target variance explained by the model relative to a naive mean baseline. $R^2 = 0.85$ means 85% of price variation is accounted for by the inputs.

9. End-to-End Implementation with Scikit-Learn

The complete executable workflow: synthetic generation with realistic Gaussian variance, train/test partition, model fitting, parameter inspection, test set scoring, and single-sample inference:

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score

# 1. Synthesize 100 realistic real estate samples with controlled noise
rng = np.random.default_rng(42)
area = rng.uniform(500, 3000, size=100)
# Ground-truth: Price = 10 + 0.05 * Area + Gaussian Noise
price = 10 + 0.05 * area + rng.normal(0, 5, size=100)

df = pd.DataFrame({"area": area, "price": price})

# 2. Separate 2D Feature Matrix (X) and 1D Target Vector (y)
X = df[["area"]]
y = df["price"]

# 3. Partition 80% Train, 20% Test
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.20, random_state=42
)

# 4. Instantiate and fit Ordinary Least Squares estimator
model = LinearRegression()
model.fit(X_train, y_train)

# 5. Inspect learned parameters
print("Learned Slope (w):", round(model.coef_[0], 4))
print("Learned Intercept (b):", round(model.intercept_, 4))

# 6. Evaluate predictions on holdout test partition
y_pred = model.predict(X_test)

mae = mean_absolute_error(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(y_test, y_pred)

print(f"MAE:  {mae:.2f} Lakh BDT")
print(f"RMSE: {rmse:.2f} Lakh BDT")
print(f"R² Score: {r2:.4f}")

# 7. Perform inference on a newly listed 1,500 sq ft property
new_apartment = pd.DataFrame({"area": [1500]})
pred_price = model.predict(new_apartment)
print(f"Predicted Price for 1500 sqft: {pred_price[0]:.2f} Lakh BDT")

10. Five Classical Assumptions of Linear Regression

For OLS coefficient estimates to be Best Linear Unbiased Estimators (Gauss-Markov Theorem), five diagnostic assumptions must hold:

1. Linearity in Parameters The relationship between predictor variables and the conditional mean of the target must be linear. Curvilinear trends require polynomial basis expansions.
2. Independence of Errors (No Autocorrelation) Residuals of distinct observations must be uncorrelated ($\text{Cov}(e_i, e_j) = 0$). Autocorrelation is frequent in time-series and sequential data.
3. Homoscedasticity (Equal Variance) The variance of the residual errors must remain constant across all levels of the fitted values ($\text{Var}(e_i) = \sigma^2$). Expanding error cones indicate Heteroscedasticity.
4. No Perfect Multicollinearity Predictor features must not be exact linear combinations of one another, which renders the Gram matrix $X^T X$ non-invertible.
5. Normality of Residuals Residual errors should follow a Gaussian distribution ($\epsilon \sim \mathcal{N}(0, \sigma^2)$) for valid hypothesis tests ($p$-values) and confidence intervals.

11. Limitations & Production Caveats

Outlier Leverage Because OLS squares errors ($e_i^2$), even a single extreme outlier exerts tremendous leverage, skewing the fitted line away from standard data.
Extrapolation Hazard Inferring values far outside the observed feature envelope (e.g. predicting a 10,000 sq ft mansion with a model trained on 500–3,000 sq ft flats) yields untrustworthy estimates.
Correlation vs. Causation Statistical association between $X$ and $y$ does not establish physical causation. OLS identifies predictive correlations, not causal mechanisms.
Underfitting Non-Linearity Applying a straight line to non-linear phenomena results in high bias underfitting.
Interactive Simulator

Linear Regression Laboratory

Hands-on OLS line fitting, residual geometry inspection, and outlier distortion test

Tune Slope & Bias to minimize loss:

Adjust sliders to observe real-time changes in MSE, RMSE, and $R^2$

Slope ($w$): 0.030 Range: 0.01 – 0.09
Intercept ($b$): 25.0 Range: 0 – 30
500 sq ft Floor Area ($x$) 2,500 sq ft
Mean Squared Error 124.5
Root MSE (RMSE) 11.16
Mean Absolute Error 9.40
R² Score 0.521

12. Summary & Key Takeaways

Linear Formulation In $\hat{y} = wx + b$, slope ($w$) captures the expected marginal rate of change per unit feature increase, while intercept ($b$) acts as baseline calibration.
OLS Loss Minimization Ordinary Least Squares identifies the unique global minimum of Residual Sum of Squares ($\text{RSS}$) using closed-form linear algebra.
Four Core Metrics MAE communicates intuitive average error, RMSE penalizes large catastrophic failures, and $R^2$ indicates total variance explained.
Classical Assumptions Linearity, homoscedasticity, error independence, and absence of multicollinearity must be verified for unbiased statistical inference.
Next Lesson · Lesson 14

Lesson 15.14: Polynomial Regression & Nonlinear Relationships

Real-world phenomena frequently deviate from straight lines. In the next lesson, we will synthesize Polynomial Features ($x^2, x^3$) to capture non-linear curvatures using linear models, analyzing polynomial degrees, bias-variance tradeoffs, and regularization.

Proceed to Next Lesson