預測明日需求

閱讀約需 69 分鐘 分鐘,7 節 中共有 3 個範例。

版次 2026.11.11 範例於 2026年11 月 20 通過測試 41 個範例中有 41 個通過 變更內容

由 AI 翻譯。經人工以英文驗證。 我們如何製作書籍

譯自英文書,版次 2026.11.11。 閱讀原文

本章建立第一個明日需求預測,以及之後每個預測都必須超越的簡單基準。你會載入單一客戶的每小時需求,用季節性天真基準(seasonal naive baseline)與一個統計模型預測它的下一天,並在同樣的 7 天上為兩者評分。結果刻意保持粗略:沒有預測區間,沒有調校,而且只以一位客戶來判斷。後續的每一章會把其中一個部分做得更穩固。你需要具備 Python、pandas、樣本平均數,以及誤差是什麼的基本概念,不需要其他背景;核心術語會在第一次出現的地方用一行說明。

明天的電力必須在今天、在一天開始之前,以每小時為單位購買。購買電力的人需要一份預測,說明客戶在每個小時會用多少電;預測每有一個小時失準,採購計畫就是依據錯誤的數字安排了那一個小時。因此在信任任何方法之前,要先回答兩個問題。只憑購電之前記錄的讀數所做出的預測,是否接近客戶實際的用電量?它是否優於任何人都能做出的最簡單預測,也就是直接複製昨天的用電量?

此部分尚未翻譯,因此以英文呈現。

The case and its data

最近一次變動於第 2026.11.11 版

This book follows one case throughout: an electricity supplier that buys power a day ahead for its clients, which we call the supplier.

The supplier commits to its purchases before the day starts, and it needs a range as well as a single number, because buying too little costs more than buying too much. This book builds the forecast that such a purchase starts from. A forecast here is the expected demand of one client in each hour, made from readings recorded before the forecast was made.

Three terms fix what a forecast is. The moment a forecast is made is its cutoff. A forecast uses only the readings before its cutoff, and it reaches forward a fixed number of hours, its horizon. A window is one cutoff with its horizon and the forecast it produces. Here the horizon is 24 hours, so each window covers one day: the 24 hours that start at its cutoff.

The timing matters as much as the method. Every window in this book has its cutoff at 00:00 on the day it predicts, so the last reading it can use is the one for 23:00 on the day before. The case buys before the day starts, so a midnight cutoff is a simplification. The book keeps it so that each window needs only the day before. A supplier that buys earlier would cut earlier and forecast further ahead. A forecast that reads one hour past its cutoff would use information the supplier does not have when it buys, and its score would flatter it.

The data is public. It is the ElectricityLoadDiagrams20112014 dataset from the UCI Machine Learning Repository, by Trindade (2015), with the DOI 10.24432/C58C86. It is licensed under CC BY 4.0. The book ships a cut of it, electricity_hourly.csv.gz, with the licence beside it in the same folder. The data card gives the source, the cut and its limits.

The raw file holds 370 clients, with a reading every 15 minutes. The cut averages the four readings of each hour, which gives the energy used in that hour in kWh, and it keeps two whole years, 2013 and 2014. One client, MT_223, has no non-zero reading in that window, so the cut drops it. The 369 clients that remain are sorted by id, and 30 are kept at evenly spaced positions. A reader who cuts the raw file must drop MT_223 and take the same 30 evenly spaced positions, or the counts in this book will not match.

The clients have anonymous ids such as MT_014. The dataset does not say what they are, so the book calls them clients. It does not describe them as companies or households.

Two groups of clients recur through the book. The thirty clients are every client in the cut. The 8 clients of SUBSET8 are every fourth client of the thirty, starting with the second. Later chapters use that subset where a full run would take too long, and it includes one client that starts late. The lead client, MT_014, is the first client of SUBSET8. This chapter and its single-client examples use it.

