Linear Regression
Linear regression is one of the simplest and most fundamental machine learning algorithms. Despite its simplicity, it serves as an excellent baseline model and foundation for understanding more complex algorithms.
Regression Problem Setup
In regression, we aim to learn a function that maps input features to continuous output values.
Dataset: training examples
For each example :
- is the input feature vector (D features)
- is the scalar target (ground truth)
Goal: Learn such that for all training examples.
Examples of Regression Problems
| Problem | Input | Target |
|---|---|---|
| Housing prices | Square footage, location, # bedrooms/bathrooms | House price |
| Weather prediction | Temperature, humidity, wind speed | Amount of rainfall |
| Revenue forecasting | Previous sales data | Company revenue |
The Linear Model
The simplest assumption we can make is that the relationship between inputs and outputs is linear.
Model Definition
Or in compact form:
Where:
- are the weights (model parameters)
- is the bias term (intercept)
Why linear? Linear models are:
- Simple to understand and interpret
- Computationally efficient to train
- Serve as good baseline models
- Can be extended with feature engineering (polynomial features, etc.)
Why a bias term? The bias allows the model to fit data that doesn’t pass through the origin. Without it, we force .
Vectorized Form
We can express this more compactly using vectors:
where and
Absorbing the Bias
To simplify notation, we absorb the bias into the weight vector by adding a dummy feature :
Now our model becomes simply:
Predictions for All Training Examples
Define the design matrix (rows are transposed feature vectors):
Then predictions for all examples:
where
Loss and Cost Functions
Loss Function
The loss function quantifies how bad a prediction is for a single example.
We use squared error loss:
Why this form?
- The square ensures we minimize the magnitude of the residual
- The factor of makes derivative calculations convenient (cancels with the power of 2)
Cost Function
The cost function is the average loss across all training examples:
Expanding with squared error:
Note: In practice, “loss” and “cost” are often used interchangeably.
Vectorized Cost Function
Define the target vector:
Then:
This is called the Mean Squared Error (MSE) cost function.
Why Vectorize?
Vectorized computations offer several advantages:
- Speed: Operations run in parallel on CPU/GPU → reduced computation time
- Cleaner code: No explicit loops → easier to read and maintain
- Memory efficiency: Better handling of large datasets
- Optimized support: Libraries (NumPy, PyTorch, etc.) are built for vectorized operations
Computing the Gradient
To find optimal weights, we minimize the cost function:
Strategy:
- Take derivatives of with respect to
- Set derivatives to zero
- Solve for
Gradient of the Loss Function
Since the cost is the average of losses, we first compute .
For a single example:
Using the chain rule:
where:
- (derivative of squared error)
- (derivative of linear model)
Therefore:
The full gradient vector:
Gradient of the Cost Function
The cost is the average of losses:
Vectorized Gradient
To vectorize :
Define residuals: (an vector)
Then:
Therefore, the vectorized gradient:
Direct Solution (Normal Equations)
Set the gradient to zero and solve:
This is called the normal equations or closed-form solution.
Advantages and Disadvantages
Advantages:
- No iteration required, computes optimal weights in one step
- Guaranteed to find the global minimum (for convex problems)
Disadvantages:
- Computing is expensive: complexity
- Requires to be invertible
- Does not generalize to other models or loss functions
- Impractical when (number of features) is very large
Linear Regression Properties
Advantages
- Interpretable: Weights directly show feature importance
- Efficient: Fast to train on moderate-sized datasets
- Good baseline: Establishes performance floor for more complex models
Limitations
- Assumes linearity: Cannot capture nonlinear relationships without feature engineering
- Sensitive to outliers: Squared error heavily penalizes large residuals
- Continuous features: Requires numerical inputs (categorical features need encoding)
- Multicollinearity: Performance degrades when features are highly correlated
- High bias: May underfit complex data (simple model)
Summary
| Component | Formula |
|---|---|
| Linear Model | |
| Loss Function | |
| Cost Function (MSE) | |
| Gradient | |
| Direct Solution |
Direct Solution:
- No iteration required
- Computationally expensive ()
- Does not generalize to other models
Connection to Modern Practice
MSE as Gaussian MLE
Minimizing the MSE cost function is equivalent to maximum likelihood estimation under the assumption . The negative log-likelihood:
Minimizing over reduces to minimizing the sum of squared residuals. This statistical perspective explains why MSE is the “default” regression loss: it is optimal when errors are Gaussian. For non-Gaussian errors (zero-inflated, heavy-tailed), alternative losses such as Tweedie, Huber, or quantile loss are more appropriate. See the Loss Functions article.
Regularized Variants
| Method | Penalty | Effect |
|---|---|---|
| Ridge (L2) | Shrinks all weights toward zero, handles multicollinearity | |
| Lasso (L1) | Induces sparsity (feature selection) | |
| Elastic Net | Combines L1 sparsity with L2 stability |
Ridge regression has a closed-form solution: . The term ensures invertibility even when is singular or ill-conditioned (more features than observations).
Beyond Linear Features
Linear regression on nonlinear features is the basis for many modern methods:
- Polynomial regression: features are
- Kernel regression / Gaussian processes: features are kernel evaluations
- Neural network linear heads: the final layer of a neural network is linear regression on the learned hidden representation
The power of linear regression lies not in the linearity of the input-output relationship but in the linearity of the parameters, which guarantees convex optimization and closed-form solutions.