Quiz 2

Multiple & Polynomial Regression

2240 words
11 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Multiple & Polynomial Regression ## 🎯 Learning Objectives - Formulate multiple linear regression with vectorized notation - Understand feature scaling and why it's critical for gradient descent - Implement polynomial regression by adding polynomial features - Detect when a polynomial model is overfitting - Compar...

Multiple & Polynomial Regression

🎯 Learning Objectives

  • Formulate multiple linear regression with vectorized notation
  • Understand feature scaling and why it's critical for gradient descent
  • Implement polynomial regression by adding polynomial features
  • Detect when a polynomial model is overfitting
  • Compare linear, quadratic, and cubic models using validation curves

📋 Prerequisites

  • Linear Regression — the foundation we extend here
  • Matrix multiplication — for the vectorized hypothesis
  • Gradient descent — we'll use the same optimization

📖 Core Content

3.1 Intuition: Why Multiple Features?

House price prediction using only square footage is like judging a book by its page count. Yes, page count matters, but so do genre, author, publication year, and reviews. Multiple linear regression lets us use ALL available information — every column in our dataset becomes a feature.
y^=θ0+θ1x1+θ2x2+θ3x3++θnxn\hat{y} = \theta_0 + \theta_1 x_1 + \theta_2 x_2 + \theta_3 x_3 + \dots + \theta_n x_n
Where nn is the number of features. (Diagram) Polynomial regression extends this further — what if the relationship isn't a straight line? Maybe price increases faster for larger houses (diminishing returns on small houses, luxury premium on large ones). We can create new features like x2x^2, x3x^3, or x\sqrt{x} to model curves.

3.2 Multiple Linear Regression — Vectorized Form

The Hypothesis (vectorized):
hθ(x)=θTx=θ0x0+θ1x1++θnxnh_\theta(x) = \theta^T x = \theta_0 x_0 + \theta_1 x_1 + \dots + \theta_n x_n
Where x0=1x_0 = 1 (the bias term). In matrix form:
y^=Xθ\hat{y} = X\theta
Design Matrix:
X=[1x1(1)x2(1)xn(1)1x1(2)x2(2)xn(2)1x1(m)x2(m)xn(m)]X = \begin{bmatrix} 1 & x_1^{(1)} & x_2^{(1)} & \dots & x_n^{(1)} \\ 1 & x_1^{(2)} & x_2^{(2)} & \dots & x_n^{(2)} \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ 1 & x_1^{(m)} & x_2^{(m)} & \dots & x_n^{(m)} \end{bmatrix}
Gradient Descent (single update for all j):
θj:=θjα1mi=1m(hθ(x(i))y(i))xj(i)\theta_j := \theta_j - \alpha \frac{1}{m} \sum_{i=1}^{m} (h_\theta(x^{(i)}) - y^{(i)}) x_j^{(i)}
Normal Equation (closed-form):
θ=(XTX)1XTy\theta = (X^T X)^{-1} X^T y

3.3 Worked Example 1: Two-Feature Multiple Regression

Predict exam score (yy) from hours studied (x1x_1) and practice tests taken (x2x_2).
StudentHours ( x1x_1 )Tests ( x2x_2 )Score ( yy )
A2165
B4275
C6385
D8495
Design Matrix:
X=[121142163184],y=[65758595]X = \begin{bmatrix} 1 & 2 & 1 \\ 1 & 4 & 2 \\ 1 & 6 & 3 \\ 1 & 8 & 4 \end{bmatrix}, \quad y = \begin{bmatrix} 65 \\ 75 \\ 85 \\ 95 \end{bmatrix}
Normal Equation:
XTX=[420102012060106030]X^T X = \begin{bmatrix} 4 & 20 & 10 \\ 20 & 120 & 60 \\ 10 & 60 & 30 \end{bmatrix}
Compute inverse (using formula or calculator):
(XTX)1=[3.750.6251.250.6250.1250.251.250.250.5](X^T X)^{-1} = \begin{bmatrix} 3.75 & -0.625 & -1.25 \\ -0.625 & 0.125 & 0.25 \\ -1.25 & 0.25 & 0.5 \end{bmatrix}
Compute θ\theta:
XTy=[3201740870]X^T y = \begin{bmatrix} 320 \\ 1740 \\ 870 \end{bmatrix} θ=(XTX)1XTy=[45510]\theta = (X^T X)^{-1} X^T y = \begin{bmatrix} 45 \\ 5 \\ 10 \end{bmatrix}
Model: y^=45+5x1+10x2\hat{y} = 45 + 5x_1 + 10x_2 Interpretation:
  • θ0=45\theta_0 = 45: baseline score with 0 hours and 0 tests
  • θ1=5\theta_1 = 5: each additional hour adds 5 points (holding tests constant)
  • θ2=10\theta_2 = 10: each practice test adds 10 points (holding hours constant) Predictions:
  • Student A: 45+5(2)+10(1)=6545 + 5(2) + 10(1) = 65
  • Student C: 45+5(6)+10(3)=10545 + 5(6) + 10(3) = 105 — wait, that's > 100! Edge case break: Our model predicts Student C would score 105, but scores are capped at 100. This reveals that the linear relationship breaks down at the boundaries — a limitation of linear models.

