Cheat sheets › Chapter 3
Regression and optimization cheat sheet
Fit a line, measure the error, and walk downhill to the best model. Every lesson in one page: the key idea, the pseudocode and the terms.
Linear regression
Each bar is one house: size along the floor, price as height. Bigger houses tend to cost more, but not perfectly. There is noise.
# x = house size, y = price
# goal: one straight line through the points
w, b = 0.1, 1.8 # a first guess
guess(x):
return w × x + b # the line
miss = y − guess(x) # how far off each house is
w, b = the best line # smallest misses
guess(9) # price for a new houseTerms: residual
Loss functions
We have a line and its residuals. To compare two lines we need one number that sums up how wrong a line is. That number is the loss.
mean_squared_error(y, guess):
misses = y − guess
return average(misses²) # square, then average
mean_absolute_error(y, guess):
return average(|misses|) # no squaring
loss = mean_squared_error(prices, line) # one numberTerms: loss, mean squared error
Gradient descent
Plot the loss for every possible value of a weight w and you get a valley. Training means finding the bottom. We start at a random spot, w = 7.5.
w = 7.5 # start anywhere
step_size = 1.0 # the learning rate
repeat 10 times:
slope = slope of loss at w
w = w − step_size × slope # step downhill
show w and loss
# w ends near 4: the bottom of the valleyTerms: slope
The learning rate
With lr = 0.1, each step is tiny. After 8 steps the ball has barely moved. Training would take forever.
try step sizes 0.1, 1.0, 3.0, 4.4:
w = 7.5
repeat 8 times:
w = w − step_size × slope(w)
show where w ended up
# 0.1: crawls 1.0: smooth
# 3.0: bounces 4.4: blows upTerms: divergence, schedule
Underfitting and overfitting
The bars follow a gentle wave, plus random noise. The noise is not a pattern. It will not repeat on new data. A good model should catch the wave and ignore the noise.
# how bendy is the curve allowed to be?
for bendiness in [1, 3, 9]:
curve = fit(training points, bendiness)
train_error = error(curve, training points)
test_error = error(curve, new points)
# 1: both errors high (too simple)
# 3: both errors low (just right)
# 9: train ≈ 0, test high (memorized)Terms: underfitting, overfitting
Revise with flashcards and quizzes. Free practice for every lesson in this chapter.
Open in the app