CSE-41XX
CS-4125 ML

Lecture 04: Linear Regression with Multiple Variables

A comprehensive guide to multivariate linear regression, covering gradient descent with multiple features, feature scaling, learning rate selection, polynomial regression, and the normal equation method.

Linear Regression with Multiple Features

Overview & Notation

Multivariate linear regression handles problems where we have multiple input variables (multiple features) to predict a target variable.

  • Single-variable linear regression (univariate):

    • x=house sizex = \text{house size} (single feature)
    • y=house pricey = \text{house price} (target output)
  • Multi-variable linear regression (multivariate):

    • Multiple features such as house size, number of bedrooms, number of floors, age of home:
      • x1=x_1 = size (sq ft\text{sq ft})
      • x2=x_2 = number of bedrooms
      • x3=x_3 = number of floors
      • x4=x_4 = age of home (years)
      • y=y = price (target output)

Notation Summary

  • n=number of featuresn = \text{number of features} (e.g., n=4n = 4)
  • m=number of training examplesm = \text{number of training examples} (number of rows in data table)
  • x(i)=input feature vector for the ith training examplex^{(i)} = \text{input feature vector for the } i^{\text{th}} \text{ training example}
    • ii is an index into the training set (1im1 \le i \le m)
    • x(i)x^{(i)} is an nn-dimensional feature vector
    • Example: x(3)x^{(3)} represents the 4 features for the 3rd3^{\text{rd}} house in the dataset
  • xj(i)=value of feature j in the ith training examplex_j^{(i)} = \text{value of feature } j \text{ in the } i^{\text{th}} \text{ training example}
    • Example: x2(3)x_2^{(3)} represents the number of bedrooms in the 3rd3^{\text{rd}} house

Hypothesis Representation

Previously, for a single feature, our hypothesis took the linear form:

hθ(x)=θ0+θ1xh_\theta(x) = \theta_0 + \theta_1 x

Now, with nn features, our hypothesis takes the form:

hθ(x)=θ0+θ1x1+θ2x2+θ3x3++θnxnh_\theta(x) = \theta_0 + \theta_1 x_1 + \theta_2 x_2 + \theta_3 x_3 + \dots + \theta_n x_n
  • Example for house price prediction (n=4n = 4):
hθ(x)=80+0.1x1+0.01x2+3x32x4h_\theta(x) = 80 + 0.1 x_1 + 0.01 x_2 + 3 x_3 - 2 x_4

Vectorized Notation

For mathematical convenience, define an extra base feature x0=1x_0 = 1 for every training example (x0(i)=1x_0^{(i)} = 1).

This allows us to represent the feature vector xx and parameter vector θ\theta as (n+1)(n+1)-dimensional column vectors:

x=[x0x1x2xn]Rn+1,θ=[θ0θ1θ2θn]Rn+1x = \begin{bmatrix} x_0 \\ x_1 \\ x_2 \\ \vdots \\ x_n \end{bmatrix} \in \mathbb{R}^{n+1}, \quad \theta = \begin{bmatrix} \theta_0 \\ \theta_1 \\ \theta_2 \\ \vdots \\ \theta_n \end{bmatrix} \in \mathbb{R}^{n+1}

The hypothesis can then be written as a dot product (matrix multiplication):

hθ(x)=θ0x0+θ1x1+θ2x2++θnxn=θTxh_\theta(x) = \theta_0 x_0 + \theta_1 x_1 + \theta_2 x_2 + \dots + \theta_n x_n = \theta^T x
  • θT\theta^T is a [1×(n+1)][1 \times (n+1)] row vector.
  • xx is an [(n+1)×1][(n+1) \times 1] column vector.
  • θTx\theta^T x evaluates to a [1×1][1 \times 1] scalar prediction value.

This model is known as multivariate linear regression.


Gradient Descent for Multiple Variables

Parameters & Cost Function