The test period is the last week of 2014, from Dec 25 to Dec 31, 2014. The forecasts in this chapter are scored on it, and it is called the held-out week. Each forecast uses only readings from before its cutoff, so no forecast learns from the day it predicts. The week is not quiet. Dec 25, 2014 is Christmas Day, a national holiday in Portugal, where the data's clock is set. This chapter scores the week as it is, and the scores show what the holiday does. Chapter 5 tests a holiday flag on holiday windows and does not keep it, so the book does not repair the holiday here. Chapter 10 shows its cost.

A forecast says what demand is likely to be. It does not say why. The data records how much each client used. It cannot say what demand would have been under a different price or contract. That is a causal question, and it needs a different design.

Working rule: Check the cut against the data card before any forecast is made. The file should hold 30 clients, and the example counts how many of them have a full two years of hourly rows. Those counts should match the card. Confirm that MT_223 is missing and explained. A cut that does not match the card is different data, and every number computed from it describes that data, not this one.

此部分尚未翻譯,因此以英文呈現。

Load one client's hourly demand

最近一次變動於第 2026.11.5 版

A time series is a sequence of readings in time order. In the book's file, each row is one client in one hour, and each client's hours are in time order. To load one client, keep that client's rows. The helper load in examples/lib/electricity.py does that and returns four columns. unique_id names the client. ds is the hour. y is the energy used in that hour, in kWh. quirk tells you whether the row needs special handling.

The ds column is the start of the hour, in local clock time with no time zone. The data card gives this label, and the book's examples treat the index as one naive hourly index. Each row's quirk is one of four labels:

  • normal is an ordinary hour.
  • before_first_reading is an hour before a client's first non-zero reading. Only a late-starting client has these rows.
  • clock_change_gap is 01:00 on a March clock-change day. The dataset's note says it reads zero for every client. The data card measures it: of 57 such hours with non-zero neighbours, 55 read below 5% of them.
  • clock_change_repeat is 01:00 on an October clock-change day. It holds about two hours of energy under one label.

The book keeps every value as the meter recorded it. Nothing is filled, smoothed, removed or rescaled. A zero in a gap hour and a doubled October hour are therefore still in the file, flagged but not corrected. Chapter 3 decides what each flagged row means for a model. This chapter only needs to know the labels exist, and to check that none of them falls inside the windows it scores.

The lead client has readings in every hour of the window, so none of its rows are before_first_reading. Over the two years it has 17516 ordinary rows. It has 2 gap rows and 2 repeat rows, one of each in each year.

load-lead-client.py Python 3.13.16 · numpy 2.5.5 · pandas 2.3.3 · utilsforecast 0.2.17 通過
"""Loads the lead client's hourly demand, counts its quirk labels, and checks the eight-week history before eachheld-out cutoff. The point rests on the last printed line: no history holds a clock-change row."""from lib.backtest import held_out_cutoffs, history_beforefrom lib.electricity import loadfrom lib.settings import LEAD, showdef fmt(ts):    return ts.strftime("%Y-%m-%d %H:%M")FULL_ROWS = 2 * 365 * 24  # two years of hours; 2013 and 2014 are not leap yearseveryone = load()show("clients in the file", everyone["unique_id"].nunique())show(f"clients with {FULL_ROWS} rows", int((everyone.groupby("unique_id").size() == FULL_ROWS).sum()))df = load([LEAD])show("rows", len(df))show("first reading", fmt(df["ds"].min()))show("last reading", fmt(df["ds"].max()))for quirk in ["normal", "before_first_reading", "clock_change_gap", "clock_change_repeat"]:    show(f"{quirk} rows", int((df["quirk"] == quirk).sum()))# history_before keeps the HISTORY_HOURS hours (eight weeks) before each cutoff, and raises if a count is off.windows = [history_before(df, cutoff) for cutoff in held_out_cutoffs()]show("history rows per window", min(len(w) for w in windows))show("longest history rows", max(len(w) for w in windows))show("first history reading", fmt(windows[0]["ds"].min()))# Counts only the two clock-change labels.show("clock-change rows in held-out histories",     sum(int(w["quirk"].isin(["clock_change_gap", "clock_change_repeat"]).sum()) for w in windows))
輸出python load-lead-client.py
clients in the file: 30
clients with 17520 rows: 30
rows: 17520
first reading: 2013-01-01 00:00
last reading: 2014-12-31 23:00
normal rows: 17516
before_first_reading rows: 0
clock_change_gap rows: 2
clock_change_repeat rows: 2
history rows per window: 1344
longest history rows: 1344
first history reading: 2014-10-30 00:00
clock-change rows in held-out histories: 0

