Skip to content

MLDay 8 of 50Foundations

Project 1

a Bike-Share Demand Baseline

7 min read

The bike-share's operations team wants a forecast of rentals for every hour of the coming months. Before anyone tries a clever model, they need two things: a score that any model must beat, and a plain list of where today's model goes wrong.

The idea

A baseline is the simplest honest model: the score a fancier model has to beat. This project builds three models, each a step up from the last, and scores all of them on the same held-out hours.

  1. Frame it. Predict cnt, the rentals in one hour, from what is known before that hour starts: the date, the hour, and the weather (in practice, a forecast of it).
  2. Remove the leak. Drop any column that holds the answer.
  3. Split by time. Train on the past and test on the future, as in Day 6.
  4. Climb the ladder. The mean baseline, then one feature, then many.
  5. Report. A table of test RMSE, plus what the best model still can't see.

An honest baseline is worth more than a flattering score. It tells the next model exactly what to fix.

The formula

A bare RMSE of 183 is hard to judge. Comparing it with the baseline's RMSE makes it readable:

improvement=1−RMSEmodelRMSEbaseline\text{improvement} = 1 - \frac{\text{RMSE}_{\text{model}}}{\text{RMSE}_{\text{baseline}}}
Symbol Meaning
RMSEmodel\text{RMSE}_{\text{model}} the model's test RMSE, a typical miss in rentals (Day 5)
RMSEbaseline\text{RMSE}_{\text{baseline}} the test RMSE of always predicting the training mean
improvement the share of the baseline's error the model removes: 0 is no better, 1 is perfect

Worked: 1−183.5236.5=1−0.776=0.2241 - \frac{183.5}{236.5} = 1 - 0.776 = 0.224, so the model removes about 22% of the baseline's error.

In code

The steps below are one script, run top to bottom.

Step 1: load. The file has 17,379 hours of Capital Bikeshare rentals from 2011 and 2012.

# script_id: day_008_project_bike_share_baseline/baseline
import os
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import root_mean_squared_error
from sklearn.model_selection import train_test_split

DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "bike_sharing" / "hour.csv", parse_dates=["dteday"])
print(df.shape)
print(df[["dteday", "hr", "temp", "casual", "registered", "cnt"]].head(3).to_string(index=False))
(17379, 17)
    dteday  hr  temp  casual  registered  cnt
2011-01-01   0  0.24       3          13   16
2011-01-01   1  0.22       8          32   40
2011-01-01   2  0.22       5          27   32

Step 2: drop the leaky columns. casual and registered count the two kinds of riders in that hour. You only learn them after the hour ends, and they add up to the target.

# script_id: day_008_project_bike_share_baseline/baseline
same = (df["casual"] + df["registered"] == df["cnt"]).mean()
print(f"rows where casual + registered == cnt: {same:.0%}")
df = df.drop(columns=["casual", "registered"])
rows where casual + registered == cnt: 100%

Keep them and the model just adds two columns together. Its score would look perfect and mean nothing.

Step 3: split by time. The rows are already in time order, so shuffle=False puts the oldest 75% in training and the newest 25% in the test set.

# script_id: day_008_project_bike_share_baseline/baseline
train, test = train_test_split(df, test_size=0.25, shuffle=False)   # oldest 75% to train
for name, part in [("train", train), ("test", test)]:
    print(f"{name}: {len(part):,} rows, {part['dteday'].min():%Y-%m-%d} to {part['dteday'].max():%Y-%m-%d}")
train: 13,034 rows, 2011-01-01 to 2012-07-02
test: 4,345 rows, 2012-07-02 to 2012-12-31

The cut falls partway through 2 July 2012. Every test hour comes after every training hour.

Step 4: three models. The baseline predicts the training mean for every hour. The second model is Day 4's line on temperature (temp is °C ÷ 41, which changes only the weight, not the predictions). The third uses every remaining column except the row number and the date, as in Day 7.