In multivariate linear regression:

  • Parameters: θ=[θ0,θ1,,θn]TRn+1\theta = [\theta_0, \theta_1, \dots, \theta_n]^T \in \mathbb{R}^{n+1}
  • Cost function J(θ)J(\theta):
J(θ)=12mi=1m(hθ(x(i))y(i))2J(\theta) = \frac{1}{2m} \sum_{i=1}^m \left( h_\theta(x^{(i)}) - y^{(i)} \right)^2

Cost function J(theta) for multivariate linear regression

Instead of viewing JJ as a function of n+1n+1 separate scalar numbers, we view J(θ)J(\theta) as a function of the parameter vector θ\theta.


Gradient Descent Algorithm

Gradient descent algorithm update step

The gradient descent algorithm updates all parameters θj\theta_j simultaneously:

Repeat until convergence: {θj:=θjαθjJ(θ)}(simultaneously update for j=0,,n)\text{Repeat until convergence: } \left\{ \theta_j := \theta_j - \alpha \frac{\partial}{\partial \theta_j} J(\theta) \right\} \quad (\text{simultaneously update for } j = 0, \dots, n)

Comparing Univariate vs. Multivariate Update Rules

Single variable (n=1n = 1):

Gradient descent update rules for single variable linear regression

θ0:=θ0α1mi=1m(hθ(x(i))y(i))θ1:=θ1α1mi=1m(hθ(x(i))y(i))x(i)\begin{aligned} \theta_0 &:= \theta_0 - \alpha \frac{1}{m} \sum_{i=1}^m \left( h_\theta(x^{(i)}) - y^{(i)} \right) \\ \theta_1 &:= \theta_1 - \alpha \frac{1}{m} \sum_{i=1}^m \left( h_\theta(x^{(i)}) - y^{(i)} \right) x^{(i)} \end{aligned}

(Note that for θ0\theta_0, x0(i)=1x_0^{(i)} = 1 was implicitly present).

Multivariate case (n1n \ge 1):

Multivariate gradient descent update rule

Repeat: {θj:=θjα1mi=1m(hθ(x(i))y(i))xj(i)}(for j=0,1,,n)\text{Repeat: } \left\{ \theta_j := \theta_j - \alpha \frac{1}{m} \sum_{i=1}^m \left( h_\theta(x^{(i)}) - y^{(i)} \right) x_j^{(i)} \right\} \quad (\text{for } j = 0, 1, \dots, n)

Comparison of single variable and multivariate gradient descent update rules

Interpretation of Update Rule

For each parameter θj\theta_j (where j{0,,n}j \in \{0, \dots, n\}):

  • We update θj\theta_j simultaneously on each iteration.
  • Subtract learning rate α\alpha multiplied by 1m\frac{1}{m} times the sum over all mm examples of: (prediction error (hθ(x(i))y(i))(h_\theta(x^{(i)}) - y^{(i)})) multiplied by (the jthj^{\text{th}} feature value xj(i)x_j^{(i)} of that training example).
  • The algorithms for n=1n=1 and n1n \ge 1 are structurally identical.

Gradient Descent in Practice: Feature Scaling

Motivation

When features have significantly different scales, gradient descent can take a long time to reach the global minimum.

  • Example:
    • x1=x_1 = size of house (02000 sq ft0 - 2000 \text{ sq ft})
    • x2=x_2 = number of bedrooms (151 - 5)
  • Plotting contours of J(θ)J(\theta) (θ1\theta_1 vs. θ2\theta_2) yields extremely tall, thin ellipses due to the large difference in feature scales.

Contour plot comparison showing impact of feature scaling on gradient descent path

Gradient descent will oscillate back and forth across the steep walls of the narrow valley, taking a very long path and requiring many iterations to reach the minimum (pathological input).


Rescaling Methods

Rescaling features so they take on comparable ranges ensures contour lines are more circular, allowing gradient descent to move directly toward the minimum.

Feature Scaling (Scaling by Range/Max)