The file holds 30 clients. The lead client has 17520 rows, from 2013-01-01 00:00 to 2014-12-31 23:00.

Two years of hours is 17520 rows for each client, and 30 of 30 clients have exactly that many, so no hour is missing from the file for those clients. A window with fewer hours than its history should hold has a gap, and the gap would be the first thing to explain. Check the client count and the row count against the card.

A forecast needs history. The book's history is 8 weeks, which is 1344 hours, and each cutoff in the held-out week gets exactly that much before it. The shortest history has 1344 rows, and the longest has 1344.

For the first cutoff of the held-out week, the history begins at 2014-10-30 00:00. That is after the clock change of Oct 26, 2014, which the data card dates. So none of the 7 histories holds a clock-change hour, and the example counts 0 clock-change rows across all seven.

The rest of this chapter can leave the clock-change rows alone for that reason. Chapter 3 meets them, and Chapter 4 meets the late starter.

Working rule: Choose the client and the window first, then count the quirks in that window's history before any model sees it. If a history holds a clock-change label or a before_first_reading row, do not hand it to a model unchanged, because the model will read the label's value as demand. Chapter 3 and Chapter 4 give the rules for those rows. A window that holds neither can use its rows as they are, as this chapter does.

以季節性單純法預測隔天

最近一次變動於第 2026.11.5 版

第一個預測是最簡單的一個,之後的每個預測都必須勝過它。它使用案例與資料中所定的案例截止點與預測期程,以及載入單一客戶所說明的歷史資料。

季節性單純法(seasonal naive)主張,每個未來的值都等於同一季節中最後一次觀測到的值。Hyndman 與 Athanasopoulos 針對任意季節長度 m 定義了這個方法:未來某個值的預測,就是前一個季節所觀測到的值(Hyndman and Athanasopoulos, Forecasting: Principles and Practice, ch. 5)。在逐時資料與以日為週期的情況下,季節長度為 24 小時,因此明天某一小時的預測值,就是今天同一小時的讀數。以本書的記號來表示,第 t 小時的預測為 y(t - 24)。

這條規則沒有任何東西需要擬合。預測值就是資料的複製,因此不需要估計步驟。無論截止點為何,它都不會讀取截止點之後的資料。對於從截止點起到其後 23 小時為止的每個小時,t - 24 都落在截止點前 24 小時到截止點前一小時之間,所以這份複製只用到歷史資料。

保留的一週共有 7 個視窗,對應 2014 年 12 月 25 日至 12 月 31 日的每一天,每個視窗都在 00:00 建立。供應商關心的問題是 MT_014 明天的需求量。對 12 月 25 日而言,預測值複製 12 月 24 日每個小時的讀數,同一規則也依據前一天,為這一週的其他每一天給出預測。

以 12 月 25 日 00:00 的視窗為例。它對 12 月 25 日 00:00 的預測,就是 12 月 24 日 00:00 的讀數;它對 12 月 25 日 23:00 的預測,就是 12 月 24 日 23:00 的讀數。在其歷史的 1344 個小時中,這個方法只用到最後 24 個,因為 statsforecast 的 _seasonal_naive 會重複最後一個季節的值(statsforecast 2.1.1,statsforecast/utils.py)。範例仍然把全部歷史傳入,因為同一個呼叫也要服務會用到更多歷史的模型,而以同一種歷史長度進行同一個呼叫,只需學一種形式,而不是兩種。

為什麼用一天而不是一週?以 168 小時為季節,會複製前一週同一個星期幾的同一小時,對於具有每週節律的序列,這是另一種有效的基準。本章採用以日為單位的季節,是因為問題是隔天的需求,也因為本案例所需要的正是隔日預測。

