DS Linear Regression Case
Time to put the whole DS Advanced section together. The Riverside Bikes manager asks:
"How many bikes should we put on the street tomorrow? And which factors really matter?"
We'll answer with a regression that uses temperature, rain and weekend together, interpret every part of the output, and produce a forecast with an honest range.
Step 1: Choose the variables
From the correlation matrix we know rides relate strongly to temperature (0.85), moderately to weekend (0.43) and rain (−0.41), and barely to humidity (0.06). The p-value lesson confirmed that humidity adds nothing. So our model is:
rides = b0 + b1 × temp_c + b2 × rain_mm + b3 × weekend + errorStep 2: Fit and read the coefficient table
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 + rain_mm + weekend", data=bikes).fit()
print(model.summary2().tables[1].round(3))
print()
print(f"n = {int(model.nobs)}, R2 = {model.rsquared:.3f}, adj R2 = {model.rsquared_adj:.3f}, "
f"p(F) = {model.f_pvalue:.1e}") Coef. Std.Err. t P>|t| [0.025 0.975]
Intercept 157.221 11.312 13.899 0.0 134.561 179.882
temp_c 11.494 0.582 19.736 0.0 10.327 12.661
rain_mm -9.112 1.067 -8.541 0.0 -11.249 -6.975
weekend 64.164 9.637 6.658 0.0 44.860 83.468
n = 60, R2 = 0.916, adj R2 = 0.911, p(F) = 5.1e-30
Step 3: Interpret in plain language
| Term | Estimate | Plain language |
|---|---|---|
| Intercept | ≈ 157 | Baseline for a dry weekday at 0 °C (outside our data — not meaningful alone) |
| temp_c | ≈ +11.5 | Each extra degree adds about 11–12 rides, holding rain and weekday fixed |
| rain_mm | ≈ −9.1 | Each millimetre of rain costs about 9 rides |
| weekend | ≈ +64 | A Saturday or Sunday brings about 64 more rides than a weekday with the same weather |
All three p-values are essentially 0, all confidence intervals exclude 0, and together the variables explain about 92 % of the variation (R² ≈ 0.916). Compare that with 73 % for temperature alone.
Because we simulated the data, we can check the answers against the true rule (150 + 12·temp − 8·rain + 60·weekend). Every true value lies inside its 95 % confidence interval. That's the best possible outcome — on real data, of course, nobody tells you the truth.
Step 4: Forecast with a range
A single number like "474 rides" hides uncertainty. get_prediction() gives two kinds of interval:
- the confidence interval (
mean_ci) for the average rides on days like this, and - the wider prediction interval (
obs_ci) for one particular day, which includes the day-to-day noise.
For planning bikes on the street, the prediction interval is the relevant one.
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 + rain_mm + weekend", data=bikes).fit()
scenarios = pd.DataFrame({
"temp_c": [22, 22, 12],
"rain_mm": [0, 6, 0],
"weekend": [1, 1, 0],
}, index=["sunny Saturday", "wet Saturday", "cool weekday"])
pred = model.get_prediction(scenarios).summary_frame(alpha=0.05)
pred.index = scenarios.index
print(pred[["mean", "mean_ci_lower", "mean_ci_upper", "obs_ci_lower", "obs_ci_upper"]].round(0)) mean mean_ci_lower mean_ci_upper obs_ci_lower obs_ci_upper
sunny Saturday 474.0 457.0 491.0 407.0 541.0
wet Saturday 420.0 401.0 439.0 352.0 487.0
cool weekday 295.0 283.0 308.0 229.0 361.0
For a sunny 22 °C Saturday the model expects about 474 rides; on any single such day, anything from roughly 407 to 541 would be normal. Planning for the upper end of the prediction interval keeps riders from finding empty stations.
Step 5: Check the residuals
Before trusting the forecast, check that the residuals look like random noise — no pattern against the fitted values:
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 + rain_mm + weekend", data=bikes).fit()
fig, ax = plt.subplots(figsize=(7, 4))
ax.scatter(model.fittedvalues, model.resid, s=15)
ax.axhline(0, color="red")
ax.set_xlabel("Fitted rides")
ax.set_ylabel("Residual (actual − fitted)")
ax.set_title("Residuals vs fitted values")
plt.show()
print("Residual standard deviation:", round(np.sqrt(model.mse_resid), 1), "rides")
print("Share of residuals within ±60 rides:", (model.resid.abs() <= 60).mean().round(2))Residual standard deviation: 32.4 rides
Share of residuals within ±60 rides: 0.95
The residuals scatter evenly around zero with no visible curve or funnel, and their standard deviation (≈ 32 rides) is close to the noise level built into the simulation (30). The model is a sound basis for the forecast.
The answer for the manager
Temperature, rain and the day of the week explain about 92 % of the variation in daily rides. Each degree warmer adds about 12 rides, each millimetre of rain removes about 9, and weekends add about 64. For a sunny 22 °C Saturday, plan for about 474 rides and be ready for up to about 540.
Test yourself
In the three-variable model, what does the weekend coefficient of ≈ 64 mean?
- 64 % of rides happen at weekends
- Weekends have about 64 more rides than weekdays with the same temperature and rain
- There are 64 weekend days
- Weekend rides vary by 64
Which interval should you use to plan how many bikes one specific day might need?
- The confidence interval of the mean (
mean_ci) - The prediction interval (
obs_ci) - The coefficient's confidence interval
- The IQR
Why did R² rise from 0.726 to about 0.915?
- More rows were used
- Rain and weekend explain variation that temperature alone could not
- The intercept was removed
- Humidity was added