3.4 Feature Scaling

When features have different scales (e.g., income in 50k50k-150k and age in 20-60), gradient descent becomes inefficient. The cost function contours become elongated ellipses. Standardization (Z-score normalization):
xj(i):=xj(i)μjσjx_j^{(i)} := \frac{x_j^{(i)} - \mu_j}{\sigma_j}
Where μj\mu_j is the mean and σj\sigma_j is the standard deviation of feature jj. Min-Max Scaling (Normalization):
xj(i):=xj(i)min(xj)max(xj)min(xj)x_j^{(i)} := \frac{x_j^{(i)} - \min(x_j)}{\max(x_j) - \min(x_j)}
Range: [0, 1]
MethodWhen to UseRange
StandardizationFeatures have outliersCentered at 0, σ=1
Min-MaxFeatures bounded, no outliers[0, 1]
Robust (IQR)Many outliersCentered at median

3.5 Polynomial Regression

Sometimes the relationship isn't linear. Consider housing prices:
python
# runnable
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
# Non-linear data: y = 2 + 3x - 0.5x² + noise
np.random.seed(42)
X = np.linspace(0, 5, 20).reshape(-1, 1)
y = 2 + 3*X.ravel() - 0.5*X.ravel()**2 + np.random.randn(20) * 0.5
# Linear model
linear = LinearRegression()
linear.fit(X, y)
# Polynomial model (degree 2)
poly = PolynomialFeatures(degree=2, include_bias=False)
X_poly = poly.fit_transform(X)
poly_reg = LinearRegression()
poly_reg.fit(X_poly, y)
print(f"Linear:   y = {linear.intercept_:.2f} + {linear.coef_[0]:.2f}x")
print(f"Polynomial: y = {poly_reg.intercept_:.2f} + {poly_reg.coef_[0]:.2f}x + {poly_reg.coef_[1]:.2f}x²")
# Plot
X_plot = np.linspace(0, 5, 100).reshape(-1, 1)
plt.scatter(X, y, label='Data')
plt.plot(X_plot, linear.predict(X_plot), 'r--', label='Linear')
plt.plot(X_plot, poly_reg.predict(PolynomialFeatures(2).fit_transform(X_plot)), 'g-', label='Quadratic')
plt.legend()
plt.grid(True)
plt.show()

3.6 Worked Example 2: Polynomial Degree Selection

Let's fit polynomials of increasing degree to the same data:
python
# runnable
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
# Generate data
np.random.seed(0)
X = np.linspace(0, 3, 15).reshape(-1, 1)
y = np.sin(X).ravel() + np.random.randn(15) * 0.15
degrees = [1, 3, 9, 15]
plt.figure(figsize=(12, 8))
for i, deg in enumerate(degrees):
    poly = PolynomialFeatures(degree=deg, include_bias=False)
    X_poly = poly.fit_transform(X)
    model = LinearRegression()
    model.fit(X_poly, y)
    X_plot = np.linspace(0, 3, 200).reshape(-1, 1)
    y_plot = model.predict(PolynomialFeatures(deg).fit_transform(X_plot))
    plt.subplot(2, 2, i+1)
    plt.scatter(X, y, color='blue', alpha=0.7)
    plt.plot(X_plot, y_plot, 'r-')
    plt.title(f'Degree {deg}')
    plt.grid(True)