seasonal-naive-next-day.py Python 3.13.16 · numpy 2.5.5 · pandas 2.3.3 · statsforecast 2.1.1 · utilsforecast 0.2.17 通過
"""Forecasts the lead client's next day with seasonal naive for each day of the held-out week, then scores it.The point rests on the MAE and RMSE lines, which score a copy of yesterday, and on the missing forecasts line."""import pandas as pdfrom statsforecast import StatsForecastfrom statsforecast.models import SeasonalNaivefrom lib.backtest import forecast_windows, held_out_cutoffs, scoring_counts, score_windows, window_maefrom lib.electricity import loadfrom lib.settings import HORIZON, LEAD, showdef day_mean(day):    return df[df["ds"].dt.normalize() == pd.Timestamp(day)]["y"].mean()# statsforecast reads a frame with three columns: the series id, the time and the value.df = load([LEAD])[["unique_id", "ds", "y"]]# season_length 24 is the daily cycle of hourly data; freq "h" is pandas' code for hourly steps; one job runs in one process.sf = StatsForecast(models=[SeasonalNaive(season_length=24)], freq="h", n_jobs=1)forecasts = forecast_windows(sf, df, held_out_cutoffs())scores = score_windows(df, forecasts, "SeasonalNaive")counts = scoring_counts(df, forecasts, "SeasonalNaive")show("horizon hours", HORIZON)show("windows", counts["windows"])show("scored hours", counts["scored_hours"])show("missing forecasts", counts["missing_forecasts"])# The readings at the forecast hours, which are the hours the scores cover.show("mean demand", df[df["ds"].isin(forecasts["ds"])]["y"].mean())show("mean demand 2014-12-24", day_mean("2014-12-24"))show("mean demand 2014-12-25", day_mean("2014-12-25"))show("MAE", scores["mae"])show("RMSE", scores["rmse"])for day, mae_day in window_mae(df, forecasts, "SeasonalNaive").items():    show(f"MAE {day:%Y-%m-%d}", mae_day)# The check is run on a history with one hour removed, to show it refuses a short history.cutoff = held_out_cutoffs()[0]gap = df[df["ds"] != cutoff - pd.Timedelta(hours=1)]  # drops the hour just before the first cutofftry:    forecast_windows(sf, gap, [cutoff])  # history_before raises ValueError unless every client has exactly HISTORY_HOURS rows before the cutoff.    refused = "no"except ValueError:    refused = "yes"show("history with one hour removed refused", refused)
輸出python seasonal-naive-next-day.py
horizon hours: 24
windows: 7
scored hours: 168
missing forecasts: 0
mean demand: 46.62
mean demand 2014-12-24: 47.58
mean demand 2014-12-25: 38.40
MAE: 8.36
RMSE: 10.87
MAE 2014-12-25: 9.41
MAE 2014-12-26: 12.16
MAE 2014-12-27: 5.10
MAE 2014-12-28: 11.16
MAE 2014-12-29: 8.68
MAE 2014-12-30: 5.26
MAE 2014-12-31: 6.75
history with one hour removed refused: yes

每個預測都會與其後的讀數比較評分,而且 168 個評分小時中,每一個都有預測值。這些小時的平均為 46.62 kWh,這是解讀本章每個誤差時所依據的水準。

季節性單純法是一種基準,當日週期主導序列時,它可能相當強。它的弱點在於只複製單一天。異常的一天會成為下一天的預測,而這個方法無法把它平均掉。

實用原則: 對於具有日週期的逐時序列,每次比較都要保留季節性單純法。它不需要擬合,因此在每個視窗上執行都不增加成本。無法在相同視窗上勝過它的模型,就不值得多花那些功夫。在閱讀預測分數之前,先檢查預測是否有缺失值,因為最後一個季節中的缺漏讀數,會變成缺漏的預測。第 3 章提供了在任何模型執行之前填補這些小時的規則。

此部分尚未翻譯,因此以英文呈現。

Forecast the next day with one model

最近一次變動於第 2026.11.11 版

