予測を運用し続ける

読了まで約43 分分、7 節 節の 5 例 例。

第2026.11.11版 2026年11月20日時点で例が通過 41 例中 41 例が合格 変更点

AIによる翻訳。英語版は人による検証済みである。 当社の書籍の作り方

英語版の書籍(版2026.11.11)から翻訳した。 原文を読む

予測が毎日動くようになると、問いは、予測の成績が良かったかどうかから、実際に使う日にもなお通用するかどうかへと変わる。この章では、その問いに答えるループを組み立てる。予測を一定のスケジュールで再学習し、各日の予測を実測値が存在する前に記録し、その記録が到着済みのデータだけを使っていることを検査し、実測値が入るたびに採点し、バックテストと比べて誤差が不自然な日にフラグを立て、モデルをいつ退役させるべきかを述べる。

懸かっているのは、次の買い付けである。供給事業者は翌日の電力を予測にもとづいて確約するので、誰にも気づかれないまま外れてしまった予測は、その調達で損失を生む。この章はそのリスクをゼロにするものではない。リスクが現れた当日に、そのとき供給事業者が知っていた情報だけを使って、リスクを見えるようにするものである。

これまでの章では、供給事業者の予測を過去のデータで検証した。各手法は、2014年末の最後の数日について、すべての実測値が手元にある状態で事後に採点された。運用では順序が逆になる。供給事業者は、2014年12月29日の電力を、その日の締め切りである12月29日00:00の時点で作った予測から買い付ける。使えるのはその時点で知っている情報だけであり、実際に何が起きたかは1日後に知る。バックテストで通用した予測も、ずれることがある。クライアントが変わる、休日が窓の中に入る、メーターのフィードが数時間止まる、といった場合である。供給事業者は、四半期末のレビューではなく、次の買い付けの前にそれを把握する必要がある。

この章では、2014年の最後の7日間、12月25日から12月31日までのループを回す。各日には、30のクライアントそれぞれについて、その日自身の午前0時の締め切りから作った予測が1つずつある。この章の時刻はすべてデータ時刻である。締め切りはその日の00:00であり、実測値はその1時間の終わりに到着する。判断用の実行と較正用の実行は、それぞれ2014年11月25日と12月9日に始まり、再学習の周期は2014年11月24日(月)を起点とする。これらはいずれも2014年1月16日より後に始まる。1月16日は、開始規則によって30のクライアントすべてが1つのモデルに入る最初の午前0時である。MT_115の最初の実測値は2014年1月14日00:00にあり、規則はそこから48時間分の履歴を必要とする。これは第6章で述べたとおりである。

予測が述べるのは、実測値がこの先どう動くかであって、なぜそう動くかではない。ループが供給事業者に伝えられるのは、需要が予測から離れたということまでである。どの習慣や価格や天候がその動きを引き起こしたのかは伝えられないし、この章もそれを試みない。通用する予測は因果についての主張ではなく、この章のどのフラグも因果の主張に変わることはない。

スケジュールに従った再学習

最終変更:版2026.11.5

再学習(refit)とは、あるカットオフ時点で既知の履歴を用いて、モデルのパラメータを推定し直すことである。再学習と再学習の間、モデルは同じ木を保持する。各予測は、ラグ入力を作るために直近の測定値を読み込むので、木が変わらなくても、予測には直近数時間の状況が反映される。

見落とされやすい点が一つある。mlforecast 1.1.0 は、新しい履歴から予測するたびに、各クライアントのスケーリングを改めて当てはめる。predict に new_df を渡すと、その履歴に対してターゲット変換が当てはめられる(固定したリリースでは forecast.py の 1374 行から 1412 行、core.py の 536 行から 540 行)。したがって、各クライアントの平均と散らばりは、すべてのカットオフで、その時点で既知の履歴から得られ、再学習を待つのは木だけである。この履歴はカットオフ時点で既知であるから、これはリークではない。

この語には一つ注意が必要である。Hyndman と Athanasopoulos の Forecasting: Principles and Practice 第3版(FPP3)では、refit() は、当てはめ済みのモデルを推定し直さずに適用することを指す(FPP3, Chapter 13)。ここでの「再学習」は、木を推定し直すことを意味する。

再学習は、これから予測する測定値を使ってはならない。カットオフ c での再学習が読んでよいのは、c までに届いた測定値だけである。ループはこれを構造上保証している。再学習用の履歴も、すべての予測用の履歴も、カットオフまでに届いた測定値だけを含むので、予測対象の日の実測値がそこに入ることはない。

残る選択は頻度である。ここでは、毎日再学習する場合と、7日ごとに再学習する場合の二つの頻度を検討した。どちらも、毎日それぞれのカットオフから予測し、第6章と同じグローバルモデルを用いる。このモデルは、30クライアントにわたるスケーリング済みの LightGBM 一つで、24時間と168時間のラグ、およびクライアント識別子を入力とする。ここでグローバルモデルを使うのは、判定用の期間で選択できるモデルのうち最良だからである。第9章に記録されたモデルには、この期間の予測がないので、選択の対象にならない。二つの頻度の違いは、木を推定し直す頻度だけである。週次のサイクルは 2014年11月24日(月)を起点とするので、再学習は月曜日、すなわち 11月24日、12月1日、12月8日などに行われる。したがって、実行の再学習日は、実行を開始する日に左右されない。各予測は、カットオフ以前で最も近い月曜日に当てはめたモデルを用いる。