plt.tight_layout()
plt.show()
Observations:
  • Degree 1: Underfitting — too simple, misses the curve
  • Degree 3: Good fit — captures the sine shape well
  • Degree 9: Overfitting — wiggly, memorizes noise
  • Degree 15: Severe overfitting — extreme oscillations between points

3.7 The Bias-Variance Tradeoff

(Diagram)
RegimeTraining ErrorTest ErrorFix
UnderfittingHighHighAdd features, increase model complexity
OverfittingVery LowHighAdd data, regularize, simplify model
Good FitLowLow

3.8 When to Use / Not Use

Polynomial Regression ✅❌ When NOT to Use
Non-linear relationships you can model with polynomialsData with periodic patterns (use Fourier features)
Feature interactions matterVery high-dimensional data (n > 50)
Interpretability still needed (coefficients have meaning)Extrapolation beyond training range (polynomials blow up)
Smooth, continuous relationshipsData with abrupt changes or discontinuities

📐 Key Formulas / Concepts

ConceptFormulaNotes
Multiple Linear Hypothesishθ(x)=θTxh_\theta(x) = \theta^T xVectorized: n+1 parameters
Normal Equationθ=(XTX)1XTy\theta = (X^T X)^{-1} X^T yO(n³) complexity
Standardizationz=xμσz = \frac{x - \mu}{\sigma}Zero mean, unit variance
Min-Max Scalingx=xminmaxminx' = \frac{x - min}{max - min}Range [0, 1]
Polynomial Featuresϕ(x)=[1,x,x2,,xd]\phi(x) = [1, x, x^2, \dots, x^d]Create design matrix with powers
R² with n featuresSame formulaAdjust for n: Adj R²

⚠️ Common Pitfalls

Pitfall 1: Not Scaling Features for Gradient Descent

The mistake: Training with features on vastly different scales (income: $50k vs. age: 30). Why: Gradient descent zigzags slowly down the elongated cost function, taking many iterations. Fix: Standardize all features to have mean 0 and std 1.

Pitfall 2: Using Too High a Polynomial Degree

The mistake: Assuming higher degree = better model (degree 15 polynomial on 15 points). Why: The model perfectly interpolates every training point but oscillates wildly between them. Fix: Use cross-validation to determine the optimal degree. Start with degree 1-3 and increase only if validation error decreases.

Pitfall 3: Extrapolating Polynomials

The mistake: Predicting outside the training range (e.g., house price at 10,000 sq. ft. when max training was 3,000). Why: Polynomials grow extremely fast outside the training region — tiny input changes produce massive output swings. Fix: Never extrapolate far beyond training data range. Use splines or GPs for extrapolation tasks.

📝 Practice Questions

Q1: A model has 3 features. How many parameters does it have?
Answer: 4 parameters — θ0\theta_0 (intercept) + θ1,θ2,θ3\theta_1, \theta_2, \theta_3 (one per feature). The hypothesis is: hθ(x)=θ0+θ1x1+θ2x2+θ3x3h_\theta(x) = \theta_0 + \theta_1 x_1 + \theta_2 x_2 + \theta_3 x_3 Q2: Feature A has range [0.001, 0.01] and Feature B has range [100, 1000]. Why must we scale?
Answer: Without scaling, gradient descent updates for Feature A will be tiny (gradient ~ average error × 0.001) and for Feature B will be huge (gradient ~ average error × 100). This causes uneven convergence — B converges quickly while A barely changes. Standardization or min-max scaling fixes this imbalance. Q3: Compute (X^T X)^{-1} X^T y for points (1,1), (2,3), (3,6) with a quadratic model y = θ₀ + θ₁x + θ₂x²
Design Matrix:
>X=[111124139]>> X = \begin{bmatrix} 1 & 1 & 1 \\ 1 & 2 & 4 \\ 1 & 3 & 9 \end{bmatrix} >
Compute:
>XTX=[361461436143698],(XTX)1=[0.50.500.51.0830.2500.250.083]>> X^T X = \begin{bmatrix} 3 & 6 & 14 \\ 6 & 14 & 36 \\ 14 & 36 & 98 \end{bmatrix}, \quad (X^T X)^{-1} = \begin{bmatrix} 0.5 & -0.5 & 0 \\ -0.5 & 1.083 & -0.25 \\ 0 & -0.25 & 0.083 \end{bmatrix} >
>XTy=[102567],θ=(XTX)1XTy=[00.50.5]>> X^T y = \begin{bmatrix} 10 \\ 25 \\ 67 \end{bmatrix}, \quad \theta = (X^T X)^{-1}X^T y = \begin{bmatrix} 0 \\ 0.5 \\ 0.5 \end{bmatrix} >
Model: y^=0+0.5x+0.5x2\hat{y} = 0 + 0.5x + 0.5x^2
Check: x=1: 1.0 (actual 1), x=2: 3.0 (actual 3), x=3: 6.0 (actual 6) — perfect fit! Q4: What is the main advantage of vectorized implementation?
Answer: Vectorized code (using matrix operations) is much faster than explicit loops because:
  1. It uses highly optimized BLAS linear algebra libraries
  2. It leverages CPU cache and SIMD instructions
  3. It avoids Python loop overhead