The baseline above answers what a forecast gets with no model at all. The question here is whether a fitted model does better on the same 7 windows, and the model is AutoETS. statsforecast 2.1.1 describes AutoETS as selecting the best ETS (error, trend and seasonality) form with an information criterion (statsforecast/models.py, class AutoETS). The criterion AutoETS uses is AICc, the Akaike information criterion corrected for small samples. It is set in ets_f, in statsforecast/ets.py, and AutoETS offers no other.

The model string sets which forms the model may take, with one letter each for error, trend and season. Z lets AICc choose, and A fixes the form to additive. This chapter uses ZZA: AICc chooses the error and the trend, and the season is additive, so every candidate has a daily cycle. The default, ZZZ, also lets AICc choose the season. On this client and these 7 cutoffs it chose no season in every window, a flat form, ETS(A,N,N), so its forecast is one value repeated for the day. This chapter asks whether a model with the daily cycle beats a copy of yesterday, so it does not use that form. Other seasonal forms score differently on this week, and Chapter 4 looks at the forms and the choice.

A fit does three things, and each one matters for what the score means. At a cutoff, AutoETS reads the 1344 hours before it and compares the candidate forms, keeping the one with the lowest AICc. AICc rewards a close fit to the history and charges for each parameter the form uses, so a form with more parameters must fit much better to win. The model then projects that form 24 hours ahead. The held-out week therefore means 7 separate selections, not one. In this week 7 windows chose ETS(A,N,A): additive error, no trend and an additive daily season. The 7 fits still differ in their parameters. The book does not quote them, because each is a detail of one fit, and a reader should not take it as a finding.

The comparison is fair only when nothing else changes. It uses the same 7 cutoffs and the same 1344 hours of history before each one, and it refits the model at every cutoff using only the history before that cutoff. Only the model differs from the baseline.

autoets-next-day.py Python 3.13.16 · numpy 2.5.5 · pandas 2.3.3 · statsforecast 2.1.1 · utilsforecast 0.2.17 通過
"""Forecasts the lead client's next day with AutoETS for each day of the held-out week, then scores it.The point rests on the MAE and RMSE lines, read against the seasonal naive example, and on the form counts."""import numpy as npfrom statsforecast import StatsForecastfrom statsforecast.models import AutoETSfrom lib.backtest import chosen_forms, forecast_windows, held_out_cutoffs, scoring_counts, score_windows, window_maefrom lib.electricity import loadfrom lib.settings import HORIZON, LEAD, SEED, show# Seeded by convention. AutoETS's point forecast draws no random numbers, so this line changes nothing here.np.random.seed(SEED)# statsforecast reads a frame with three columns: the series id, the time and the value.df = load([LEAD])[["unique_id", "ds", "y"]]# model="ZZA": AICc chooses the error and trend forms; the seasonal form is fixed to additive, so every form has a day cycle.sf = StatsForecast(models=[AutoETS(season_length=24, model="ZZA")], freq="h", n_jobs=1)forecasts = forecast_windows(sf, df, held_out_cutoffs())scores = score_windows(df, forecasts, "AutoETS")counts = scoring_counts(df, forecasts, "AutoETS")# chosen_forms refits at each cutoff to read the form each fit picked; the forecasts above do not report it.forms = chosen_forms(sf, df, held_out_cutoffs())show("horizon hours", HORIZON)show("windows", counts["windows"])show("scored hours", counts["scored_hours"])show("missing forecasts", counts["missing_forecasts"])for form, n in forms.items():    show(f"windows that chose {form}", n)show("MAE", scores["mae"])show("RMSE", scores["rmse"])for day, mae_day in window_mae(df, forecasts, "AutoETS").items():    show(f"MAE {day:%Y-%m-%d}", mae_day)
輸出python autoets-next-day.py
horizon hours: 24
windows: 7
scored hours: 168
missing forecasts: 0
windows that chose ETS(A,N,A): 7
MAE: 8.86
RMSE: 10.91
MAE 2014-12-25: 13.51
MAE 2014-12-26: 11.21
MAE 2014-12-27: 4.17
MAE 2014-12-28: 10.03
MAE 2014-12-29: 9.53
MAE 2014-12-30: 6.33
MAE 2014-12-31: 7.25