Divide each feature value by the maximum value (or range) of that feature:

x1=size2000,x2=number of bedrooms5x_1 = \frac{\text{size}}{2000}, \quad x_2 = \frac{\text{number of bedrooms}}{5}
  • Rule of Thumb for Acceptable Feature Ranges:
    • Aim for features to be approximately in the range 1xi+1-1 \le x_i \le +1.
    • 3xi+3-3 \le x_i \le +3 is generally fine.
    • 13xi+13-\frac{1}{3} \le x_i \le +\frac{1}{3} is okay.
    • Avoid ranges that are much larger (e.g., 100 to +100-100 \text{ to } +100) or much smaller (e.g., 0.0001 to +0.0001-0.0001 \text{ to } +0.0001).

Mean Normalization

Replace feature xix_i with (xiμi)/si(x_i - \mu_i) / s_i, where μi\mu_i is the average value of feature ii in the training set, and sis_i is the range (maxmin)(\text{max} - \text{min}) or standard deviation:

xi:=xiμisix_i := \frac{x_i - \mu_i}{s_i}

Mean normalization formula for feature scaling

  • Example for housing size (1000 sq ft1000 \text{ sq ft} average, 2000 max2000 \text{ max}): x1=size10002000x_1 = \frac{\text{size} - 1000}{2000}
  • Example for bedrooms (2 average2 \text{ average}, 5 max5 \text{ max}): x2=bedrooms25x_2 = \frac{\text{bedrooms} - 2}{5}
  • Result: Scaled features have approximately zero mean (typically 0.5xi0.5-0.5 \le x_i \le 0.5).
  • Note: Never apply feature scaling to x0=1x_0 = 1.

Gradient Descent in Practice: Learning Rate

Debugging Gradient Descent & Convergence

To ensure gradient descent is functioning properly, plot the cost function J(θ)J(\theta) against the number of iterations:

Plot of cost function J(theta) over gradient descent iterations

  • Expected behavior: J(θ)J(\theta) should decrease after every single iteration.
  • Convergence: When the curve flattens out, gradient descent has converged.
  • Number of iterations needed: Varies widely across problems (e.g., 30 iterations, 3,000 iterations, or 3,000,000 iterations). Visualizing the J(θ)J(\theta) curve after 100 iterations often gives a good estimate of total iterations required.
  • Automatic Convergence Test:
    • Declare convergence if J(θ)J(\theta) decreases by less than a small threshold ϵ\epsilon (e.g., 10310^{-3}) in one iteration.
    • Setting ϵ\epsilon properly can be difficult; inspecting the plot visually is usually more reliable.

Diagnosing Learning Rate Issues

1. Cost function increases (J(θ)J(\theta) rising)

Cost function increasing over iterations due to large learning rate

  • Cause: Learning rate α\alpha is too large.
  • Gradient descent overshoots the minimum and steps away instead of toward it.

2. Cost function oscillates (wave-like pattern)

Cost function oscillating over iterations due to large learning rate

  • Cause: Learning rate α\alpha is too large.
  • Solution: Reduce the learning rate α\alpha.

3. Summary of Learning Rate Selection

  • If α\alpha is sufficiently small, J(θ)J(\theta) is guaranteed to decrease on every iteration.
  • However, if α\alpha is too small, gradient descent will be extremely slow to converge.
  • Trial range for picking α\alpha (3-fold steps):
α{0.001,0.003,0.01,0.03,0.1,0.3,1,}\alpha \in \{0.001, 0.003, 0.01, 0.03, 0.1, 0.3, 1, \dots\}

Plot J(θ)J(\theta) versus iterations for each α\alpha, and select the largest value that achieves rapid convergence without overshooting.


Features and Polynomial Regression

Designing New Features