With NumPy, theta = np.linalg.inv(X.T @ X) @ X.T @ y is both cleaner and faster than any loop-based implementation. Q5: With 10 features and 1000 datapoints, which is better: Normal Equation or gradient descent?
Answer: Both work fine for 10 features (Normal Equation is O(n³) = O(1000), cheap for n=10). But gradient descent scales better to larger datasets and integrates with regularization. For n=10, m=1000, either choice is acceptable — use Normal Equation for simplicity. Q6: A degree-20 polynomial perfectly fits training data (R²=1) but fails on test data. What's happening and what do you do?
Answer: This is overfitting — the model has memorized the training data including noise. Solutions:
  1. Reduce polynomial degree (try 2-5)
  2. Add regularization (Ridge/Lasso)
  3. Get more training data
  4. Use cross-validation to select optimal degree
The training R² of 1.0 is misleading — it doesn't indicate generalization. Q7: Transform y = 3 + 2x + 0.5x² into polynomial features for sklearn
python
from sklearn.preprocessing import PolynomialFeatures
import numpy as np

X = np.array([1], [2], [3](/courses/bscs2004/notes/1%5D%2C%20%5B2%5D%2C%20%5B3))
poly = PolynomialFeatures(degree=2, include_bias=False)
X_poly = poly.fit_transform(X)
# X_poly columns: [x, x²]
# For x=2: [2, 4]
PolynomialFeatures with include_bias=False creates columns [x, x², x³, ...]. The bias term (column of 1's) is added by the linear regression automatically. Q8: What's the difference between standardization and min-max scaling?
Answer:
  • Standardization subtracts mean and divides by standard deviation. Result: mean=0, std=1. Not bounded — can be any value. Good with outliers.
  • Min-Max scaling subtracts min and divides by range. Result: range [0, 1]. Bounded. Sensitive to outliers (a single outlier compresses most values into a small range).
Use standardization for algorithms that assume normally distributed data (SVM, PCA, linear regression). Use min-max for neural networks. Q9: Using our model ŷ = 45 + 5x₁ + 10x₂, interpret θ₂ = 10
Answer: Holding hours studied (x1x_1) constant, each additional practice test (x2x_2) is associated with a 10-point increase in exam score (y^\hat{y}). This is the ceteris paribus (all else equal) interpretation — it controls for the effect of the other feature. Q10: Your linear model performs poorly but adding x² helps. What does this suggest?
Answer: The relationship between X and Y is non-linear. Adding x² (a quadratic term) captures curvature. The sign of the x² coefficient tells you the direction:
  • Positive coefficient: concave up (U-shaped)
  • Negative coefficient: concave down (inverted-U) Q11: Why does the rank of X^T X matter for the Normal Equation?
Answer: If XTXX^T X is not full rank (determinant = 0), it's non-invertible. This happens when:
  1. Features are linearly dependent (e.g., one column = 2× another)
  2. More features than training examples (underdetermined system)
Solution: Remove collinear features, use pseudo-inverse np.linalg.pinv, or add L2 regularization (Ridge regression). Q12: Compare linear (deg=1), quadratic (deg=2), and cubic (deg=3) polynomial models.
Answer:
AspectDegree 1Degree 2Degree 3
Parameters234
ShapeStraight lineSingle curve (U or ∩)S-curve (one inflection)
BiasHighestMediumLower
VarianceLowestMediumHigher
Training errorHighestLowerLowest
RiskUnderfittingGood balanceOverfitting risk
Rule of thumb: start with degree 1-3 and use validation to select.

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.