3.1 Linear Models
3.1 Linear Models
Key Concepts
3.1.1 Linear Regression
Linear regression models the relationship between features and a continuous target as a linear combination.
Model Formulation
y_hat = w0 + w1*x1 + w2*x2 + ... + wn*xn
= w^T * x + b
= X @ w (with bias absorbed into X)
Where:
- w = weight vector (parameters)
- x = feature vector
- b = bias (intercept)Loss Function (Mean Squared Error)
L(w) = (1/n) * sum((yi - y_hat_i)^2)
= (1/n) * ||y - X @ w||^2Closed-Form Solution (Normal Equation)
Setting the gradient to zero:
grad_L = -2 * X^T @ (y - X @ w) = 0
X^T @ y = X^T @ X @ w
w* = (X^T @ X)^(-1) @ X^T @ yRequirements:
- X^T @ X must be invertible (full rank)
- n >= d (more samples than features)
Complexity: O(n*d^2 + d^3) for matrix operations
Gradient Descent Solution
# Initialize weights
w = np.zeros(d)
# Iterate
for epoch in range(max_epochs):
# Compute gradient
gradient = -2/n * X.T @ (y - X @ w)
# Update weights
w = w - learning_rate * gradientComplexity per iteration: O(n*d)
When to Use Which
| Scenario | Closed-Form | Gradient Descent |
|---|---|---|
| Small n, small d | Preferred | Works |
| Large n, small d | Preferred | Works |
| Small n, large d | May fail (singular) | Preferred |
| Large n, large d | Too slow O(d^3) | Preferred |
| Online learning | Not possible | Required |
| Regularization | Modified formula | Easy to add |
Rule of thumb: Use closed-form for d < 10,000; gradient descent otherwise.
3.1.2 Assumptions of Linear Regression
For valid statistical inference (confidence intervals, p-values), linear regression assumes:
1. Linearity
The relationship between X and y is linear.
True: y = b0 + b1*x + e
Not: y = b0 + b1*x^2 + e (need to transform features)Check: Residual plot should show no pattern
2. Independence
Observations are independent of each other.
Violations:
- Time series data (autocorrelation)
- Clustered data (students in same class)
- Spatial data (nearby locations correlated)
Check: Durbin-Watson test for autocorrelation
3. Homoscedasticity
Constant variance of residuals across all levels of X.
Fix: Weighted least squares, transform y (log, sqrt)
4. Normality of Residuals
Residuals are normally distributed: e ~ N(0, sigma^2)
Check: Q-Q plot, Shapiro-Wilk test
Note: Less important for large samples (CLT), mainly affects confidence intervals.
5. No Multicollinearity
Features are not highly correlated with each other.
Check: VIF (Variance Inflation Factor) < 5-10
Fix: Remove features, PCA, Ridge regression
3.1.3 Logistic Regression
Logistic regression is a classification algorithm that models the probability of class membership.
Why Not Linear Regression for Classification?
Linear regression for binary y in {0, 1}:
- Predictions can be < 0 or > 1 (invalid probabilities)
- Assumes constant effect regardless of probability level
The Sigmoid Function
Maps any real number to (0, 1):
sigmoid(z) = 1 / (1 + e^(-z))
Properties:
- sigmoid(0) = 0.5
- sigmoid(inf) = 1
- sigmoid(-inf) = 0
- sigmoid'(z) = sigmoid(z) * (1 - sigmoid(z))Model Formulation
P(y=1|x) = sigmoid(w^T @ x + b) = 1 / (1 + e^(-(w^T @ x + b)))
Log-odds (logit):
log(P(y=1) / P(y=0)) = w^T @ x + b
Interpretation: Linear in log-odds spaceDecision Boundary
Predict y = 1 if P(y=1|x) > 0.5
<=> sigmoid(w^T @ x + b) > 0.5
<=> w^T @ x + b > 0
Decision boundary: w^T @ x + b = 0 (hyperplane)Loss Function (Binary Cross-Entropy)
L(w) = -1/n * sum(yi * log(p_hat_i) + (1-yi) * log(1-p_hat_i))
Where p_hat_i = sigmoid(w^T @ xi + b)Why this loss?
- Derived from maximum likelihood estimation
- Convex -> guaranteed global minimum
- Penalizes confident wrong predictions heavily
Gradient
dL/dw = 1/n * sum((p_hat_i - yi) * xi)
= 1/n * X^T @ (p_hat - y)
Same form as linear regression! (but p_hat is non-linear in w)No Closed-Form Solution
Unlike linear regression, logistic regression has no closed-form solution because:
- The sigmoid makes the equation non-linear in w
- Must use iterative optimization (gradient descent, Newton's method)
3.1.4 Multiclass Classification (Softmax)
Extend logistic regression to K > 2 classes.
Softmax Function
P(y=k|x) = e^(wk^T @ x) / sum_j(e^(wj^T @ x))
Properties:
- All probabilities in (0, 1)
- Sum to 1 across classes
- Generalizes sigmoid (K=2 reduces to sigmoid)Cross-Entropy Loss (Multiclass)
L = -1/n * sum_i sum_k (y_ik * log(p_hat_ik))
Where y_ik = 1 if sample i belongs to class kOne-vs-Rest (OvR) Alternative
Train K binary classifiers, each distinguishing one class from all others.
Classifier 1: Class 1 vs {2, 3, ..., K}
Classifier 2: Class 2 vs {1, 3, ..., K}
...
Classifier K: Class K vs {1, 2, ..., K-1}
Prediction: argmax of all classifier scores3.1.5 Regularized Linear Models
Ridge Regression (L2)
L_ridge = ||y - X @ w||^2 + lambda * ||w||^2
Closed-form: w* = (X^T @ X + lambda * I)^(-1) @ X^T @ y
Benefits:
- Always invertible (even if X^T @ X is singular)
- Handles multicollinearity
- Shrinks coefficients toward zeroLasso Regression (L1)
L_lasso = ||y - X @ w||^2 + lambda * ||w||_1
No closed-form (use coordinate descent, LARS)
Benefits:
- Feature selection (sparse solutions)
- Interpretable modelsQuestions & Answers
Q1: What are the assumptions of linear regression?
Answer:
Linear regression makes five key assumptions for valid statistical inference:
1. Linearity
- Relationship between X and y is linear
- Check: Residual plot shows no pattern
- Fix: Transform features (polynomial, log)
2. Independence
- Observations are independent
- Violated in: time series, clustered data
- Check: Durbin-Watson test
3. Homoscedasticity
- Constant variance of residuals
- Check: Residuals vs fitted plot
- Fix: Weighted least squares, transform y
4. Normality of Residuals
- Residuals ~ N(0, sigma^2)
- Check: Q-Q plot
- Less critical for large samples
5. No Multicollinearity
- Features not highly correlated
- Check: VIF < 5-10
- Fix: Remove features, Ridge regression
Important distinction:
- For prediction: Only linearity matters much
- For inference (p-values, CIs): All assumptions matter
Q2: What is the closed-form solution of linear regression? When is gradient descent better?
Answer:
Closed-form (Normal Equation):
w* = (X^T @ X)^(-1) @ X^T @ yDerivation:
- Loss: L(w) = ||y - X @ w||^2
- Gradient: grad_L = -2 * X^T @ (y - X @ w)
- Set to zero: X^T @ y = X^T @ X @ w
- Solve: w* = (X^T @ X)^(-1) @ X^T @ y
Complexity: O(n*d^2 + d^3)
When gradient descent is better:
| Scenario | Closed-Form | Gradient Descent |
|---|---|---|
| d > 10,000 | O(d^3) too slow | O(n*d) per iteration |
| X^T @ X singular | Fails | Works with regularization |
| Online/streaming | Impossible | Natural fit |
| Memory limited | Stores full matrices | Mini-batch possible |
| With regularization | Modified formula | Easy to add |
Practical rule:
- d < 10,000 and X^T @ X invertible -> closed-form
- Otherwise -> gradient descent (or variants like SGD, Adam)
Q3: How does logistic regression work?
Answer:
Logistic regression models the probability of binary outcomes using the sigmoid function.
Model:
P(y=1|x) = sigmoid(w^T @ x + b) = 1 / (1 + e^(-(w^T @ x + b)))Key components:
- Linear combination: z = w^T @ x + b
- Sigmoid transformation: Maps z to probability (0, 1)
- Decision rule: Predict 1 if P(y=1|x) > 0.5
Training:
- Loss: Binary cross-entropy
L = -sum(y * log(p_hat) + (1-y) * log(1-p_hat)) - Optimization: Gradient descent (no closed-form)
- Gradient: dL/dw = X^T @ (p_hat - y)
Decision boundary:
- Linear hyperplane: w^T @ x + b = 0
- Points where P(y=1) = 0.5
Interpretation:
- Coefficients represent change in log-odds per unit change in feature
- exp(wi) = odds ratio for feature i
Advantages:
- Probabilistic outputs
- Interpretable coefficients
- Works well for linearly separable data
- Convex loss -> global optimum
Q4: Write the loss function for logistic regression and prove it has a global minimum.
Answer:
Loss function (Binary Cross-Entropy / Negative Log-Likelihood):
L(w) = -1/n * sum(yi * log(sigmoid(w^T @ xi)) + (1-yi) * log(1 - sigmoid(w^T @ xi)))Proof of convexity (guarantees global minimum):
A function is convex if its Hessian is positive semi-definite.
Step 1: Compute the Hessian
First derivative (gradient):
dL/dw = 1/n * sum((sigmoid(w^T @ xi) - yi) * xi)Second derivative (Hessian):
H = d^2L/dw^2 = 1/n * sum(sigmoid(w^T @ xi) * (1 - sigmoid(w^T @ xi)) * xi @ xi^T)
= 1/n * X^T @ D @ X
Where D = diag(pi * (1-pi)) and pi = sigmoid(w^T @ xi)Step 2: Show H is positive semi-definite
For any vector v:
v^T @ H @ v = 1/n * v^T @ X^T @ D @ X @ v
= 1/n * (X @ v)^T @ D @ (X @ v)
= 1/n * sum(pi * (1-pi) * (v^T @ xi)^2)Since:
- pi in (0,1) -> pi * (1-pi) > 0
- (v^T @ xi)^2 >= 0
Therefore v^T @ H @ v >= 0 for all v, so H is positive semi-definite.
Conclusion: L(w) is convex, so any local minimum is a global minimum. Gradient descent will find it.
Q5: How do you modify logistic regression for quadratically separable data?
Answer:
If data is not linearly separable but can be separated by a quadratic boundary, add polynomial features.
Original features: x = [x1, x2]
Expanded features (degree 2):
phi(x) = [1, x1, x2, x1^2, x2^2, x1*x2]New model:
P(y=1|x) = sigmoid(w^T @ phi(x))
= sigmoid(w0 + w1*x1 + w2*x2 + w3*x1^2 + w4*x2^2 + w5*x1*x2)Decision boundary:
w0 + w1*x1 + w2*x2 + w3*x1^2 + w4*x2^2 + w5*x1*x2 = 0This is a conic section (ellipse, parabola, hyperbola, or circle).
Implementation:
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LogisticRegression
poly = PolynomialFeatures(degree=2)
X_poly = poly.fit_transform(X)
model = LogisticRegression()
model.fit(X_poly, y)Considerations:
- Higher degree -> more features -> risk of overfitting
- Use regularization with polynomial features
- Alternative: kernel methods (SVM with RBF kernel)
Q6: What would the parameters look like for a decision tree with just 2 features? What about logistic regression?
Answer:
Decision Tree (2 features: x1, x2):
Parameters are split rules (axis-aligned):
Tree structure:
[x1 < 3?]
/ \
Yes No
/ \
[x2 < 5?] Class B
/ \
Yes No
/ \
Class A Class B
Parameters:
- Split feature at each node (x1 or x2)
- Split threshold at each node (3, 5, ...)
- Class label at each leafDecision boundary: Axis-aligned rectangular regions
Logistic Regression (2 features):
Parameters are weights:
P(y=1) = sigmoid(w0 + w1*x1 + w2*x2)
Parameters:
- w0 (bias/intercept)
- w1 (weight for x1)
- w2 (weight for x2)
Total: 3 parametersDecision boundary:
w0 + w1*x1 + w2*x2 = 0
x2 = -(w0 + w1*x1) / w2
A single straight lineComparison:
| Aspect | Decision Tree | Logistic Regression |
|---|---|---|
| Boundary shape | Axis-aligned rectangles | Single line/hyperplane |
| Parameters | Splits + thresholds | d+1 weights |
| Flexibility | Can model complex regions | Only linear boundaries |
| Interpretability | If-then rules | Coefficient interpretation |
| Extrapolation | Constant outside training range | Continues linear trend |