You can create new features to build better prediction models.

  • House price prediction example:
    • Feature x1=x_1 = frontage (width of plot along road)
    • Feature x2=x_2 = depth (depth of plot)
    • Instead of fitting hθ(x)=θ0+θ1x1+θ2x2h_\theta(x) = \theta_0 + \theta_1 x_1 + \theta_2 x_2, define a new feature:
      • x3=frontage×depth=land areax_3 = \text{frontage} \times \text{depth} = \text{land area}
    • Hypothesis: hθ(x)=θ0+θ1x3h_\theta(x) = \theta_0 + \theta_1 x_3
    • Land area x3x_3 is often a much stronger predictor of price than frontage and depth separately.

Polynomial Regression

When linear functions do not fit the data well, polynomial functions can provide a better model.

Comparison of polynomial regression curves fitted to housing data

Models:

  1. Quadratic model: hθ(x)=θ0+θ1x+θ2x2h_\theta(x) = \theta_0 + \theta_1 x + \theta_2 x^2
    • Problem: Quadratic curves eventually turn back down as xx increases (inflection point), implying larger houses become cheaper.
  2. Cubic model: hθ(x)=θ0+θ1x+θ2x2+θ3x3h_\theta(x) = \theta_0 + \theta_1 x + \theta_2 x^2 + \theta_3 x^3
    • Fits data better as it continues rising.
  3. Square root model: hθ(x)=θ0+θ1x+θ2xh_\theta(x) = \theta_0 + \theta_1 x + \theta_2 \sqrt{x}
    • Increases steadily without turning back down.

Mapping to Linear Model:

Define new features:

  • x1=xx_1 = x
  • x2=x2x_2 = x^2
  • x3=x3x_3 = x^3

The polynomial hypothesis becomes a standard multivariate linear hypothesis:

hθ(x)=θ0+θ1x1+θ2x2+θ3x3h_\theta(x) = \theta_0 + \theta_1 x_1 + \theta_2 x_2 + \theta_3 x_3

We can apply all standard linear regression machinery directly!

Important: Feature scaling is critical for polynomial regression. If x[1,1000]x \in [1, 1000], then x2[1,106]x^2 \in [1, 10^6] and x3[1,109]x^3 \in [1, 10^9]. Scale features into comparable ranges before running gradient descent.


Normal Equation

Overview & Intuition

For some linear regression problems, the Normal Equation provides an analytical solution to solve for θ\theta directly in a single step without iteration.

1D Calculus Analogy

To minimize a 1D quadratic function J(θ)=aθ2+bθ+cJ(\theta) = a \theta^2 + b \theta + c (where θR\theta \in \mathbb{R}):

Minimizing 1D cost function by taking derivative and setting to zero

  1. Take derivative ddθJ(θ)\frac{d}{d\theta} J(\theta)
  2. Set derivative to zero: ddθJ(θ)=0\frac{d}{d\theta} J(\theta) = 0
  3. Solve directly for θ\theta.

Multivariate Extension

For vector θRn+1\theta \in \mathbb{R}^{n+1}:

  1. Take partial derivative with respect to each parameter θj\theta_j: θjJ(θ)\frac{\partial}{\partial \theta_j} J(\theta)
  2. Set all partial derivatives equal to zero:
θjJ(θ)=0for all j=0,,n\frac{\partial}{\partial \theta_j} J(\theta) = 0 \quad \text{for all } j = 0, \dots, n
  1. Solve the system of equations for θ0,θ1,,θn\theta_0, \theta_1, \dots, \theta_n.

Concrete Example

Consider a housing dataset with m=4m = 4 examples and n=4n = 4 features:

Housing dataset table with m=4 examples and n=4 features

Step-by-Step Implementation:

  1. Add an extra column x0=1x_0 = 1 for all examples.
  2. Construct the Design Matrix XX ([m×(n+1)][m \times (n+1)] matrix) containing all input features.
  3. Construct the output column vector yy ([m×1][m \times 1] vector).
  4. Compute parameter vector θ\theta using the Normal Equation:

Normal equation formula theta = (X^T X)^-1 X^T y