頻度の選択は、通常の4日間の判定用期間、すなわち 2014年11月25日、11月26日、12月2日、12月3日で行う。このいずれもポルトガルの祝日ではなく、ホールドアウトした週は使わない。規則は、これらの期間でMASEの平均が低いほうを採ることである。この章のすべての実行は、第2章の規則に従い、2014年11月25日より前の測定値から読み取った、クライアントごとの一つのスケールを用いる。判定用期間、較正用期間、ホールドアウトした週は、この同じ尺度を共有する。判定用と較正用の履歴は、2014年10月26日の時刻変更をまたいでさかのぼる。ループは、第3章と同じく、その1時台を前後の時間から補う。

両方の頻度を、4日間の判定用期間で実行する。週次のモデルは、この期間では0日から2日前のものなので、0日から6日までの各経過日数のモデルでも、同じ日々を予測する。

refit-cadence-decision.py Python 3.13.16 · holidays 0.110.dev20261118063242 · lightgbm 4.7.0 · mlforecast 1.1.0 · numpy 2.5.5 · pandas 2.3.3 · statsforecast 2.1.1 · utilsforecast 0.2.17 合格
"""Choose the refit cadence on the four decision days, Nov 25 to Dec 3, 2014: a refit every day or every seven days onMondays, with the global model from Chapter 6. The cadence with the lower `mean MASE` line is the one the rule takes, andthe `model aged` lines show how far a model's age alone moves that score. The held-out week is not used."""import pandas as pdfrom lib.electricity import loadfrom lib.panel import ALL30from lib.running import DECISION_DAYS, daily_mase, feed, fit_at, forecast_at, prepare, run_days, scale_from, with_actualsfrom lib.settings import showraw = load(ALL30)df = prepare(raw)scale = scale_from(raw)  # one MASE scale, read before Nov 25, used by every run in the chaptershow("decision days", len(DECISION_DAYS))# feed returns (train, known, pending count, read_by); [0] is trainshow("rows read by one refit", len(feed(df, DECISION_DAYS[0])[0]))names = {1: "daily", 7: "weekly"}  # the keys are the refit interval in daysmeans = {}for every in names:    scored = with_actuals(run_days(df, DECISION_DAYS, refit_every=every), df)  # refit_every: a refit every this many days    means[every] = daily_mase(scored, scale).mean()  # the mean over the four decision days of each day's MASE    show(f"refits, {names[every]}", scored["refit"].nunique())  # the distinct refit days the decision days use    show(f"MAE, {names[every]}", scored["ae"].mean())    show(f"mean MASE, {names[every]}", means[every], digits=3)show("mean MASE, daily minus weekly", means[1] - means[7], digits=3)  # positive when the weekly cadence has the lower meanshow("chosen cadence", names[min(means, key=means.get)])  # the lower mean wins; the close-call tie-break is made in the prosemodels = {}for age in range(7):    parts = []    for day in DECISION_DAYS:        fit_day = day - pd.Timedelta(days=age)  # a model aged `age` days, fitted that many days before the decision day        if fit_day not in models:  # a model is fitted once and reused by every decision day it serves            models[fit_day] = fit_at(df, fit_day)[0]  # fit_at returns (model, read_by); [0] is the model        # forecast_at returns (forecast, pending count, read_by); the first is the forecast        part, _, _ = forecast_at(models[fit_day], df, day)        parts.append(part.assign(cutoff=day))  # daily_mase groups each forecast by its cutoff    show(f"mean MASE, model aged {age} days", daily_mase(with_actuals(pd.concat(parts), df), scale).mean(), digits=3)
出力python refit-cadence-decision.py
decision days: 4
rows read by one refit: 40320
refits, daily: 4
MAE, daily: 66.81
mean MASE, daily: 0.754
refits, weekly: 2
MAE, weekly: 67.64
mean MASE, weekly: 0.746
mean MASE, daily minus weekly: 0.008
chosen cadence: weekly
mean MASE, model aged 0 days: 0.754
mean MASE, model aged 1 days: 0.747
mean MASE, model aged 2 days: 0.748
mean MASE, model aged 3 days: 0.741
mean MASE, model aged 4 days: 0.748
mean MASE, model aged 5 days: 0.758
mean MASE, model aged 6 days: 0.750

判定用期間では、週次の頻度のほうが MASE の平均が低く、その差は 0.008 である。しかも、この4日間で必要な当てはめの回数は半分で、日次では再学習が 4 回、週次では 2 回である。1回の再学習は 40320 行を読み込む。これは30クライアントに1,344時間の履歴を掛けた数である。運用では、週次の頻度なら当てはめは7分の1で済む。

経過日数が6日までのモデルは、判定用期間で新しいモデルに近い成績を示す。経過日数の確認が主張するのはそこまでである。MASE の平均は、0日から6日のうち最も低い、3日経過の 0.741 から、最も高い、5日経過の 0.758 までの範囲にあり、新しいモデルは 0.754 である。経過日数に傾向は見られず、7通りの経過日数全体での散らばりは、二つの頻度の差より大きい。この差は小さく、4日間では二つの頻度を区別できないので、この例は週次のほうが優れていることを示すものではない。より大きなモデルや、より長い予測期間を扱う読者は、自分の判定用期間で同じ確認を行うべきである。

規則は、平均が低いことを理由に週次を選ぶ。ただし、その差はモデルの経過日数だけで生じる散らばりの内側にあり、二つの頻度は近い。近い場合、実践ルールは再学習の回数が少ないほうを採るので、本書もここでそう述べる。採るのは週次である。

