Linear Regression
Foundation of supervised learning - regression, OLS, gradient descent
Overview
Linear regression models the relationship between features and a continuous target as a linear combination, finding weights that minimize prediction error.
Core Formulation
Model
Matrix form:
Loss Function (Mean Squared Error)
Goal
Find weights
Solution Methods
Method 1: Normal Equation (Closed-Form)
Derivation:
- Take derivative:
- Set to zero and solve:
- Result:
| Aspect | Details |
|---|---|
| When to use | |
| Time complexity | |
| Space complexity |
Method 2: Gradient Descent
Update rule:
Gradient:
python
def gradient_descent_linear(X, y, lr=0.01, n_iters=1000):
n, d = X.shape
w = np.zeros(d)
for _ in range(n_iters):
predictions = X @ w
gradient = (2/n) * X.T @ (predictions - y)
w = w - lr * gradient
return w| Aspect | Details |
|---|---|
| When to use | Large |
| Time complexity |
Regularization
| Method | Loss Function | Effect | Closed-Form |
|---|---|---|---|
| Ridge (L2) | Shrinks weights toward zero | ||
| Lasso (L1) | Drives weights to exactly zero | No (use coordinate descent) | |
| Elastic Net | Combines sparsity + stability | No |
Assumptions
| Assumption | Meaning | Check | If Violated |
|---|---|---|---|
| Linearity | Residual vs. fitted plot | Add polynomial features | |
| Independence | Errors are independent | Durbin-Watson test | Time-series models |
| Homoscedasticity | Constant error variance | Residuals vs. fitted | Weighted least squares |
| Normality | Q-Q plot | Less critical for large | |
| No multicollinearity | Features not highly correlated | VIF > 10 is concerning | Remove features or regularize |
Interpretation
Coefficient Meaning
- Standardized features: "A 1 std increase in
std change in " - Raw features: "A 1 unit increase in
unit change in "
(Coefficient of Determination)
| Value | Interpretation |
|---|---|
| Perfect fit | |
| No better than mean | |
| Worse than mean |
Adjusted
Interview Questions
Q1: When use linear regression over complex models?
- Interpretability needed - stakeholders must understand contributions
- Approximately linear relationship - or can engineer features
- Limited data - complex models overfit
- Baseline model - always start simple
Q2: L1 vs L2 regularization?
| L1 (Lasso) | L2 (Ridge) |
|---|---|
| Drives weights to exactly zero | Shrinks but keeps all features |
| Feature selection | Handles correlated features better |
| Sparse models | More stable coefficients |
If unsure: Use Elastic Net (combines both) with cross-validation.
Q3: What does multicollinearity do?
- Effect: Coefficients unstable, uninterpretable (high variance)
- Detection: Correlation matrix, VIF > 10
- Fix: Remove correlated features, combine them, or use regularization
Q4: Non-linear relationships?
- Feature engineering - polynomial (
, ), interactions ( ), log transforms - Splines - piecewise polynomial fitting
- Non-linear models - trees, neural networks
Code Reference
python
import numpy as np
class LinearRegression:
def __init__(self, method='normal', lr=0.01, n_iters=1000,
regularization=None, lambda_=0.1):
self.method = method
self.lr = lr
self.n_iters = n_iters
self.regularization = regularization
self.lambda_ = lambda_
self.weights = None
def fit(self, X, y):
X = np.c_[np.ones(len(X)), X] # Add bias
if self.method == 'normal':
if self.regularization == 'l2':
I = np.eye(X.shape[1])
I[0, 0] = 0 # Don't regularize bias
self.weights = np.linalg.inv(X.T @ X + self.lambda_ * I) @ X.T @ y
else:
self.weights = np.linalg.inv(X.T @ X) @ X.T @ y
else: # Gradient descent
self.weights = np.zeros(X.shape[1])
for _ in range(self.n_iters):
grad = (2/len(X)) * X.T @ (X @ self.weights - y)
if self.regularization == 'l2':
grad[1:] += 2 * self.lambda_ * self.weights[1:]
self.weights -= self.lr * grad
def predict(self, X):
X = np.c_[np.ones(len(X)), X]
return X @ self.weights
def score(self, X, y):
"""R^2 score"""
y_pred = self.predict(X)
ss_res = np.sum((y - y_pred) ** 2)
ss_tot = np.sum((y - np.mean(y)) ** 2)
return 1 - ss_res / ss_totQuick Reference Card
LINEAR REGRESSION
-------------------------------------------------
Model: y_hat = Xw
Loss: MSE = (1/n)||y - Xw||^2
Solution: w = (X'X)^{-1}X'y OR gradient descent
REGULARIZATION
-------------------------------------------------
L2 (Ridge): + lambda||w||^2 -> shrinks weights
L1 (Lasso): + lambda|w| -> sparse weights
ASSUMPTIONS
-------------------------------------------------
1. Linearity
2. Independence of errors
3. Homoscedasticity (constant variance)
4. Normality of errors
5. No multicollinearity
COMPLEXITY
-------------------------------------------------
Normal equation: O(nd^2 + d^3) time, O(d^2) space
Gradient descent: O(nd) per iteration
USE WHEN
-------------------------------------------------
- Interpretability needed
- Linear relationship (or engineerable)
- Baseline model
- Small-medium dataset