Paul's Python CoursePPC

Linear regression

Not met yet

Linear regression predicts a number with a straight line: prediction = w * x + b. w is the slope, how much the prediction changes for each unit of x, and b is the intercept, the prediction at x = 0. The best line is the one with the smallest mean squared error; for one feature there's a formula for it, and gradient descent finds the same line by walking. Trust a line near the readings it was fitted to, and less the further you go.

Try it

main.py
import numpy as np

x = np.array([0.0, 5.0, 10.0])
y = np.array([42.3, 41.7, 41.1])
w = np.sum((x - x.mean()) * (y - y.mean())) / np.sum((x - x.mean()) ** 2)
b = y.mean() - w * x.mean()
print(f"y = {w:.2f} * x + {b:.1f}")

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks the best line is the one that passes exactly through the most points.
  • Thinks the slope of the best line is the mean of y divided by the mean of x.
  • Thinks a fitted line predicts just as well far outside the readings it was fitted to.
  • Thinks the intercept b is the first reading's y value, rather than where the line crosses x = 0.

Where it comes up