holehouse.org Blog Machine learning notes

02: Linear Regression with One Variable

What this chapter covers

Linear Regression

Training set — m = 47 examples
Size in feet2 (x)Price ($) in 1000's (y)
2104460
1416232
1534315
852178
hθ(x)=θ0+θ1x

Linear regression - implementation (cost function)

12mi=1m(hθ(x(i))y(i))2
J(θ0,θ1)=12mi=1m(hθ(x(i))y(i))2

Cost function - a deeper look

hθ(x)=θ1x(θ0=0) J(θ1)=12mi=1m(hθ(x(i))y(i))2 minimizeθ1J(θ1)
import numpy as np

x = np.array([1, 2, 3])   # the simplified data set used above
y = np.array([1, 2, 3])
m = 3

def J(theta1):            # cost with theta0 = 0
    return ((theta1 * x - y) ** 2).sum() / (2 * m)

J(1)      # 0.0    - a perfect fit
J(0.5)    # 0.583  - the ~0.58 read off the plot above
J(0)      # 2.333  - the ~2.3 read off the plot above

The three worked values from the bullets above, computed rather than read off the plot.

A deeper insight into the cost function - simplified cost function

Gradient descent algorithm

How does it work?

A more formal definition

θjθjαθjJ(θ0,θ1) for j = 0 and j = 1
temp0θ0αθ0J(θ0,θ1) temp1θ1αθ1J(θ0,θ1) θ0temp0 θ1temp1 Both parameters are updated from the old values — compute both temps first.
alpha = 0.1
h = theta0 + theta1 * x   # hypothesis for every example

temp0 = theta0 - alpha * (h - y).mean()
temp1 = theta1 - alpha * ((h - y) * x).mean()
theta0, theta1 = temp0, temp1   # update together, at the end

One simultaneous update, exactly as the equations above — both temps are computed from the old values before either parameter changes.

Understanding the algorithm

Linear regression with gradient descent

θjJ(θ0,θ1)=θj12mi=1m(hθ(x(i))y(i))2 =θj12mi=1m(θ0+θ1x(i)y(i))2
j=0:θ0J(θ0,θ1)=1mi=1m(hθ(x(i))y(i)) j=1:θ1J(θ0,θ1)=1mi=1m(hθ(x(i))y(i))x(i)
theta = np.zeros(2)
for _ in range(2000):
    h = theta[0] + theta[1] * x
    grad0 = (h - y).mean()           # the j = 0 derivative
    grad1 = ((h - y) * x).mean()     # the j = 1 derivative
    theta = theta - 0.1 * np.array([grad0, grad1])

theta   # [0., 1.]  -> h(x) = 0 + 1x, the perfect fit, found by descent

Batch gradient descent run to convergence on the simple data set: it lands on θ0 = 0, θ1 = 1 with cost zero.

What's next - important extensions
Two extension to the algorithm

X=[ 21045145 14163240 15343230 8522136 ]
y=[ 460 232 315 178 ]