回測時不偷看未來
閱讀約需 72 分鐘 分鐘,10 節 中共有 7 個範例。
本章教你在一年份的預測截止時間點上,為隔日預測評分,同時不讓未來的資料進入它的歷史;教你處理資料中兩個因時鐘調整而出現的小時;也教你執行位移測試,找出讀取了截止時間之後資料的特徵。你需要具備第 2 章所提供的基礎:季節性樸素基準、MAE,以及取自歷史資料的尺度。方法本身不變,改變的是評分的次數,以及每次切分資料時所需的謹慎程度。
此部分尚未翻譯,因此以英文呈現。
Why one test week misleads
So far the evidence is the held-out week of Chapter 1: seven day-ahead forecasts for one client, 168 scored hours in all. A sample that size can be lucky. A forecast can match a calm week and miss the next, and one week cannot tell the two apart. Before the supplier trusts a method with each day's purchase, it needs to know how a forecast does across many days, the unusual ones included.
A backtest answers that question with the data you already have. It makes a forecast at many past moments, each with only the readings available at that moment, and scores each one against the readings that followed. Each such moment is a cutoff. Each cutoff, with the hours it forecasts, is a window. The scores of all the windows together say how the method behaves across the year, not on one week.
This matters most for the clock changes. A year of cutoffs contains the March change, when the 01:00 hour does not occur on the clock, and the October change, when one 01:00 label holds two hours of energy. A single week, such as the last week of December, contains neither. A backtest that does not reach those dates cannot show what the method does on them, so the sample has to be chosen with them in mind.
Working rule: Prefer a year of cutoffs before you trust a difference between two methods. When cost forces fewer, say so beside each score, as Chapters 4 to 9 do. Make sure the sample reaches the odd days of the year. Report how many windows and how many scored hours stand behind each number. A figure from one week is one sample, and a reader should be able to see that.
此部分尚未翻譯,因此以英文呈現。
Roll the cutoff forward
A window has three parts: the cutoff, the horizon and the history. The cutoff is the moment the forecast is made. The horizon is how far ahead it reaches, which is 24 hours here, so the forecast covers the 24 hours that start at the cutoff. The history is the readings before the cutoff that the model may use, which the book sets at 1,344 hours, or eight weeks. Move the cutoff by a step and you have the next window. The step is one week for the Sunday sample, and one day for the daily samples in the two clock-change subsections, The March hour that reads zero and The October hour that holds two.
In words, each window's targets are the 24 hours from its cutoff, and its history is the readings from 1,344 hours before the cutoff up to, but not including, the cutoff. The next window moves both by one step. A reading can therefore be a target in one window and history in a later one. That is correct, because by the later cutoff the reading lies in the past, and it is the same reading in both places.
The Sunday sample runs seasonal naive over every Sunday of 2014, from Jan 5 to Dec 28, 2014. The EU puts every clock change on the last Sunday of March and of October (Directive 2000/84/EC, Articles 2 and 3), and both changes of 2014, on Mar 30 and Oct 26, are in the sample. The sample uses SUBSET8, the book's eight-client subset. Here the year is scored on those eight clients, window by window:
1"""Seasonal naive over the 52 Sunday cutoffs of 2014, for eight clients, with no clock-change rule: how much history each2window gets, then the year's scores. The prose's headline rests on the mean per-client MASE line."""3import pandas as pd4from holidays import country_holidays5from statsforecast import StatsForecast6from statsforecast.models import SeasonalNaive78from lib.backtest import forecast_windows, history_before9from lib.electricity import load10from lib.quirks import year_scores11from lib.scoring import book_scale, clients_left_out12from lib.settings import HISTORY_HOURS, HORIZON, SUBSET8, show1314COLS = ["unique_id", "ds", "y"]15cutoffs = pd.date_range("2014-01-05", "2014-12-28", freq="W-SUN") # 52 Sundays, both clock changes among them16df = load(SUBSET8)[COLS + ["quirk"]]17sf = StatsForecast(models=[SeasonalNaive(season_length=24)], freq="h", n_jobs=1) # 24 hourly readings a day: each hour copies the same hour of the day before18forecasts = forecast_windows(sf, df[COLS], cutoffs, h=HORIZON)19scored = forecasts.merge(df, on=["unique_id", "ds"]) # attaches each forecast hour's reading and its quirk flag20scale = book_scale(df, cutoffs[0]) # the MASE scale: every reading before the first cutoff, from 2013 on21sizes = pd.concat([history_before(df, c).groupby("unique_id").size() for c in cutoffs]) # history rows per client in each window22assert sizes.min() == sizes.max() == HISTORY_HOURS # every window's history is the same length, the prose's claim23holidays = country_holidays("PT", years=[2014])2425show("windows", len(cutoffs))26show("history hours per series, min over windows", sizes.min())27show("history hours per series, max over windows", sizes.max())28show("Sunday windows on a Portuguese holiday", sum(c.date() in holidays for c in cutoffs))29show("client left out of MASE", ", ".join(clients_left_out(df, cutoffs[0])))30for label, value in year_scores(scored, scale).items(): # pooled MAE and RMSE, per-client MASE, the largest client's share31 show(label, value)
python backtest-sundays-2014.pywindows: 52
history hours per series, min over windows: 1344
history hours per series, max over windows: 1344
Sunday windows on a Portuguese holiday: 1
client left out of MASE: MT_115
scored hours: 9936
scored hours before a first reading: 48
MAE: 382.02
RMSE: 1369.57
largest client by absolute error: MT_370
largest client's share of absolute error, percent: 88.69
clients in MASE: 7
mean MASE: 0.97
lowest client MASE: 0.77
highest client MASE: 1.26
Every window's history holds the same 1344 hours for each client, the eight weeks the book specifies, and the example asserts that the length is the same in every window. The 52 windows score 9936 hours: eight clients, 24 hours each, times the windows, less the hours of one late starter before its first reading, which the next paragraphs explain.
The headline is the mean per-client MASE, not the pooled error. The MASE scale is one number per client, and scoring.book_scale computes it for the whole book: every reading before the first cutoff, with the clock-change hours masked and each client's leading zeros removed. The first cutoff is Jan 5, 2014, so this sample's scale is read from Jan 1, 2013 to Jan 4, 2014. The mean of the per-client MASE values is 0.97, with the lowest at 0.77 and the highest at 1.26, over 7 clients.
The pooled MAE, 382.02 kWh over the scored hours, compares methods on the same clients and windows, but it cannot compare clients with each other. Its largest client, MT_370, carries 88.69 percent of the absolute error, because that client uses thousands of kilowatt hours an hour, so its errors are in the thousands too. The RMSE is 1369.57 kWh.
Client MT_115 has no reading before Jan 14, 2014. Until then the meter reports zeros, and the data card says those zeros are not demand. The code leaves the 48 hours before its first reading out of every score, which are the first two windows. Its history still holds those zeros, because the start rule for histories belongs to Chapter 4. Its MASE is left out for a different reason: its scale is read from the readings before Jan 5, 2014, and it has none. The output lists that client as left out of MASE, and the start rule is left to that chapter.
The statsforecast library has a function for this loop, cross_validation, and it is possible to call it without the window you wanted. At version 2.1.1, the training slice of each window starts at the first reading of the series unless you pass input_size. The history then grows from one window to the next, and the eight-week rule is not in force. Hyndman and Athanasopoulos state the principle that the training set consists only of observations before the test set (Forecasting: Principles and Practice, 3rd ed., chapter 5). The code behind cross_validation decides the length of that set (statsforecast 2.1.1, statsforecast/core.py). Its cutoff is the last hour a window trains on, where this chapter's cutoff is the first hour it forecasts, so the two names differ by one hour. This chapter builds each window's history itself, from the cutoff backwards. That gives the same 1,344 hours at every window and makes the rule visible in the code.
Working rule: Set the history length explicitly, in hours, and check that it is the same for every window. When a library loops over windows for you, read how it sets the training slice before you trust its output, because its default may be an expanding window rather than the length you chose.
此部分尚未翻譯,因此以英文呈現。
Keep the future out of the history
A backtest leaks when a window's model sees a reading from the hours it is asked to forecast. The reading can reach the model in several ways: through the history, through a feature, or through a scale computed from data that includes the target. Hewamalage, Ackermann and Bergmeir describe rolling-origin evaluation as prone to exactly this, because the test data of one window becomes training data of the next. In forecasting, they note, the leak is easier to make and harder to avoid than in other machine learning tasks (2022, section 3.4).
One rule closes the history path. Each window's history is the readings whose timestamps fall in the eight weeks before its cutoff, and nothing at or after the cutoff. In the book's code, history_before keeps the rows with ds from the cutoff minus 1,344 hours up to, but not including, the cutoff. The reading at the cutoff itself belongs to the target day, so the same comparison excludes it. Membership is decided by timestamps, not by row positions, so a missing row cannot shift a window by an hour. history_before also raises an error unless every client has exactly 1,344 rows in the window.
The window's own first hour is the cutoff, so a cut that is one hour too generous passes the first target reading into the history, and nothing in a forecast shows it. A row count can catch it, and the example below counts the rows.
1"""One window's history, cut by its cutoff: its first and last timestamps, and what a cut that keeps the cutoff hour adds.2The prose's timestamps rest on the first two lines, and its off-by-one point on the row counts3with the cutoff hour in and out."""4import pandas as pd56from lib.backtest import history_before7from lib.electricity import load8from lib.settings import HISTORY_HOURS, LEAD, show910df = load([LEAD]) # the lead client's readings only: one series is enough to show the cut11cutoff = pd.Timestamp("2014-12-29") # the window's cutoff at midnight, which is also its first forecast hour12hist = history_before(df, cutoff) # the 1,344 hours before the cutoff; the cutoff hour itself is not in it13show("history rows", len(hist))14show("first history timestamp", hist["ds"].min().strftime("%Y-%m-%d %H:%M"))15show("last history timestamp", hist["ds"].max().strftime("%Y-%m-%d %H:%M"))1617wrong = df[(df["ds"] >= cutoff - pd.Timedelta(hours=HISTORY_HOURS)) & (df["ds"] <= cutoff)] # the off-by-one cut: <= keeps the cutoff hour18show("history rows with ds at or before the cutoff", len(wrong))19show("target-day readings in that cut", int((wrong["ds"] == cutoff).sum()))
python history-cut-check.pyhistory rows: 1344
first history timestamp: 2014-11-03 00:00
last history timestamp: 2014-12-28 23:00
history rows with ds at or before the cutoff: 1345
target-day readings in that cut: 1
Keeping the cutoff hour adds one row, and the count shows it. The history for the cutoff of Dec 29, 2014 runs from 2014-11-03 00:00 to 2014-12-28 23:00 and holds 1344 rows. A cut with ds <= cutoff holds 1345 rows, because the target day's first reading, the cutoff hour, has entered the history. A count one row too high is the sign of that error.
The same care applies to the scale. evaluate in utilsforecast takes a training frame for its scale, and it cuts that frame by time only when the forecast frame carries a cutoff column. Then it keeps the training rows with ds at or before the cutoff, which includes the cutoff hour itself (utilsforecast 0.2.17, evaluation.py). This chapter does not use that option. Its scale comes from scoring.book_scale, which passes only the rows before the first cutoff, and the frame it scores has no cutoff column.
Working rule: Slice each window's history by its cutoff, never by the start of its test window, and pass a library only the rows it may use. Check the first and last timestamps of every history, and make sure the last one is an hour before the cutoff.
認識時鐘變更
資料中有兩個小時,打破了「每個時鐘小時對應一筆讀數」的簡單設想。在三月的變更日,當地時鐘會從 00:59 直接跳到 02:00,因此 01:00 這個小時在時鐘上並不存在。葡萄牙本土冬季採用格林威治標準時間,而歐盟在格林威治標準時間 01:00 調整時鐘,也就是當地時間 02:00(Directive 2000/84/EC,第 2 條)。在十月的變更日,時鐘會從 02:00 撥回 01:00,因此 01:00 這個小時會出現兩次。檔案中每天只有一列 01:00 的資料,在本書的資料裡標記為 clock_change_gap 或 clock_change_repeat。
本書讀取這個檔案時採用一項明確的假設,後續每一章都依賴這項假設。讀數的時間戳記 ds 是該小時在當地時鐘時間下的起點,而索引則是一個不含時區的單一原生(naive)每小時索引。三月的證據支持這種解讀。資料集本身的說明載於 Dataset 321 of the UCI Machine Learning Repository,其中指出三月變更日的 01:00 數值對所有客戶而言皆為零。檔案大致與此相符,第一個小節會說明這一點,第二個小節則會呈現十月標籤中的那兩個小時。
此部分尚未翻譯,因此以英文呈現。
The March hour that reads zero
On Mar 30, 2014, the 01:00 label reads zero for 5 of the eight clients in the subset. The others read a small amount, not an hour of demand. The census covers all thirty clients.
1"""The clock-change hours of all thirty clients, each against its neighbours. The point that the March hours read near zero2rests on the gap rows below 5 percent of their neighbours, with the zero count and the median ratio beside them."""3from lib.electricity import load4from lib.quirks import clock_ratios5from lib.settings import show67r = clock_ratios(load()) # each clock-change hour divided by the mean of the hour before and the hour after8gap = r[r["quirk"] == "clock_change_gap"] # the file's flag: 01:00 on the March change day, an hour the clock skips9repeat = r[r["quirk"] == "clock_change_repeat"] # the file's flag: 01:00 holds two hours on the October change day10show("gap rows", len(gap))11show("gap rows that read zero", int((gap["y"] == 0).sum()))12show("gap rows that read above zero", int((gap["y"] > 0).sum()))13show("gap rows below 5 percent of their neighbours", int((gap["ratio"] < 0.05).sum())) # a NaN ratio, where both neighbours are zero, counts in neither line14show("gap rows at or above 5 percent of their neighbours", int((gap["ratio"] >= 0.05).sum()))15show("median gap ratio to neighbours", gap["ratio"].median(), digits=3)16show("repeat rows", len(repeat))17show("median repeat ratio to neighbours", repeat["ratio"].median(), digits=3)
python clock-change-census.pygap rows: 57
gap rows that read zero: 40
gap rows that read above zero: 17
gap rows below 5 percent of their neighbours: 55
gap rows at or above 5 percent of their neighbours: 2
median gap ratio to neighbours: 0.000
repeat rows: 58
median repeat ratio to neighbours: 1.948
Most flagged hours read near zero: 55 of the 57 flagged client-hours on the two March change days sit below 5 percent of their neighbouring hours, which is what this chapter means by near zero. The median ratio to the neighbours is 0.000.
The file mostly agrees with the dataset's note: 40 of the 57 read exactly zero, and 17 read above zero.
The data say zero or near zero, enough for the rule. The meter recorded nothing for an hour that did not occur on the clock, so the reading is not demand.
Seasonal naive copies the last day's values forward, so the forecast for 01:00 on Mar 30 is the demand of Mar 29 at 01:00. That is an ordinary hour, and where the reading is zero, the error is the whole forecast.
Make a guess before the next run. The cutoff of Mar 31 looks back over 24 hours, and those hours include the zero. How large is the error at 01:00 on Mar 31 compared with an ordinary hour? The run covers the 15 daily cutoffs from Mar 23 to Apr 6, 2014, first with no rule and then with the rule from the next section:
1"""Seasonal naive around the March clock change, for eight clients: the raw failure, then the rule. The prose's claims rest2on the gap-hour and next-day 1am lines, with and without the rule, the median client ratios, and the count of missing3forecasts without the fill."""4import pandas as pd56from lib.backtest import history_before7from lib.electricity import load8from lib.quirks import filled_history, mae_of, mask_clock_changes, median_client_ratio, seasonal_naive_at9from lib.settings import SUBSET8, show1011cutoffs = pd.date_range("2014-03-23", "2014-04-06", freq="D") # 15 daily cutoffs around Mar 30, 201412next_day = pd.Timestamp("2014-03-31 01:00") # 01:00 the day after the change: the forecast that copies the zero13df = load(SUBSET8)[["unique_id", "ds", "y", "quirk"]]14masked = mask_clock_changes(df) # a copy with the gap and repeat hours set to NaN1516raw = seasonal_naive_at(df, cutoffs, lambda c: history_before(df, c)) # no rule: the history keeps the zeros as the file has them17gap = raw["quirk"] == "clock_change_gap" # the file's flag marks the gap hours18at_next_day = raw["ds"] == next_day19show("gap hours in actuals", int(gap.sum()))20show("gap hours that read zero", int((raw[gap]["y"] == 0).sum()))21show("gap-hour MAE with no rule", mae_of(raw[gap]))22show("other-hour MAE with no rule", mae_of(raw[~gap]))23# per client: the mean error at gap hours over the mean at other hours, then the median across clients24show("median client ratio, gap hour to other hours, no rule", median_client_ratio(raw, gap, ~gap))25show("next-day MAE at 1am with no rule", mae_of(raw[at_next_day]))26# a forecast of exactly zero is the March zero copied forward from the day before27show("next-day 1am forecasts that are zero, no rule", int((raw[at_next_day]["SeasonalNaive"] == 0).sum()))28show("median client ratio, next-day 1am to other hours, no rule", median_client_ratio(raw, at_next_day, ~gap))2930no_fill = seasonal_naive_at(masked, cutoffs, lambda c: history_before(masked, c)) # masked history, no fill: a NaN copies forward and stays NaN31show("NaN forecasts without the fill", int(no_fill["SeasonalNaive"].isna().sum()))3233fixed = seasonal_naive_at(masked, cutoffs, lambda c: filled_history(masked, c)) # the rule: masked hours filled from the history before each cutoff34show("next-day MAE at 1am with the rule", mae_of(fixed[fixed["ds"] == next_day]))35show("other-hour MAE with the rule", mae_of(fixed[fixed["quirk"] != "clock_change_gap"]))
python clock-gap-daily-cutoffs.pygap hours in actuals: 8
gap hours that read zero: 5
gap-hour MAE with no rule: 2322.69
other-hour MAE with no rule: 234.21
median client ratio, gap hour to other hours, no rule: 7.93
next-day MAE at 1am with no rule: 2393.01
next-day 1am forecasts that are zero, no rule: 5
median client ratio, next-day 1am to other hours, no rule: 9.92
NaN forecasts without the fill: 8
next-day MAE at 1am with the rule: 274.41
other-hour MAE with the rule: 228.31
For the median client, the error at 01:00 on Mar 31 is 9.92 times its error at other hours. The forecast for that hour copies the zero for 5 clients.
The gap hour itself fails as well. Its pooled error is 2322.69 kWh, against 234.21 kWh at other hours, and the median client's ratio is 7.93. Both pooled figures are set mostly by the largest client, while the per-client median counts each client once.
Pooled, the next day's error at 01:00 is 2393.01 kWh, about as much as the gap hour's. The method is wrong on the change hour, and wrong by about as much the day after, because it copied the zero.
Working rule: Treat a 01:00 reading of zero on a March clock-change day as a missing hour, not as zero demand. Keep it out of a model's history and out of the scores, and do not let a seasonal method copy it into the next day.
十月那個包含兩小時的時段
2014 年 10 月 26 日,01:00 這個標籤涵蓋了約兩小時的電量。普查結果顯示,該小時與前後相鄰小時的比值中位數為 1.948,統計範圍是檔案中 58 筆被標記的客戶小時資料。UCI 的說明也一致:01:00 的數值是兩小時用電量的加總。
這個失誤與三月的情況正好相反。在時間變更當天,季節性 naive 預測以前一天的 01:00 標籤作為依據,而那是一個普通的小時,實際值卻約為其兩倍。10 月 27 日的截止點會複製這個加倍的值,因此 10 月 27 日 01:00 的預測值約為普通小時的兩倍,而實際值是普通的。
同樣的比較也套用在 2014 年 10 月 19 日至 11 月 2 日的 15 個每日截止點上:
1"""Seasonal naive around the October clock change, for eight clients: the raw failure, then the rule. The prose's claims rest2on the repeat-hour and next-day 1am lines, the median client ratios, and the count of missing forecasts without the fill."""3import pandas as pd45from lib.backtest import history_before6from lib.electricity import load7from lib.quirks import filled_history, mae_of, mask_clock_changes, median_client_ratio, seasonal_naive_at8from lib.settings import SUBSET8, show910cutoffs = pd.date_range("2014-10-19", "2014-11-02", freq="D") # 15 daily cutoffs around Oct 26, 201411next_day = pd.Timestamp("2014-10-27 01:00") # 01:00 the day after the change: the forecast that copies the doubled value12df = load(SUBSET8)[["unique_id", "ds", "y", "quirk"]]13masked = mask_clock_changes(df) # a copy with the gap and repeat hours set to NaN1415raw = seasonal_naive_at(df, cutoffs, lambda c: history_before(df, c)) # no rule: the history keeps the doubled 01:00 value16repeat = raw["quirk"] == "clock_change_repeat" # the file's flag: two hours of energy in one 01:00 label17at_next_day = raw["ds"] == next_day18show("repeat hours in actuals", int(repeat.sum()))19show("repeat-hour MAE with no rule", mae_of(raw[repeat]))20show("other-hour MAE with no rule", mae_of(raw[~repeat]))21# per client: the mean error at the repeat hour over the mean at other hours, then the median across clients22show("median client ratio, repeat hour to other hours, no rule", median_client_ratio(raw, repeat, ~repeat))23show("next-day MAE at 1am with no rule", mae_of(raw[at_next_day]))24show("median client ratio, next-day 1am to other hours, no rule", median_client_ratio(raw, at_next_day, ~repeat))2526no_fill = seasonal_naive_at(masked, cutoffs, lambda c: history_before(masked, c)) # masked history, no fill: a NaN copies forward and stays NaN27show("NaN forecasts without the fill", int(no_fill["SeasonalNaive"].isna().sum()))2829fixed = seasonal_naive_at(masked, cutoffs, lambda c: filled_history(masked, c)) # the rule: masked hours filled from the history before each cutoff30show("next-day MAE at 1am with the rule", mae_of(fixed[fixed["ds"] == next_day]))31show("other-hour MAE with the rule", mae_of(fixed[fixed["quirk"] != "clock_change_repeat"]))
python clock-repeat-daily-cutoffs.pyrepeat hours in actuals: 8
repeat-hour MAE with no rule: 637.18
other-hour MAE with no rule: 397.96
median client ratio, repeat hour to other hours, no rule: 6.98
next-day MAE at 1am with no rule: 1524.26
median client ratio, next-day 1am to other hours, no rule: 7.53
NaN forecasts without the fill: 8
next-day MAE at 1am with the rule: 184.22
other-hour MAE with the rule: 394.23
彙總後的數字低估了時間變更當小時的失誤。在該小時,預測值是普通小時,實際值卻加倍,因此彙總誤差為 637.18 kWh,其他小時則為 397.96 kWh。這個差距看起來比實際小,原因是最大客戶在每個小時的誤差都很大。以中位數客戶而言,時間變更當小時的誤差是其他小時誤差的 6.98 倍。
加倍的值在隔天造成的傷害最大。10 月 27 日 01:00 的預測複製了該值,因此該處的彙總誤差為 1524.26 kWh,是三者中最大的,而中位數客戶的比值為 7.53。若讀者把十月的原始標籤當成普通小時處理,就會先低估一個小時的用電量,接著又高估下一個小時。
實用原則: 請把十月的 01:00 標籤視為一個時段內含兩小時的電量,絕不可當成普通小時。也不要為了讓它看起來像一小時而將其減半,原因見下一節。
將時鐘變更的時段標記為缺失值
本書採用的規則是一項選擇,本節把它集中說明一次,讓之後每一章都能呼叫同一段程式碼。兩個 01:00 的時段,也就是 3 月的空缺與 10 月的重複,在歷史資料與評分中都設為缺失,因此被遮罩的時段不會被評分。能接受缺失值的模型會略過該時段。無法接受缺失值的模型,例如季節性樸素法(seasonal naive),則改為讀取填補後的值,因為缺失值會被複製到隔天的預測中。無論哪一種做法,該時段都不會被評分,而預測仍會為其標籤產生一個值,因為輸出的網格必須保持完整。填補值是前一小時與後一小時的平均,且只取自截止時間點之前的歷史資料。這是針對夾在兩個一般時段之間的時段所用的經驗法則,本書也如此標示。
另一種做法是把 10 月的標籤對半分,使每個實際時段各得一半的讀數,但這假設兩個時段的用電量相同。資料卡並未顯示這一點,所以本書不採用。
若不做填補,在每次變更的隔天,01:00 的預測在 3 月有 8 個(共八個客戶)缺失,在 10 月則有 8 個缺失。
做了填補之後,該時段的隔日誤差在 3 月從 2393.01 降到 274.41 kWh,在 10 月從 1524.26 降到 184.22 kWh,其他時段的誤差變動不大。
全年每個星期日截止點的測試性質不同,因為它是把遮罩套用在評分上,填補並未發揮作用。把全年分別以未遮罩與遮罩的方式各評分一次,就能看出這兩個時段讓整體指標移動了多少。
1"""The Sunday backtest of 2014 for eight clients, scored twice: as the readings stand, and with the clock-change rule, which2leaves the masked hours out of the scores and fills the history. The prose's comparison rests on the masked-hour count,3the two pooled MAE lines, the two mean MASE lines and the two scored-hour lines."""4import pandas as pd56from lib.backtest import history_before7from lib.electricity import load8from lib.quirks import CLOCK_CHANGE_QUIRKS, filled_history, mask_clock_changes, seasonal_naive_at, year_scores9from lib.scoring import book_scale10from lib.settings import SUBSET8, show1112cutoffs = pd.date_range("2014-01-05", "2014-12-28", freq="W-SUN") # the same 52 Sunday cutoffs as the plain backtest13df = load(SUBSET8)[["unique_id", "ds", "y", "quirk"]]14masked = mask_clock_changes(df) # a copy with the gap and repeat hours set to NaN; the rule's scores skip them15scale = book_scale(df, cutoffs[0]) # book_scale masks the clock-change hours itself, so both runs share this one scale1617plain = seasonal_naive_at(df, cutoffs, lambda c: history_before(df, c)) # as the readings stand: the zeros and the doubled hour stay in18ruled = seasonal_naive_at(masked, cutoffs, lambda c: filled_history(masked, c)) # the rule: history filled from before each cutoff19show("masked hours in scored windows", int(plain["quirk"].isin(CLOCK_CHANGE_QUIRKS).sum())) # counted in the plain run, where the flags are still present20for tag, scored in [("without the mask", plain), ("with the mask", ruled)]:21 result = year_scores(scored, scale)22 show(f"scored hours {tag}", result["scored hours"])23 show(f"MAE {tag}", result["MAE"])24 show(f"mean MASE {tag}", result["mean MASE"])
python clock-masked-backtest.pymasked hours in scored windows: 16
scored hours without the mask: 9936
MAE without the mask: 382.02
mean MASE without the mask: 0.97
scored hours with the mask: 9920
MAE with the mask: 380.25
mean MASE with the mask: 0.96
遮罩從評分視窗中移除了 16 個被遮罩的時段,也就是子集中 3 月與 10 月的那些時段,而彙總的 MAE 只有小幅變動,從 382.02 kWh 變為 380.25 kWh。
平均 MASE 從 0.97 變為 0.96,評分的時段數為 9920,而非 9936。這個差異來自被移除的時段。
星期日的樣本完全無法顯示填補的效果,因為季節性樸素法只讀取每個截止點的前一天,而每個星期日截止點的前一天都是星期六,沒有任何一個星期六含有時鐘變更。
實用原則: 在每一份歷史資料與每一次評分中,都把兩個時鐘變更的時段標記為缺失,在報告中記下被遮罩的時段數,並且只有在模型無法接受缺失值時,才以截止點之前的歷史資料填補這些時段。如果被遮罩的時段數在不同次執行之間有變動,就表示樣本或檔案的旗標已經改變,重新執行評分之前應先查明原因。
此部分尚未翻譯,因此以英文呈現。
Check a backtest for leakage
Every window in a backtest should be built from data available at its cutoff, so the check for a leak is simple to state. A feature for a window must have the same value whether it is computed from the history cut at the cutoff or from the whole series. If the two values differ, the feature read a reading after the cutoff, and the backtest flatters the method. The shift test compares a feature computed from the history cut at the cutoff with the same feature computed from the whole series. It is cheap to run, and it catches a mistake that the backtest cannot catch on its own, because a leaking feature scores well by design.
The test has two halves, and each catches what the other misses. Take the lead client, MT_014, and three features over its hourly readings. The first is a trailing mean: the average of the 24 hours up to and including each hour, which reads nothing after its hour. The second is the same mean shifted one hour forward, so each value is the average of a window that ends one hour later, and it reads the first hour after the cutoff. The third is a lag of one hour, the most common day-ahead leak. The history half compares each feature on the rows of the eight weeks before each of the three evaluation cutoffs, Dec 29 to Dec 31, 2014. The target half compares the 24 hours that each cutoff forecasts, computed from the readings before the cutoff only. Both versions start from the same first reading, so the warm-up of a rolling mean matches on both sides. Computed from different starts, the warm-up and floating-point rounding would show as false differences, which is why the check compares with a tolerance:
1"""Shift test: a feature must read nothing from its cutoff on, on the history rows and on the target hours. The prose's2point rests on the counts of differing rows: an honest feature shows zero, and a leaking one shows its leak."""3from lib.electricity import load4from lib.leakage import history_test, lag, peeking_mean, target_test, trailing_mean5from lib.settings import EVAL_CUTOFFS, LEAD, show67y = load([LEAD]).set_index("ds")["y"] # indexed by timestamp, so each feature can be cut at a cutoff by time89compared, honest = history_test(y, trailing_mean) # rows compared, and the rows where cutting at the cutoff changes the feature10_, peeking = history_test(y, peeking_mean) # the leaking feature: its last value before each cutoff reads the cutoff hour11_, lag1_history = history_test(y, lag(1)) # lag 1 reads only the past on history rows, so this half passes it12show("cutoffs", len(EVAL_CUTOFFS))13show("rows compared", compared)14show("rows differing for the trailing mean", honest)15show("rows differing for the peeking mean", peeking)16show("rows differing for lag 1", lag1_history)1718targets, lag1_target = target_test(y, lag(1)) # target hours compared, and the hours that differ, over the 24 hours of each cutoff19_, lag24_target = target_test(y, lag(24))20show("target hours compared", targets)21show("target hours differing for lag 1", lag1_target)22show("target hours differing for lag 24", lag24_target)
python leakage-shift-check.pycutoffs: 3
rows compared: 4032
rows differing for the trailing mean: 0
rows differing for the peeking mean: 3
rows differing for lag 1: 0
target hours compared: 72
target hours differing for lag 1: 69
target hours differing for lag 24: 0
On the history rows, the shifted mean differs on 3 of the 4032 compared, one at each cutoff: the last hour before each cutoff, whose value depends on the reading at the cutoff itself. The trailing mean differs on 0 of them.
The lag of one hour is the case the history half cannot catch. It differs on 0 history rows, because every row it reads lies in the past, so the history half alone passes it.
On the 72 target hours it differs on 69, since for every target hour after the first, the reading it uses is in the day being forecast. The lag of 24 hours differs on 0 of them, because it reads the same hour of the day before, which was known at each cutoff.
The shift test checks features and nothing else. It does not check the scale, the fill or the model's own code, which is why the earlier sections set those rules separately. Run it on every feature a model reads, at several cutoffs spread through the year, and include a cutoff on a clock-change day if the feature reads the hour before it.
When a feature fails the test, do not fix the score. Move the feature back until it reads only what was known at its cutoff, then run the test again until the count is zero.
Working rule: Keep every lag at least the horizon, 24 hours, so that the reading a lag uses for any target hour was known at the cutoff. Before you trust a backtest with features, run both halves of the shift test on every feature, at several cutoffs spread through the year, and require zero differing rows for every feature the model reads. A feature that differs is reading the future, so fix or remove it before you score anything.
此部分尚未翻譯,因此以英文呈現。
What goes wrong in production
A backtest is a sample of the past, and the sample is chosen. Every clock change falls on the last Sunday of March or October (Directive 2000/84/EC, Articles 2 and 3), so a Sunday sample reaches every change. A sample of Mondays would reach the day after each change without reaching the change hour itself, so the choice of days changes what the backtest can see. Record which dates the sample covers, and rerun the clock check when the sample's dates change.
Calendar effects are a separate sample problem. Easter Sunday, Apr 20, 2014, is a Portuguese holiday, which the holidays package lists for Portugal, and the run counts it: 1 of 52 windows. The held-out week contains Dec 25, 2014, a national holiday in Portugal, and a week of ordinary days and one holiday gives a different score from a week of ordinary days alone. A backtest that uses holiday features must count the holidays in its windows, and say how many fall in the sample.
A pooled error hides the windows that went wrong. A year of windows can average to a respectable number while one month, or one client, carries the error. Break the scores down by month and by client before you report one figure, and look at the worst windows, not only the average.
The masked count follows the calendar flag, not the readings. It changes when the sample's dates or the file's flags change, and it cannot see drift in the readings. Count the masked hours on every run, and alarm on a change in the count, because it is the cheapest signal that the sample or the file has changed. Drift in the readings needs the census: the gap hours that read zero, and the repeat hours against their neighbours. Chapter 10 returns to this in the running log.
Finally, a backtest that passes the shift test can still leak through the scale or the fill, if either is taken from data after the cutoff. The checks in this chapter cover those paths in the examples and the rules, not in every library a reader might use. A reader who adds a library should read how it cuts its training data, as the default of cross_validation shows.
Working rule: Run the clock and shift checks again on every data refresh, and before any change to the sample's dates, the history length or the scale. Keep the masked-hour count, the census counts and the shift-test counts in the run log next to the scores, so that a later change in either can be traced to its cause.
本章的決定
- 回測使用 2014 年每個星期日的截止時間點。每一次時鐘調整都落在星期日,因此樣本涵蓋每一次調整,2014 年的兩次調整都在其中。
- 每個視窗的歷史資料是截止時間點之前的 1,344 小時,並以截止時間點切開,長度寫定在程式碼中,不採用函式庫的預設值。
- 時間戳記
ds是該小時的起點,採用當地時鐘時間,不帶時區,本書以此假設讀取檔案。 - 兩個時鐘調整的小時,在每一份歷史資料與每一個評分中都予以遮蔽。無法處理缺失值的模型,會讀取截止時間點之前歷史資料中相鄰小時的平均值。
- 將 10 月那個小時減半的做法遭到否決,因為這個做法假設兩個實際的小時用電量相同,而資料並未顯示這一點。
- 主要指標是各客戶 MASE 的平均值,採用第 2 章到
scoring.book_scale所用的同一個尺度。彙總 MAE 是第二條指標,並印出最大客戶所占的比例。 - 內文引用的每一個數字,都如第 1 章所述,繫結到其範例輸出中有標籤的一行,因此函式庫更新會改變本章的數字,而不必有人重新輸入。
- 在第一個截止時間點之前沒有任何讀數的客戶,不納入 MASE。較晚開始的客戶,在其第一筆讀數之前的小時,不納入任何評分。歷史資料的起始規則由第 4 章負責規定。
- 位移檢定對每一項特徵、兩個半段都執行。每個延遲至少等於預測期距,在任何截止時間點上有差異的特徵都不使用。
本章,於本版次中
版次 2026.11.11範例於 2026年11 月 20 通過測試本章 7 個範例 個範例中有 7 個通過
譯自英文書,版次 2026.11.11。