AI: predicting with linear regression
At the heart of a lot of AI is learning from examples. The simplest method is linear regression: we look for the line y = a × x + b that passes as close as possible to the known points, then use it to predict a new value.
The slope a comes from the means: add up the shared deviations of x and y, then divide by the squared deviations of x. Then b = mean(y) − a × mean(x). That's exactly what libraries like scikit-learn do, only faster.
hours = [1, 2, 3, 4, 5]
scores = [52, 58, 65, 70, 77]
n = len(hours)
mx = sum(hours) / n
my = sum(scores) / n
a = sum((x - mx) * (y - my) for x, y in zip(hours, scores)) / sum((x - mx) ** 2 for x in hours)
b = my - a * mx
print("slope:", round(a, 2), "intercept:", round(b, 2))
print("prediction for 6 h:", round(a * 6 + b, 1))