実践ルール: 再学習の頻度は、ホールドアウトした週より前の通常の日々で選び、それらの最初の日より前に読み取った一つのスケールで採点する。MASE の平均が低いほうの頻度を採り、二つが近い場合は、再学習の回数が少ないほうを採り、そのことを明記する。予測する日の測定値で再学習してはならない。

この部分はまだ翻訳されていないため、英語で表示している。

Log every forecast before its actuals arrive

最終変更:版2026.11.5

A forecast log is a table with one row for each client and hour. Each row holds the cutoff the forecast was made at, the time the row was written, the client, the hour, the forecast, its lower and upper bounds, the refit day of the model, two arrival times described below, and the count of readings filled for that forecast. The log has one job. It proves what the forecast said at the time, and what the loop could see when it said it. Without it, nobody can tell whether a later report used the forecast that was made, or a forecast rebuilt afterwards from a newer model and the actuals. A rebuilt log is leakage in disguise, because it knows what the forecast should have been.

The band in each row is built the way Chapter 8 builds one. It is the forecast plus the scaled residuals of the same hour, taken from the calibration windows, Dec 9 to Dec 20, 2014. They come before every held-out day and are fixed before the week begins. Each hour's residuals are pooled over the thirty clients, so each hour has 360 of them, not twelve. Chapter 8's client bands pool the same residuals and are offered at 95% as well. This loop logs the 80% level only, because the retirement trigger in the last section reads the 80% band, and one level keeps the log and the trigger in step. The band is computed from the logged forecast and the fixed calibration residuals, so it needs no reading from the day it covers.

A log proves less than it appears to unless its checks can fail. The rule is that a model and a forecast read only readings that had arrived by the time they were made. The log therefore records two arrival times for each row. fit_read_by is the last arrival among the readings the model was fitted on, and it must be no later than the model's refit day. read_by is the last arrival among the readings the forecast read, and it must be no later than the cutoff. A comparison of written_at with the arrival of a reading would not test this. The replay writes written_at as the cutoff, so that comparison passes for any code. In production, written_at would come from the append-only store's clock. A replay can only label it. Both checks run on every row of the held-out week, and the model's check runs again on a deliberately leaky week, which it must catch.

rolling-refit-seven-days.py Python 3.13.16 · holidays 0.110.dev20261118063242 · lightgbm 4.7.0 · mlforecast 1.1.0 · numpy 2.5.5 · pandas 2.3.3 · statsforecast 2.1.1 · utilsforecast 0.2.17 合格
"""Runs the held-out week, Dec 25 to Dec 31, 2014: one forecast a day from its own midnight cutoff, with the weekly refitcycle and the late-data fill, each logged when it is made. The `log rows` lines show both arrival checks pass, and theleaky run fails the first. The `MAE` and `coverage 80` lines give each day's mean absolute error and how often its 80%band held. The 80% bands use calibration days Dec 9 to Dec 20, 2014, earlier than every scored day."""import pandas as pdfrom lib.electricity import loadfrom lib.panel import ALL30from lib.running import CAL_DAYS, HELD_OUT_DAYS, REFIT_EVERY, band, coverage_by_day, prepare, run_days, scale_from, with_actualsfrom lib.settings import showraw = load(ALL30)df = prepare(raw)scale = scale_from(raw)cal = with_actuals(run_days(df, CAL_DAYS), df)  # the residuals that set the bands, from days earlier than the weekbands = band(with_actuals(run_days(df, HELD_OUT_DAYS), df), cal, scale)# leak=True refits each day's model on the next day's readingsleaky = with_actuals(run_days(df, HELD_OUT_DAYS, leak=True), df)# refit dates in the week; the Dec 22 refit is dated before itin_week = sorted({d for d in bands["refit"] if d >= HELD_OUT_DAYS[0]})show("refit every (days)", REFIT_EVERY)show("refit days in the week", ", ".join(f"{d:%Y-%m-%d}" for d in in_week))show("models used in the week", bands["refit"].nunique())show("log rows", len(bands))# hour 0 holds 12 calibration days times 30 clientsshow("calibration residuals per hour, pooled over clients", cal.dropna(subset=["e"]).groupby("hour").size().iloc[0])# a model may read only readings that had arrived by its refit dayshow("log rows whose model read only readings in by its refit day", int((bands["fit_read_by"] <= bands["refit"]).sum()))# a forecast may read only readings that had arrived by its cutoffshow("log rows whose forecast read only readings in by its cutoff", int((bands["read_by"] <= bands["cutoff"]).sum()))show("leaky log rows whose model read only readings in by its refit day", int((leaky["fit_read_by"] <= leaky["refit"]).sum()))# a reading arrives at the end of its hour, so any other arrival is lateshow("readings that arrived late", int((bands["arrives"] != bands["ds"] + pd.Timedelta(hours=1)).sum()))# every row of a cutoff has the same count, so the first row gives itshow("forecast inputs filled, Dec 29", int(bands.loc[bands["cutoff"] == "2014-12-29", "filled"].iloc[0]))# the last of Dec 28's readings to arrivedone = bands.loc[bands["cutoff"] == "2014-12-28", "arrives"].max()show("Dec 28 complete at", f"{done:%H:%M on %b %d, %Y}")mae = bands.groupby("cutoff")["ae"].mean()cov = coverage_by_day(bands)for day in mae.index:    show(f"MAE {day:%Y-%m-%d}", mae[day])for day in cov.index:    show(f"coverage 80 {day:%Y-%m-%d}", cov[day], digits=3)show("leaky MAE 2014-12-25", leaky.loc[leaky["cutoff"] == "2014-12-25", "ae"].mean())
出力python rolling-refit-seven-days.py
refit every (days): 7
refit days in the week: 2014-12-29
models used in the week: 2
log rows: 5040
calibration residuals per hour, pooled over clients: 360
log rows whose model read only readings in by its refit day: 5040
log rows whose forecast read only readings in by its cutoff: 5040
leaky log rows whose model read only readings in by its refit day: 0
readings that arrived late: 6
forecast inputs filled, Dec 29: 6
Dec 28 complete at: 09:00 on Dec 29, 2014
MAE 2014-12-25: 447.59
MAE 2014-12-26: 203.43
MAE 2014-12-27: 54.14
MAE 2014-12-28: 71.67
MAE 2014-12-29: 111.64
MAE 2014-12-30: 87.37
MAE 2014-12-31: 167.15
coverage 80 2014-12-25: 0.232
coverage 80 2014-12-26: 0.431
coverage 80 2014-12-27: 0.790
coverage 80 2014-12-28: 0.764
coverage 80 2014-12-29: 0.713
coverage 80 2014-12-30: 0.782
coverage 80 2014-12-31: 0.701
leaky MAE 2014-12-25: 351.79

