DS Linear Regression
Linear regression finds the straight line that best describes how a dependent variable (the one you want to explain or predict) changes with one or more explanatory variables. You already did it once with np.polyfit. In this section you'll use statsmodels, which also tells you how much to trust the line.
For Riverside Bikes the question is: how do daily rides depend on temperature?
rides = intercept + slope × temp_c + errorThe error term (also called the residual) is everything the line doesn't capture: rain, weekends, events in town, pure chance.
Least squares, intuitively
For any candidate line we can measure how far each day's actual rides lie from the line. Regression picks the line that makes the sum of squared errors (SSE) as small as possible. Let's compare a few hand-picked lines with the best one:
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
def sse(intercept, slope):
predicted = intercept + slope * bikes["temp_c"]
return ((bikes["rides"] - predicted) ** 2).sum()
for b, a in [(100, 10), (150, 12), (200, 9), (135.81, 12.54)]:
print(f"intercept {b:7.2f}, slope {a:5.2f} -> SSE = {sse(b, a):10.0f}")intercept 100.00, slope 10.00 -> SSE = 598942
intercept 150.00, slope 12.00 -> SSE = 192886
intercept 200.00, slope 9.00 -> SSE = 231221
intercept 135.81, slope 12.54 -> SSE = 190638
The last line — the least-squares solution — has the smallest SSE of all. No other straight line does better on this data.
Fitting with statsmodels
statsmodels offers a formula interface borrowed from R: "rides ~ temp_c" means "explain rides by temp_c". An intercept is added automatically.
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
model = smf.ols("rides ~ temp_c", data=bikes).fit()
print(model.params.round(2))
print()
new_days = pd.DataFrame({"temp_c": [8, 16, 24]})
print(model.predict(new_days).round(0))Intercept 135.81
temp_c 12.54
dtype: float64
0 236.0
1 337.0
2 437.0
dtype: float64
smf.ols(formula, data)describes the model;.fit()estimates it and returns a results object.model.paramsholds the estimated coefficients: intercept ≈ 135.81 and slope ≈ 12.54 — the same valuesnp.polyfitfound.model.predict(df)applies the line to new data, which must contain the same column names.
Seeing the fit and its errors
Plotting the line together with the vertical distances (the residuals) shows exactly what least squares minimises:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.formula.api as smf
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
model = smf.ols("rides ~ temp_c", data=bikes).fit()
fitted = model.fittedvalues
plt.vlines(bikes["temp_c"], fitted, bikes["rides"], color="grey", alpha=0.5, label="Residuals")
plt.scatter(bikes["temp_c"], bikes["rides"], s=15, zorder=3, label="Observed")
order = bikes["temp_c"].argsort()
plt.plot(bikes["temp_c"].iloc[order], fitted.iloc[order], color="red", label="Regression line")
plt.xlabel("Temperature (°C)")
plt.ylabel("Rides")
plt.legend()
plt.show()
print("Largest positive residual:", model.resid.max().round(1))
print("Largest negative residual:", model.resid.min().round(1))
print("Mean residual:", abs(model.resid.mean().round(6)))Largest positive residual: 136.9
Largest negative residual: -163.4
Mean residual: 0.0
Residuals of a least-squares line with an intercept always average to zero: the line runs through the "middle" of the data. Individual days still miss by up to about 160 rides — the line explains a lot, but not everything.
Assumptions in brief
Linear regression's numbers are most trustworthy when:
- The relationship is roughly linear.
- The residuals are independent of each other (one day's error doesn't predict the next).
- The residuals have roughly constant spread across the range.
- The residuals are roughly normally distributed (matters most for small samples).
The Residual Analysis lesson shows how to check these. For now, the scatter plot tells us a straight line is a reasonable first model.
Test yourself
What does least squares minimise?
- The number of points off the line
- The sum of squared vertical distances between points and line
- The slope
- The sum of the residuals
In the formula "rides ~ temp_c", which variable is the dependent variable?
- temp_c
- rides
- Both
- Neither
What does model.predict(new_days) require?
- A list of slopes
- A DataFrame with the same explanatory column names used in the formula
- The original data only
- A new formula