12-04 更新 实时
首页/ 产业落地/ 正文

LightGBM 与四周均值预测共享单车租赁量

产业落地 来源:Towards Data Science 2026-11-21 00:30 1 阅读 机器翻译
LightGBM 与四周均值预测共享单车租赁量

这正是我希望在本文中探讨的内容。

我使用华盛顿特区 Capital Bikeshare 的历史数据,来检验自己能在多大程度上预测未来 48 小时逐小时的共享单车租借量(每次预测都在午夜发布)。核心问题是:一个更复杂的模型,能否比「前四周同一时段租借量」的简单平均值表现更好?而如果确实更好,这种改善在之后的评估期里是否依然存在?

在梳理数据的过程中,我发现模型选择与训练只是这场战役的一半。部分小时的记录存在缺失,所以在决定如何处理它们之前,我必须先弄清楚这些缺失究竟意味着什么。我还必须确保模型没有使用任何在预测时点尚不可得的信息。拿到结果之后,我又不得不追问:模型之间的差异究竟具有显著性,还是仅仅源于我所选取的特定时间段。

真正让我印象深刻的一点是,简单的四周季节性平均值竟如此有竞争力。在开发阶段,表现最好的 LightGBM 流程也只是略胜基线,而统计检验并未给我足够证据断定两者的平均预测误差存在差异。然而在 11 月至 12 月的评估期,LightGBM 的平均绝对误差比同一基线低了 19.6%。

这种反差给我留下了一些仅靠简单模型排名根本无法回答的问题。

在本文中,我将梳理整个分析过程、我在其中做出的各项决策,以及这些结果让我对模型评估流程有了哪些认识。我并不是想主张传统模型优于基础模型(本文实际上并未对两者进行比较)。我想说明的是,理解数据、选对基线、避免数据泄漏,以及批判性地评估结果,这些依然很重要——无论你用什么模型或工具来生成预测。

完整的实现、调参实验以及保存的结果,都可以在文末链接的 GitHub 仓库中找到。

缺失的小时意味着什么

我使用了 Fanaee-T 的 UCI Bike Sharing Dataset(UCI 共享单车数据集),其中包含 2011–2012 年的逐小时和逐日租赁数据,以及日历和天气数据。我留出 2012 年 11 月和 12 月的数据,用于后续的历史评估,并将截至 10 月 31 日的数据用于开发。

我首先需要的是一份可靠的逐小时目标数据。开发数据中提供了 15,919 条逐小时记录,但完整的民用时间网格共有 16,080 个位置。缺失的位置中有两个实际上是夏令时拨快时钟导致的不存在的小时。这样算下来,仍有 159 个真正缺失的小时需要处理。

我本可以用插值来填补这些空缺,这样做既简单又直接,但我不认为这是正确的做法。那样做意味着在尚未确认是否真的有租赁数据缺失之前,就凭空编造出正的租赁数值。

幸运的是,数据集还包含每日租赁总量,所以我先检查了这些。我把每天可获得的逐小时计数相加,并与对应的每日总量进行比较。这里,hourly 和 daily 已经限定为开发集数据:

recon = (hourly.groupby(hourly.index.normalize())["cnt"].agg(["sum", "size"]) .join(daily["cnt"].rename("day_total")))assert (recon["sum"] == recon["day_total"]).all()

全部 670 天都完全匹配,其中包括 72 天小时记录少于 24 条的情况。小时文件里也没有任何显式的零。记录的最小逐小时计数为 1。

假设每日总量包含了所有已记录的租赁,那么匹配的小时总和就没有额外的租赁可分配给缺失的真实小时。因此,我没有通过插值来编造数值,而是把 159 个缺失的真实小时视为推断出的零。

不过,这里有一个重要区别。我重建的是已记录的租赁,而不一定是实际需求。数据无法告诉我有多少人可能想租自行车却找不到车,而总量匹配也无法揭示两个文件中都缺失的交易。

我注意到的另一件事是,这些缺失的小时中有一些是连续较长的一段,而不是随机散布在数据中。我事后标记为可能中断的四段连续缺失,占了推断零值中的 83 个。我是通过结合正常繁忙时段缺失记录以及异常低的每日租赁总量来识别它们的。它们帮助我理解了数据中一些更不寻常的时期,但它们并不是模型能够提前知道的预警信号。

这也影响了我为建模准备数据的方式。在用于评估预测的实际租赁计数中,我保留了推断出的零值。不过,对于基于滞后的特征,我使用了一个单独的序列,在那些被标记为中断的时段以及夏令时缺口处,用前几周的观测值进行替换。这样一来,我就能调整历史输入,而不改变我试图预测的租赁计数。