The counts match the baseline's, so the two scores cover the same 168 hours, and all 7 windows chose the same form. The model makes 7 fits, one at each cutoff, and each sees only what was known at its cutoff. The next section sets the scores side by side.

Working rule: Add a model only with a baseline it has to beat on the same windows. Refit the model at each cutoff, using history from before that cutoff only. A model fitted once on the whole series and then scored on that series has seen the answers, and its score is not a forecast score.

此部分尚未翻譯,因此以英文呈現。

Score both on a held-out week

最近一次變動於第 2026.11.11 版

Both examples have now made 7 day-ahead forecasts, from the two sections above. A score turns the errors of a set of forecasts into one number. The error of an hour is the actual demand minus the forecast. This chapter uses two scores. The mean absolute error, MAE, is the average size of the miss: MAE = mean(abs(actual - forecast)). The root mean squared error, RMSE, is RMSE = sqrt(mean((actual - forecast)^2)). Both are in kWh, and they answer different questions. Hyndman and Athanasopoulos, in Forecasting: Principles and Practice, ch. 5, note that a forecast minimising MAE is a forecast of the median, and one minimising RMSE is a forecast of the mean. Because RMSE squares each error, a few large misses raise it more than they raise MAE.

Both scores come from utilsforecast (0.2.17). Its mae is the mean of the absolute errors, and its rmse is the square root of the mean of the squared errors (utilsforecast/losses.py, functions mae and rmse). The scores pool the 168 scored hours. Each hour counts once, and each of the 7 windows contributes 24 of them.

Read the table against the mean demand of 46.62 kWh an hour: a lower number means forecasts closer to the readings.

Model MAE (kWh) RMSE (kWh)
SeasonalNaive 8.36 10.87
AutoETS 8.86 10.91

AutoETS's errors are higher than the baseline's on both scores, as the table shows, with MAE at 8.86 kWh against 8.36. The MAE is the number to plan with, because it is the typical miss in each hour. RMSE is always at least MAE. For normal errors RMSE is about 1.25 times MAE, so a ratio well above that means a few large misses. This section reads the two scores together and goes no further, because one client over one week cannot show the spread of the misses.

Both models do worst around Christmas, but on different days. The daily lines show where: the baseline's worst day is Dec 26, the day after Christmas, when it copies Christmas Day, at 12.16 kWh an hour, the largest of the 7. AutoETS's worst day is Dec 25 itself, at 13.51 kWh, against 9.41 for the baseline. A gap of this size on one client over one week is not a verdict. Seven forecasts make a small sample, and a ranking built on one week can flip on the next. Chapter 3 backtests seasonal naive over a year of Sunday cutoffs.

The score also has to match the decision, and the purchase is lopsided: as the case says, buying too little costs more than buying too much. MAE and RMSE treat a miss in either direction alike, because they use the size of each miss and not its sign. That is enough for this chapter, which asks whether a forecast is close. It is not enough for the purchase. Chapter 8 builds ranges for that decision, and scores them against what happened.

Working rule: Score each model on forecasts it made without the scored hours in its history, over more than one day, and report the number of windows and hours behind each score. Compare models only on the same windows. Read MAE and RMSE together. If they disagree about which model is better, look at the largest misses in the windows before you choose, because a few large misses can decide the result.

此部分尚未翻譯,因此以英文呈現。

What goes wrong in production

最近一次變動於第 2026.11.11 版

The forecasts and scores above can go wrong in 5 ways, and only some of them print an error. The cutoff rule and the seasonal naive rule say what each window must hold.

The first failure is a label that is off by an hour, and no score in this chapter detects it. If a reader takes ds as the end of its hour rather than the start, the forecasts and the readings they are scored against carry the same shift, so the score does not change. The error is in the purchase instead: the forecast would cover different hours from the ones the supplier buys for. The data card fixes the label, so it is the first thing to check when a forecast is moved to new data.

Leakage flatters a window whose history includes the hours it predicts, and nothing in the score says so. Hewamalage, Ackermann and Bergmeir (2022) warn that rolling-origin evaluation is prone to this leak when it is not done with care. The checks here are the cutoff rule and the history length. Each history must end before its cutoff and hold 1344 rows. history_before raises an error when a history is short or long. A history with one hour removed is refused: the check at the end of the seasonal naive example prints yes for it.