Normal equation matrix equation

θ=(XTX)1XTy\theta = (X^T X)^{-1} X^T y

Computing this formula directly yields the vector θ\theta that minimizes J(θ)J(\theta).


General Case

Given mm training examples and nn features:

  1. Design Matrix XX (m×(n+1)m \times (n+1)): Take each example vector x(i)x^{(i)} (an (n+1)(n+1)-dimensional column vector), transpose it to a row vector (x(i))T(x^{(i)})^T, and stack as rows of XX:

    Design matrix X constructed from transposed training feature vectors

X=[(x(1))T(x(2))T(x(m))T]=[x0(1)x1(1)xn(1)x0(2)x1(2)xn(2)x0(m)x1(m)xn(m)]Rm×(n+1)X = \begin{bmatrix} (x^{(1)})^T \\ (x^{(2)})^T \\ \vdots \\ (x^{(m)})^T \end{bmatrix} = \begin{bmatrix} x_0^{(1)} & x_1^{(1)} & \dots & x_n^{(1)} \\ x_0^{(2)} & x_1^{(2)} & \dots & x_n^{(2)} \\ \vdots & \vdots & \ddots & \vdots \\ x_0^{(m)} & x_1^{(m)} & \dots & x_n^{(m)} \end{bmatrix} \in \mathbb{R}^{m \times (n+1)}
  1. Vector yy (m×1m \times 1):
y=[y(1)y(2)y(m)]Rm×1y = \begin{bmatrix} y^{(1)} \\ y^{(2)} \\ \vdots \\ y^{(m)} \end{bmatrix} \in \mathbb{R}^{m \times 1}
  1. Normal Equation Formula:

Normal equation solution formula

θ=(XTX)1XTy\theta = (X^T X)^{-1} X^T y
  • (XTX)1(X^T X)^{-1} denotes the inverse of the matrix (XTX)(X^T X).
  • In MATLAB / Octave:
    theta = pinv(X'*X) * X' * y

Feature Scaling Note: If you use the Normal Equation, feature scaling is not necessary. Gradient descent requires feature scaling to iterate efficiently, but the normal equation solves for θ\theta exactly in one closed-form computation regardless of feature scales.


Gradient Descent vs. Normal Equation

FeatureGradient DescentNormal Equation
Learning Rate α\alphaMust choose learning rate α\alphaNo need to choose α\alpha
IterationsRequires many iterations (O(kn2)O(k n^2))Closed-form solution; no iterations
Feature ScalingRequired for efficient convergenceNot required
Feature Scale (nn)Works extremely well even when nn is very large (millions)Requires computing matrix inverse (XTX)1(X^T X)^{-1} of size [n×n][n \times n], costing O(n3)O(n^3)
RecommendationPreferred when n>10,000n > 10,000Efficient when nn is relatively small (n10,000n \le 10,000)

Normal Equation and Non-Invertibility

When computing θ=(XTX)1XTy\theta = (X^T X)^{-1} X^T y, an edge case occurs if the matrix (XTX)(X^T X) is non-invertible (singular or degenerate).

  • Invertibility in Practice:
    • Non-invertibility is rare in linear regression.
    • In Octave / MATLAB, using pinv(X'*X) (pseudo-inverse) calculates the correct parameters even if (XTX)(X^T X) is non-invertible, whereas inv(X'*X) will throw an error.

Causes of Non-Invertibility

  1. Redundant Features (Linearly Dependent Features):

    • Example: x1=x_1 = size in square feet, x2=x_2 = size in square meters (x1=10.764x2x_1 = 10.764 x_2).
    • Solution: Remove one of the redundant features.
  2. Too Many Features (mnm \le n):

    • Example: m=10m = 10 training examples, n=100n = 100 features (fitting 101 parameters with 10 data points).
    • Solution:
      • Delete some features.
      • Use regularization (which allows fitting models with many features and limited training data).

On this page