カレンダー特徴量とラグ特徴量を加える
読了まで約55 分分、8 節 節の 2 例 例。
この章を終えると、次のことができるようになる。1 人のクライアントの時間別履歴を特徴量テーブルに変換する。翌日予測が参照してよいラグ、カレンダー特徴量、祝日特徴量を加える。同じウィンドウで各特徴量が何を加えるかを測定する。予測対象の日を読んでしまうラグを見つける。
第 4 章の統計モデルが見るのは系列だけである。これらのモデルは系列の水準と日内のリズムを知っているが、それ以外は何も知らない。2014 年 12 月 25 日が祝日であったことも、月曜日が日曜日と異なることも、需要が季節とともに動くことも、モデルには分からない。第 1 章は、それがどのような代償を生むかを示した。季節ナイーブのベースラインは、クリスマスの翌日である 12 月 26 日に最も悪い日を迎えた。祝日の読み取り値をそのまま先へ写したためである。勾配ブースティングモデルは、こうした事実を列として取り込める。ただし供給元は対象の日が始まる前に購入するため、予測に入れてよいのは、カットオフ時点で分かっている列だけである。この章では、8 クライアントのサブセットにカレンダー列と祝日列を加え、それぞれを採用する前に検証する。祝日フラグは 12 月 26 日の失敗を直さない。12 月 26 日は祝日ではないからである。これを直せる特徴量は祝日翌日フラグであり、これも事前に分かる。しかしこの章ではそれを作らず、この章の標準のカットオフには祝日が含まれず、祝日は採点されない。
この部分はまだ翻訳されていないため、英語で表示している。
Turn history into features
The table comes first, because every feature in this chapter is a column of it. A feature table has one row for each hour a model must predict. Each row of a feature table holds the value to predict, which the book calls the target, and the features: the readings and facts the model may use for the row's hour. A gradient-boosting model learns a mapping from the columns to the target, one row at a time, so the table is all the model can know.
A row's features must be known at the cutoff of the window that forecasts it, because the forecast is made there. The target is the reading at the hour. The model needs two kinds of row. Training rows are the hours of the history before the cutoff, each with its own features and its own reading as the target. Forecast rows are the 24 hours after the cutoff, with features but no target. The model is fitted on the first kind and predicts the second.
Take the cutoff at 00:00 on Dec 30, 2014. Its forecast rows are the 24 hours of Dec 30, from 00:00 to 23:00, and each has a blank target. Its training rows run back eight weeks, to Nov 4, 2014, one row per client and hour, with the reading as the target. Take the row for Dec 15 at 18:00: its target is the reading at that hour, and its features are readings from earlier hours, such as the reading 24 hours before. No row is a daily total.
Each window's training table is built from the 1,344 hours of history before its cutoff, eight weeks, for each client in SUBSET8. The eight clients are stacked in one table, and the same construction repeats for every decision window and for the three standard cutoffs, Dec 29 to Dec 31, 2014. The first week of history has no reading a week earlier, so it leaves the table: 1,344 hours less 168 hours leaves 1,176 rows per client in each window. One model is fitted per window on that window's history alone, so no training row comes from the days being forecast.
For the lags-only set the columns are the two lags and the target y; the hour of the day arrives with the other calendar columns later in the chapter, and the holiday column after them. MLForecast in mlforecast 1.1.0 takes the series and produces the training rows in fit and the forecast rows in predict. Two of its defaults matter here. A training row whose features are missing is dropped (dropna=True, in mlforecast/core.py), and the first hours of each history drop out because they have no reading a week earlier. Nothing in the library stops a feature from reading the hour it predicts. The rule that stops it is the one you write and check.
Working rule: Build every feature row as if the cutoff were the last reading you have. A feature for a forecast hour must be computable from readings at or before the cutoff of its window. Before any shift test, ask whether the feature is known at the cutoff. Then check it with the shift test from Chapter 3, and do not train on a table you have not checked.
予測が参照できるラグを加える
そのテーブルに最初に加える列はラグである。ラグとは、同じクライアントの過去の読み取り値のことである。時刻 t に対する k 時間のラグは、t から k を引いた時刻の読み取り値である。ラグは、系列のリズムをモデルに与える最も手軽な方法である。ラグ 24 は昨日の同じ時刻の読み取り値であり、ラグ 168 は 1 週間前の同じ時刻の読み取り値である。モデルは、それぞれをどの程度信頼すべきかを学習する。また、ラグ 168 は丸 1 週間さかのぼるので同じ曜日を読むことになり、曜日の列がなくても週次のパターンを捉えられる。
ラグが既知であるかどうかは、予測の対象期間によって決まる。00:00 に行う予測は、カットオフから 24 時間を対象とする。その日の各時間を、カットオフから数えて 0 から 23 とする。ラグ k は時間 j − k を読むので、対象時間 j に対してカットオフより前の読み取り値を読むのは、j − k が負の場合に限られる。これは 0 から 23 のすべての j について成り立たなければならず、そのためには k が 24 以上である必要がある。ラグ 1 は最初の時間については既知である。カットオフ前の最後の読み取り値を読むからである。残りの 23 時間については、予測が持っていない読み取り値を読むことになる。
次の表は、カットオフが 00:00 の翌日予測における 3 種類の対象時間を示している。時間 0 はカットオフ後の最初の時間であり、時間 23 は最後の時間である。
| 対象時間 | ラグ 1 が読む時刻 | ラグ 1 はカットオフ時点で既知か | ラグ 24 が読む時刻 | ラグ 24 はカットオフ時点で既知か |
|---|---|---|---|---|
| 00:00(時間 0) | 前日の 23:00 | はい | 前日の 00:00 | はい |
| 01:00(時間 1) | 予測日の 00:00 | いいえ | 前日の 01:00 | はい |
| 23:00(時間 23) | 予測日の 22:00 | いいえ | 前日の 23:00 | はい |
供給元の 2 つのラグ、24 と 168 は、翌日予測のどの時間でも既知である。したがって、モデルがまだ存在しない読み取り値を必要とすることはない。lgbm-feature-sets はこの 2 つのラグを MLForecast に渡し、残りはライブラリが行う。
第 3 章の時計の規則はラグにも及ぶ。2014 年 3 月 30 日の欠落した時間は欠損に設定されるので、それを読む特徴量もすべて欠損になる。2014 年 4 月 1 日のカットオフの履歴では、lgbm-feature-sets はマスクされた時間を 1 件見つけ、それを読むラグを持つ行は 1 行ある。欠落の 24 時間後の行である。各ウィンドウのモデルを学習する前に、そのウィンドウのマスクされた時間は、第 3 章が埋めるのと同じ方法で、そのウィンドウ自身の履歴から埋められる。この補完はカットオフより後のものを何も読まない。補完された時間は読み取り値になるので、それを読む行は値を保持し、LightGBM がラグから欠損値を受け取ることはない。この規則は、明示された選択であり、測定によって得た最適値ではない。その横に出力される件数が、読者が確認すべきものである。
実践ルール: 対象期間以上の長さのラグだけを使う。対象期間が 24 時間であれば 24 時間以上を意味し、本書では 24 と 168 を用いる。それより短いラグには理由が必要であり、短いラグを使うモデルは、そのスコアを誰かが信頼する前にシフトテストに合格しなければならない。ラグには時計の規則を適用し続け、ラグがマスクされた時間を読む行の数と、履歴から補完した時間の数を数えること。
この部分はまだ翻訳されていないため、英語で表示している。
Add calendar and holiday features
Lags are built from readings. Calendar features, unlike lags, are facts about the target hour itself: its hour of day, its day of the week and its month. They are known in advance, because the clock states them before any reading exists. They need no lag and no cutoff rule. Their value at a target hour cannot depend on any reading, so the shift test has nothing to catch.
The supplier's demand follows the day. The hour of day repeats what the lags already carry: the daily rhythm. The weekday adds what they do not. It tells the model that Saturday and Sunday differ from the working days. The month is the third column, and it is a weak one with this history. Eight weeks of history span two or three calendar months, so month can only tell a few weeks of the history from the rest, and on the standard cutoffs every forecast hour falls in December. The book uses three mlforecast date features, named by their attribute: hour, dayofweek and month. The weekday column already holds the weekend, so the book adds no separate weekend flag. In pandas, dayofweek counts Monday as 0 and Sunday as 6, so Saturday and Sunday are the two values a tree must separate from the rest. A tree can split on that in one step, which is why the weekday is cheap to test.
A public holiday does not follow the weekday. A model with only weekday features reads Dec 25, 2014 as an ordinary Thursday, and it reads a holiday on a Sunday as an ordinary Sunday. The holiday feature answers this. It is a function of the timestamp, is_holiday in the shared module examples/lib/features.py, which returns 1 on a Portuguese national holiday and 0 otherwise. mlforecast accepts such a function as a date feature and names its column after the function. The holidays come from the holidays package 0.110.dev20261118063242, under the MIT licence, through holidays.country_holidays("PT", years=[2013, 2014]). For the two years in the data, the package lists 18 dates. The book does not ship that list. Each run builds it from the package's calendar.
The standard cutoffs are Dec 29 to Dec 31, 2014, and none of their 72 hours per client is a holiday. The held-out week's Dec 25 is outside them, so the feature's effect on that day is not scored in this chapter. On the standard cutoffs, it reaches the scores only through the training history, which contains the holidays of Dec 8 and Dec 25, 2014.
The holiday list is a fact known in advance, like the weekday. It comes from a published calendar and not from the readings, so it cannot leak a reading from the target day. Calendar features answer the question in the working rule at every target hour, by construction, and a lag passes only when it is at least as long as the horizon.
Working rule: Add the calendar features the case's rhythm needs, and keep each one only if it helps on the same windows, as the next section measures. For holidays, use a calendar that covers every year in your data and every year you will forecast, and print how many holidays it holds for those years. A count of zero for a forecast year means the list is missing that year, not that the year had no holidays.
決定ウィンドウで選択する
決定ウィンドウとは、特徴量セットを選ぶために用いるウィンドウであり、本書が報告する標準のカットオフとは別のものである。決定ウィンドウには2種類ある。1つ目は、2014年11月25日、11月26日、12月2日、12月3日という4つの通常カットオフである。2つ目は7つの祝日カットオフであり、2014年のポルトガルの国民の祝日のうち、12月25日より前で、8週間分の履歴がそろっているものを指す。すなわち、4月18日、4月20日、4月25日、5月1日、6月10日、8月15日、12月8日である。通常のウィンドウには祝日が含まれないため、祝日特徴量がそこで選ばれることはあり得ない。祝日特徴量が選ばれる可能性があるのは、祝日ウィンドウにおいてである。したがって、選択には決定ウィンドウをすべて用いる。候補のセットの1つが祝日特徴量を含むからである。標準のカットオフは、選択を終えた後で採点し、選択結果と並べて示す。標準のカットオフは選択には一切関与しない。
祝日フラグは2通りに作用する。決定ウィンドウでは、採点対象の時間帯でフラグが立つため、予測を変えうる。標準のカットオフでは、採点対象の時間帯に祝日がないため、フラグがそれらのスコアを変えるのは学習を通じてのみである。
実践ルール: 特徴量は、ホールドアウト週より前にあり、かつその特徴量が対象とする種類の日を含むウィンドウで選択する。祝日特徴量には祝日ウィンドウが必要である。標準のカットオフは選択結果と並べて報告するが、選択そのものには用いない。
各特徴量が加えるものを測る
特徴量を残す価値があるのは、モデルが学習に使わなかったウィンドウで誤差が下がるときである。それを測るには、ほかの条件をすべて固定する。同じウィンドウ、同じ履歴、同じ設定を用いる。3つの特徴量セットを1つずつ当てはめる。1つ目はラグのみである。2つ目はこれにカレンダー特徴量を加える。3つ目はさらに祝日特徴量を加える。各セットはウィンドウごとに1回当てはめ、SUBSET8の8クライアントすべてに対して1つのモデルを使う。そして、それぞれを同じウィンドウ上の季節ナイーブ予測と比較する。
各セットには2つのスコアを付ける。プールしたMAEは、ウィンドウ内のすべてのクライアント時間にわたるMAEであり、供給事業者全体を表す単一の数値である。クライアントごとのMASEの平均は、クライアントごとにMASEを求め、8クライアントで平均したものである。MASEは、各クライアントの誤差をスケールで割る。このスケールは、そのクライアント自身の読み取り値に対して季節ナイーブ予測が標本内で出す平均絶対誤差である。本書ではどこでも1つのスケール関数、scoring.book_scaleを使う。このスケールは、セットで最初に採点するウィンドウ(2014年4月18日0時)より前のすべての読み取り値を、時刻変更の時間帯をマスクして読むため、採点するウィンドウに依存せず、リークも起きない。1つのクライアントには注意が要る。MT_115は2014年1月14日に読み取りが始まっており、最初の読み取りより前のゼロは、最初の読み取りから数えるため、そのスケールから除かれる。第4章では、遅れて開始するクライアントに対するこの規則を扱う。
1"""Compare three feature sets for the global LightGBM forecast of SUBSET8 on the decision windows (B-5, B-9, B-10): four2ordinary cutoffs and seven 2014 holidays before Dec 25, each fitted scaled and unscaled. The mean MASE lines carry the3choice; the standard-cutoff lines are reported beside it and choose nothing."""4import pandas as pd56from lib.backtest import history_before7from lib.electricity import load8from lib.features import CALENDAR, PT_HOLIDAYS, is_holiday, rows_reading_missing, score_feature_sets9from lib.panel import DECISION_CUTOFFS, HOLIDAY_DECISION_CUTOFFS10from lib.quirks import mask_clock_changes11from lib.settings import EVAL_CUTOFFS, LEAD, SUBSET8, show1213LAGS = [24, 168] # both at least the 24-hour horizon, so each is known at every forecast hour14# CALENDAR is hour, dayofweek and month, as mlforecast date features; the holiday set adds is_holiday to them15FEATURE_SETS = {"lags_only": [], "with_calendar": CALENDAR, "with_holidays": CALENDAR + [is_holiday]}16MODELS = ["SeasonalNaive", *FEATURE_SETS, *[f"unscaled_{name}" for name in FEATURE_SETS]]17DECISION = sorted([*DECISION_CUTOFFS, *HOLIDAY_DECISION_CUTOFFS]) # the decision windows; standard cutoffs are not here18raw = load(SUBSET8)1920# DECISION[0] is the first decision window, Apr 18, 2014: the MASE scale reads only the readings before it21forecasts, scored, per_client = score_feature_sets(raw, DECISION, LAGS, FEATURE_SETS, DECISION[0])22show("clients", forecasts["unique_id"].nunique())23show("decision windows", len(DECISION))24show("scored hours", len(scored))25show("Portuguese holidays in 2013 and 2014", len(PT_HOLIDAYS))26show("holiday hours in the decision windows", int(is_holiday(scored["ds"]).sum()))27for model in MODELS:28 show(f"MAE {model.replace('unscaled_', 'unscaled ')}", (scored["y"] - scored[model]).abs().mean())29for model in MODELS:30 show(f"mean MASE {model.replace('unscaled_', 'unscaled ')}", per_client[model].mean(), digits=3)31for model in MODELS:32 # the prose does not quote this client, so this line is for reference only33 show(f"MASE MT_268 {model.replace('unscaled_', 'unscaled ')}", per_client.loc["MT_268", model], digits=3)3435# The standard cutoffs, reported beside the choice above. Nothing is chosen from them.36# The scale here reads the readings before the first standard cutoff, Dec 29, 2014.37_, _, standard = score_feature_sets(raw, EVAL_CUTOFFS, LAGS, FEATURE_SETS, EVAL_CUTOFFS[0])38for model in MODELS:39 show(f"standard cutoffs, mean MASE {model.replace('unscaled_', 'unscaled ')}", standard[model].mean(), digits=3)4041# Clock-change check: the history of a 1 April 2014 cutoff holds the 30 March gap, which the feature rules must reach.42march = history_before(mask_clock_changes(load([LEAD])), pd.Timestamp("2014-04-01")) # the Chapter 3 mask, then the cut43show("masked hours in the history", int(march["y"].isna().sum()))44# a row counts when either lag, 24 or 168, reads a masked hour45show("rows whose lag reads a masked hour", rows_reading_missing(march.set_index("ds")["y"], LAGS))
python lgbm-feature-sets.pyclients: 8
decision windows: 11
scored hours: 2112
Portuguese holidays in 2013 and 2014: 18
holiday hours in the decision windows: 1344
MAE SeasonalNaive: 305.21
MAE lags_only: 280.57
MAE with_calendar: 270.57
MAE with_holidays: 267.40
MAE unscaled lags_only: 304.03
MAE unscaled with_calendar: 271.63
MAE unscaled with_holidays: 280.75
mean MASE SeasonalNaive: 0.934
mean MASE lags_only: 0.886
mean MASE with_calendar: 0.894
mean MASE with_holidays: 0.893
mean MASE unscaled lags_only: 1.115
mean MASE unscaled with_calendar: 1.119
mean MASE unscaled with_holidays: 1.139
MASE MT_268 SeasonalNaive: 0.840
MASE MT_268 lags_only: 0.797
MASE MT_268 with_calendar: 0.758
MASE MT_268 with_holidays: 0.789
MASE MT_268 unscaled lags_only: 0.855
MASE MT_268 unscaled with_calendar: 0.871
MASE MT_268 unscaled with_holidays: 0.936
standard cutoffs, mean MASE SeasonalNaive: 1.162
standard cutoffs, mean MASE lags_only: 1.057
standard cutoffs, mean MASE with_calendar: 1.165
standard cutoffs, mean MASE with_holidays: 1.134
standard cutoffs, mean MASE unscaled lags_only: 1.357
standard cutoffs, mean MASE unscaled with_calendar: 1.494
standard cutoffs, mean MASE unscaled with_holidays: 1.486
masked hours in the history: 1
rows whose lag reads a masked hour: 1
ここでの基準は季節ナイーブ予測である。2112の採点時間(24時間のウィンドウ11個にわたる8クライアント)でプールしたそのMAEは305.21 kWhである。
スケーリングなしでは、ラグのみのモデルはクライアントごとの見方では季節ナイーブ予測に及ばない。クライアントごとのMASEの平均は1.115であり、季節ナイーブ予測の0.934より悪い。クライアントの規模は大きく異なり、最大のクライアントの読み取り値は最小のものの何倍にもなる。グローバルモデルはすべてのクライアントの行にわたって1つの損失を当てはめ、ここでその損失はkWh単位の二乗誤差であるため、最大のクライアントの誤差が分割を決め、小さなクライアントはほとんど重みを持たない。原因は個々のクライアントの範囲ではなく損失にあると考えられる。以下のスケーリングありの実行ではこの差が消えるので、この解釈が支持される。ただし、これはこれらの数値からの判断であり、証明ではない。
スケーリングありの実行では、mlforecastのLocalStandardScaler(mlforecast/target_transforms.py)で各クライアントの目的変数を標準化する。これはクライアントの平均を引き、標準偏差で割る。どちらもカットオフ以前のウィンドウの履歴から求められ、fitの内部で当てはめられ、predictはそれを逆変換するだけである。カットオフ以後の読み取り値はこれらを決めないので、このスケーリングは特徴量と同じ検査に通る。make_forecasterは既定でscaled=Trueを取り、第6章でもこの既定を再び使う。
スケーリングすると比較の結果が変わり、ラグのみでもクライアントごとの見方では季節ナイーブ予測を上回る。平均MASEは0.886であり、季節ナイーブ予測の0.934より小さい。プールしたMAEは280.57 kWhである。
カレンダーのセットは、ラグのみに勝てない。それでも季節ナイーブ予測には勝つ。平均MASEは0.894、プールしたMAEは270.57 kWhである。
カレンダーのセットに加えた祝日フラグは差を縮めるが、埋めるには至らない。平均は0.893、プールしたMAEは267.40 kWhである。
第4章では、AutoETSとARIMAを、勾配ブースティングモデルが超えるべき基準として設定した。標準のカットオフでは、ラグのみもこの基準を下回る。同じクライアント、カットオフ、スケールで、1.057に対してARIMAは1.09である。
実践ルールに従えば、残すのはラグだけであり、決め手はクライアントごとの見方である。クライアントの予測にとって重要なのはこの見方だからである。カレンダーのセットの平均MASEはラグのみより高いため、残さない。プールした見方はここでは逆を指している。カレンダーのセットのプールMAEはラグのみより低く、祝日のセットはさらに低い。本章は実践ルールの求めどおり両方を報告し、両者を一致させるためにモデルを調整することはしない。
このルールは、特徴量が拡張元のセットの誤差を下げる場合にのみ、その特徴量を残す。祝日フラグはカレンダーのセットの平均MASEをわずかに下げるが、改善と呼ぶには小さすぎ、これを含むセットもなおラグのみより高い。フラグは各祝日のウィンドウで丸1日、全クライアントについて、1344クライアント時間でオンになるので、機会は十分にあったが、採用には値しない。したがって本書は、ラグのみのセットを第6章に引き継ぐ。この結果は11個のウィンドウによるものであり、小さな検証である。
実践ルール: 特徴量セットは、同じウィンドウ上で、拡張元のセットに対してクライアントごとのMASEの平均を下げる場合にのみ残す。その横にプールしたMAEも報告する。2つの見方の不一致を消すためにモデルを調整してはならない。
この部分はまだ翻訳されていないため、英語で表示している。
Catch a lag that leaks the future
The measurements above assume that each feature is known at its cutoff. A leak is a feature that uses a reading the forecast cannot have at its cutoff. In the book's view, a leak is a likely reason a backtest looks better than the model will be, and it can be built by accident. One pattern builds the feature table once from the whole series, so each target hour carries its lag, and then scores the table's forecast rows as if they were out of sample. Nothing fails. The score is too good, and nothing in it says so.
The library adds a second trap of its own. MLForecast predicts recursively by default. In recursive prediction, for a 24-hour horizon, MLForecast forecasts one hour, writes that forecast back as the reading for the next hour, and repeats (_predict_recursive in mlforecast/core.py). A lag of 1 therefore reads a forecast for every hour after the first, while training read actual readings for that lag. Calling that mismatch a leak is the book's judgement. It is one more reason to choose lags of 24 or more. With lags of 24 and 168, every step of the 24 reads actual readings, so the recursion never feeds this model its own forecasts. With max_horizon set, the library trains one model per horizon instead, and predicts with them in _predict_multi. The rule does not change with it: a feature must still be known at the cutoff of the window it forecasts.
The shift test from Chapter 3 carries over with one change: compare the lag at the target hours after the cutoff, not at the history rows. Compute the lag for each target hour twice: once from the history cut at the cutoff, and once from the whole series. Count the hours where the two differ. A lag of 24 agrees on every target hour, because each of the 24 hours reads a reading before the cutoff. A lag of 1 agrees only on the first hour.
Which do you expect to have the lower error, the model with a lag of 1 or the one without it? Both are fitted on the same training rows with the same settings, for each of the three standard cutoffs. The honest model uses lags 24 and 168. The leaky model adds a lag of 1, read from the whole series for the target hours, which is what the table built once would do.
1"""Shows which lag leaks: a lag of 1 reads the hour before each target hour, which a 24-hour forecast does not have at its2cutoff. The rows-differing lines are the shift test, and the two MAE lines show how much the leak flatters the score."""3import numpy as np4import pandas as pd56from lib.electricity import load7from lib.features import fit_window_mae, lag_values8from lib.settings import EVAL_CUTOFFS, HORIZON, LEAD, show910y = load([LEAD]).set_index("ds")["y"].asfreq("h") # asfreq gives every hour a row, so a missing hour is NaN, not skipped11HONEST, LEAKY = [24, 168], [1, 24, 168] # HONEST lags are both at least the horizon; LEAKY adds lag 112CUTOFFS = pd.to_datetime(EVAL_CUTOFFS)131415def shift_test(lag):16 """Target hours where the lag differs between the history cut at each cutoff and the whole series, and how many."""17 compared = differing = 018 for c in CUTOFFS:19 targets = pd.date_range(c, periods=HORIZON, freq="h") # the 24 hours each forecast must predict20 honest = lag_values(y[y.index < c], lag, targets) # readings before the cutoff only, as the forecast has them21 whole = lag_values(y, lag, targets) # the same lag read from the whole series, as a table built once would read it22 same = (honest == whole) | (np.isnan(honest) & np.isnan(whole)) # NaN never equals NaN, so the second term counts two missing readings as the same23 compared += len(targets)24 differing += int((~same).sum())25 return compared, differing262728show("cutoffs", len(CUTOFFS))29show("rows compared", shift_test(1)[0]) # the first value is the hours compared, the same for every lag30for lag in (1, 24, 168):31 show(f"rows differing for lag {lag}", shift_test(lag)[1])32show("MAE honest, lags 24 and 168", fit_window_mae(y, HONEST, CUTOFFS, leaky=False)) # the table holds the lags and the hour of day; leaky=False reads the target lags from the cut history33show("MAE leaky, lags 1, 24 and 168", fit_window_mae(y, LEAKY, CUTOFFS, leaky=True)) # leaky=True reads the whole series
python lag-leak-check.pycutoffs: 3
rows compared: 72
rows differing for lag 1: 69
rows differing for lag 24: 0
rows differing for lag 168: 0
MAE honest, lags 24 and 168: 5.36
MAE leaky, lags 1, 24 and 168: 2.87
Only the lag of 1 fails the shift test. Of the 72 target hours compared, 69 read a different value from the cut history than from the whole series: every hour of each window but the first. The lags of 24 and 168 differ on 0 and 0 rows. The lag of 1 agrees only on the first hour of each window, because that hour reads the last reading before the cutoff, which the forecast does have.
The leaky model looks almost twice as good: its MAE is 2.87 kWh, against 5.36 kWh for the honest model. The gap is the leak. Its lag of 1 reads the hour before the target, which for most target hours is an hour of the forecast window itself. The honest model never sees that hour, so its error is the one that production will show.
Working rule: Run the shift test on every lag and every window feature before a model trains on it, and treat any differing row as a leak until you have shown otherwise. When an error falls sharply after you add a feature, check that feature first, before you credit it.
この部分はまだ翻訳されていないため、英語で表示している。
What goes wrong in production
A holiday list that stops at the end of the data reads zero for every later holiday. The flag then stays off for every day of the forecast year, and the model forecasts holidays as ordinary days. The first holiday shows up as a large miss on the dashboard. The holiday count printed by the example is the check: a list for a new year that prints zero holidays is missing that year. A later version of holidays can also change its calendar, so pin the version, as the book does, and rerun the count after any upgrade.
A lag shorter than the horizon, carried over from an hourly model used for a day-ahead forecast, scores well in the backtest, because the backtest was built from the whole series. In production, the later hours read the model's own forecasts. Compare the live error by hour of the day-ahead forecast with the backtest's own error by hour. A model without the leak should show about the error the backtest showed at each hour. Error that grows with the hour of the horizon, beyond that, is the sign of feedback from the model's own forecasts.
The clock rule can still go wrong in the pipeline. Masked hours make some forecast features missing, and a pipeline can drop those rows, or fill those hours, without saying so. Print the masked hours and the rows they affect every time the history changes.
A pooled score can hide the typical client. In lgbm-feature-sets, the unscaled lags-only model's pooled MAE, 304.03 kWh, is below seasonal naive's 305.21 kWh, but its mean per-client MASE is 1.115, against 0.934. The supplier buys power for each client, so the per-client figure is the one that decides a client's forecast. A supplier that reports only the pooled MAE will sell the wrong forecast to the clients the pooled figure hides. Report the per-client MASE next to the pooled figure, and look at the worst client first.
Results can also depend on the machine. LightGBM's parameter reference says deterministic gives stable results for the same data and the same parameters on the CPU device type, and warns that results can differ with other LightGBM versions, with binaries compiled by other compilers, or on other systems. The book sets deterministic, row-wise histograms, one thread and a fixed seed, under LightGBM 4.7.0. Those settings make the output repeatable on one machine with one thread count: the output was identical in three runs on the recording machine. They do not promise agreement across machines, and the book has not tested that. The scores are quoted rounded, and rounding does not make two machines agree. If a release machine prints different values, the recorded output needs a fresh recording, and the prose needs the same check.
Working rule: Recheck the holiday count for each forecast year, the masked hours and the rows they reach, and the lag lengths whenever the data or a library changes. Run the shift test on every lag, and read the per-client MASE beside the pooled MAE. A check that changes is a reason to stop and read the cause before the next forecast is published.
この部分はまだ翻訳されていないため、英語で表示している。
Decisions this chapter made
The choices below are the ones a reader would have to make differently to change the results. Each one is the book's choice, open to revision when a later edition measures something else.
- The handed-on model uses lags 24 and 168 only. Lag 1 appears only in the leak check, never in a forecast.
- The calendar set is
hour,dayofweekandmonth. It is measured and not kept: on the per-client view it is worse than lags alone. There is no separate weekend flag, because the weekday carries the weekend. - The holiday flag is measured only on top of the calendar set, on all the decision windows. It is not kept, because the set that holds it is still worse than lags alone. Chapter 6 gets the lags-only set.
- Holidays come from the
holidayspackage for Portugal, for the two years in the data. Theis_holidayfunction lives inexamples/lib/features.py. - Each client's target is scaled by default, with
make_forecaster(scaled=True). The scaler is fitted on each window's history only. The unscaled run is printed once, to show the failure that scaling corrects. - Each window's masked clock-change hours are filled from that window's history before the fit, so no row is dropped for them and LightGBM never receives a missing value.
- The LightGBM settings are
LGBM_PARAMSinexamples/lib/features.py: deterministic, row-wise histograms, one thread and seed 0. They sit there, not insettings.py, which this chapter leaves unchanged. - The MASE scale is
scoring.book_scale. It starts at each client's first reading and reads the readings before the first decision window, Apr 18, 2014. - On the decision windows, the lags-only model beats seasonal naive on mean per-client MASE. The chapter does not tune the model to change that result.
- The feature sets are chosen on the decision windows, not on the standard cutoffs or the held-out week. The holiday windows end on Dec 8, so the holiday's effect on Dec 25 is not measured in this chapter. Whether calendar features pay on a longer history is also not measured here.
- The leak check uses
MT_014, one client, because the leak is a property of the lag and not of the client mix, so its target is not scaled. The feature sets useSUBSET8. - Chapter 6 reuses
make_forecaster,mlforecast_windows,fit_window_mae,lag_tableandis_holidayfromexamples/lib/features.py.make_forecasterscales by default. - The lesson is an order of tests: the shift test runs before any score, and the per-client MASE decides which features stay.
この版における本章
第2026.11.11版2026年11月20日時点で例が通過この章の2 例件のうち2件が合格
英語版の書籍(版2026.11.11)から翻訳した。