Seyed Masoud Hosseini · Overview · Study log · Weekly summaries · Ideas · Search · Transcript · RSS feed

Machine Learning · Lecture 2 of 21 · 1:18:17

Lecture 2: Linear Regression and Gradient Descent

Stanford CS229: Machine Learning - Linear Regression and Gradient Descent |  Lecture 2 (Autumn 2018) on YouTube

Study guide

What this lecture covers

This lecture works through the first full learning algorithm of the course: linear regression. It builds the notation used throughout CS229 (hypothesis, parameters, training examples, cost function), then shows two ways to find the parameters that fit a dataset: the iterative gradient descent algorithm and the closed-form normal equations. The running example is predicting house prices from house size (and later, number of bedrooms) using real listings from Portland, Oregon.

By the end, you should be able to write out the linear regression hypothesis and cost function, explain how gradient descent updates parameters step by step, distinguish batch from stochastic gradient descent, and know when the normal equations give you the answer directly instead of iterating.

Key ideas

  • Hypothesis: the function h(x) the learning algorithm outputs to map inputs (house features) to a predicted output (price); for linear regression h(x) = theta_0 + theta_1*x_1 + ... + theta_n*x_n, with a dummy feature x_0 = 1 so the sum starts at j = 0.
  • Parameters (theta): the values the learning algorithm chooses to make h(x) fit the training data well.
  • Cost function J(theta): one-half the sum of squared differences between predicted and actual prices across all training examples; linear regression minimizes this, which is why it's also called ordinary least squares.
  • Gradient descent: an iterative algorithm that repeatedly adjusts theta in the direction that decreases J(theta) fastest, controlled by a learning rate alpha.
  • Batch gradient descent: each update uses the entire training set, which is accurate but slow on large datasets.
  • Stochastic gradient descent: each update uses just one training example at a time, making faster but noisier progress, and is preferred for large datasets.
  • Normal equations: a closed-form solution, theta = (X^T X)^-1 X^T y, that solves for the optimal theta in one step, but only works for linear regression.
  • Design matrix X: the matrix formed by stacking each training example's feature vector as a row, used to write the cost function and normal equations compactly.

Walkthrough

Setting up linear regression (0:45)

Ng connects this lecture back to Monday's self-driving car demo, framing it as supervised regression, then motivates linear regression with a simpler example: predicting house prices from a dataset of Portland-area listings. He introduces the standard supervised learning pipeline: a training set is fed to a learning algorithm, which outputs a hypothesis h(x) that maps house size to a predicted price.

Notation and parameters (8:27)

Ng builds out the notation used for the rest of the course. With multiple input features (size and number of bedrooms), the hypothesis becomes h(x) = theta_0 + theta_1*x_1 + theta_2*x_2, simplified using a dummy feature x_0 = 1 so it can be written as a sum from j = 0 to n. He defines m as the number of training examples, n as the number of features, x^(i), y^(i) as the i-th training example, and theta as the parameters the algorithm must choose.

The cost function (14:44)

To choose good parameters, the lecture defines the cost function J(theta) as one-half the sum over all training examples of the squared difference between h(x) and the true label y. Minimizing squared error is called ordinary least squares; Ng notes that the choice of squared rather than absolute error will be justified later when the course covers generalized linear models.

Gradient descent (18:06)

Gradient descent starts at some initial value of theta (often all zeros) and repeatedly takes a small step in the direction that most steeply reduces J(theta), using a learning rate alpha to scale each step. Ng visualizes this as standing on a bowl-shaped surface and walking downhill, noting that the starting point can matter for functions with multiple local optima, though linear regression's cost function is quadratic and has only one (global) minimum. He then derives the update rule by taking the partial derivative of J(theta) with respect to each theta_j, arriving at theta_j := theta_j - alpha * sum((h(x^(i)) - y^(i)) * x_j^(i)). Too large a learning rate can overshoot and even increase J(theta); too small a rate makes convergence slow, so in practice you try several values, often on an exponential scale like 0.01, 0.03, 0.1.

Batch vs. stochastic gradient descent (42:34)

The version of gradient descent that sums over the entire training set on every update is called batch gradient descent. Its drawback is that with very large datasets, a single parameter update requires scanning the whole dataset, which becomes expensive. Stochastic gradient descent instead updates the parameters using just one training example at a time, looping through examples one by one. This takes a noisier, more meandering path toward the minimum and technically never fully converges, but makes much faster progress on large datasets, so it's used more often in practice. Ng mentions that decreasing the learning rate over time is a common way to shrink the oscillations as training proceeds, and briefly notes mini-batch gradient descent (using small batches of examples) as a middle ground covered in more depth in CS230.