The log has 5040 rows, one for each of thirty clients' 24 hours on seven days, and 5040 pass the model's arrival check, and 5040 pass the forecast's. The week uses two models. The one fitted on Monday, Dec 22, serves Dec 25 to Dec 28, and the one refitted on Monday, Dec 29, serves Dec 29 to Dec 31, so the refit falls inside the week.

A check that never fails tells you little, so the week also runs with a leak. In that run, each day's model is refitted on the next day's readings, so it has seen the day it forecasts, and the model's check fails for every row: 0 rows pass. The leak also flatters the forecast. Its MAE on Dec 25 is 351.79 kWh, against 447.59 kWh for the honest run. The check is the thing to keep. An edit that moves a refit onto the next day's readings turns the printed count to zero, and the recorded output then fails.

Working rule: Write each forecast's rows at its cutoff, from the readings that have arrived by then, with the refit day and both arrival times beside them. Never rebuild a past log from a newer model or from the actuals. If a day's rows are lost, mark that day as missing in the log, and do not fill it in afterwards.

実績が届くたびにログを採点する

最終変更:版2026.11.11

読み取り値は、届いた時点で、その時刻についてログに記録された予測を採点する。1日のスコアは、その日の日次 MASE である。日次 MASE は、各クライアントについて1日24時間の平均絶対誤差を求め、それをそのクライアントのスケールで割り、30クライアントにわたって平均したものである。

