Multiple & Polynomial Regression
2240 words
11 min read
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.
Where n 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 x2, x3, or x to model curves.
3.2 Multiple Linear Regression — Vectorized Form
The Hypothesis (vectorized):
Where x0=1 (the bias term). In matrix form:
Design Matrix:
Gradient Descent (single update for all j):
Normal Equation (closed-form):
3.3 Worked Example 1: Two-Feature Multiple Regression
Predict exam score (y) from hours studied (x1) and practice tests taken (x2).
| Student | Hours ( x1 ) | Tests ( x2 ) | Score ( y ) |
|---|---|---|---|
| A | 2 | 1 | 65 |
| B | 4 | 2 | 75 |
| C | 6 | 3 | 85 |
| D | 8 | 4 | 95 |
Design Matrix:
Normal Equation:
Compute inverse (using formula or calculator):
Compute θ:
Model: y^=45+5x1+10x2
Interpretation:
- θ0=45: baseline score with 0 hours and 0 tests
- θ1=5: each additional hour adds 5 points (holding tests constant)
- θ2=10: each practice test adds 10 points (holding hours constant) Predictions:
- Student A: 45+5(2)+10(1)=65 ✓
- Student C: 45+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 50k−150k and age in 20-60), gradient descent becomes inefficient. The cost function contours become elongated ellipses.
Standardization (Z-score normalization):
Where μj is the mean and σj is the standard deviation of feature j.
Min-Max Scaling (Normalization):
Range: [0, 1]
| Method | When to Use | Range |
|---|---|---|
| Standardization | Features have outliers | Centered at 0, σ=1 |
| Min-Max | Features bounded, no outliers | [0, 1] |
| Robust (IQR) | Many outliers | Centered 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)
| Regime | Training Error | Test Error | Fix |
|---|---|---|---|
| Underfitting | High | High | Add features, increase model complexity |
| Overfitting | Very Low | High | Add data, regularize, simplify model |
| Good Fit | Low | Low | ✓ |
3.8 When to Use / Not Use
| Polynomial Regression ✅ | ❌ When NOT to Use |
|---|---|
| Non-linear relationships you can model with polynomials | Data with periodic patterns (use Fourier features) |
| Feature interactions matter | Very high-dimensional data (n > 50) |
| Interpretability still needed (coefficients have meaning) | Extrapolation beyond training range (polynomials blow up) |
| Smooth, continuous relationships | Data with abrupt changes or discontinuities |
📐 Key Formulas / Concepts
| Concept | Formula | Notes |
|---|---|---|
| Multiple Linear Hypothesis | hθ(x)=θTx | Vectorized: n+1 parameters |
| Normal Equation | θ=(XTX)−1XTy | O(n³) complexity |
| Standardization | z=σx−μ | Zero mean, unit variance |
| Min-Max Scaling | x′=max−minx−min | Range [0, 1] |
| Polynomial Features | ϕ(x)=[1,x,x2,…,xd] | Create design matrix with powers |
| R² with n features | Same formula | Adjust 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
>X=111123149>Q1: A model has 3 features. How many parameters does it have?Answer: 4 parameters — θ0 (intercept) + θ1,θ2,θ3 (one per feature). The hypothesis is: hθ(x)=θ0+θ1x1+θ2x2+θ3x3 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:
>XTX=361461436143698,(XTX)−1=0.5−0.50−0.51.083−0.250−0.250.083>Compute:
>XTy=102567,θ=(XTX)−1XTy=00.50.5>
Model: y^=0+0.5x+0.5x2Check: 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:
- It uses highly optimized BLAS linear algebra libraries
- It leverages CPU cache and SIMD instructions
- It avoids Python loop overhead
With NumPy,theta = np.linalg.inv(X.T @ X) @ X.T @ yis 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:
- Reduce polynomial degree (try 2-5)
- Add regularization (Ridge/Lasso)
- Get more training data
- 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 sklearnpythonfrom 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 withinclude_bias=Falsecreates 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 θ₂ = 10Answer: Holding hours studied (x1) constant, each additional practice test (x2) is associated with a 10-point increase in exam score (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 XTX is not full rank (determinant = 0), it's non-invertible. This happens when:
- Features are linearly dependent (e.g., one column = 2× another)
- More features than training examples (underdetermined system)
Solution: Remove collinear features, use pseudo-inversenp.linalg.pinv, or add L2 regularization (Ridge regression). Q12: Compare linear (deg=1), quadratic (deg=2), and cubic (deg=3) polynomial models.Answer:
| Aspect | Degree 1 | Degree 2 | Degree 3 |
|---|---|---|---|
| Parameters | 2 | 3 | 4 |
| Shape | Straight line | Single curve (U or ∩) | S-curve (one inflection) |
| Bias | Highest | Medium | Lower |
| Variance | Lowest | Medium | Higher |
| Training error | Highest | Lower | Lowest |
| Risk | Underfitting | Good balance | Overfitting risk |
Rule of thumb: start with degree 1-3 and use validation to select.
🔗 Cross-References
- Next Topic: Logistic Regression — classification with linear decision boundaries
- Related: Regularization — Ridge/Lasso for polynomial models
- Related: Gradient Descent — optimization algorithms
- External: IITM BSCS2004 Week 3, Pattern Recognition and Machine Learning (Bishop) Ch. 3.1 Join Discord PreviousGradient Descent VariantsNextLogistic Regression