The normal equations (53:16)

For linear regression specifically, there's a way to solve for the optimal theta directly instead of iterating. Ng introduces a compact matrix-derivative notation, then defines the design matrix X (training examples stacked as rows) and the label vector y, showing that J(theta) can be written as (1/2) * (X*theta - y)^T * (X*theta - y). Taking the derivative of this expression with respect to theta and setting it to zero yields the normal equations, X^T*X*theta = X^T*y, so theta = (X^T*X)^-1 * X^T*y. This gives the global minimum in one computation, though it doesn't generalize to the other algorithms covered later in the course. If X^T*X is not invertible, it usually means some features are linearly dependent (for example, a repeated feature).

Before you watch

  • Watch Lecture 1 first for the course's framing of supervised learning and regression versus classification.
  • Basic linear algebra (matrix and vector multiplication, transpose) and single-variable calculus (derivatives, partial derivatives) make the notation and the gradient descent derivation much easier to follow.

Check your understanding

  1. Why does linear regression's cost function J(theta) have no local optima other than the global minimum?
  2. What is the practical trade-off between batch gradient descent and stochastic gradient descent on a very large dataset?
  3. What happens to gradient descent if the learning rate alpha is set too large, and how can you tell from watching J(theta)?
  4. Why can't the normal equations be used for algorithms other than linear regression?

Vocabulary

linear regression (noun)
A method that predicts a continuous value as a weighted sum of input features.
Linear regression predicts house price from its size.
hypothesis (noun)
The function a learning algorithm outputs to make predictions.
The hypothesis combines features with weights to predict price.
parameter (noun)
A value the algorithm adjusts to make its predictions fit the data.
Theta represents the parameters the algorithm must choose.
training example (noun)
A single data point with known input and output used to fit a model.
Each house listing is one training example.
cost function (noun)
A formula that measures how far a model's predictions are from the true answers.
The cost function sums up the squared prediction errors.
squared difference (noun)
The result of subtracting two numbers and multiplying the result by itself.
The cost function sums the squared difference between prediction and truth.
ordinary least squares (noun)
A method that fits a model by minimizing the sum of squared prediction errors.
Linear regression is also called ordinary least squares.
learning rate (noun)
A number controlling how big each step of an optimization update is.
The learning rate alpha scales each gradient descent step.
convergence (noun)
The process of an algorithm settling toward a stable final answer.
Too small a learning rate makes convergence slow.
local optimum (noun)
A point that looks best nearby but might not be the overall best solution.
The starting point matters for functions with more than one local optimum.
global minimum (noun)
The single lowest possible value a function can reach anywhere.
Linear regression's cost function has only one global minimum.
quadratic (adjective)
Shaped like a smooth bowl or parabola curve.
The cost function for linear regression is quadratic.
batch gradient descent (noun)
An update method that uses the entire training set for every single step.
Batch gradient descent scans all examples before updating once.
stochastic gradient descent (noun)
An update method that uses just one training example at a time.
Stochastic gradient descent makes faster but noisier progress.
mini-batch (noun)
A small group of training examples used together for one update.
Mini-batch gradient descent uses a small group of examples per step.
normal equations (noun)
A direct formula that solves for the best parameters in one step.
The normal equations give theta without any iteration.
closed-form (adjective)
Describes a solution obtained by a direct formula rather than repeated steps.
The normal equations give a closed-form solution for linear regression.
design matrix (noun)
A matrix formed by stacking each training example's features as a row.
The design matrix X holds every house's feature vector.
invertible (adjective)
Describes a matrix that can be reversed by another matrix to give the identity.
If X transpose X is not invertible, some features are likely redundant.
linearly dependent (adjective)
Describes features where one can be written as a combination of the others.
Repeated features make the matrix linearly dependent.

Chapters

From the YouTube description

For more information about Stanford’s Artificial Intelligence professional and graduate programs, visit: https://stanford.io/ai

This lecture covers supervised learning and linear regression.

Andrew Ng
Adjunct Professor of Computer Science
https://www.andrewng.org/

To follow along with the course schedule and syllabus, visit:
http://cs229.stanford.edu/syllabus-autumn2018.html

#andrewng #machinelearning

Chapters:
00:00 Intro
00:45 Motivate Linear Regression
03:01 Supervised Learning
04:44 Designing a Learning Algorithm
08:27 Parameters of the learning algorithm
14:44 Linear Regression Algorithm
18:06 Gradient Descent
33:01 Gradient Descent Algorithm
42:34 Batch Gradient Descent
44:56 Stochastic Gradient Descent

← Lecture 1: Course Overview and What Machine Learning Is · Lecture 3: Locally Weighted and Logistic Regression →