夏令时还需要多留意一点。春季拨快时钟时那些不存在的小时未被评分,而数据集也无法区分秋季拨回时钟时重复出现的小时。所以当我说 48 步预测时,我指的是在无时区的民用时间网格上的 48 个位置,在时钟切换前后,这并不总是恰好 48 个流逝小时。

图 1。在整个开发期内,每日租赁总量变化显著,其中四个事后标记的干扰期以阴影标示(上)。2012 年 6 月三周的逐小时计数显示出周期性高峰和夜间低谷时段(下)。计数包含在所述重建假设下推断出的零值;阴影并不确认系统关闭。

每日模式在一周内如何变化

在理清缺失的小时之后,我想在决定尝试哪些模型之前,更好地了解租赁数据中的模式。

图 1 显示了明显的日周期节奏,白天繁忙,夜间则安静得多。但我觉得更有意思的是,这种节奏在工作日和周末之间的变化有多大。

例如,在上午 8 点,工作日平均租赁次数是周末平均值的 4.56 倍。但到中午,周末的租赁量反而更高:工作日租赁量平均仅为周末数字的 0.53 倍。

所以只知道一天中的小时数其实并不够。周一早上 8 点的预测,与周日早上 8 点的预测,是两个截然不同的问题。

图 2。小时×星期几热力图(左)与工作日/周末分时曲线(右)展示了开发期间的平均租借量。工作日的早高峰明显更强,而周末的租借量在中午前后更高。

这是我在构建模型时必须纳入考虑的一点。与其把小时和星期几当作完全独立的两类信息,我希望模型能够捕捉二者之间的交互作用。实现方式之一就是引入周内小时(hour-of-week)特征,它能标识出一周中的 168 个小时。基于树的模型也可以从小时和星期几这两个特征中学习到这类交互。

但这也让我不禁思考:我一开始究竟有多需要一个复杂模型。如果租借量遵循如此清晰的每周规律,那么也许只需对前几周同一时段的租借量取平均,就已经能给出相当不错的预测了。

这便成了我期望那些更复杂的模型能够超越的基线。

我该使用哪些历史租借量?

起初,使用昨天同一小时的租借量看起来是显而易见的选择。但这里有个问题:我是在午夜一次性做出全部 48 个预测的,并不会随着新的租借量数据到来而更新预测。

这意味着我无法对每个预测都使用 24 小时滞后。对于第二个预测日,这需要用到第一个预测日的租借量,而那时我还没有观测到这些数据。

所以我决定对回归模型采用一条简单规则:只使用相对于被预测小时至少 48 小时的滞后项。这样一来,我就知道在我发布预测时,每一个历史值都已经可得。这是一个保守的选择,因为我排除了一些本可用于较早预测小时的更近期信息,但它让整个 48 小时区间内保持了一致。

当我查看过去与当前租赁数量之间的相关性时,另一点引起了我的注意。一周前同一小时的数量(滞后 168)相关系数为 0.8807,而滞后 48 小时的为 0.6900。

换句话说,知道上周同一时间发生了什么,似乎比单纯回看两天前更具信息量。考虑到我已经看到的工作日与周末模式,这说得通。

原文较长,译文为节选;译文由英文原文机器翻译,术语按行业惯例统一,可在文末展开原文核对。

查看英文原文(LightGBM vs. a Four-Week Average for Forecasting Bike-Share Rentals)

That's what I was hoping to look at in this article.

I used historical data from Washington, D.C.'s Capital Bikeshare to see how well I could predict hourly bike-share rentals for the next 48 hours (with each forecast being issued at midnight). The basic question was: could a more sophisticated model do better than the simple average of the rental count for the same hours over the prior four weeks? And if it could, would that improvement still be there in a later evaluation period?

As I went through the data, I found that the model selection and training was only half the battle. There were some missing hourly records, so I had to figure out what those actually meant before I could decide how to deal with them. I also had to ensure that the models weren't using any information that would have been unavailable at the time of the forecast. Once I had the results, I then had to ask whether the differences between the models were anything of significance or just the result of the particular periods that I'd looked at.

One thing that really struck me was just how competitive a simple four-week seasonal average was. During the development phase, the best-performing LightGBM pipeline was only just ahead of the baseline, and the statistical tests didn't give me enough evidence to conclude that their mean forecast errors were different. In the November–December evaluation period, however, LightGBM's mean absolute error was 19.6% lower than that same baseline.

That contrast left me with questions that a simple model ranking just couldn't answer.

