Back
Module03
Title

Gradient descent

Synthetic Course: written to test the Site template, from no Professor's material

Worked examples

TopicGradient descent
Title

Two steps of gradient descent

ExampleW03.1
Step1 / 5
Mode
Given
Given

Fit the line h(x)=θ0+θ1xh(x) = \theta_0 + \theta_1 x to the three points by gradient descent on J(θ)=12m∑i(h(xi)−yi)2J(\theta) = \frac{1}{2m} \sum_i \left( h(x_i) - y_i \right)^2. Start from θ(0)=(0,0)\theta^{(0)} = (0, 0) with learning rate α=0.1\alpha = 0.1 and take two steps, updating θ0\theta_0 and θ1\theta_1 together.

  • Points (0,1)(0, 1), (1,3)(1, 3), (2,4)(2, 4), so m=3m = 3
  • θ(0)=(0,0)\theta^{(0)} = (0, 0)
  • α=0.1\alpha = 0.1
Each step: θ:=θ−α∇J(θ)\theta := \theta - \alpha \nabla J(\theta)
kkθ0\theta_0θ1\theta_1J(θ)J(\theta)
0
1
2
0.00.51.01.52.02.5012345yyxx
Fig.The three points, and the line after two steps

Read the problem

Each row of the table is one value of θ\theta and its cost. A step moves both parameters against the gradient, ∂J∂θ0=1m∑i(h−y)\frac{\partial J}{\partial \theta_0} = \frac{1}{m} \sum_i (h - y) and ∂J∂θ1=1m∑i(h−y)x\frac{\partial J}{\partial \theta_1} = \frac{1}{m} \sum_i (h - y) x.
Sim

Gradient descent on the three points

Drag the start θ(0)\theta^{(0)} on the contours of JJ, change α\alpha or the number of steps. The table fills step by step; past the largest α\alpha that converges, the steps overshoot and JJ grows.

Assumed
supplied here, not in the Materials: θ0\theta_0 and θ1\theta_1 tuned from −1-1 to 33 in steps of 0.10.1 · α\alpha tuned from 0.010.01 to 11 in steps of 0.010.01 · up to 3030 steps
θ1\theta_1θ0\theta_0
Fig.Contours of J(θ)J(\theta). Drag θ(0)\theta^{(0)} to start somewhere else.
yyxx
Fig.The data, and the line after 2 steps
kkθ0\theta_0θ1\theta_1J(θ)J(\theta)
00.00000.00004.3333
10.26670.36672.5231
20.47000.64561.4741

After 2 steps: θ0\theta_0 = 0.4700, θ1\theta_1 = 0.6456, J(θ)J(\theta) = 1.4741

Python

The same line by the normal equation

Real Python with numpy: the line gradient descent steps towards, solved in one step by θ=(XTX)−1XTy\theta = (X^{\mathsf{T}} X)^{-1} X^{\mathsf{T}} y. Edit the code and run it live.

01230123456yyxxhθ(x)h_\theta(x)
Fig.The three points and the least-squares line hθ(x)=θ0+θ1xh_\theta(x) = \theta_0 + \theta_1 x

The plot and output the code gave at build. Run live downloads Python (16.5 MB) and runs the code as you edit it.

Output
theta0 = 1.1667
theta1 = 1.5000
J(theta) = 0.0278