Fitting a Line
Linear regression in plain words: find the line that best fits the data, then use it to predict.
Objective
By the end of this lesson, you can fit a linear regression, explain its slope and intercept, and make a prediction with it.
What regression is
Regression is supervised learning that predicts a number: tomorrow's power demand, a home's energy use, the number of riders on a bus route.
Linear regression draws the straight line that best fits the data. "Best" means the line with the smallest total squared distance from the points. This method is called least squares.
A line has two parts:
- Slope: how much the prediction changes when the input goes up by one.
- Intercept: the prediction when the input is zero.
Fit one by hand
Read the slope: each extra degree adds about 4.46 units of demand in this sample.
Read the intercept with care: -12.7 is the "prediction" at 0F. Negative demand is impossible. The intercept only makes sense inside the range of data you trained on.
Extrapolation
The data runs from 70F to 95F. Predicting at 100F is extrapolation: going beyond the data. It may be close. But on an extreme heat day, demand may jump faster than the line, as air conditioners max out. Models are least trustworthy at the edges, which is often where decisions matter most.
With scikit-learn
Run this in Google Colab:
from sklearn.linear_model import LinearRegression
X = [[70], [75], [80], [85], [90], [95]] # inputs go in as a list of rows
y = [300, 320, 345, 365, 390, 410]
model = LinearRegression().fit(X, y)
print(model.coef_, model.intercept_)
print(model.predict([[100]]))
With more columns, like temperature, humidity, and weekday, the same code fits multiple regression: one slope per input.
A national example
Reflection
Discussion
Ask. Answer. Build together.
Loading…