In this piece, I'm going to walk through the analysis, the decisions I made along the way, and what the results have taught me about the process of model evaluation. I'm not trying to argue that traditional models are better than foundation models (I haven't actually compared the two in this piece). What I'm trying to show is that understanding the data, picking the right baselines, avoiding data leakage, and critically assessing the results are still important, regardless of what model or tool you're using to generate your forecasts.

The full implementation, the tuning experiments, and the saved results are all available in the GitHub repository linked at the end.

What the Missing Hours Meant

I used Fanaee-T's UCI Bike Sharing Dataset, containing hourly and daily rental data for 2011–2012, along with calendar and weather data. I held out November and December 2012 for a later historical evaluation and used the data up to October 31st for development.

The first thing I needed was a reliable hourly target. The dev data had 15,919 supplied hourly rows but the full civil-time grid had 16,080 positions. Two of those missing positions were actually nonexistent hours caused by the clocks moving forward for daylight-saving time. That still left 159 genuine missing hours to account for.

I could have filled those gaps using interpolation, which would have been easy and straightforward, but I wasn't convinced that was the right approach. Doing so would have meant making up positive rental figures without first establishing whether any rentals were actually missing.

Luckily, the dataset also includes daily rental totals, so I checked those first. I added up the available hourly counts for each day and compared them with the corresponding daily totals. Here, hourly and daily have already been restricted to development:

recon = (hourly.groupby(hourly.index.normalize())["cnt"].agg(["sum", "size"]) .join(daily["cnt"].rename("day_total")))assert (recon["sum"] == recon["day_total"]).all()

All 670 days matched exactly, including the 72 days that had fewer than 24 hourly records. There weren't any explicit zeros in the hourly file either. The smallest recorded hourly count was one.

Assuming the daily totals included all recorded rentals, the matching hourly sums left no additional rentals to assign to the absent genuine hours. So rather than inventing values through interpolation, I treated the 159 missing genuine hours as inferred zeros.

There was an important distinction here, though. I was reconstructing recorded rentals, not necessarily actual demand. The data couldn't tell me how many people might have wanted a bike but couldn't find one, and matching totals wouldn't reveal transactions missing from both files.

Another thing I noticed was that some of these missing hours occurred in longer stretches rather than being scattered randomly through the data. Four runs that I retrospectively labelled as possible disruptions accounted for 83 of the inferred zeros. I identified them using a combination of missing records during normally busy hours and unusually low daily rental totals. They helped me understand some of the more unusual periods in the data, but they weren't warnings a model could have known about in advance.

This also affected how I prepared the data for modeling. I kept the inferred zeros in the actual rental counts used to evaluate the forecasts. For the lag-based features, however, I used a separate series that substituted observations from earlier weeks at those disruption-labelled hours and the daylight-saving gaps. That way, I could adjust the historical inputs without changing the rental counts I was trying to predict.

Daylight-saving time needed one more bit of care. The nonexistent spring-forward hours weren't scored, and the dataset couldn't distinguish the repeated hours when the clocks went back in autumn. So when I refer to a 48-step forecast, I mean 48 positions on a timezone-naive civil-time grid, which isn't always exactly 48 elapsed hours around a clock change.

Figure 1. Daily rental totals change substantially across the development period, with four retrospectively labelled disruption periods shaded (top). Three weeks of June 2012 hourly counts show recurring peaks and quiet overnight hours (bottom). Counts include inferred zeros under the stated reconstruction assumption; the shading does not confirm system closures.

How the Daily Pattern Changed Across the Week

Once I'd sorted out the missing hours, I wanted to get a better sense of the patterns in the rental data before deciding which models to try.

Figure 1 shows an obvious daily rhythm, with busy periods during the day and much quieter nights. But what I found more interesting was how much that rhythm changed between weekdays and weekends.

For example, at 8 a.m., the average number of rentals on weekdays was 4.56 times the weekend average. By noon, though, weekend rentals were higher: weekday rentals averaged only 0.53 times the weekend figure.

So knowing the hour of the day wasn't really enough. An 8 a.m. forecast on a Monday was a very different problem from an 8 a.m. forecast on a Sunday.

Figure 2. An hour-by-weekday heatmap (left) and weekday/weekend hourly profiles (right) show average rentals during development. The weekday morning peak is much stronger, while weekend rentals are higher around noon.

This was something I needed to account for when building the models. Rather than treating the hour and weekday as completely separate pieces of information, I wanted the models to be able to capture their interaction. One way to do that was through an hour-of-week feature, which identifies each of the 168 hours in a week. Tree-based models could also learn these interactions from the hour and weekday features.

But it also made me wonder how much I really needed a sophisticated model in the first place. If rental counts followed such recognizable weekly patterns, perhaps simply averaging the counts from the same hours over the previous few weeks would already give me a pretty good forecast.

That became the baseline I wanted the more complicated models to beat.

Which Past Rental Counts Could I Use?

At first, using yesterday's rental count at the same hour seemed like an obvious choice. But there was a catch. I was making all 48 predictions at midnight, not updating the forecast as new rental counts came in.

That meant I couldn't use a 24-hour lag for every prediction. For the second forecast day, it would require rental counts from the first forecast day, which I wouldn't have observed yet.

So I decided to use a simple rule for the regression models: only use lags of at least 48 hours relative to the hour being predicted. That way, I knew every historical value would already be available when I issued the forecast. It was a conservative choice, since I was leaving out some more recent information that I could have used for the earlier forecast hours, but it kept things consistent across the full 48-hour period.

When I looked at the correlations between past and current rental counts, something else caught my attention. The count at the same hour one week earlier (lag 168) had a correlation of 0.8807, compared with 0.6900 for the 48-hour lag.

In other words, knowing what happened at the same time last week appeared to be more informative than simply looking two days back. Given the weekday and weekend patterns I'd already seen, that made sense.

Figure 3. Historical lag correlations show strong weekly peaks. Lags below 48 hours aren't available for the final step of a 48-hour forecast, although some can be used for earlier steps.

This influenced the features I ended up using. Along with recent historical lags, I included observations from the same hours in earlier weeks, averages over the previous two, three, and four weeks, measures of recent variation, and calendar information. Altogether, I had 45 calendar and historical features before adding weather.

This is the lag-building part of the feature code. Here, HORIZON=48, WEEK=168, src is the engineered historical series described earlier, and index contains the target timestamps.

SHORT_LAGS = list(range(HORIZON, HORIZON + 25)) # 48 through 72WEEKLY_LAGS = [WEEK - 1, WEEK, WEEK + 1, 2 * WEEK, 3 * WEEK]ALL_LAGS = SHORT_LAGS + WEEKLY_LAGSfor L in ALL_LAGS: X[f"lag_{L}"] = src.reindex(index - pd.Timedelta(hours=L)).to_numpy()

The important thing was that these features weren't just related to rental counts in the historical data. They were also things I could genuinely know at midnight, when the forecast was supposed to be made.

How I Compared the Forecasts

Now that I had a better understanding of the data and the information I could actually use for forecasting, I needed a way to compare the different approaches fairly.

I didn't want to judge a model based on how well it performed over just one particular stretch of time. A model might do really well during a fairly predictable week but struggle when rental patterns changed. So I wanted to see how the different approaches performed across a range of periods, while making sure none of them had access to future information.

I used a chronological evaluation, moving forward through the data and generating a complete 48-hour forecast at midnight each time. The forecast periods didn't overlap, and at every starting point, the models were fitted using only the observations available before the forecast began.

The core loop looked like this:

for _, f in folds.iterrows(): train = df.loc[df.index < f["val_start"]] val_index = pd.date_range(f["val_start"], f["val_end"], freq="h") pred = np.asarray(fit_predict(train, val_index), dtype=float)

This excerpt shows the fitting and prediction steps and leaves out the checks and storage.

I divided the development period into two stages. First, I used 22 forecast starting points, spaced four days apart between February and April 2012, to tune the models. Then I used 92 later starting points, spaced two days apart from late April through October, to compare the tuned approaches and decide which model family to take forward.

That second stage gave me 4,416 hourly predictions per approach, all made for the same forecast periods. I kept the selected model settings fixed across those comparisons, although the models themselves were refitted as new historical data became available.

For measuring accuracy, I mainly focused on mean absolute error (MAE). I liked that it was easy to interpret: it told me, on average, how many rentals a forecast was off by. I also looked at RMSE, which puts more weight on large errors, and MASE, which scales the errors against a simple historical reference. I didn't use percentage error as my main measure because the rental counts included zeros.

Another thing I wanted to avoid was relying too much on the overall model rankings. Since every approach was making predictions for the same hours, I could compare their absolute errors on the same forecast paths and look at how consistent the differences really were.

That distinction became particularly important once I started looking at the results. As it turned out, having the lowest average error didn't necessarily mean I had enough evidence to say one approach was genuinely better than another.

Four Matching Weeks Were Harder to Beat Than I Expected

Before trying more sophisticated models, I wanted to see how far I could get with a few simple forecasting methods.

I started with three. The first was a daily naive forecast, which simply repeated the most recently observed day's hourly rental pattern. The second was a weekly naive forecast, which used the corresponding hours from one week earlier. And the third was a four-week seasonal average, which took the average rental count from the same hour and weekday over the previous four weeks.

I chose the four-week window before running this comparison rather than searching for the best number of weeks. All three approaches used the same prepared historical series.

The four-week average was calculated like this. Here, WEEK=168, and y_lagsrc is the prepared historical series described earlier.

def hour_of_week_climatology(train, val_index, n_weeks=4): stack = [ train["y_lagsrc"] .reindex(val_index - pd.Timedelta(hours=WEEK * k)) .to_numpy() for k in range(1, n_weeks + 1) ] return np.nanmean(np.vstack(stack), axis=0)

I expected the weekly patterns to be useful, especially after seeing how differently rental counts behaved on weekdays and weekends. But I was still surprised by just how much difference a simple average could make.

Across the 92 development evaluation periods, the daily naive forecast had a mean absolute error (MAE) of 105.824 rentals. Using the same hour from the previous week brought that down to 60.075. And averaging the matching hours over four weeks reduced it further to 49.856.

That was a much stronger starting point than I'd expected.

Figure 4. Baseline forecast errors by clock hour (left), forecast day (middle), and evaluation period (right). The four-week seasonal average was the most accurate of the three approaches, although errors still varied considerably across periods.

There was another interesting difference when I looked at the two forecast days separately. The daily naive method got considerably worse on the second day, with MAE increasing from 82.61 to 129.04. The weekly naive and four-week averages were much more consistent across the two days.

That didn't necessarily mean the extra forecast lead time was causing all of the difference, since the hours being predicted also changed between the two days. But it did show how differently these simple approaches behaved over the full 48-hour forecast.

By this point, I had a much better idea of what a useful forecasting model would need to achieve. Beating yesterday's rental pattern wasn't going to be particularly convincing. If a more complicated model was worth using, I wanted to see whether it could improve on the four-week average.

The Model Leaderboard Didn't Settle the Question

After seeing how well the four-week average performed, I was curious to find out whether any of the more sophisticated models could actually improve on it.

I tried several approaches. Ridge regression gave me a relatively simple linear model, while XGBoost and LightGBM could capture more complicated relationships between the calendar and historical rental counts. I also included SARIMA and Prophet, two approaches designed specifically for time-series forecasting.

I tuned the models using the earlier development periods, then compared their predictions over the same 92 forecast paths. At this stage, I left weather out of the picture so I could focus on how much each approach could learn from the rental history and calendar information alone.

Table 1. Forecasting performance across the same 92 development evaluation periods, with 4,416 hourly predictions per approach. Model tuning and training histories differed between methods.

So LightGBM came out on top. But looking at the numbers, I wasn't sure how much that first-place position really meant.

Its MAE was 49.025, compared with 49.856 for the four-week average. That's a difference of just 0.831 rentals per hour.

And when I looked beyond the overall averages, things became even more interesting. The four-week baseline actually had a lower error on half of the 92 forecast paths.

This made me wonder whether LightGBM's small advantage was consistent enough to be convincing, or whether the ranking might have looked different if I'd evaluated the models over a different set of periods.

To investigate that, I compared the models' errors on the same forecast paths rather than treating their overall MAE scores as the whole story. I also ran statistical comparisons, adjusting for the fact that I was testing multiple pairs of models and checking how the results changed when I allowed for dependence between successive forecast periods.

For LightGBM versus the four-week average, the Holm-adjusted p-values were 0.9553 under the simpler independent-path assumption and 0.9634 when I accounted for temporal dependence. Neither comparison gave me sufficient evidence to conclude that their mean forecast errors were different.

Figure 5. Path-level forecast errors (left) and how often each model ranked first when the observed forecast paths were resampled (right). The resampling included independent draws and moving blocks of different lengths.

I also explored how stable the rankings were by resampling the observed forecast paths. LightGBM still came first quite often: in 75.6% of the independent resamples and 87.8% of the resamples using 12-origin blocks. That suggested its first-place ranking wasn't particularly fragile to these resampling choices, although those frequencies weren't probabilities that it was truly the best model.

So I had a model that ranked first, and I had reasons to take its performance seriously. But I still didn't have a convincing case that it was better than the much simpler four-week average.

That was probably the most interesting result of this stage of the experiment. The leaderboard had given me a winner, but it hadn't really answered the question I cared about.

Weather Helped, but the Timing Mattered

After comparing the models using rental history and calendar information, I wanted to see whether adding weather could improve the forecasts.

It seemed like a sensible thing to try. Weather can affect how many people decide to ride a bike, so temperature, wind, and general weather conditions might help explain some of the variation that the calendar patterns couldn't capture.

But there was a catch. Just as with the rental counts, I had to think about what weather information would actually be available when I issued the forecast at midnight. I couldn't simply use the temperature or weather conditions at each future rental hour, because those observations wouldn't exist yet.

So I started with observed weather from 48 hours before each hour I wanted to predict. I included temperature, humidity, wind speed, weather conditions, and squared temperature. I also made sure that any missing weather values were filled using only earlier observations and checked that the inputs were available at forecast time.

I kept the LightGBM settings I'd already selected and used the 22 earlier tuning periods to decide whether adding weather was worthwhile. I'd set a minimum improvement of 0.25 rentals in MAE as the condition for keeping the extra features.

The initial result looked promising. MAE fell from 51.005 to 49.435, an improvement of 1.570 rentals per hour.

But when I carried that same approach forward to the 92 development comparison periods, the improvement was much smaller. LightGBM's MAE went from 49.025 without weather to 48.590 with weather, a difference of just 0.435 rentals per hour.

So the historical weather information did help, at least in terms of the observed average errors, but not nearly as much as the early tuning results had suggested. And even with weather included, the model's advantage over the four-week seasonal average wasn't statistically convincing in the paired comparisons.

I then tried something else, mainly because I was curious about how much difference more timely weather information could make.

In a separate experiment, I gave LightGBM the actual weather conditions at the hours it was supposed to predict. I kept the selected model settings the same and refitted the models at each forecast starting point, but this time they had access to weather observations from the future.

The difference was striking. MAE dropped to 38.909, almost 20% lower than the version using historical weather.

Of course, that wasn't a forecast I could actually have produced at midnight. I was giving the model information that would only become available later. But it was useful for understanding how much the available weather information mattered.

If I wanted to get closer to that result in a real forecasting system, I'd need to use archived weather forecasts showing what was predicted at each midnight forecast origin, rather than the conditions that were eventually observed.

For me, this was another reminder that the information available when a forecast is made matters just as much as the model making it.

LightGBM Was Still Leaning on the Four-Week Idea

After seeing how competitive the four-week average was, I wanted to understand what LightGBM was actually learning from the data. Was it finding patterns that the simple baseline couldn't capture, or was it mostly making use of the same weekly information?

I started by looking at feature importance in a LightGBM model fitted on the full development data. What caught my attention was that just four features accounted for 58.4% of the total tree-split gain. These were the average rental counts for the same hour over the previous two, three, and four weeks, along with the variation across those four weeks.

In other words, the model was relying heavily on information that was closely related to my simple four-week baseline.

I wanted to check that another way, so I ran a small experiment. I took 31 forecast periods from the development comparison and shuffled those four weekly summary features together before making predictions, without changing the fitted models.

The difference was enormous. MAE went from 45.265 to 209.529.

Now, shuffling features like this can create combinations of values that wouldn't normally occur together, so I wouldn't interpret that increase as the exact cost of removing those features. But it certainly showed how sensitive the predictions were to the weekly summaries.

Weather, by comparison, seemed to play a much smaller role. It accounted for 4.2% of the split gain in the inspection model, and shuffling the weather features increased MAE by just 0.257 on those same 31 forecast periods.

What I took away from this was that the weekly pattern wasn't just something LightGBM had to compete against. It was also a big part of what the model itself was using to make predictions.

Where the Forecasts Went Wrong

I also wanted to look beyond the average error and see when the model was struggling.

One thing I noticed was how differently the errors behaved throughout the day. At 5 p.m., when average rentals were around 689, the model's mean absolute error was 113.6 rentals. At 4 a.m., the error was only 4.0 rentals, but the average rental count at that hour was just 9.1.

So the busiest hours tended to produce the largest mistakes in absolute numbers, while even a small mistake overnight could be quite large relative to the usual number of rentals.

Figure 6. Errors from the LightGBM pipeline with lagged weather across the 92 development forecast periods. Absolute errors were larger during busy hours, while errors relative to typical rental counts were larger overnight. The relative measure shown is not MAPE.

But the biggest problem wasn't an ordinary rush hour.

The model's worst development forecast began on October 29, 2012, during Hurricane Sandy. Recorded rentals dropped sharply, but the model continued predicting substantial activity. That single 48-hour forecast had an MAE of 259.6 rentals.

It was a striking example of how a model could learn the usual patterns quite well and still struggle when something happened that was far outside the ordinary.

There were 36 hours associated with Sandy among the development forecasts, and I checked whether leaving those hours out of the error calculations would change the model rankings. It didn't. I kept them in the main evaluation, though, because they were part of the rental history I was trying to predict.

By this point, I had a model that could make good use of the regular weekly patterns, but I could also see where that strength had its limits. The next question was whether its advantage over the four-week average would hold up when I moved to the later evaluation period.

November and December Told a Different Story

After everything I'd seen during development, I was particularly curious about what would happen when I moved to the November–December evaluation period.

LightGBM had come out on top, but its advantage over the four-week average had been small. Would that advantage disappear in a different period, or would the more sophisticated model finally show a clearer improvement?

To find out, I took the selected LightGBM pipeline with lagged weather and compared it with the three seasonal baselines. I kept the model settings, feature rules, and evaluation procedure fixed. The models were still refitted as new historical observations became available, but I didn't do any further tuning.

This gave me 30 complete, nonoverlapping 48-hour forecasts, covering November 1 through December 30, 2012, with 1,440 hourly predictions in total.

Table 2. Forecasting performance across the 30 November–December evaluation periods. RMSE is pooled across hourly predictions, while MASE uses a historical 24-hour seasonal scale.

This time, the difference was much more noticeable. LightGBM's MAE was 12.652 rentals per hour lower than the four-week baseline, a 19.6% reduction.

That was a very different result from the development period, where the advantage had been less than one rental per hour.

I wanted to understand why the gap had changed so much, so I looked more closely at the two evaluation periods. One thing that stood out was the difference in rental levels. During development, there had been an average of 279.5 recorded rentals per scored hour. In November and December, that dropped to 190.0, a decrease of about 32%.

Interestingly, the four-week average actually performed worse in this later period, while the daily naive forecast improved. That suggested the models were responding differently to the changing rental patterns, rather than simply becoming more or less accurate together.

There were other differences between the periods too, including their seasonal composition and the absence of disruption-labelled runs comparable to Hurricane Sandy in the final block. I couldn't isolate exactly which of these factors explained the larger gap.

Still, the result was encouraging. For this later period, LightGBM delivered substantially more accurate forecasts than the four-week average. I hadn't run a separate statistical significance test on these final differences, and the historical holdback wasn't completely untouched: an earlier data-quality check had already identified four missing timestamps and their inferred zeros. But the model configuration had been selected without using the later forecast errors or rental outcomes.

What I found interesting was the contrast itself. The development results had made me cautious about declaring a winner, while the later results gave me a much stronger observed improvement. Both were part of understanding how the forecasting approaches performed.

Better Point Forecasts Weren't the End of the Evaluation

Getting a lower average error was encouraging, but I also wanted to know something more practical: how much uncertainty was there around each prediction?

If the model predicted 400 rentals for a particular hour, for example, how much confidence could I really place in that number? A single prediction doesn't tell me how far the actual count might be from it.

So I decided to look at prediction intervals as well.

My aim was to construct intervals that would contain roughly 80% of individual hourly rental counts. I used earlier forecast errors to estimate how far predictions tended to miss, following an empirical approach based on conformal prediction.

I tried two versions. The first calculated a separate interval width for each of the 48 forecast steps. The second used one common width across all steps. In both cases, I clipped the lower bounds at zero, since rental counts can't be negative.

I first checked these approaches during development, using 55 earlier forecast periods for calibration and 37 later periods to assess coverage. The per-horizon intervals covered 81.9% of the observed hourly counts, while the pooled intervals covered 81.6%. Those assessment periods had also played a role in model selection, so I treated this as a development check rather than an independent evaluation of the entire pipeline.

For the final November–December evaluation, I recalculated the interval thresholds using all 92 development forecast periods and then kept them fixed. I didn't use the final-period errors to adjust them.

Table 3. Observed coverage and average interval width for nominal 80% pointwise prediction intervals. The development check used 55 calibration and 37 assessment paths; final intervals were calibrated using all 92 development paths.

Neither approach quite reached the 80% target in the final period. The separate per-step intervals came closer, although they were also a little wider on average.

Figure 7. Prediction interval coverage across the 48 forecast steps, final-period MAE for the four forecasting approaches, and actual versus predicted rentals with nominal 80% intervals for November 1–8.

What I found useful about this exercise was that it gave me another way to judge the forecasts beyond their average accuracy. LightGBM could produce better point predictions while the uncertainty estimates still needed work.

These were empirical intervals built from historical errors, not a guarantee that 80% coverage would hold in every future period. They also described uncertainty around individual hourly predictions, rather than guaranteeing that an entire 48-hour forecast would fall within its intervals.

For me, that was an important part of the evaluation. A model can give you a more accurate prediction, but understanding how much to trust that prediction is a separate question.

Where Foundation Models and Agents Fit into This Story

One question I wanted to come back to was how all of this fits into forecasting today, when we have time series foundation models that can generate predictions with little or no task-specific training, and AI agents that can automate much of the workflow.

I haven't tested models like TimesFM or Chronos in this project, so I can't say how they would have performed compared with LightGBM. That's something I'd actually be interested in exploring next.

But looking back at the experiment, I don't think using a foundation model would have made the questions I struggled with any less important.

I would still have needed to work out what the missing hourly records meant, make sure the model wasn't using information from the future, and decide what a reasonable benchmark should look like. And even if a foundation model had come out on top, I'd still want to know whether its advantage was consistent across different periods and how well its predictions held up when something unusual happened.

An AI agent could certainly help with many of these steps, from preparing the data to running comparisons and checking results. But I'd still want to understand the decisions being made and check whether the evidence actually supported the conclusions.

For me, that's where much of the value of going through this project came from. It wasn't just about finding a model that produced accurate forecasts. It was about learning how to judge those forecasts in the first place.

I started with a fairly simple question: could a more sophisticated forecasting model beat the average rental count from the same hours over the previous four weeks?

The answer turned out to be more interesting than I expected.

During development, LightGBM was only slightly ahead of that simple baseline, and the statistical comparisons didn't give me enough evidence to conclude that their mean forecast errors were different. But when I moved to the November–December evaluation period, the selected LightGBM pipeline achieved 19.6% lower observed MAE than the four-week average.

What surprised me most was how much I learned from the baseline itself. It was far more competitive than I'd expected, and when I looked at what LightGBM was using to make its predictions, I found that the same weekly patterns were playing a major role there too.

I also came away with a better appreciation of how much the evaluation setup matters. The missing hourly records affected what I was trying to predict, the timing of the inputs determined which features I could use, and the errors during Hurricane Sandy showed how badly a model could struggle outside the usual patterns. Even after getting better point forecasts, I still had to look at how well the prediction intervals represented uncertainty.

There are still questions I'd like to explore. I'd be interested in testing the selected approach on genuinely new data, comparing it with a time series foundation model under the same evaluation rules, and seeing what happens when I use actual weather forecasts available at the time of prediction rather than historical observations or future weather.

I wouldn't take the results of this one experiment as proof that LightGBM is generally better than a simple seasonal average. But I do think I've found a promising approach worth testing further.

More importantly, I've come away with a much better understanding of what I'd need to check before trusting a forecasting result, regardless of which model produced it.

Sources and Companion Material

The figures and results in this article come from my own experiments using the UCI Bike Sharing Dataset. I've included the full implementation, model tuning, feature engineering, backtesting, and prediction interval calculations in the companion notebook.

Project code and notebook

Fanaee-T, H. (2013). Bike Sharing Dataset. UCI Machine Learning Repository. DOI: 10.24432/C5W894.

Fanaee-T, H., & Gama, J. (2014). Event labeling combining ensemble detectors and background knowledge. Progress in Artificial Intelligence.

The dataset is available under the Creative Commons Attribution 4.0 International license. My analysis includes reconstructed hourly targets and engineered features derived from the original data.

Forecasting methods and evaluation

Diebold, F. X., & Mariano, R. S. (1995). Comparing Predictive Accuracy. Background reading on forecast comparisons; statsmodels documentation for Holm's multiple-testing adjustment.

National Weather Service: Post-Tropical Storm Sandy.

Thanks for reading! If you have any questions about the choices I made or ideas for a useful follow-up experiment, I'd love to hear them!

Explained with visualizations.

October 8, 20204 min read

The words that are significant to a class can be used improve the precision-recall trade off in classification. Using the top significant...

December 23, 20194 min read

Making SageMaker Pipelines more resilient with retry policies

March 27, 20223 min read

How the latest language model from OpenAI can help write poetry, fiction, and screenplays

January 4, 202316 min read

An advanced explanation (Classification tasks) - Part 1

December 21, 20209 min read

August 24, 202111 min read

Improve your grid search with this small change

March 14, 20226 min read

Visualising geological data using Python's most popular data visualisation library

April 19, 20237 min read

Does CNN attain the properties of human-level vision? - A exploratory study

December 14, 20205 min read

原文为英文,正文由自动抓取并保留原文。

本文由采集器自动同步

原文发布于 Towards Data Science(LightGBM vs. a Four-Week Average for Forecasting Bike-Share Rentals),标题、摘要与正文由机器翻译,术语按行业惯例统一,未经人工逐句校订。

阅读原文 ↗