Skip to content

Using Supervised Machine Learning to Model and Forecast Bike Rental Demand

Ivy Araujo edited this page Jul 14, 2025 · 3 revisions

Introduction

Supervised machine learning plays a pivotal role in forecasting and decision-making by leveraging historical data to train predictive models. This technique enables organisations to uncover relationships within past observations and project future outcomes with good accuracy. By establishing patterns and quantifying variable influence, supervised learning supports evidence-based decision-making, resource optimisation, and strategic planning in dynamic environments. Organisations with access to rich historical datasets are especially well-positioned to benefit from this approach. Their existing data becomes a strategic asset, offering insights that might otherwise go unnoticed.

Linear regression is a fundamental predictive technique in statistical modelling. A simple linear regression (SLR) model relates a dependent variable to a single independent variable, while a multiple linear regression (MLR) model expands this relationship to incorporate two or more predictors, offering improved flexibility and accuracy by capturing the influence of multiple features.

In this tutorial, we apply both SLR and MLR to forecast bike rental demand (dataset from Fanaee-T & Gama (2013)). The dataset contains information about daily bike rentals, weather conditions, and temporal variables. We'll perform exploratory analysis, build and assess multiple regression models, visualise results, and interpret the findings. The source data can be downloaded here bike_dataset.

Loading the Dataset and Creating Train-Test Split

We split the dataset into 80% training and 20% testing data.

bike_dataset <- read.csv("bike_dataset.csv")

set.seed(123)
sample_index <- sample(1:nrow(bike_dataset), 0.8 * nrow(bike_dataset))
train_data <- bike_dataset[sample_index, ]
test_data <- bike_dataset[-sample_index, ]

Predicting Demand by Temperature (SLR)

A linear regression model of type cnt = b0 + b1 * temp is trained to predict bike rental demand (cnt) using temperature (temp) as the only predictor and the results are visualised on a graphic.

  • b0 is the intercept (the predicted value when x=0, in this case, the predicted number of bike rentals (cnt) when the temperature (temp) is 0°C)

  • b1 is the slope coefficient (how much y changes for a 1 unit increase in x, in this case, average change in bike rentals (cnt) for each 1°C increase in temperature (temp))

model_temp <- lm(cnt ~ temp, data = train_data)
summary(model_temp)

Results:

  • The intercept (b₀ ≈ 1234.4) represents the expected number of rentals when the temperature is 0°C.
  • The slope (b₁ ≈ 159.6) shows that for each 1°C increase, bike rentals increase by around 160 bikes.
  • The R² = 0.38 indicates that temperature alone explains ~38% of the variability in rental demand — a moderate relationship.
  • The residual standard error (RSE) of ~1529 is quite high, suggesting large unexplained variance.
  • This shows temperature is a significant driver of demand but not the only one. Other variables like weather conditions, day of the week, or holidays likely influence bike usage as well

Visualising the Fit

ggplot(train_data, aes(x = temp, y = cnt)) +
  geom_point(alpha = 0.5) +
  geom_smooth(method = "lm", color = "blue") +
  labs(title = "Bike Demand vs Temperature", 
       x = "Temperature (°C)",
       y = "Count of Bike Rentals") +
  theme(plot.title = element_text(hjust = 0.5, face = "bold"))
image

The scatterplot and regression line above illustrate a clear upward trend: bike rental demand tends to increase as temperature rises. However, the data exhibits considerable noise, indicating variability not solely explained by temperature. The fitted linear regression model reveals a positive correlation, suggesting that for every 1°C increase in temperature, rental counts rise by approximately 160 bikes. The model accounts for about 38.1% of the variation in demand (Multiple R-squared: 0.3808), demonstrating that while temperature plays a significant role, it is far from the only factor influencing rental behavior.

The residual standard error of 1529 and the wide spread of residuals (ranging from -4568 to +3771) indicates significant prediction errors in the model. This shows that bike demand could be influenced by other factors, not only temperature, such as time of year, day of the week, weather conditions, and holidays. Adding these variables in the model, can improve the model’s predictive accuracy.

It is observed that within the time frame considered, a 1°C increase in temperature corresponds to an average rise in bike rental demand of ~ 159.589 rentals. This positive relationship between temperature and bike demand is quantified using the slope coefficient (b₁) from the fitted linear regression model above, highlighting the direct influence of temperature fluctuations on rental activity.

coef(model_temp)[1] #b0

coef(model_temp)[2] #b1

The relationship between temperature and demand is illustrated in the graphic below, which compares the actual bike rental counts (solid blue line) with the predicted values generated by the linear model (dashed green line) over time. The chart spans the full date range of the dataset and reveals how well the model estimates rental trends based solely on temperature. While the predicted line broadly tracks the peaks and troughs of actual demand, noticeable discrepancies emphasise the influence of additional factors beyond temperature.

image

Predicting Demand Over Time

Another simple linear regression model was developed using the instant variable, which represents the sequential day index in the dataset. Since instant increases by one each day, it effectively captures the progression of time from 01-Jan-2018 to 31-Dec-2019. This model estimates bike rental demand over time as a linear function: cnt = b0 + b1 * instant

The model output shows a statistically significant positive slope of approximately 5.74, indicating an average daily increase of about 5.74 rentals. Over a week, this translates to roughly 40 additional rentals. With an R² value of 0.39, the model explains around 39% of the variability in demand, confirming a meaningful upward trend but also suggesting that many influencing factors remain unaccounted for.

Prediction results for January 1, 2019 demonstrate the model’s limitations: it overestimated demand by roughly 827 rentals. This emphasises the need to include more granular features (such as weather conditions or seasonality) for improved forecasting accuracy.

# Fit model using date proxy
model_instant <- lm(cnt ~ instant, data = train_data)
summary(model_instant)

