MLDay 4 of 50Foundations
Fit Your First Model
a Straight Line
Tomorrow afternoon will be 25 °C, and a city bike-share must decide how many bikes to put out. "Warm days are busy" is true, but a truck driver can't load "busy". A straight line turns that hunch into a number.
The idea
A model is a rule that turns an input into a guess. Here the input, called the feature, is the temperature. The guess, called the prediction, is the number of rentals in one hour.
A straight line is the simplest model. It has two parameters, numbers you are free to choose. The slope says how many extra rentals each extra degree brings. The intercept is the guess at 0 °C.
Fitting means choosing those two numbers so the line runs through the middle of the data. Each point's residual is the real value minus the prediction. A good fit leaves small residuals.
A tiny example
Here are five hours at one small dock:
| Temperature (°C) | 5 | 10 | 15 | 20 | 25 |
|---|---|---|---|---|---|
| Rentals | 50 | 120 | 150 | 190 | 260 |
Rentals rise by about 50 every 5 degrees, so the slope is about 10 per degree. The 25 °C hour had 260 rentals, so the intercept is 260 − 10 × 25 = 10. The line is: rentals ≈ 10 × temperature + 10.
- At 15 °C the line predicts 10 × 15 + 10 = 160. The real count was 150, so the residual is 150 − 160 = −10. The line guessed 10 bikes too many.
- For a new 18 °C hour, it predicts 10 × 18 + 10 = 190.
The formula
The prediction is the slope times the feature, plus the intercept:
| Symbol | Meaning |
|---|---|
| the prediction ("y-hat"; the hat marks a guess) | |
| the feature, here the temperature in °C | |
| the weight, or slope: how much rises when grows by 1 | |
| the bias, or intercept: the prediction when |
Worked: , and give .
For a row whose real value is , the residual is .
Try it
Fit the line to the five dock hours
Move the sliders until the red gaps (the residuals) are as small as you can get them.
ŷ = 3·x + 0RMSE 119.56
The line starts far too flat. Drag to tilt it and to slide it, until the residuals look small. The error shown is RMSE, a typical miss size in rentals (Day 5 defines it). Then press Show the best line: it jumps to , , and still misses every point a little.
In code
scikit-learn's LinearRegression does the fitting. It picks the line whose squared residuals add up to the
smallest total, a rule called least squares.
# script_id: day_004_first_model_straight_line/tiny_fit
import numpy as np
from sklearn.linear_model import LinearRegression
temps = np.array([[5], [10], [15], [20], [25]]) # 5 rows, 1 column: the feature
rentals = np.array([50, 120, 150, 190, 260]) # the real values
model = LinearRegression().fit(temps, rentals) # fitting: choose w and b
print(f"w = {model.coef_[0]:.2f}, b = {model.intercept_:.2f}")
print(f"prediction at 18 °C: {model.predict([[18]])[0]:.1f}")
print("residuals:", np.round(rentals - model.predict(temps), 1))
w = 9.80, b = 7.00
prediction at 18 °C: 183.4
residuals: [ -6. 15. -4. -13. 8.]
The fitted line, , is close to the hand guess. coef_ holds and intercept_
holds ; the trailing underscore marks values that fit learned.
Now the same fit on 17,379 real hours of Capital Bikeshare rentals in Washington, D.C. The file stores the temperature as °C ÷ 41, so the script multiplies it back.
# script_id: day_004_first_model_straight_line/bikes
import os
from pathlib import Path
import pandas as pd
from sklearn.linear_model import LinearRegression
DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "bike_sharing" / "hour.csv", parse_dates=["dteday"])
df = df.assign(temp_c=df["temp"] * 41) # undo the ÷ 41
model = LinearRegression().fit(df[["temp_c"]], df["cnt"]) # cnt: rentals that hour
print(f"w = {model.coef_[0]:.2f} rentals per °C, b = {model.intercept_:.2f}")
new = pd.DataFrame({"temp_c": [25.0, -5.0]})
for t, p in zip(new["temp_c"], model.predict(new)):
print(f"{t:5.1f} °C -> {p:6.1f} rentals per hour")
w = 9.30 rentals per °C, b = -0.04
25.0 °C -> 232.5 rentals per hour
-5.0 °C -> -46.5 rentals per hour
Each extra degree adds about 9.3 rentals an hour, so at 25 °C the crew should plan for about 232, whatever the hour. At −5 °C the line predicts −46.5 rentals, which is impossible. The coldest hour in the data was 0.8 °C, and a line never bends, so past the data it keeps falling below zero.
Quick check
Quick check
1. The bike-share line has w = 9.30. What does that mean?
2. An hour had 120 rentals, and the line predicted 110. What is the residual?
3. Why does the line predict −46.5 rentals at −5 °C?
Next
Is this line any good? Day 5: Measure Error turns residuals into one score and checks the line against simply predicting the average.
Data: Bike Sharing Dataset (UCI Machine Learning Repository, dataset 275), CC BY 4.0; cite Fanaee-T, H. and Gama, J. (2013), "Event labeling combining ensemble detectors and background knowledge", Progress in Artificial Intelligence, doi:10.1007/s13748-013-0040-3.