明日の需要を予測する
読了まで約42 分分、7 節 節の 3 例 例。
本章では、明日の需要に対する最初の予測と、以降のすべての予測が上回らなければならない単純なベースラインを構築する。1 つの顧客の1時間ごとの需要を読み込み、季節ナイーブ・ベースラインと 1 つの統計モデルで翌日を予測し、両者を同じ 7 日間で評価する。結果は意図的に粗いものにしてある。予測区間はなく、チューニングも行わず、判断の材料は 1 つの顧客だけである。以降の各章では、そのうちの一つの部分を確かなものにしていく。必要な知識は、Python、pandas、標本の平均、そして誤差とは何かだけである。中心となる用語は、初めて現れる箇所で一行ずつ定義する。
明日の電力は、今日のうちに、一日が始まる前に、1時間ずつ購入しなければならない。購入する側には、顧客がそれぞれの時間にどれだけ使うかという予測が必要であり、予測が外れた時間はすべて、誤った数字を前提に購入計画が立てられた時間になる。したがって、どの手法を信頼するかを決める前に、二つの問いに答えなければならない。購入前に記録された測定値だけから作った予測は、顧客が実際に使った量に近いか。そして、その予測は、誰にでも作れる最も単純な予測、すなわち昨日をそのまま写す予測よりも優れているか。
事例とそのデータ
本書は全体を通して一つの事例を追う。顧客向けに電力を前日に調達する電力小売事業者であり、以下ではこれを小売事業者と呼ぶ。
小売事業者は、その日が始まる前に購入量を確定させる。購入が少なすぎるときのコストは多すぎるときのコストより大きいため、単一の数値だけでなく幅も必要になる。本書は、こうした購入の出発点となる予測を構築する。ここでの予測とは、予測を行う前に記録された計測値から求める、1顧客の各時間における期待需要である。
予測が何であるかは、三つの用語で定まる。予測を行う時点をカットオフと呼ぶ。予測はカットオフより前の計測値だけを使い、固定された時間数だけ先まで及ぶ。この時間数がホライズンである。ウィンドウとは、一つのカットオフとそのホライズン、およびそこから得られる予測をひとまとめにしたものである。ここではホライズンが24時間であるため、各ウィンドウは1日、すなわちカットオフから始まる24時間を対象とする。
タイミングは手法と同じくらい重要である。本書のすべてのウィンドウでは、カットオフを予測対象の日の00:00に置く。したがって使える最後の計測値は前日の23:00のものである。この事例では日が始まる前に購入するため、午前0時のカットオフは単純化である。本書がこれを採用するのは、各ウィンドウが前日分だけを必要とするようにするためである。より早く購入する小売事業者であれば、カットオフも早くなり、より先まで予測することになる。カットオフを1時間でも越えて読む予測は、小売事業者が購入する時点では持っていない情報を使うことになり、そのスコアは実力以上によく見えてしまう。
データは公開されている。UCI Machine Learning RepositoryのElectricityLoadDiagrams20112014データセットで、作成者はTrindade (2015)、DOIは10.24432/C58C86である。ライセンスはCC BY 4.0である。本書はその一部を切り出したelectricity_hourly.csv.gzを同梱しており、ライセンス文書は同じフォルダに置かれている。データカードには、出典、切り出し方、およびその限界が記されている。
元のファイルには370の顧客が含まれ、15分ごとに計測値がある。切り出し版では各時間の4つの計測値を平均して、その時間に使われたエネルギーをkWhで表し、2013年と2014年の丸2年分を残している。顧客の一つMT_223は、この期間に0でない計測値が一つもないため、切り出し時に除外した。残る369の顧客をidで並べ、等間隔の位置から30を選んでいる。元のファイルから自分で切り出す読者は、MT_223を除外し、同じ30の等間隔の位置を取らなければならない。そうしないと本書の件数と一致しない。
顧客にはMT_014のような匿名のidが付いている。データセットはそれらが何であるかを述べていないため、本書では顧客と呼ぶ。企業や世帯であるとは述べない。
本書には二つの顧客グループが繰り返し登場する。30顧客は、切り出し版のすべての顧客である。SUBSET8の8顧客は、30顧客のうち2番目から始めて4顧客ごとに選んだものである。後の章では、全件を実行すると時間がかかりすぎる場合にこの部分集合を使う。この部分集合には、データの開始が遅い顧客が1つ含まれる。主役の顧客MT_014はSUBSET8の最初の顧客である。この章と、単一顧客を扱う例ではこの顧客を使う。
テスト期間は2014年の最終週、2014年12月25日から12月31日までである。この章の予測はこの期間でスコアを付け、これを保持週と呼ぶ。各予測はカットオフより前の計測値だけを使うため、予測対象の日から学習する予測は一つもない。この週は平穏ではない。2014年12月25日はクリスマスで、データの時計が設定されているポルトガルでは祝日である。この章はこの週をそのままスコア付けし、そのスコアは祝日の影響を示す。第5章では祝日フラグを祝日のウィンドウで検証するが、採用はしない。そのため本書はここで祝日の影響を補正しない。第10章でそのコストを示す。
予測が述べるのは、需要がどうなりそうかであり、その理由ではない。データが記録しているのは各顧客がどれだけ使ったかである。価格や契約が異なっていた場合に需要がどうなっていたかは、データからは言えない。それは因果の問いであり、別の設計を必要とする。
実践ルール: 予測を行う前に、切り出し版をデータカードと照合する。ファイルには30の顧客が含まれているはずであり、この例ではそのうち丸2年分の時間別の行を持つ顧客がいくつあるかを数える。これらの件数はカードと一致しなければならない。MT_223が存在せず、その理由が説明されていることを確認する。カードと一致しない切り出し版は別のデータであり、そこから計算したすべての数値は、本書のデータではなくそのデータを記述している。
この部分はまだ翻訳されていないため、英語で表示している。
Load one client's hourly demand
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:
normalis an ordinary hour.before_first_readingis an hour before a client's first non-zero reading. Only a late-starting client has these rows.clock_change_gapis 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_repeatis 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.
1"""Loads the lead client's hourly demand, counts its quirk labels, and checks the eight-week history before each2held-out cutoff. The point rests on the last printed line: no history holds a clock-change row."""3from lib.backtest import held_out_cutoffs, history_before4from lib.electricity import load5from lib.settings import LEAD, show678def fmt(ts):9 return ts.strftime("%Y-%m-%d %H:%M")101112FULL_ROWS = 2 * 365 * 24 # two years of hours; 2013 and 2014 are not leap years1314everyone = load()15show("clients in the file", everyone["unique_id"].nunique())16show(f"clients with {FULL_ROWS} rows", int((everyone.groupby("unique_id").size() == FULL_ROWS).sum()))1718df = load([LEAD])19show("rows", len(df))20show("first reading", fmt(df["ds"].min()))21show("last reading", fmt(df["ds"].max()))22for quirk in ["normal", "before_first_reading", "clock_change_gap", "clock_change_repeat"]:23 show(f"{quirk} rows", int((df["quirk"] == quirk).sum()))2425# history_before keeps the HISTORY_HOURS hours (eight weeks) before each cutoff, and raises if a count is off.26windows = [history_before(df, cutoff) for cutoff in held_out_cutoffs()]27show("history rows per window", min(len(w) for w in windows))28show("longest history rows", max(len(w) for w in windows))29show("first history reading", fmt(windows[0]["ds"].min()))30# Counts only the two clock-change labels.31show("clock-change rows in held-out histories",32 sum(int(w["quirk"].isin(["clock_change_gap", "clock_change_repeat"]).sum()) for w in windows))
python load-lead-client.pyclients 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.
季節ナイーブ法による翌日の予測
最初の予測は最も単純なものであり、以降のすべての予測はこれを上回らなければならない。この予測では、事例とそのデータで示した事例のカットオフと予測期間、および1クライアントの読み込みで説明した履歴を用いる。
季節ナイーブ法は、将来の各値が同じ季節に最後に観測された値に等しいとみなす。Hyndman と Athanasopoulos は、任意の長さの季節 m についてこれを定義している。将来の値の予測は、1季節前に観測された値とする(Hyndman and Athanasopoulos, Forecasting: Principles and Practice, ch. 5)。1時間ごとのデータで日周期を扱う場合、季節は24時間であり、明日のある時刻の予測は今日の同じ時刻の読み取り値になる。本書の表記では、時刻 t の予測は y(t - 24) である。
この規則には、当てはめるものが何もない。予測はデータの複製であるから、推定の手順を必要としない。また、どのカットオフであっても、カットオフより先のデータを読むことはない。カットオフからその23時間後までの各時刻について、t - 24 はカットオフの24時間前からその1時間前までの範囲に収まるので、複製に使われるのは履歴だけである。
保持した1週間には、7 個のウィンドウがある。2014年12月25日から12月31日までの各日に1つずつあり、いずれも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 が値の最後の1季節を繰り返すからである(statsforecast 2.1.1、statsforecast/utils.py)。それでも例ではすべての履歴を渡している。履歴をより多く使うモデルにも同じ呼び出しを使えるためであり、履歴の長さを1通りにした1つの呼び出しなら、覚える形は2つではなく1つで済む。
なぜ1週間ではなく1日なのか。168時間の季節を使えば、前週の同じ曜日の同じ時刻を複製することになり、週単位のリズムをもつ系列にとってはこれも有効なベースラインである。本章で日単位の季節を使うのは、問いが翌日の需要であり、事例が必要とするのが翌日の予測だからである。
1"""Forecasts the lead client's next day with seasonal naive for each day of the held-out week, then scores it.2The point rests on the MAE and RMSE lines, which score a copy of yesterday, and on the missing forecasts line."""3import pandas as pd4from statsforecast import StatsForecast5from statsforecast.models import SeasonalNaive67from lib.backtest import forecast_windows, held_out_cutoffs, scoring_counts, score_windows, window_mae8from lib.electricity import load9from lib.settings import HORIZON, LEAD, show101112def day_mean(day):13 return df[df["ds"].dt.normalize() == pd.Timestamp(day)]["y"].mean()141516# statsforecast reads a frame with three columns: the series id, the time and the value.17df = load([LEAD])[["unique_id", "ds", "y"]]18# season_length 24 is the daily cycle of hourly data; freq "h" is pandas' code for hourly steps; one job runs in one process.19sf = StatsForecast(models=[SeasonalNaive(season_length=24)], freq="h", n_jobs=1)20forecasts = forecast_windows(sf, df, held_out_cutoffs())21scores = score_windows(df, forecasts, "SeasonalNaive")22counts = scoring_counts(df, forecasts, "SeasonalNaive")2324show("horizon hours", HORIZON)25show("windows", counts["windows"])26show("scored hours", counts["scored_hours"])27show("missing forecasts", counts["missing_forecasts"])28# The readings at the forecast hours, which are the hours the scores cover.29show("mean demand", df[df["ds"].isin(forecasts["ds"])]["y"].mean())30show("mean demand 2014-12-24", day_mean("2014-12-24"))31show("mean demand 2014-12-25", day_mean("2014-12-25"))32show("MAE", scores["mae"])33show("RMSE", scores["rmse"])34for day, mae_day in window_mae(df, forecasts, "SeasonalNaive").items():35 show(f"MAE {day:%Y-%m-%d}", mae_day)3637# The check is run on a history with one hour removed, to show it refuses a short history.38cutoff = held_out_cutoffs()[0]39gap = df[df["ds"] != cutoff - pd.Timedelta(hours=1)] # drops the hour just before the first cutoff40try:41 forecast_windows(sf, gap, [cutoff]) # history_before raises ValueError unless every client has exactly HISTORY_HOURS rows before the cutoff.42 refused = "no"43except ValueError:44 refused = "yes"45show("history with one hour removed refused", refused)
python seasonal-naive-next-day.pyhorizon 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 であり、本章のすべての誤差はこの水準に照らして読むべきである。
季節ナイーブ法はベースラインであり、日周期が系列を支配している場合には強力なベースラインになりうる。弱点は、1日分しか複製しない点にある。普段と異なる日があると、それが翌日の予測になってしまい、この方法にはそれを平均化する手段がない。
実践ルール: 日周期をもつ1時間ごとの系列では、あらゆる比較に季節ナイーブ法を含めること。当てはめが不要なので、追加の費用なしにすべてのウィンドウで実行できる。同じウィンドウでこれを上回れないモデルは、余分な手間に見合うとはいえない。スコアを読む前に、予測に欠損値がないかを確認すること。最後の季節に欠損した読み取り値があると、それが欠損した予測になるからである。それらの時間を、モデルを実行する前に補完する規則は、第3章で示す。
この部分はまだ翻訳されていないため、英語で表示している。
Forecast the next day with one model
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.
1"""Forecasts the lead client's next day with AutoETS for each day of the held-out week, then scores it.2The point rests on the MAE and RMSE lines, read against the seasonal naive example, and on the form counts."""3import numpy as np4from statsforecast import StatsForecast5from statsforecast.models import AutoETS67from lib.backtest import chosen_forms, forecast_windows, held_out_cutoffs, scoring_counts, score_windows, window_mae8from lib.electricity import load9from lib.settings import HORIZON, LEAD, SEED, show1011# Seeded by convention. AutoETS's point forecast draws no random numbers, so this line changes nothing here.12np.random.seed(SEED)13# statsforecast reads a frame with three columns: the series id, the time and the value.14df = load([LEAD])[["unique_id", "ds", "y"]]15# model="ZZA": AICc chooses the error and trend forms; the seasonal form is fixed to additive, so every form has a day cycle.16sf = StatsForecast(models=[AutoETS(season_length=24, model="ZZA")], freq="h", n_jobs=1)17forecasts = forecast_windows(sf, df, held_out_cutoffs())18scores = score_windows(df, forecasts, "AutoETS")19counts = scoring_counts(df, forecasts, "AutoETS")20# chosen_forms refits at each cutoff to read the form each fit picked; the forecasts above do not report it.21forms = chosen_forms(sf, df, held_out_cutoffs())2223show("horizon hours", HORIZON)24show("windows", counts["windows"])25show("scored hours", counts["scored_hours"])26show("missing forecasts", counts["missing_forecasts"])27for form, n in forms.items():28 show(f"windows that chose {form}", n)29show("MAE", scores["mae"])30show("RMSE", scores["rmse"])31for day, mae_day in window_mae(df, forecasts, "AutoETS").items():32 show(f"MAE {day:%Y-%m-%d}", mae_day)
python autoets-next-day.pyhorizon 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.
保留した1週間で両者を採点する
前の二つの節で、二つの例はいずれも7回の翌日予測を作り終えている。スコアとは、予測の集合がもつ誤差を一つの数値にまとめたものである。ある時間の誤差は、実際の需要から予測を引いた値である。この章では二つのスコアを用いる。平均絶対誤差(MAE)は外れの大きさの平均であり、MAE = mean(abs(actual - forecast))で表される。二乗平均平方根誤差(RMSE)はRMSE = sqrt(mean((actual - forecast)^2))で表される。どちらもkWh単位であるが、答える問いは異なる。HyndmanとAthanasopoulosは Forecasting: Principles and Practice, ch. 5 で、MAEを最小にする予測は中央値の予測であり、RMSEを最小にする予測は平均の予測であると述べている。RMSEは各誤差を二乗するため、少数の大きな外れはMAEよりもRMSEを大きく押し上げる。
両方のスコアはutilsforecast(0.2.17)から得る。そのmaeは絶対誤差の平均であり、rmseは二乗誤差の平均の平方根である(utilsforecast/losses.py、関数maeとrmse)。スコアは採点対象の168時間をまとめて集計する。各時間は1回ずつ数えられ、7個のウィンドウのそれぞれが24時間分を提供する。
表は、1時間あたりの平均需要46.62 kWhと照らして読む。数値が小さいほど、予測は実測値に近い。
| モデル | MAE (kWh) | RMSE (kWh) |
|---|---|---|
| SeasonalNaive | 8.36 | 10.87 |
| AutoETS | 8.86 | 10.91 |
表が示すとおり、AutoETSの誤差は二つのスコアのどちらでもベースラインより大きく、MAEは8.86 kWhで、ベースラインの8.36を上回る。計画に用いるべき数値はMAEである。各時間における典型的な外れを表すからである。RMSEは常にMAE以上になる。誤差が正規分布に従うとき、RMSEはMAEのおよそ1.25倍であるため、この比を大きく超える場合は少数の大きな外れがあることを意味する。この節では二つのスコアを並べて読むにとどめ、それ以上は踏み込まない。1週間分の1クライアントでは、外れのばらつきを示せないからである。
両モデルともクリスマス前後で最も成績が悪いが、悪化する日は異なる。日別の出力行がそれを示している。ベースラインの最悪日は、クリスマスの翌日の12月26日である。この日はクリスマス当日をそのまま写すため、1時間あたり12.16 kWhとなり、7日間で最大である。AutoETSの最悪日は12月25日そのものであり、その値は13.51 kWhで、同じ日のベースラインは9.41である。 1クライアント・1週間でこの程度の差があっても、結論にはならない。7回の予測は小さな標本であり、1週間で作った順位は翌週に入れ替わりうる。第3章では、日曜日を起点とする1年分のカットオフで季節ナイーブをバックテストする。
スコアは意思決定にも合っていなければならない。購入の損失は非対称である。事例が述べるとおり、買いすぎよりも買い足りないほうが費用は大きい。MAEとRMSEは各外れの符号ではなく大きさを用いるため、どちらの向きの外れも同じに扱う。予測が近いかどうかを問う本章にはそれで足りるが、購入の判断には足りない。第8章ではその判断のために範囲を作り、実際に起きた結果に照らして採点する。
実践ルール: 各モデルは、採点対象の時間を履歴に含めずに作った予測で、複数日にわたって採点する。各スコアの根拠となるウィンドウ数と時間数も報告する。モデルの比較は同じウィンドウでのみ行う。MAEとRMSEは併せて読む。どちらのモデルが優れているかについて両者が食い違う場合は、選ぶ前にウィンドウ内の最大の外れを調べる。少数の大きな外れが結果を左右しうるからである。
本番環境で何が問題になるか
上で示した予測とスコアは5通りの仕方で誤りうるが、エラーを出力するものはそのうちの一部にすぎない。カットオフの規則と季節ナイーブの規則は、各ウィンドウが何を含まなければならないかを定めている。
1つ目の失敗は、ラベルが1時間ずれることであり、この章のどのスコアもこれを検出しない。読み手が ds を、その時間の開始ではなく終了とみなした場合、予測も、それを採点する実測値も同じずれを抱えるため、スコアは変わらない。誤りが現れるのは購入の側である。予測は、供給業者が購入の対象とする時間とは別の時間を対象にしてしまう。ラベルはデータカードで固定されているので、予測を新しいデータに移すときは、まずこれを確認する。
リーケージは、予測対象の時間を履歴に含むウィンドウを実際よりよく見せるが、スコアにはそれを示すものが何もない。Hewamalage, Ackermann and Bergmeir (2022)は、ローリングオリジン評価は注意深く行わないとこの漏れを起こしやすいと警告している。ここでの検査は、カットオフの規則と履歴の長さである。各履歴はそのカットオフより前で終わり、1344 行を含まなければならない。history_before は、履歴が短いか長いときにエラーを送出する。1時間を取り除いた履歴は拒否される。季節ナイーブの例の末尾にある検査は、この場合に yes を出力する。
季節ナイーブは昨日をそのままコピーするので、異例の日は翌日の予測になってしまう。そして、ホールドアウトした1週間にはそうした日が1日含まれている。2014年12月25日はクリスマスであり、主要クライアントのその日の平均需要は1時間あたり 38.40 kWh で、12月24日の 47.58 kWh と比べて大きく異なる。12月26日のウィンドウはその日をコピーするため、7つのウィンドウのうち MAE が最大となり、その値は 12.16 kWh である。これが失敗であり、スコアにもそれが表れている。祝日1日では祝日効果を測るには少なすぎるので、事例とそのデータで説明しているとおり、本書はこれには手をつけない。その代償は第10章で示す。
欠測した値は、検査されないまま通り抜ける。statsforecast の季節ナイーブは入力を検査しない。直前の季節の値を繰り返すだけなので、その季節に欠測値があれば、それが欠測した予測になる(予測値の欠測となる)(statsforecast 2.1.1、statsforecast/utils.py、関数 _seasonal_naive)。季節ナイーブの例は欠測した予測を数えており、ここでは 0 である。予測に穴があれば、その時間はスコアが記述しない時間になるからである。第3章では、モデルを実行する前に、補完が必要な時間をカットオフより前のデータから埋める。
最後に、ウィンドウそのものが手法を実際よりよく見せることがある。異例の日がない週では、ほとんどどんな予測でもよく見えうるし、異例の日がある週では、どの予測も悪く見えうる。ホールドアウトした週には祝日が含まれており、それでも1クライアントの1週間にすぎないため、そのスコアが記述するのは手法よりもむしろその週である。対策は幅を持たせることだ。順位を信頼する前に、種類の異なる複数のウィンドウでモデルを比較する。
実践ルール: スコアを信頼する前に、次の3点をこの順に確認する。各ウィンドウの最初の予測時間がそのカットオフであること、各履歴がカットオフより前で終わり履歴の全長を満たしていること、そして欠測した予測がないことである。最初の2つについてはヘルパーがエラーを送出し、3つ目は例が出力する。3つすべてを通過して初めて、スコアは知見として扱える。
この章で下した決定
この章では九つの選択を行った。その多くはexamples/lib/settings.pyの設定であるため、後の版でそのうちの一つを変更すれば、それを使うすべての章に反映される。残りは、データカードまたはこの章で述べている。第2章は、この二つの予測と二つのスコアから出発し、どちらかが行動に移せるほど良いかどうかを問う。
- 各ウィンドウのカットオフは、そのウィンドウが予測する日の 00:00 に置く。予測期間は24時間であり、各ウィンドウはその日1日を対象とする。
- 各カットオフより前の履歴は1344時間であり、これは8週間に当たる。
- 主役のクライアントは
MT_014である。ホールドアウトした週は2014年12月25日から12月31日であり、7個のウィンドウと168時間の採点対象時間からなる。 - スコアは MAE と RMSE であり、これらの採点対象時間全体でプールして、小数第2位まで表示する。
- モデルは、季節の長さを24時間とする季節ナイーブ法と、モデル文字列を
ZZA、季節の長さを24時間とする AutoETS である。いずれの実行も statsforecast を用い、ジョブ数は1である。どちらの点予測も乱数を使わないため、AutoETS の例が慣例として設定するシードは、その予測に影響しない。 - カットでは
MT_223を除外し、30のクライアントを残す。その理由はデータカードで説明している。 - 時計の切り替え(夏時間の変更)に関する行と、遅れて開始したクライアントの行は、そのまま残す。この章で扱う履歴にはそれらが含まれないためである。第3章と第4章で扱う。
- 本文が引用するすべての数値は、その例の記録された出力にあるラベル付きの行に結び付けてある。そのため、本文と出力が気付かれないまま食い違うことはない。
- この章で作るのは1クライアントの予測であり、予測区間は扱わない。予測区間は第8章から始める。
この版における本章
第2026.11.11版2026年11月20日時点で例が通過この章の3 例件のうち3件が合格
英語版の書籍(版2026.11.11)から翻訳した。