# script_id: day_008_project_bike_share_baseline/baseline
features = ["season", "yr", "mnth", "hr", "holiday", "weekday", "workingday",
            "weathersit", "temp", "atemp", "hum", "windspeed"]
one = LinearRegression().fit(train[["temp"]], train["cnt"])
full = LinearRegression().fit(train[features], train["cnt"])
preds = {
    "mean baseline": np.full(len(test), train["cnt"].mean()),
    "temperature only": one.predict(test[["temp"]]),
    "12 features": full.predict(test[features]),
}

Step 5: the scoreboard. Every model is scored on the same test hours.

# script_id: day_008_project_bike_share_baseline/baseline
base = root_mean_squared_error(test["cnt"], preds["mean baseline"])
print(f"{'model':<18}{'test RMSE':>10}{'improvement':>13}")
for name, p in preds.items():
    rmse = root_mean_squared_error(test["cnt"], p)
    print(f"{name:<18}{rmse:>10.1f}{1 - rmse / base:>13.0%}")
model              test RMSE  improvement
mean baseline          236.5           0%
temperature only       217.2           8%
12 features            183.5          22%

Each step helps: Day 7's four features scored 198.1, and the other eight columns trim that to 183.5. But a typical miss of 183 rentals is still large, since the median test hour has only 214.

Step 6: report the blind spots. Compare the average real and predicted rentals at each hour of the day.

# script_id: day_008_project_bike_share_baseline/baseline
print(f"weight on hr: {full.coef_[features.index('hr')]:+.1f} rentals per hour of the clock")
by_hour = test.assign(pred=preds["12 features"]).groupby("hr")[["cnt", "pred"]].mean()
print(by_hour.loc[[3, 8, 17, 23]].round().astype(int).to_string())
print(f"mean rentals: train {train['cnt'].mean():.0f}, test {test['cnt'].mean():.0f}")

FIG_DIR = Path(os.environ.get("ML_FIG_DIR", "figures"))
FIG_DIR.mkdir(exist_ok=True)
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(by_hour.index, by_hour["cnt"], color="#2a78d6", lw=2, marker="o", ms=4, label="actual")
ax.plot(by_hour.index, by_hour["pred"], color="#eb6834", lw=2, label="12-feature model")
ax.set(title="Hour as a number: a ramp misses both rush hours",
       xlabel="Hour of day", ylabel="Mean rentals per hour (test set)", xticks=range(0, 24, 3))
ax.grid(alpha=0.3)
ax.legend()
fig.tight_layout()
fig.savefig(FIG_DIR / "rentals_by_hour.png", dpi=120)
plt.close(fig)
weight on hr: +6.9 rentals per hour of the clock
    cnt  pred
hr           
3    15   165
8   491   211
17  618   325
23  119   317
mean rentals: train 168, test 255

Hour as a number: a ramp misses both rush hours

The report, in three lines:

  • Hour is treated as a number. One weight means each later hour adds about 7 rentals. So the model can't draw the 8:00 and 17:00 commuter peaks, and it predicts 317 rentals at 23:00 when the real average is 119. Treating hour as a category, in Day 14, fixes this.
  • Other codes are numbers too. weathersit and season are labels stored as 1–4, so the model also assumes each step up has the same effect.
  • Demand grew. The test hours average 255 rentals against 168 in training. A mean from the past starts out too low.

Quick check

Quick check

1. Why drop casual and registered before training?

2. The baseline's test RMSE is 200 and a model's is 150. What is the improvement?

3. The 12-feature model predicts 317 rentals at 23:00, but the real average is 119. Why?

Next

The fit itself has been a black box so far: Day 9: Gradient Descent, and Why Scaling Matters shows how a model finds its weights by stepping downhill.

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.

Next · Day 9 · 8 minGradient Descent, and Why Scaling Matters← Previous: Day 7 · Use Many Features: Multiple Linear Regression
Not tapped yet