daily MASE = mean over clients of (MAE over the day's 24 hours / scale)

スケールは再学習の節で定めたものであり、2014年11月25日より前のデータから読み取ったものである。このスケールは日ごとに変わらない。読み取り値は、その値自身の日のスコアに入り、しかも届いたあとにだけ入る。したがって、スコアは、供給者がその時点で持っていなかった値を使うことがない。これはログの節で述べたリーク防止規則の後半にあたる。1日は、その最後の読み取り値が届いた時点で採点する。12月29日の場合は、12月30日の0時00分である。

ほとんどの日は欠けることなく届く。しかし、評価用に取り分けた1週間には、そうでない日が1日ある。先頭クライアントの2014年12月28日の最後の6つの読み取り値(18時00分から23時00分まで)は、12月29日の9時00分に届く。これは12月29日の予測時刻から9時間後であり、12月29日の予測はそれらなしで作らなければならない。この場合の規則は本書独自の選択であり、これを裏づける出典はない。

  • 予測時刻の時点で届いていない読み取り値は、その日の再学習から除外する。
  • その予測時刻における予測では、欠けた値を、届いている1週間前の同じ時刻の読み取り値で埋める。ログには、埋めた値の個数を記録する。
  • 読み取り値が届いても、予測はやり直さない。
  • 読み取り値は届いた時点で採点し、その日は最後の読み取り値が届いた時点で採点する。

最初に試したのは、欠損値をそのまま残す方法であった。ライブラリはこれを受け付けなかった。固定されたバージョンである 1.1.0 では、予測を作る際に次のエラーが出た。

ValueError: y column contains null values.

欠けた部分を埋める方法は2つある。前方補完は、届いた最後の読み取り値を繰り返す。先頭クライアントの18時00分から23時00分の値がすべて17時00分の値になるため、夕方が平坦になり、ラグ24がその平坦な夕方を翌日の夕方の予測に持ち込む。1週間前の同じ時刻で埋める方法は、夕方の形を保つ。補完方法は、評価用の1週間ではなく、判断用の期間で選んだ。そこでは、各判断時刻の前に同じ6つの読み取り値を遅れたものとし、両方の補完でそこから予測する。

late-fill-decision.py Python 3.13.16 · holidays 0.110.dev20261118063242 · lightgbm 4.7.0 · mlforecast 1.1.0 · numpy 2.5.5 · pandas 2.3.3 · statsforecast 2.1.1 · utilsforecast 0.2.17 合格
"""Chooses how a late reading is filled on the decision windows, Nov 25 to Dec 3, 2014: the lead client's last six readingsof the day before arrive at 09:00 on each cutoff day, as the Dec 28 readings do in the held-out week. The`MAE, lead client hours 18 to 23` lines decide between forward fill and a fill from the same hour a week earlier; onlythose hours change, because lag 24 reads them, and the held-out week is not used."""import pandas as pdfrom lib.electricity import loadfrom lib.panel import ALL30from lib.running import DECISION_DAYS, LATE_CLIENT, feed, late_copy, prepare, run_days, with_actualsfrom lib.settings import showraw = load(ALL30)df = prepare(raw)# feed returns (train, known, pending count, read_by); [2] is the pending countshow("readings late for each decision cutoff", feed(late_copy(df, DECISION_DAYS[0]), DECISION_DAYS[0])[2])errors = {}for rule in ("forward", "week"):    parts = []    for day in DECISION_DAYS:        # the day before's last six readings arrive at 09:00 on this day, after its cutoff, so the fill applies        scored = with_actuals(run_days(late_copy(df, day), [day], fill=rule), df)        # 18:00 to 23:00 of the day scored, which lag 24 reads from the day before        parts.append(scored.loc[(scored["unique_id"] == LATE_CLIENT) & (scored["hour"] >= 18), "ae"])    errors[rule] = pd.concat(parts).mean()    show(f"hours scored, {rule} fill", len(pd.concat(parts)))    show(f"MAE, lead client hours 18 to 23, {rule} fill", errors[rule])show("chosen late fill", min(errors, key=errors.get))
出力python late-fill-decision.py
readings late for each decision cutoff: 6
hours scored, forward fill: 24
MAE, lead client hours 18 to 23, forward fill: 7.92
hours scored, week fill: 24
MAE, lead client hours 18 to 23, week fill: 5.03
chosen late fill: week

2つのうち、1週間前で埋める方法のほうが精度が高い。先頭クライアントの18時00分から23時00分の時刻について、24の予測時間にわたる平均絶対誤差は、1週間前で埋める場合が 5.03 kWh、前方補完の場合が 7.92 kWh である。本書では、すべての実行でこの補完を用いる。

評価用の1週間は、この規則が実際に働く様子を示す。遅れて届いた読み取り値は6件であり、12月29日の予測では6個の入力を埋めた。12月29日の再学習では同じ6つの読み取り値を除外したので、読み取り値を再学習から除外する分岐は、この週にも実行される。12月28日は09:00 on Dec 29, 2014の時点で完全にそろった。

1日分の MAE だけでは、その日が悪かったのかどうかは分からない。需要の水準は日ごとに変わるからである。次の節のフラグが基準値で割るのは、このためである。

実践ルール: 各日は、その最後の読み取り値が届いた時点で、予測時刻にログに記録された予測に対して、章で用いる唯一のスケールを使って採点する。読み取り値が遅れて届いたときは、その時点で採点し、ログに数え、記録済みの予測には手を加えない。予測時刻のあとに予測を変更してはならない。変更によってスコアが良くなる場合でも同様である。

バックテストに対するドリフトの検出

最終変更:版2026.11.5

前の節で求めた日次スコアには、ある日が基準から外れていることを示す線が必要である。フラグは、その日についての問いであり、判定ではない。この規則が問うのは、ある日の日次 MASE が、それ以前のモデルの挙動から外れているかどうかである。日次 MASE が基準値の2倍を上回った日にフラグを立てる。基準値は、較正ウィンドウ(2014年12月9日から12月20日)の日次 MASE の中央値である。これらの日は、フラグが判定するどの日よりも前にある。これらの日のどれもポルトガルの祝日ではない。ただし、12月9日のラグ24の読み取り値は12月8日にさかのぼり、この日は国民の祝日である無原罪の御宿り(Imaculada Conceição)にあたる。この影響は1日分であり、中央値がそれを和らげる。

2という係数は、本書の経験則である。この種のフラグについて公表された閾値を私たちは知らないので、この数値は私たち独自のものであり、そのように明記する。この値は決定ウィンドウで確認した。そこでは、4日分の通常の日が、既知の原因がないのにフラグが立つかどうかを試すことになる。

drift-flag-rolling.py Python 3.13.16 · holidays 0.110.dev20261118063242 · lightgbm 4.7.0 · mlforecast 1.1.0 · numpy 2.5.5 · pandas 2.3.3 · statsforecast 2.1.1 · utilsforecast 0.2.17 合格
"""Flags drift against the backtest: a day is flagged when its daily MASE is above FLAG_FACTOR times the reference, themedian daily MASE of the calibration days, Dec 9 to Dec 20, 2014, which are earlier than the held-out week. The`largest decision day` and `decision days flagged` lines show the ordinary days staying under the line, and the `MASE`and `held-out days flagged` lines show which held-out days cross it."""from lib.electricity import loadfrom lib.panel import ALL30from lib.running import (CAL_DAYS, DECISION_DAYS, FLAG_FACTOR, HELD_OUT_DAYS, daily_mase, flagged, prepare, run_days,                         scale_from, with_actuals)from lib.settings import showraw = load(ALL30)df = prepare(raw)scale = scale_from(raw)reference = daily_mase(with_actuals(run_days(df, CAL_DAYS), df), scale).median()  # the median, not the mean, so one unusual calibration day moves it littleshow("reference, median daily MASE", reference)show("flag above, MASE", FLAG_FACTOR * reference)  # FLAG_FACTOR is 2, the chapter's rule of thumbdecision = daily_mase(with_actuals(run_days(df, DECISION_DAYS), df), scale)show("largest decision day, times the reference", decision.max() / reference)show("decision days flagged", len(flagged(decision, reference)))held = daily_mase(with_actuals(run_days(df, HELD_OUT_DAYS), df), scale)for day, value in held.items():    show(f"MASE {day:%Y-%m-%d}", value)show("held-out days flagged", len(flagged(held, reference)))show("flagged held-out days", ", ".join(f"{day:%Y-%m-%d}" for day in flagged(held, reference)))
出力python drift-flag-rolling.py
reference, median daily MASE: 0.72
flag above, MASE: 1.43
largest decision day, times the reference: 1.44
decision days flagged: 0
MASE 2014-12-25: 4.62
MASE 2014-12-26: 2.00
MASE 2014-12-27: 0.73
MASE 2014-12-28: 0.76
MASE 2014-12-29: 0.85
MASE 2014-12-30: 0.76
MASE 2014-12-31: 1.14
held-out days flagged: 2
flagged held-out days: 2014-12-25, 2014-12-26

係数2では、通常の決定日にフラグは立たない(フラグが立った日は0日)。最大の決定日は基準値の1.44倍である。1.5のようにもっと小さい係数にすると、その日との余裕がほとんどなくなり、わずかに普段と異なる通常の日にフラグが立つ可能性がある。余裕を考えて2を採用した。通常の日が4日だけでは、通常の日にどのくらいの頻度でフラグが立つかは示せない。

保持した7日のうち2日が線を超えており、それは12月25日と12月26日である。これらの日次 MASE は4.62と2.00であり、フラグの線は1.43である。次に高いのは大晦日の12月31日だが、線を下回っている。

どちらのフラグにも既知の原因がある。12月25日はクリスマスであり、ポルトガルの祝日である。モデルには祝日の入力がない。第5章では、部分集合の決定ウィンドウでカレンダー列と祝日列を試し、祝日の列もその中に含めたが、単純なラグを上回るものはなかった。そのため第6章では、グローバルモデルにそれらを与えなかった。12月26日はポルトガルでは祝日ではないが、そのラグ24の読み取り値は12月25日である。12月26日の各時刻の予測は、12月25日の同じ時刻を読むので、祝日のパターンが翌日に持ち越される。これらはカレンダー効果であって、ドリフトではないが、ループはその違いを見分けられない。ループは日にフラグを立てるだけである。人が各フラグを読み、カレンダーを確認する。

1日だけでは判定にならない。1日だけ高くなる原因には、祝日、嵐、誤って入力された読み取り値などがある。カレンダー上の原因がないまま2日続けてフラグが立った場合は、モデルを調べる理由になる。そのときに何をするかは次の節で述べる。

実践ルール: 日次 MASE が、それ以前の較正ウィンドウの中央値の2倍を上回った日にフラグを立て、その上でカレンダー上の原因によって説明できるかどうかを問う。原因がある場合は、フラグの横にその原因を記録する。説明のつかないフラグが2日続いた場合は、モデルを退役させるかどうかの確認の始まりとして扱い、モデルが壊れているという証拠とは決してみなさない。

モデルを退役させる時期を見極める

最終変更:版2026.11.11

モデルの退役とは、そのモデルの使用を止めて別のモデルに置き換えることである。再学習はそれより軽い対応であり、先に検討する。この章では、どちらの対応にも使える三つの引き金を挙げる。いずれも、ループがすでに記録している数値を読むものである。一つ目の退役の引き金は持続的なドリフトである。これは、暦上の原因がないまま、連続する日にフラグが立つ状態を指す。二つ目の退役の引き金は、予測帯がカバーしていない状態である。80%予測帯が、数日にわたって観測値の80%をかなり下回る割合でしか覆わない場合がこれに当たる。三つ目は、モデルが依存するライブラリの変更である。

二つ目の引き金を使うには、通常のカバレッジがどの程度かを知っておく必要がある。通常の日、すなわち12月27日から12月31日までは、80%のカバレッジは0.701から0.790の間に収まっている。遅れた観測値が届く12月29日と、大晦日の12月31日も、ここでは通常の日に数える。12月25日は0.232とそれより低く、12月26日は0.431である。理由はフラグが示したとおりで、12月25日は祝日であり、12月26日はそれをラグ24を通して読み取るからである。第8章で見たように、予測帯は通常の日でもやや狭い。したがって、ここでは0.70から0.80の間の日は正常であり、それをはるかに下回る日は正常ではない。

フラグと予測帯が何を捉えるかを示すために、この章では変化を人為的に起こす。これは検証のために作ったもので、供給元のデータに関する事実ではない。2014年12月27日以降、30クライアントすべての観測値に0.6を掛ける。需要が40%落ち込んだかのような状況である。その後、保留した1週間を、変化後の観測値で実行する。再学習の頻度、基準、規則、予測帯は、これまでと同じである。

drift-after-a-change.py Python 3.13.16 · holidays 0.110.dev20261118063242 · lightgbm 4.7.0 · mlforecast 1.1.0 · numpy 2.5.5 · pandas 2.3.3 · statsforecast 2.1.1 · utilsforecast 0.2.17 合格
"""Shows how a change appears in the flags: a stated test, not a fact about the data, in which every reading from Dec 27,2014 is multiplied by 0.6, as if demand had dropped by 40%. The calibration windows are earlier than the change, so thereference and bands are fixed before it happens. The `held-out days flagged` and `coverage 80` lines show what the flagsand bands do, with the same cadence, reference, rule and bands as the held-out runs in drift-flag-rolling androlling-refit-seven-days."""import pandas as pdfrom lib.electricity import loadfrom lib.panel import ALL30from lib.running import (CAL_DAYS, HELD_OUT_DAYS, band, coverage_by_day, daily_mase, flagged, prepare, run_days,                         scale_from, with_actuals)from lib.settings import showraw = load(ALL30)df = prepare(raw)scale = scale_from(raw)cal = with_actuals(run_days(df, CAL_DAYS), df)  # calibration windows come before the change, so the reference is fixed before itreference = daily_mase(cal, scale).median()changed = df.copy()after = changed["ds"] >= pd.Timestamp("2014-12-27")  # the first changed day, Dec 27, from its midnight onchanged.loc[after, "y"] = changed.loc[after, "y"] * 0.6  # a stated test: every reading from Dec 27 at 60%, as if demand fell 40%held = with_actuals(run_days(changed, HELD_OUT_DAYS), changed)  # the changed readings go through the same loop, refits includedshow("reference, median daily MASE", reference)mase = daily_mase(held, scale)for day, value in mase.items():    show(f"MASE {day:%Y-%m-%d}", value)show("held-out days flagged", len(flagged(mase, reference)))cov = coverage_by_day(band(held, cal, scale))  # the bands use the unchanged calibration days, as in the held-out runfor day, value in cov.items():    show(f"coverage 80 {day:%Y-%m-%d}", value, digits=3)
出力python drift-after-a-change.py
reference, median daily MASE: 0.72
MASE 2014-12-25: 4.62
MASE 2014-12-26: 2.00
MASE 2014-12-27: 4.74
MASE 2014-12-28: 2.93
MASE 2014-12-29: 1.68
MASE 2014-12-30: 1.78
MASE 2014-12-31: 1.89
held-out days flagged: 7
coverage 80 2014-12-25: 0.232
coverage 80 2014-12-26: 0.431
coverage 80 2014-12-27: 0.078
coverage 80 2014-12-28: 0.179
coverage 80 2014-12-29: 0.328
coverage 80 2014-12-30: 0.328
coverage 80 2014-12-31: 0.333

保留した7日はすべてフラグが立つ。12月25日と12月26日は、これまでと同じくクリスマスとその余波によるフラグである。変化の最初の日である12月27日以降も、毎日フラグが立つ。12月27日の日次MASEは4.74で、この日のカバレッジは0.078に落ち、1週間で最低となる。

予定された再学習を1回行っても、フラグは消えなかった。12月29日(月)の再学習は、この検証で変化後の観測値を使って再学習する唯一の段階であり、12月27日と12月28日を低い水準で読み取った。日次MASEは12月28日の2.93から12月29日の1.68へ約40%下がったが、12月30日と12月31日は基準線を上回ったままだった。カバレッジは12月29日に0.328、12月31日に0.333へ回復したが、80%にはなお遠く及ばない。

このようなフラグの連続が、これほど低いカバレッジとともに現れた場合は、早期の再学習を行う根拠になる。本書の規則も、早期に再学習することである。ただし、早期の再学習を独立した1日で検証してはいない。したがってこの規則は経験則であり、測定された結果ではない。

三つ目の引き金はライブラリの変更である。ライブラリは頻繁にリリースされ、後のリリースでは、コードが同じでも出力が変わることがある。このループは、mlforecast 1.1.0とlightgbm 4.7.0に依存している。第9章で1.5.0に固定したProphetはこのループには含まれないが、同じく固定されたライブラリの一つであり、そのリリース履歴を見れば、この種のライブラリがどれほどの頻度で更新されるかがわかる(PyPIのリリース履歴)。リリースは、この章の検査をやり直す理由になる。しかし、それだけでモデルを退役させる理由にはならない。

ここで挙げた検査は、予測ログ、フラグ、予測帯のカバレッジである。これらは監視システムではない。監視システムは、アラート、ダッシュボード、多数のフィードにわたるデータ品質、そして対応する人員までを含む。本番環境でのモデル監視を扱う後続の書籍で、この事例を続けることができる。この章は、その書籍が始まるところで終わる。

実践ルール: 暦上の原因がないままフラグが数日続けて立つとき、または80%予測帯のカバレッジが数日にわたって80%を大きく下回るときは、早期に再学習し、その引き金をログとともに記録する。早期の再学習でフラグが消えない場合は、モデルを退役させる。固定したライブラリがリリースされたら、この章の検査をやり直し、新しいバージョンで検査に通るまでは固定を維持する。

本番で起こる問題

フィードは、履歴の途中で止まることがある。ループは、フィードが届けなかった読み取り値を補完しない。途中に欠損があると、すべてのラグがずれてしまう。そのためコードは、代わりにエラーを送出する。補完されるのは、時計の切り替えによる時間帯だけであり、これは第3章の規則による。履歴の末尾でまだ欠けている読み取り値は別の扱いであり、遅延データの規則が処理する。

再学習がリークを起こすことがある。再学習が、これから予測する日の読み取り値を読んでしまうと、バックテストはライブ運用よりも良い結果に見える。この場合、同じ日についてライブの MASE がバックテストの MASE を大きく上回ることで気づくことになる。ループは履歴の規則によってこれを防いでおり、ループを書き直すときに残すべきものはこの規則である。第3章のリークチェックであるシフトテストと、第7章の汚染チェックも残す。汚染チェックは、カットオフ以降のすべての読み取り値に誤った値を上書きし、そのカットオフでの再学習と予測が変化しないことを確認する。

30 クライアントの平均に対するフラグは、1 つのクライアントの変化を覆い隠すことがある。1 つのクライアントに大きな変化があっても、日次 MASE が動く量は、そのクライアントの日次 MASE の変化を 30 で割った分にとどまる。ストレスの例ではすべてのクライアントを同時に動かすので、フラグが作動する。1 つのクライアントだけに変化を与える試験は行わなかった。この場合は、そのクライアント自身の MASE が較正時の中央値を大きく上回ることで気づくことになる。これが最初に埋めたい欠落であり、各クライアント自身の MASE に対する第2のフラグを設けることが考えられる。

固定したライブラリでも、固定するバージョンを更新すると挙動が変わることがある。採点の節のヌル値エラーは、mlforecast 1.1.0 の挙動である。後のバージョンでは、欠損を補完する、除外する、または受け入れるかもしれず、その場合は予測が変わる。固定バージョンの更新は予測の変更であり、チェックを再度実行する必要がある。

最後の失敗は、事後に書かれるログである。例の中には、チームが後からログを作り直すことを妨げるものは何もなく、作り直した出力は正しそうに見える。これを明らかにするのが、2 つの到着列とそれらのチェックである。これらのチェックを取り除くと、ログは何も証明しなくなる。

実践ルール: すべての実行で 3 つのチェックを維持する。各再学習と各予測から未来を締め出す履歴の規則、ログの各行に対する 2 つの到着チェック、そして第3章と第7章のリークチェックである。これらのいずれかが失敗したときは、ループを止め、次の予測の前に原因を修正する。履歴やログを手作業で修復してはならない。手作業による修復は、まさにチェックが検出するために存在する種類の変更だからである。

この章で下した判断

最終変更:版2026.11.5
  • 再学習の頻度: 7日ごと、月曜日に行う。判断用の窓では、週次のほうが平均 MASE が低く、その差は 0.008 であった。この差は、モデルの経過日数だけで生じるばらつきの範囲内にある。そのため同点時の規則を適用し、本書は再学習の回数が少ないほうの頻度を採る。
  • MASE のスケールは一つ: 2014年11月25日より前の読み取り値から求め、この章のすべての実行で用いる。これは第2章の規則に従っている。したがって、判断日、較正用の窓、保留した日は一つの物差しで採点され、採点対象の時間帯はいずれもこの物差しの設定に寄与していない。
  • フラグの規則: 較正用の窓(2014年12月9日から12月20日)の日次 MASE の中央値の2倍を超えた日にフラグを立てる。係数の2は、根拠を明示した経験則であり、通常の判断用の窓に対する余裕があることから採用している。
  • 予測帯: 80% のみとする。廃止の判断基準がこの水準を読むためである。第8章は 95% も扱っている。予測帯には、12個の較正用の窓から得た、同じ時間帯のスケール済み残差を30顧客でプールしたものを用い、保留した週の前に固定する。合計の予測、合計の予測帯、購入の分位点は記録しない。そのため、このログが検査するのは顧客ごとの予測であり、第8章が合計に対して行う購入の判断ではない。合計に対して購入する供給者は、その分位点をログに加えることになる。
  • 遅れて届く読み取り値: 再学習からは除外する。予測では1週間前の同じ時間帯の値で補完し、ログに件数を記録し、届いた時点で採点する。予測のやり直しには決して使わない。補完の方法は判断用の窓で選んだ。この規則には出典がなく、本書独自のものである。
  • 範囲: 30顧客について7日間を対象とする。1週間には、祝日、遅れて届く読み取り値、その週の内側に入る週次の再学習が含まれるため、各規則が働く様子を確認できる。より長い期間で実行すれば、通常の日にフラグが立つ頻度を測れるが、この章ではそれを測らない。
  • 監視の範囲: この章の検査のみとする。それらを時間をかけて見守る監視システムは、本書の対象外である。
  • 読者自身の事例: 本書の最後の判断は、作業を読者に引き渡すことである。供給者の事例はここで終わる。週次の再学習、各予測が読んだ内容を検査するログ、読み取り値が届くたびに行う採点、バックテストに対するフラグである。読者の事例では、これらの判断を自分のデータでやり直す必要がある。再学習の頻度は通常の判断用の窓で、遅れて届くデータの規則は実際に受け取るフィードで、フラグの係数は較正用の窓で、予測帯の水準は購入の規則が必要とするもので決める。いずれも、保留する週より前の日を使って決めること。

この版における本章

第2026.11.11版2026年11月20日時点で例が通過この章の5 例件のうち5件が合格

英語版の書籍(版2026.11.11)から翻訳した。

この節を引用する

形式

いずれの形式も、本訳書が従う英語版の書籍を出典として示す。

いずれの形式もこの版を明示している。そのリンクは現行版を開き、節の見出しには本文が最後に変更された日付が示される。アクセス日と取得日は、これを開いた日である。

このページの内容

全10章中の第10章: 予測を運用し続ける

  1. スケジュールに従った再学習
  2. Log every forecast before its actuals arrive
  3. 実績が届くたびにログを採点する
  4. バックテストに対するドリフトの検出
  5. モデルを退役させる時期を見極める
  6. 本番で起こる問題
  7. この章で下した判断

ページの先頭に戻るすべての章