DS Mini Project
Riverside Bikes is growing. The town council will pay for two new stations, and the manager has a shortlist of five candidate sites. Your job: build an evidence-based estimate of how busy a station at each site would be, and explain which site features matter.
This project walks through the full workflow from the CRISP-DM lesson — question, data, preparation, exploration, modelling, evaluation and communication — on a new invented dataset: one row per existing station.
| Column | Meaning |
|---|---|
station |
Station ID (S01 … S40) |
district |
Part of town |
dist_km |
Distance from the town centre (km) |
university |
1 if a university campus is within 500 m |
hill_m |
Height difference to the nearest river path (m) — riders dislike climbing |
rides |
Average daily rentals over the last year — the target |
Each step is a complete program. Because the playgrounds can't read files, each one starts with the same code that recreates the raw export, including its data-entry problems (they're added at the end of the block, as they would arrive from a real system).
Step 1: The question and a first look
"For a candidate site with given distance, university proximity and hilliness, how many daily rides should we expect — and how confident are we?"
Success criterion: predictions on unseen stations within ±10 rides on average (MAE ≤ 10), clearly better than just using the average station.
import numpy as np
import pandas as pd
rng = np.random.default_rng(2024)
n = 40
raw = pd.DataFrame({
"station": [f"S{i:02d}" for i in range(1, n + 1)],
"district": rng.choice(["Centre", "Northbank", "Eastside", "Harbour"], n),
"dist_km": rng.uniform(0.2, 6, n).round(1),
"university": (rng.random(n) < 0.25).astype(int),
"hill_m": rng.integers(0, 60, n).astype(float),
})
raw["rides"] = (95 - 9 * raw["dist_km"] + 30 * raw["university"]
- 0.4 * raw["hill_m"] + rng.normal(0, 8, n)).round(1)
raw.loc[[6, 21], "hill_m"] = np.nan
raw.loc[13, "rides"] = raw.loc[13, "rides"] * 10
raw.loc[30, "district"] = raw.loc[30, "district"].lower() + " "
print(raw.shape)
print(raw.head(8))
print()
print(raw.isna().sum()[raw.isna().sum() > 0])
print()
print(raw["district"].value_counts())(40, 6)
station district dist_km university hill_m rides
0 S01 Centre 1.4 0 12.0 79.1
1 S02 Eastside 2.8 0 12.0 66.4
2 S03 Centre 1.8 0 32.0 69.2
3 S04 Centre 5.3 0 22.0 38.7
4 S05 Northbank 1.4 1 31.0 85.7
5 S06 Northbank 1.8 0 12.0 67.5
6 S07 Harbour 4.9 0 NaN 43.3
7 S08 Harbour 1.8 0 17.0 64.7
hill_m 2
dtype: int64
district
Centre 12
Harbour 10
Northbank 9
Eastside 8
centre 1
Name: count, dtype: int64
Already two warning signs: two missing hill_m values, and a fifth "district" called "centre " (lower case, trailing space).
Step 2: Prepare the data
describe() reveals a third problem: a maximum of 740 rides when the 75th percentile is below 90.
import numpy as np
import pandas as pd
rng = np.random.default_rng(2024)
n = 40
raw = pd.DataFrame({
"station": [f"S{i:02d}" for i in range(1, n + 1)],
"district": rng.choice(["Centre", "Northbank", "Eastside", "Harbour"], n),
"dist_km": rng.uniform(0.2, 6, n).round(1),
"university": (rng.random(n) < 0.25).astype(int),
"hill_m": rng.integers(0, 60, n).astype(float),
})
raw["rides"] = (95 - 9 * raw["dist_km"] + 30 * raw["university"]
- 0.4 * raw["hill_m"] + rng.normal(0, 8, n)).round(1)
raw.loc[[6, 21], "hill_m"] = np.nan
raw.loc[13, "rides"] = raw.loc[13, "rides"] * 10
raw.loc[30, "district"] = raw.loc[30, "district"].lower() + " "
print(raw[["dist_km", "hill_m", "rides"]].describe().round(1))
print()
print(raw.sort_values("rides", ascending=False).head(3)[["station", "dist_km", "university", "rides"]]) dist_km hill_m rides
count 40.0 38.0 40.0
mean 2.8 27.8 85.4
std 1.5 15.4 109.3
min 0.3 0.0 16.9
25% 1.7 14.2 50.4
50% 2.2 29.0 68.4
75% 3.7 37.5 89.1
max 5.8 55.0 740.0
station dist_km university rides
13 S14 1.9 0 740.0
38 S39 1.4 1 123.1
9 S10 0.6 1 106.1
Station S14 is an ordinary station 1.9 km from the centre with no university nearby; 740 rides a day is impossible for it. The operations team confirms a misplaced decimal point: the true value is 74.0. We document three rules and apply them:
- Clean district labels with
str.strip().str.title(). - Correct S14's rides from 740.0 to 74.0 (confirmed typo).
- Fill the two missing
hill_mvalues with the median (only 2 of 40 rows; we'll check that this doesn't matter).
import numpy as np
import pandas as pd
rng = np.random.default_rng(2024)
n = 40
raw = pd.DataFrame({
"station": [f"S{i:02d}" for i in range(1, n + 1)],
"district": rng.choice(["Centre", "Northbank", "Eastside", "Harbour"], n),
"dist_km": rng.uniform(0.2, 6, n).round(1),
"university": (rng.random(n) < 0.25).astype(int),
"hill_m": rng.integers(0, 60, n).astype(float),
})
raw["rides"] = (95 - 9 * raw["dist_km"] + 30 * raw["university"]
- 0.4 * raw["hill_m"] + rng.normal(0, 8, n)).round(1)
raw.loc[[6, 21], "hill_m"] = np.nan
raw.loc[13, "rides"] = raw.loc[13, "rides"] * 10
raw.loc[30, "district"] = raw.loc[30, "district"].lower() + " "
# --- preparation (Step 2) ---
stations = raw.copy()
stations["district"] = stations["district"].str.strip().str.title()
stations.loc[13, "rides"] = stations.loc[13, "rides"] / 10 # confirmed typo: 740.0 -> 74.0
stations["hill_m"] = stations["hill_m"].fillna(stations["hill_m"].median())
print(stations["district"].value_counts())
print()
print(stations[["dist_km", "hill_m", "rides"]].describe().round(1))
print("missing values left:", int(stations.isna().sum().sum()))district
Centre 13
Harbour 10
Northbank 9
Eastside 8
Name: count, dtype: int64
dist_km hill_m rides
count 40.0 40.0 40.0
mean 2.8 27.9 68.7
std 1.5 15.0 25.9
min 0.3 0.0 16.9
25% 1.7 14.8 50.4
50% 2.2 29.0 68.4
75% 3.7 36.5 87.4
max 5.8 55.0 123.1
missing values left: 0
Step 3: Explore
Which features relate to rides? A correlation table, a district comparison and scatter plots:
import numpy as np
import pandas as pd
rng = np.random.default_rng(2024)
n = 40
raw = pd.DataFrame({
"station": [f"S{i:02d}" for i in range(1, n + 1)],
"district": rng.choice(["Centre", "Northbank", "Eastside", "Harbour"], n),
"dist_km": rng.uniform(0.2, 6, n).round(1),
"university": (rng.random(n) < 0.25).astype(int),
"hill_m": rng.integers(0, 60, n).astype(float),
})
raw["rides"] = (95 - 9 * raw["dist_km"] + 30 * raw["university"]
- 0.4 * raw["hill_m"] + rng.normal(0, 8, n)).round(1)
raw.loc[[6, 21], "hill_m"] = np.nan
raw.loc[13, "rides"] = raw.loc[13, "rides"] * 10
raw.loc[30, "district"] = raw.loc[30, "district"].lower() + " "
# --- preparation (Step 2) ---
stations = raw.copy()
stations["district"] = stations["district"].str.strip().str.title()
stations.loc[13, "rides"] = stations.loc[13, "rides"] / 10 # confirmed typo: 740.0 -> 74.0
stations["hill_m"] = stations["hill_m"].fillna(stations["hill_m"].median())
import matplotlib.pyplot as plt
print(stations[["dist_km", "university", "hill_m", "rides"]].corr()["rides"].round(2))
print()
print(stations.groupby("district")["rides"].agg(["count", "mean"]).round(1))
fig, axes = plt.subplots(1, 2, figsize=(11, 4), sharey=True)
colors = stations["university"].map({0: "#999999", 1: "#ff6f00"})
axes[0].scatter(stations["dist_km"], stations["rides"], c=colors, s=25)
axes[0].set_xlabel("distance from centre (km)")
axes[0].set_ylabel("average daily rides")
axes[0].set_title("Orange = near a university")
axes[1].scatter(stations["hill_m"], stations["rides"], c=colors, s=25)
axes[1].set_xlabel("climb to river path (m)")
plt.tight_layout()
plt.show()dist_km -0.77
university 0.71
hill_m -0.27
rides 1.00
Name: rides, dtype: float64
count mean
district
Centre 13 66.3
Eastside 8 69.2
Harbour 10 66.2
Northbank 9 74.8
EDA notes:
- Rides fall with distance from the centre (r ≈ −0.77) — the strongest single relationship.
- Stations near a university are much busier (r ≈ 0.71); in the plot, the orange points sit above the grey ones at every distance.
- Hills reduce rides somewhat (r ≈ −0.27).
- District averages are similar (66–75 rides); differences may simply reflect distance and universities.
Step 4: Model
We compare three candidate models: distance only, the three site features, and the site features plus district.
import numpy as np
import pandas as pd
rng = np.random.default_rng(2024)
n = 40
raw = pd.DataFrame({
"station": [f"S{i:02d}" for i in range(1, n + 1)],
"district": rng.choice(["Centre", "Northbank", "Eastside", "Harbour"], n),
"dist_km": rng.uniform(0.2, 6, n).round(1),
"university": (rng.random(n) < 0.25).astype(int),
"hill_m": rng.integers(0, 60, n).astype(float),
})
raw["rides"] = (95 - 9 * raw["dist_km"] + 30 * raw["university"]
- 0.4 * raw["hill_m"] + rng.normal(0, 8, n)).round(1)
raw.loc[[6, 21], "hill_m"] = np.nan
raw.loc[13, "rides"] = raw.loc[13, "rides"] * 10
raw.loc[30, "district"] = raw.loc[30, "district"].lower() + " "
# --- preparation (Step 2) ---
stations = raw.copy()
stations["district"] = stations["district"].str.strip().str.title()
stations.loc[13, "rides"] = stations.loc[13, "rides"] / 10 # confirmed typo: 740.0 -> 74.0
stations["hill_m"] = stations["hill_m"].fillna(stations["hill_m"].median())
import statsmodels.formula.api as smf
formulas = [
"rides ~ dist_km",
"rides ~ dist_km + university + hill_m",
"rides ~ dist_km + university + hill_m + C(district)",
]
for f in formulas:
m = smf.ols(f, data=stations).fit()
print(f"{f:52} adj R2={m.rsquared_adj:.3f} AIC={m.aic:.1f}")
best = smf.ols(formulas[1], data=stations).fit()
print()
print(best.summary2().tables[1].round(3))rides ~ dist_km adj R2=0.586 AIC=340.6
rides ~ dist_km + university + hill_m adj R2=0.884 AIC=291.6
rides ~ dist_km + university + hill_m + C(district) adj R2=0.889 AIC=292.5
Coef. Std.Err. t P>|t| [0.025 0.975]
Intercept 100.036 4.235 23.622 0.0 91.447 108.625
dist_km -9.556 1.004 -9.522 0.0 -11.591 -7.520
university 29.199 3.238 9.016 0.0 22.631 35.767
hill_m -0.518 0.095 -5.436 0.0 -0.711 -0.325
The three site features explain far more than distance alone (adjusted R² 0.586 → 0.884). Adding district barely changes adjusted R² and makes AIC slightly worse, so we keep the simpler model. Its coefficients read:
- about −9.6 rides per km from the centre,
- about +29 rides near a university,
- about −0.5 rides per metre of climb (−5 rides per 10 m),
all with small p-values and confidence intervals well away from zero.
Step 5: Evaluate on unseen stations
With only 40 stations, a single train/test split would be a noisy judge, so we use 5-fold cross-validation and compare with the "average station" baseline. We also re-run the analysis with the two imputed rows removed, as promised in Step 2.
import numpy as np
import pandas as pd
rng = np.random.default_rng(2024)
n = 40
raw = pd.DataFrame({
"station": [f"S{i:02d}" for i in range(1, n + 1)],
"district": rng.choice(["Centre", "Northbank", "Eastside", "Harbour"], n),
"dist_km": rng.uniform(0.2, 6, n).round(1),
"university": (rng.random(n) < 0.25).astype(int),
"hill_m": rng.integers(0, 60, n).astype(float),
})
raw["rides"] = (95 - 9 * raw["dist_km"] + 30 * raw["university"]
- 0.4 * raw["hill_m"] + rng.normal(0, 8, n)).round(1)
raw.loc[[6, 21], "hill_m"] = np.nan
raw.loc[13, "rides"] = raw.loc[13, "rides"] * 10
raw.loc[30, "district"] = raw.loc[30, "district"].lower() + " "
# --- preparation (Step 2) ---
stations = raw.copy()
stations["district"] = stations["district"].str.strip().str.title()
stations.loc[13, "rides"] = stations.loc[13, "rides"] / 10 # confirmed typo: 740.0 -> 74.0
stations["hill_m"] = stations["hill_m"].fillna(stations["hill_m"].median())
import statsmodels.formula.api as smf
from sklearn.model_selection import KFold
formula = "rides ~ dist_km + university + hill_m"
model_mae, base_mae = [], []
for train_idx, test_idx in KFold(n_splits=5, shuffle=True, random_state=0).split(stations):
train, test = stations.iloc[train_idx], stations.iloc[test_idx]
m = smf.ols(formula, data=train).fit()
model_mae.append((test["rides"] - m.predict(test)).abs().mean())
base_mae.append((test["rides"] - train["rides"].mean()).abs().mean())
print("model MAE per fold: ", np.round(model_mae, 1), " mean", round(np.mean(model_mae), 1))
print("baseline MAE per fold:", np.round(base_mae, 1), " mean", round(np.mean(base_mae), 1))
full = smf.ols(formula, data=stations).fit()
no_imputed = smf.ols(formula, data=stations[raw["hill_m"].notna()]).fit()
print()
print(pd.DataFrame({"all rows": full.params, "imputed rows dropped": no_imputed.params}).round(2))model MAE per fold: [8.8 6.7 6. 7.4 8. ] mean 7.4
baseline MAE per fold: [27. 15.2 17.9 20. 28.5] mean 21.7
all rows imputed rows dropped
Intercept 100.04 98.46
dist_km -9.56 -9.25
university 29.20 30.44
hill_m -0.52 -0.53
The model's average error on unseen stations is well under the 10-ride target and a fraction of the baseline's. Dropping the two imputed rows changes the coefficients only slightly, so the median fill didn't drive the results.
Step 6: Predict the candidate sites
Now the deliverable: expected rides for each candidate site, with a 95 % prediction interval for a single station. We also flag sites outside the range of our data, where the model would be extrapolating.
import numpy as np
import pandas as pd
rng = np.random.default_rng(2024)
n = 40
raw = pd.DataFrame({
"station": [f"S{i:02d}" for i in range(1, n + 1)],
"district": rng.choice(["Centre", "Northbank", "Eastside", "Harbour"], n),
"dist_km": rng.uniform(0.2, 6, n).round(1),
"university": (rng.random(n) < 0.25).astype(int),
"hill_m": rng.integers(0, 60, n).astype(float),
})
raw["rides"] = (95 - 9 * raw["dist_km"] + 30 * raw["university"]
- 0.4 * raw["hill_m"] + rng.normal(0, 8, n)).round(1)
raw.loc[[6, 21], "hill_m"] = np.nan
raw.loc[13, "rides"] = raw.loc[13, "rides"] * 10
raw.loc[30, "district"] = raw.loc[30, "district"].lower() + " "
# --- preparation (Step 2) ---
stations = raw.copy()
stations["district"] = stations["district"].str.strip().str.title()
stations.loc[13, "rides"] = stations.loc[13, "rides"] / 10 # confirmed typo: 740.0 -> 74.0
stations["hill_m"] = stations["hill_m"].fillna(stations["hill_m"].median())
import statsmodels.formula.api as smf
model = smf.ols("rides ~ dist_km + university + hill_m", data=stations).fit()
sites = pd.DataFrame({
"site": ["Library Square", "Hilltop Estate", "Old Brewery", "Campus North", "Ring Road Park"],
"dist_km": [0.8, 3.5, 2.0, 2.6, 7.5],
"university": [0, 0, 0, 1, 0],
"hill_m": [10, 45, 5, 20, 15],
}).set_index("site")
pred = model.get_prediction(sites).summary_frame(alpha=0.05)
result = sites.assign(expected=pred["mean"].to_numpy().round(0),
low=pred["obs_ci_lower"].to_numpy().round(0),
high=pred["obs_ci_upper"].to_numpy().round(0))
in_range = sites["dist_km"].between(stations["dist_km"].min(), stations["dist_km"].max())
result["note"] = np.where(in_range, "", "outside data range!")
print(result.sort_values("expected", ascending=False).to_string()) dist_km university hill_m expected low high note
site
Campus North 2.6 1 20 94.0 75.0 113.0
Library Square 0.8 0 10 87.0 68.0 106.0
Old Brewery 2.0 0 5 78.0 60.0 97.0
Hilltop Estate 3.5 0 45 43.0 25.0 62.0
Ring Road Park 7.5 0 15 21.0 0.0 41.0 outside data range!
Campus North and Library Square are the clear favourites. Ring Road Park lies 7.5 km out — farther than any existing station — so its forecast is an extrapolation and should be treated with caution (or checked with a pilot station).
Step 7: Communicate
The final step turns the analysis into a short, plain-language summary for the council. Generating it from the model keeps every number consistent with the analysis:
import numpy as np
import pandas as pd
rng = np.random.default_rng(2024)
n = 40
raw = pd.DataFrame({
"station": [f"S{i:02d}" for i in range(1, n + 1)],
"district": rng.choice(["Centre", "Northbank", "Eastside", "Harbour"], n),
"dist_km": rng.uniform(0.2, 6, n).round(1),
"university": (rng.random(n) < 0.25).astype(int),
"hill_m": rng.integers(0, 60, n).astype(float),
})
raw["rides"] = (95 - 9 * raw["dist_km"] + 30 * raw["university"]
- 0.4 * raw["hill_m"] + rng.normal(0, 8, n)).round(1)
raw.loc[[6, 21], "hill_m"] = np.nan
raw.loc[13, "rides"] = raw.loc[13, "rides"] * 10
raw.loc[30, "district"] = raw.loc[30, "district"].lower() + " "
# --- preparation (Step 2) ---
stations = raw.copy()
stations["district"] = stations["district"].str.strip().str.title()
stations.loc[13, "rides"] = stations.loc[13, "rides"] / 10 # confirmed typo: 740.0 -> 74.0
stations["hill_m"] = stations["hill_m"].fillna(stations["hill_m"].median())
import statsmodels.formula.api as smf
model = smf.ols("rides ~ dist_km + university + hill_m", data=stations).fit()
b = model.params
print("RIVERSIDE BIKES - NEW STATION SITES (based on 40 existing stations)")
print()
print(f"* Every km farther from the centre costs about {abs(b['dist_km']):.0f} rides a day.")
print(f"* A nearby university campus adds about {b['university']:.0f} rides a day.")
print(f"* Every 10 m of climb to the river path costs about {abs(b['hill_m']) * 10:.0f} rides a day.")
print(f"* These three features explain {model.rsquared:.0%} of the differences between stations;")
print(" on stations the model had not seen, it was off by about 7 rides a day on average.")
print()
print("Recommendation: build at Campus North and Library Square first.")
print("Ring Road Park is farther out than any current station - test it with a pilot.")
print("Limitations: one year of data; associations, not proven causes; no data on new housing.")RIVERSIDE BIKES - NEW STATION SITES (based on 40 existing stations)
* Every km farther from the centre costs about 10 rides a day.
* A nearby university campus adds about 29 rides a day.
* Every 10 m of climb to the river path costs about 5 rides a day.
* These three features explain 89% of the differences between stations;
on stations the model had not seen, it was off by about 7 rides a day on average.
Recommendation: build at Campus North and Library Square first.
Ring Road Park is farther out than any current station - test it with a pilot.
Limitations: one year of data; associations, not proven causes; no data on new housing.
Ideas to extend the project
- Add an interaction
dist_km * university: does a campus matter more far from the centre? - Replace median imputation of
hill_mwith a lookup from a terrain map — and compare. - Draw a residuals vs fitted plot and check the Q-Q plot (Residual Analysis).
- Write the Step 6 table as a bar chart with error bars — one message, one chart.
- Re-do the analysis as if you were the council's critic: what could make these forecasts wrong?
Test yourself
Why was S14's value of 740 rides corrected to 74.0 rather than simply deleted?
- Deleting rows is never allowed
- The operations team confirmed a decimal-point typo, so the true value was known
- 740 is the median
- To increase R²
Why did we keep the model without district?
- District was missing
- Adding district barely improved adjusted R² and made AIC worse — the simpler model is enough
- statsmodels can't use categories
- District had the strongest correlation
Why is Ring Road Park's forecast flagged?
- It has a university
- Its distance (7.5 km) is outside the range of the stations the model was fitted on
- Its prediction is negative
- It has no hill