Cycling duration: exploration and statistical regression¶
Question: How are recorded cycling distance and elevation gain associated with workout duration?
This notebook uses the existing Garmin export, without an account connection. Run cells in order. It fits ordinary least squares (OLS), reports heteroskedasticity-robust (HC3) confidence intervals, and evaluates predictions on the most recent 20% of rides.
These are observational associations, not causal effects. Duration also depends on terrain, stops, weather, fitness, and equipment. The target is Garmin's Time field, not elapsed time or moving time.
# Run once in the selected notebook kernel if dependencies are missing.
%pip install -q pandas numpy matplotlib statsmodels
Note: you may need to restart the kernel to use updated packages.
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
from IPython.display import display
candidates = [Path("data/Activities.csv"), Path("../data/Activities.csv")]
data_path = next((p for p in candidates if p.is_file()), None)
if data_path is None:
raise FileNotFoundError("Run from the project root or notebooks/ directory.")
raw = pd.read_csv(data_path)
print(f"Loaded {len(raw):,} activities from {data_path.resolve()}")
display(raw["Activity Type"].value_counts().rename("activities").to_frame())
Loaded 1,180 activities from /Users/edbr/Documents/dev/garminData/data/Activities.csv
| activities | |
|---|---|
| Activity Type | |
| Cross Country Classic Skiing | 442 |
| Cycling | 356 |
| Pool Swim | 103 |
| Trail Running | 63 |
| Hiking | 63 |
| Cross Country Skate Skiing | 61 |
| Running | 46 |
| Backcountry Skiing | 19 |
| Resort Skiing/Snowboarding | 10 |
| Open Water Swimming | 8 |
| Breathwork | 3 |
| Tennis | 1 |
| Indoor Rowing | 1 |
| Skating | 1 |
| Resort Skiing | 1 |
| Mountaineering | 1 |
| Road Cycling | 1 |
Prepare the analysis data¶
Keep Cycling and Road Cycling, matching the existing cycling visualization. Missing values remain missing; they are not replaced with zero. Exclude invalid dates, nonpositive distance/duration, negative ascent, and nonfinite values. Keep unusual but valid rides for inspection.
The export does not include unit metadata. The existing notebooks label distance as kilometers and ascent as meters; confirm your Garmin export settings before interpreting coefficients. Change the labels below if necessary; the model uses the numeric values as exported.
DISTANCE_UNIT = "km" # Confirm against Garmin export settings.
ASCENT_UNIT = "m"
ACTIVITY_TYPES = ["Cycling", "Road Cycling"]
rides = raw.loc[raw["Activity Type"].isin(ACTIVITY_TYPES)].copy()
selected_count = len(rides)
rides["date"] = pd.to_datetime(rides["Date"], errors="coerce")
for source, target in [("Distance", "distance"), ("Total Ascent", "ascent")]:
rides[target] = pd.to_numeric(
rides[source].astype(str).str.replace(",", "", regex=False), errors="coerce"
)
rides["duration_hours"] = pd.to_timedelta(
rides["Time"], errors="coerce"
).dt.total_seconds() / 3600
rides = rides.replace([np.inf, -np.inf], np.nan)
rides = rides.dropna(subset=["date", "distance", "ascent", "duration_hours"])
rides = rides.loc[
(rides["distance"] > 0) & (rides["ascent"] >= 0) & (rides["duration_hours"] > 0)
].sort_values("date").reset_index(drop=True)
# Scale ascent so its coefficient represents 100 exported elevation units.
rides["ascent_100"] = rides["ascent"] / 100
print(f"Included {len(rides):,} of {selected_count:,} cycling activities; excluded {selected_count-len(rides):,}.")
if len(rides) < 20:
raise ValueError("At least 20 valid rides are needed for this exploratory train/test split.")
display(rides[["date", "distance", "ascent", "duration_hours"]].describe())
display(rides.nlargest(5, "duration_hours")[["Date", "Title", "distance", "ascent", "duration_hours"]])
Included 354 of 357 cycling activities; excluded 3.
| date | distance | ascent | duration_hours | |
|---|---|---|---|---|
| count | 354 | 354.000000 | 354.000000 | 354.000000 |
| mean | 2023-12-25 14:35:07.268361 | 27.379096 | 553.251412 | 1.911795 |
| min | 2021-11-14 08:40:02 | 1.970000 | 17.000000 | 0.198333 |
| 25% | 2022-09-05 13:30:31.500000 | 14.680000 | 355.250000 | 1.088056 |
| 50% | 2023-09-04 13:25:46 | 19.545000 | 445.000000 | 1.445972 |
| 75% | 2024-10-18 14:02:23.250000 | 34.377500 | 704.000000 | 2.564028 |
| max | 2026-09-30 13:26:20 | 119.990000 | 1981.000000 | 5.915000 |
| std | NaN | 19.858037 | 322.945064 | 1.181244 |
| Date | Title | distance | ascent | duration_hours | |
|---|---|---|---|---|---|
| 128 | 2023-06-10 09:22:45 | Sardine peak | 87.22 | 1444.0 | 5.915000 |
| 306 | 2025-11-09 11:20:29 | Truckee Cycling | 58.07 | 1412.0 | 5.812500 |
| 347 | 2026-08-08 08:14:36 | Truckee Cycling | 59.54 | 1381.0 | 5.543611 |
| 84 | 2022-08-27 10:21:56 | Truckee Cycling | 59.41 | 1370.0 | 5.483333 |
| 94 | 2022-10-02 11:01:19 | Placer County Cycling | 119.99 | 1330.0 | 5.367222 |
Explore distributions and relationships¶
Look for skew, unusual rides, and correlated predictors. Distance and elevation can move together, making their separate coefficients uncertain. These exploratory plots use all rides; the later holdout is a preliminary validation, not an untouched final benchmark after model selection.
fig, axes = plt.subplots(1, 3, figsize=(14, 4))
for ax, column, label in zip(axes, ["distance", "ascent", "duration_hours"],
[f"Distance ({DISTANCE_UNIT})", f"Ascent ({ASCENT_UNIT})", "Duration (hours)"]):
ax.hist(rides[column], bins=25, edgecolor="white")
ax.set(xlabel=label, ylabel="Rides")
plt.tight_layout()
plt.show()
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
for ax, column, label in zip(axes, ["distance", "ascent"],
[f"Distance ({DISTANCE_UNIT})", f"Ascent ({ASCENT_UNIT})"]):
ax.scatter(rides[column], rides["duration_hours"], alpha=0.5)
ax.set(xlabel=label, ylabel="Duration (hours)")
plt.tight_layout()
plt.show()
display(rides[["distance", "ascent", "duration_hours"]].corr())
| distance | ascent | duration_hours | |
|---|---|---|---|
| distance | 1.000000 | 0.870678 | 0.860392 |
| ascent | 0.870678 | 1.000000 | 0.921318 |
| duration_hours | 0.860392 | 0.921318 | 1.000000 |
Fit a regression using earlier rides¶
Model: duration_hours = intercept + b_distance × distance + b_ascent × (ascent / 100).
Reserve the latest 20% of rides for testing. Rides sharing the cutoff timestamp stay together. Fit a distance-only comparison as well as the distance-plus-ascent model. HC3 standard errors allow nonconstant error variance, but do not correct serial dependence between rides or omitted variables.
cutoff = rides.iloc[int(len(rides) * 0.8)]["date"]
train = rides.loc[rides["date"] < cutoff].copy()
test = rides.loc[rides["date"] >= cutoff].copy()
if len(train) < 10 or len(test) < 2:
raise ValueError("Insufficient distinct dates for the chronological split.")
features = ["distance", "ascent_100"]
def design(frame, columns=features):
return sm.add_constant(frame[columns], has_constant="add")
X_train = design(train)
if np.linalg.matrix_rank(X_train) < X_train.shape[1]:
raise ValueError("Predictors are constant or perfectly correlated; revise the feature selection.")
model = sm.OLS(train["duration_hours"], X_train).fit(cov_type="HC3")
distance_model = sm.OLS(train["duration_hours"], design(train, ["distance"])).fit(cov_type="HC3")
print(f"Training: {len(train)} rides; test: {len(test)} rides; cutoff: {cutoff}")
print(model.summary())
coefficients = model.conf_int().rename(columns={0: "95% lower", 1: "95% upper"})
coefficients.insert(0, "coefficient (hours)", model.params)
coefficients["p value"] = model.pvalues
display(coefficients)
print(f"Distance coefficient: {model.params['distance'] * 60:.2f} minutes per {DISTANCE_UNIT}, holding ascent fixed.")
print(f"Ascent coefficient: {model.params['ascent_100'] * 60:.2f} minutes per 100 {ASCENT_UNIT}, holding distance fixed.")
Training: 283 rides; test: 71 rides; cutoff: 2025-06-27 17:36:27
OLS Regression Results
==============================================================================
Dep. Variable: duration_hours R-squared: 0.884
Model: OLS Adj. R-squared: 0.883
Method: Least Squares F-statistic: 519.9
Date: Sat, 14 Nov 2026 Prob (F-statistic): 5.42e-95
Time: 09:37:34 Log-Likelihood: -147.13
No. Observations: 283 AIC: 300.3
Df Residuals: 280 BIC: 311.2
Df Model: 2
Covariance Type: HC3
==============================================================================
coef std err z P>|z| [0.025 0.975]
------------------------------------------------------------------------------
const 0.0718 0.056 1.275 0.202 -0.039 0.182
distance 0.0147 0.003 5.159 0.000 0.009 0.020
ascent_100 0.2516 0.021 11.771 0.000 0.210 0.293
==============================================================================
Omnibus: 38.615 Durbin-Watson: 1.524
Prob(Omnibus): 0.000 Jarque-Bera (JB): 121.912
Skew: 0.553 Prob(JB): 3.37e-27
Kurtosis: 6.019 Cond. No. 71.5
==============================================================================
Notes:
[1] Standard Errors are heteroscedasticity robust (HC3)
| coefficient (hours) | 95% lower | 95% upper | p value | |
|---|---|---|---|---|
| const | 0.071801 | -0.038601 | 0.182204 | 2.024225e-01 |
| distance | 0.014675 | 0.009100 | 0.020251 | 2.482857e-07 |
| ascent_100 | 0.251552 | 0.209667 | 0.293437 | 5.501284e-32 |
Distance coefficient: 0.88 minutes per km, holding ascent fixed. Ascent coefficient: 15.09 minutes per 100 m, holding distance fixed.
Evaluate on later rides¶
Compare both regressions with a constant prediction equal to the training mean. MAE and RMSE are in minutes; lower is better. Holdout R² can be negative if predictions are worse than the holdout mean. Training R² and small p-values do not guarantee useful predictions.
actual = test["duration_hours"].to_numpy()
predictions = {
"Training mean baseline": np.full(len(test), train["duration_hours"].mean()),
"Distance only": distance_model.predict(design(test, ["distance"])).to_numpy(),
"Distance + ascent": model.predict(design(test)).to_numpy(),
}
rows = []
for name, predicted in predictions.items():
errors = actual - predicted
total = np.sum((actual - actual.mean()) ** 2)
rows.append({"model": name, "MAE (minutes)": np.mean(np.abs(errors)) * 60,
"RMSE (minutes)": np.sqrt(np.mean(errors ** 2)) * 60,
"holdout R²": 1 - np.sum(errors ** 2) / total if total > 0 else np.nan})
display(pd.DataFrame(rows).set_index("model"))
predicted = predictions["Distance + ascent"]
fig, ax = plt.subplots(figsize=(5, 5))
ax.scatter(actual, predicted, alpha=0.65)
lo, hi = min(actual.min(), predicted.min()), max(actual.max(), predicted.max())
ax.plot([lo, hi], [lo, hi], "k--", label="Perfect prediction")
ax.set(xlabel="Actual duration (hours)", ylabel="Predicted duration (hours)")
ax.legend()
plt.show()
print(f"Negative holdout predictions: {(predicted < 0).sum()} (a limitation of unconstrained OLS)")
| MAE (minutes) | RMSE (minutes) | holdout R² | |
|---|---|---|---|
| model | |||
| Training mean baseline | 51.925846 | 66.859072 | -0.001635 |
| Distance only | 25.396794 | 41.687526 | 0.610596 |
| Distance + ascent | 20.151644 | 33.120625 | 0.754198 |
Negative holdout predictions: 0 (a limitation of unconstrained OLS)
Diagnose model assumptions and influential rides¶
Curvature suggests a missing nonlinear relationship; a widening residual spread suggests changing variance. The Q–Q plot shows departures from normally distributed residuals. Cook's distance highlights rides that can strongly affect the fitted coefficients; a high value is a reason to inspect a ride, not automatically delete it.
fig, axes = plt.subplots(1, 3, figsize=(15, 4))
axes[0].scatter(model.fittedvalues, model.resid, alpha=0.5)
axes[0].axhline(0, color="black", linestyle="--")
axes[0].set(xlabel="Fitted duration (hours)", ylabel="Residual (hours)")
sm.qqplot(model.resid, line="s", ax=axes[1])
axes[2].scatter(train["date"], model.resid, alpha=0.5)
axes[2].axhline(0, color="black", linestyle="--")
axes[2].set(xlabel="Date", ylabel="Residual (hours)")
axes[2].tick_params(axis="x", rotation=45)
plt.tight_layout()
plt.show()
influential = train[["Date", "Title", "distance", "ascent", "duration_hours"]].copy()
influential["cooks_distance"] = model.get_influence().cooks_distance[0]
display(influential.nlargest(10, "cooks_distance"))
| Date | Title | distance | ascent | duration_hours | cooks_distance | |
|---|---|---|---|---|---|---|
| 216 | 2024-05-19 12:31:35 | Truckee Cycling | 93.94 | 1981.0 | 4.944444 | 0.365982 |
| 124 | 2023-05-29 10:30:31 | Truckee Cycling | 112.67 | 1524.0 | 4.675556 | 0.117685 |
| 12 | 2021-12-12 12:00:03 | Santa Cruz County Cycling | 34.70 | 1121.0 | 2.305000 | 0.083968 |
| 84 | 2022-08-27 10:21:56 | Truckee Cycling | 59.41 | 1370.0 | 5.483333 | 0.075153 |
| 247 | 2024-08-10 08:33:21 | El Dorado County Cycling | 41.52 | 1367.0 | 4.815000 | 0.059912 |
| 165 | 2023-08-05 10:10:19 | South Lake Tahoe Cycling | 41.60 | 1105.0 | 4.599444 | 0.058587 |
| 128 | 2023-06-10 09:22:45 | Sardine peak | 87.22 | 1444.0 | 5.915000 | 0.058300 |
| 184 | 2023-09-23 10:58:07 | Truckee Cycling | 59.54 | 1426.0 | 5.273611 | 0.041723 |
| 142 | 2023-07-01 08:00:20 | Truckee Cycling | 105.74 | 1695.0 | 5.288056 | 0.041119 |
| 220 | 2024-05-27 12:25:42 | Truckee Cycling | 20.51 | 514.0 | 3.774167 | 0.040228 |