Seasonal naive copies yesterday, so an unusual day becomes tomorrow's forecast, and the held-out week holds one. Dec 25, 2014 is Christmas Day, and the lead client's mean demand that day is 38.40 kWh an hour, against 47.58 kWh on Dec 24. The window for Dec 26 copies that day, so it has the largest MAE of the 7 windows, 12.16 kWh. That is the failure, and the scores show it. One holiday is too few to measure a holiday effect, so the book leaves it alone, as the case and its data explains. Chapter 10 shows its cost.

A missing reading gets through unchecked. The statsforecast seasonal naive does not check its input. It repeats the last season's values, so a missing value in that season becomes a missing forecast (statsforecast 2.1.1, statsforecast/utils.py, function _seasonal_naive). The seasonal naive example counts missing forecasts, 0 here, because a hole in the forecast is an hour the score does not describe. Chapter 3 fills the hours that need filling, from data before the cutoff, before any model runs.

Last, the window itself can flatter the method. A week with no unusual days can make almost any forecast look good, and a week with one can make every forecast look bad. The held-out week has a holiday in it, and it is still one week for one client, so its scores describe that week more than the method. The fix is breadth: compare models on several windows of different kinds before you trust a ranking.

Working rule: Before you trust a score, check three things in this order: each window's first forecast hour is its cutoff, each history ends before its cutoff and holds the full history length, and no forecast is missing. The helpers raise an error for the first two, and the examples print the third. A score counts as a finding only after all three pass.

本章做出的決定

最近一次變動於第 2026.11.5 版

本章做了九項選擇。其中大多數是 examples/lib/settings.py 中的設定,因此後續版次若更動其中任何一項,所有使用該設定的章都會隨之改變。其餘的選擇則記載於資料卡或本章之中。第 2 章從這兩個預測及其兩項分數出發,探討兩者是否好到足以據以行動。

  • 每個視窗的截止點位於它所預測那一天的 00:00,預測範圍為 24 小時,因此每個視窗涵蓋該日全天。
  • 每個截止點之前的歷史為 1344 小時,也就是 8 週。
  • 主要客戶為 MT_014。保留的測試週是 2014 年 12 月 25 日至 12 月 31 日:共 7 個視窗,168 個計分小時。
  • 分數為 MAE 與 RMSE,針對這些計分小時彙總計算,並印出至小數點後兩位。
  • 模型為季節長度 24 小時的季節性 naive,以及模型字串為 ZZA、季節長度為 24 小時的 AutoETS。每次執行皆使用 statsforecast,且只用一個工作程序。這兩個點預測都不會抽取隨機數,因此 AutoETS 範例依慣例設定的種子對它沒有影響。
  • 如資料卡所述,裁切時剔除 MT_223,保留 30 個客戶。
  • 時鐘變更與晚開始的資料列維持原樣,因為本章的歷史資料中並不包含這些列。第 3 章與第 4 章會處理它們。
  • 內文引用的每個數字,都綁定到其範例記錄的輸出中帶有標籤的一行,因此內文與輸出不會在無人察覺的情況下相互矛盾。
  • 本章只建立一個客戶的預測,不含預測區間。預測區間從第 8 章開始。

本章,於本版次中

版次 2026.11.11範例於 2026年11 月 20 通過測試本章 3 個範例 個範例中有 3 個通過

譯自英文書,版次 2026.11.11。

引用本節

格式

各種格式皆引用英文原書,本譯本即依循該原書。

每種格式都會標示本版。其連結會開啟目前版次,節標題會說明該節內文最後一次變動的時間。存取日期與擷取日期即為你開啟此頁的當日。

本頁內容

第 1 章,共 10 章: 預測明日需求

  1. The case and its data
  2. Load one client's hourly demand
  3. 以季節性單純法預測隔天
  4. Forecast the next day with one model
  5. Score both on a held-out week
  6. What goes wrong in production
  7. 本章做出的決定

返回頂端所有章節