# Average weekly increase
slope_b1 <- coef(model_instant)["instant"]
weekly_increase <- slope_b1 * 7
cat("Average weekly increase:", round(weekly_increase), "rentals\n")

# Predict demand for 01/01/2019 with 90% prediction interval
instant_target <- train_data$instant[train_data$dteday == as.Date("2019-01-01")]
predict(model_instant,
        newdata = data.frame(instant = instant_target),
        interval = "prediction",
        level = 0.90)

Multiple Linear Regression Model

We now build an MLR model using several predictors available in the dataset.

model_multi <- lm(cnt ~ temp + atemp + hum + windspeed + season + yr + mnth +
                    holiday + weekday + workingday + weathersit,
                  data = train_data)
summary(model_multi)

Results:

  • The model explains ~79.5% of rental variability — a significant improvement over single-variable models.

  • Significant predictors include:

(a) yr (annual growth): +2001 rentals

(b) season: strong seasonal variation (~+507 rentals)

(c) weathersit: poor weather reduces demand (−585 rentals)

(d) hum and windspeed: both negatively correlated with demand

(e) Some variables (e.g. temp, atemp, workingday) show marginal or no significance, hinting at multicollinearity.

Model Refinement

Refining a regression model is an essential, especially when working with multiple predictors. As models become more complex, they often include variables that contribute little to predictive performance. These weak predictors can introduce noise, reduce interpretability, and unnecessarily inflate computational cost. In this step, we retrain a simplified multiple linear regression model using only the most informative variables:

model_multi_refined <- lm(cnt ~ temp + hum + windspeed + season + yr + mnth +
                    holiday + weekday + weathersit,
                  data = train_data)
summary(model_multi_refined)

Despite dropping some predictors, the refined model achieves R² ~ 79.3%, preserving most of the predictive accuracy. This indicates that the removed variables were not contributing significant signal to the model. By reducing dimensionality, we improve model clarity and generalizability, making it easier to interpret and potentially more robust when applied to future datasets. In summary, complexity does not guarantee performance — a focused model with strong predictors often yields better insights and more reliable forecasts.

Forecasting Bike Rental Demand for 2020

To estimate future bike rental demand, we extended the linear regression model built with the instant variable. Because instant captures the day index and is readily extrapolated, it's suitable for projecting future values when other features (like weather or season) are unavailable. This approach assumes a linear growth trend and is preferred over methods like k-NN, which can’t generalise beyond known data points.

# Prepare training data
train_data$dteday <- as.Date(train_data$dteday, format = "%Y-%m-%d")

# Predict historical demand (2018–2019)
train_data$cnt_pred <- predict(model_instant, newdata = train_data)
train_data$source <- "Actual and Predicted (2018–2019)"

# Forecast demand for 2020
future_instant <- data.frame(
  instant = seq(max(train_data$instant) + 1, max(train_data$instant) + 365)
)
future_instant$cnt_pred <- predict(model_instant, newdata = future_instant)
future_instant$dteday <- seq(as.Date("2020-01-01"), by = "day", length.out = nrow(future_instant))
future_instant$source <- "Forecast (2020)"

# Combine historical and forecast data
combined_data <- bind_rows(
  train_data %>% select(dteday, cnt, cnt_pred, source),
  future_instant %>% select(dteday, cnt_pred, source)
)

# Plot demand curve
ggplot(combined_data) +
  geom_point(aes(x = dteday, y = cnt, color = "Actual"), alpha = 0.5, na.rm = TRUE) +
  geom_line(aes(x = dteday, y = cnt_pred, color = source), size = 1) +
  scale_color_manual(
    values = c("Actual" = "black",
               "Actual and Predicted (2018–2019)" = "blue",
               "Forecast (2020)" = "red"),
    labels = c("Actual", "Predicted (2018–2019)", "Forecast (2020)")
  ) +
  labs(
    title = "Bike Rental Demand Forecast for 2020",
    x = "Date",
    y = "Rental Count"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(face = "bold", hjust = 0.5),
    legend.position = "top",
    legend.title = element_blank()
  ) +
  geom_vline(xintercept = as.Date(c("2018-12-31", "2019-12-31")), linetype = "dashed", color = "gray") +
  annotate("text", x = as.Date("2018-07-01"), y = max(combined_data$cnt, na.rm = TRUE) * 0.95, label = "2018", color = "gray40") +
  annotate("text", x = as.Date("2019-07-01"), y = max(combined_data$cnt, na.rm = TRUE) * 0.95, label = "2019", color = "gray40") +
  annotate("text", x = as.Date("2020-07-01"), y = max(combined_data$cnt_pred, na.rm = TRUE) * 0.95, label = "2020", color = "gray40")

image

The model suggests a steady rise in demand continuing into 2020, with actuals shown in grey, predictions for 2018–2019 in blue, and forecasts for 2020 in red. While the upward trajectory is evident, it's important to note the model doesn't account for seasonal effects or special events, making the forecast a high-level trend rather than a granular daily estimate.

Conclusion

This analysis explored regression models to predict bike rental demand using historical data. While simple linear regression using single predictors (like temperature or time) captured basic trends, their explanatory power was limited. Multiple linear regression significantly improved predictive accuracy by incorporating diverse features such as weather conditions, seasonal cycles, and calendar effects — explaining nearly 80% of demand variation. Yet, even refined models showed overestimation on specific dates, suggesting room for further enhancement.

References

Fanaee-T, Hadi, and Gama, Joao. “Event labeling combining ensemble detectors and background knowledge”, Progress in Artificial Intelligence (2013): pp. 1–15, Springer Berlin Heidelberg, doi:10.1007/s13748-013-0040-3

R - Simple Linear Regression and Multiple Linear Regression.zip

Clone this wiki locally