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):
- (single feature)
- (target output)
-
Multi-variable linear regression (multivariate):
- Multiple features such as house size, number of bedrooms, number of floors, age of home:
- size ()
- number of bedrooms
- number of floors
- age of home (years)
- price (target output)
- Multiple features such as house size, number of bedrooms, number of floors, age of home:
Notation Summary
- (e.g., )
- (number of rows in data table)
-
- is an index into the training set ()
- is an -dimensional feature vector
- Example: represents the 4 features for the house in the dataset
-
- Example: represents the number of bedrooms in the house
Hypothesis Representation
Previously, for a single feature, our hypothesis took the linear form:
Now, with features, our hypothesis takes the form:
- Example for house price prediction ():
Vectorized Notation
For mathematical convenience, define an extra base feature for every training example ().
This allows us to represent the feature vector and parameter vector as -dimensional column vectors:
The hypothesis can then be written as a dot product (matrix multiplication):
- is a row vector.
- is an column vector.
- evaluates to a scalar prediction value.
This model is known as multivariate linear regression.
Gradient Descent for Multiple Variables
Parameters & Cost Function
In multivariate linear regression:
- Parameters:
- Cost function :

Instead of viewing as a function of separate scalar numbers, we view as a function of the parameter vector .
Gradient Descent Algorithm

The gradient descent algorithm updates all parameters simultaneously:
Comparing Univariate vs. Multivariate Update Rules
Single variable ():

(Note that for , was implicitly present).
Multivariate case ():


Interpretation of Update Rule
For each parameter (where ):
- We update simultaneously on each iteration.
- Subtract learning rate multiplied by times the sum over all examples of: (prediction error ) multiplied by (the feature value of that training example).
- The algorithms for and 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:
- size of house ()
- number of bedrooms ()
- Plotting contours of ( vs. ) yields extremely tall, thin ellipses due to the large difference in feature scales.

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:
- Rule of Thumb for Acceptable Feature Ranges:
- Aim for features to be approximately in the range .
- is generally fine.
- is okay.
- Avoid ranges that are much larger (e.g., ) or much smaller (e.g., ).
Mean Normalization
Replace feature with , where is the average value of feature in the training set, and is the range or standard deviation:

- Example for housing size ( average, ):
- Example for bedrooms (, ):
- Result: Scaled features have approximately zero mean (typically ).
- Note: Never apply feature scaling to .
Gradient Descent in Practice: Learning Rate
Debugging Gradient Descent & Convergence
To ensure gradient descent is functioning properly, plot the cost function against the number of iterations:

- Expected behavior: 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 curve after 100 iterations often gives a good estimate of total iterations required.
- Automatic Convergence Test:
- Declare convergence if decreases by less than a small threshold (e.g., ) in one iteration.
- Setting properly can be difficult; inspecting the plot visually is usually more reliable.
Diagnosing Learning Rate Issues
1. Cost function increases ( rising)

- Cause: Learning rate is too large.
- Gradient descent overshoots the minimum and steps away instead of toward it.
2. Cost function oscillates (wave-like pattern)

- Cause: Learning rate is too large.
- Solution: Reduce the learning rate .
3. Summary of Learning Rate Selection
- If is sufficiently small, is guaranteed to decrease on every iteration.
- However, if is too small, gradient descent will be extremely slow to converge.
- Trial range for picking (3-fold steps):
Plot versus iterations for each , 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 frontage (width of plot along road)
- Feature depth (depth of plot)
- Instead of fitting , define a new feature:
- Hypothesis:
- Land area 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.

Models:
- Quadratic model:
- Problem: Quadratic curves eventually turn back down as increases (inflection point), implying larger houses become cheaper.
- Cubic model:
- Fits data better as it continues rising.
- Square root model:
- Increases steadily without turning back down.
Mapping to Linear Model:
Define new features:
The polynomial hypothesis becomes a standard multivariate linear hypothesis:
We can apply all standard linear regression machinery directly!
Important: Feature scaling is critical for polynomial regression. If , then and . 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 directly in a single step without iteration.
1D Calculus Analogy
To minimize a 1D quadratic function (where ):

- Take derivative
- Set derivative to zero:
- Solve directly for .
Multivariate Extension
For vector :
- Take partial derivative with respect to each parameter :
- Set all partial derivatives equal to zero:
- Solve the system of equations for .
Concrete Example
Consider a housing dataset with examples and features:

Step-by-Step Implementation:
- Add an extra column for all examples.
- Construct the Design Matrix ( matrix) containing all input features.
- Construct the output column vector ( vector).
- Compute parameter vector using the Normal Equation:
![]()

Computing this formula directly yields the vector that minimizes .
General Case
Given training examples and features:
-
Design Matrix (): Take each example vector (an -dimensional column vector), transpose it to a row vector , and stack as rows of :

- Vector ():
- Normal Equation Formula:
![]()
- denotes the inverse of the matrix .
- 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 exactly in one closed-form computation regardless of feature scales.
Gradient Descent vs. Normal Equation
| Feature | Gradient Descent | Normal Equation |
|---|---|---|
| Learning Rate | Must choose learning rate | No need to choose |
| Iterations | Requires many iterations () | Closed-form solution; no iterations |
| Feature Scaling | Required for efficient convergence | Not required |
| Feature Scale () | Works extremely well even when is very large (millions) | Requires computing matrix inverse of size , costing |
| Recommendation | Preferred when | Efficient when is relatively small () |
Normal Equation and Non-Invertibility
When computing , an edge case occurs if the matrix 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 is non-invertible, whereasinv(X'*X)will throw an error.
Causes of Non-Invertibility
-
Redundant Features (Linearly Dependent Features):
- Example: size in square feet, size in square meters ().
- Solution: Remove one of the redundant features.
-
Too Many Features ():
- Example: training examples, 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).
Lecture 03: Linear Algebra Review
A comprehensive review of essential linear algebra concepts for machine learning, including matrices, vectors, matrix operations, inverses, transposes, eigenvalues, eigenvectors, and key properties for probabilistic models (GDA, GMM, EM).
Lecture 05: Octave
Overview and notes regarding the Octave and MATLAB programming languages used for numerical computation and rapid prototyping in machine learning.