1つのモデルで多数のクライアントを予測する

読了まで約52 分分、7 節 節の 4 例 例。

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

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

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

この章を終えると、30クライアント全体に対する1つのグローバルモデル、開始が遅いクライアントの先頭のゼロをモデルに入れないための開始規則、そして同じカットオフでクライアントごとにこのモデルを季節ナイーブ予測と並べて比較するスコアが手に入る。供給事業者の翌日分の購入量は合計値であり、第7章が30クライアントの予測から組み立てる。クライアントごとにモデルを作る場合は、ウィンドウごとに、クライアント1つにつき1回、計30回の学習が必要になる。クライアントは日周のリズムを共有しているので、全クライアントで学習した1つのモデルは、そのリズムを一度だけ学習すればよい。

第5章では、SUBSET8の8クライアントでモデルを学習した。30クライアント全体で1つのモデルを学習する際には、そのスコアを信頼できるかどうかを左右する3つの選択が生じる。モデルにクライアント識別子を与えるかどうか、開始が遅い3つのクライアント(データの途中でメーターの記録が始まるクライアント)をどう扱うか、30の予測を1つの尺度でどう採点するか、である。この章は4つの例で進める。各例はまず件数を出力するので、誤差を読む前に、モデルが対象とすべきクライアントを網羅していたかを確認できる(誤差を読む前に)。

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

One model for many clients

最終変更:版2026.11.5

Montero-Manso and Hyndman (2021), in Principles and algorithms for forecasting groups of time series: Locality and globality, show that a global model is no more restrictive than a local one, because both can produce the same forecasts. They compare global methods, which fit one model across a group of series, with local methods, which fit each series on its own. A global model fits one set of parameters to many series in a single pass, so every client contributes to what it learns. Their abstract starts from the view that for groups of similar series, global methods outperform the more established local methods, and it notes that later results in that literature show good performance of global models even in heterogeneous datasets. It also reports that global linear models can give competitive accuracy with two orders of magnitude fewer parameters than local methods. The claims in this paragraph come from that abstract. Bojer and Meldgaard (2020) found that global ensemble models and gradient-boosted trees did well in six Kaggle forecasting competitions (arXiv:2009.07701). Those are not the supplier's data, so these sources are a reason to try the approach. They are not evidence about this case. The supplier's clients have the same daily shape and different sizes, so the test has to be run on them.

The data is held in long format: one row per client and hour, with three columns. unique_id names the client, ds is the hour, and y is the kilowatt hours used in that hour. Each row carries its own lags, the readings a day and a week earlier. Chapter 5 found that calendar and holiday features did not lower the error on these eight weeks of history, so this chapter uses lags only, at 24 and 168 hours. Both lags are at least the 24-hour horizon, so neither reads the day being forecast.

The lags cost rows. A lag of 168 hours reads a week back, so the first week of each client's history has no row with every lag available. Chapter 5 showed that MLForecast drops such rows from training by default. A client's training rows are therefore fewer than the hours in its history. The forecast itself is unaffected, because each forecast hour reads only readings from before its cutoff.

Clients differ in size, and a squared-error loss over raw kilowatt hours lets the largest set the splits, while the small ones carry little weight. So each client's target is scaled before the fit. The scale is LocalStandardScaler from mlforecast 1.1.0. It gives each client its own mean and standard deviation, and the model learns the scaled values:

z = (y - mean) / standard deviation

The mean and deviation come from that client's history before the cutoff only, and the forecasts are converted back with the same two numbers. The library's source shows where this happens. MLForecast.fit reaches TimeSeries._fit in mlforecast/core.py, which fits the scaler on each client's history before the cutoff. That history includes the first week, whose rows the lags then drop from training. TimeSeries.predict in the same file inverts the scaling. The class is _BaseLocalScaler in mlforecast/target_transforms.py. Chapter 5 compared the scaled and unscaled targets on SUBSET8, and the unscaled model did worse than seasonal naive. This chapter keeps the scaled target and does not repeat that comparison.

make_forecaster in the shared module examples/lib/features.py builds one MLForecast with one LGBMRegressor, set by LGBM_PARAMS. The model is deterministic, uses one thread and a fixed seed, and runs under LightGBM 4.7.0. The module examples/lib/panel.py fits that forecaster once per window, on the panel's history before the window's cutoff. It fills any clock-change hour from that same history, as Chapter 3 does, and returns a forecast for every client.

Working rule: Fit one global model when your series share a shape and you must forecast many of them on each window. Scale each series' target with statistics from that window's history only, use only lags at least as long as the horizon, and fit once per window, not once per series. Then score the model per series against a baseline on the same windows, as the sections below do, before you trust its pooled error.

各クライアントを識別する

最終変更:版2026.11.11

行が一つの表にまとめられると、モデルはその行がどのクライアントに属するかを、こちらが教えない限り知ることができない。スケーリングは各クライアントの平均とばらつきを取り除くため、残るのは主として一日の形である。クライアント識別子は、クライアントを静的なカテゴリ特徴量として表に加える。すると木はクライアントで分割でき、そのクライアント固有の習慣を学習できる。代償として、クライアントごとに学習すべき分割が一つ増え、履歴のないクライアントには学習の元になるものがない。したがって新しいクライアントは、モデルが予測できるようになる前に再学習が必要である。

識別子を残すかどうかの規則は、第5章がすべての特徴量に課すものと同じである。標準のカットオフが使わない判断用ウィンドウで、クライアントごとの平均MASEを下げる場合に限って残す。ホールドアウト週は2014年12月25日から12月31日までで、日次のカットオフが7つある。標準の3つのカットオフ、2014年12月29日から12月31日は報告されるスコアであるため、判断には使わない。2014年12月25日から12月28日も使わない。判断用ウィンドウは、ホールドアウト週より前の通常の4日間である。カットオフは、いずれも2014年の11月25日、11月26日、12月2日、12月3日に置き、それぞれ24時間を予測する。採点される時間帯のうち、ポルトガルの祝日に当たるものはない。これらのウィンドウとホールドアウト週の間にある2014年唯一の祝日、2014年12月8日は、ウィンドウに含まれない。カレンダーには2014年12月1日に祝日の記載はない。

識別子をモデルに入れる前に、報告されるスコアが一度も触れないウィンドウで試す。この検査は、判断用の各カットオフでモデルを識別子なしと識別子ありの2通りで学習し、採点される時間帯が祝日であるか、ホールドアウト週に入っている場合は開始を拒否する。

client-identifier-check.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 合格
"""Tests whether a client identifier lowers the global model's error on four ordinary decision windows, before theheld-out week, on the book's MASE scale. The point rests on the mean per-client MASE lines and on `identifier kept`."""from lib.electricity import loadfrom lib.panel import ALL30, DECISION_CUTOFFS, check_decision_hours, mae_change, panel_windowsfrom lib.quirks import mask_clock_changesfrom lib.scoring import actual_hours, book_scale, report_scores, score_windowsfrom lib.settings import showraw = load(ALL30)                                             # all thirty clients, not the eight of SUBSET8df = mask_clock_changes(raw)[["unique_id", "ds", "y"]]        # clock-change hours are set to missing, so the scores leave them outcutoffs = DECISION_CUTOFFSactual = actual_hours(df, cutoffs)holiday_hours = check_decision_hours(actual)  # raises before any fit if a scored hour is a holiday or in the held-out weekplain = panel_windows(df, cutoffs, client_id=False, name="plain")               # the model without the identifieridentified = panel_windows(df, cutoffs, client_id=True, name="identifier")      # the same model, with the client as a featuremodels = ["plain", "identifier"]# the MASE scale reads only the readings before the first decision cutoff, so the scored hours cannot leak into itscored, per_client = score_windows(actual, plain.merge(identified, on=["unique_id", "ds"], validate="one_to_one"),                                   models, book_scale(raw, cutoffs[0]))lowers = per_client["identifier"] < per_client["plain"]size = raw.groupby("unique_id")["y"].mean().sort_values(ascending=False)   # mean kWh per client, largest firstcontrib = mae_change(scored, "plain", "identifier")           # each client's share of the pooled MAE change, kWh; the shares sum to the totalshow("first decision cutoff", f"{cutoffs[0]:%Y-%m-%d}")show("last decision cutoff", f"{cutoffs[-1]:%Y-%m-%d}")show("clients", scored["unique_id"].nunique())show("windows", len(cutoffs))show("scored hours", len(scored))show("decision hours on a holiday", holiday_hours)report_scores(scored, per_client, models)show("clients where the identifier lowers MASE", int(lowers.sum()))show("of the 15 largest clients, where the identifier lowers MASE", int(lowers[size.index[:15]].sum()))show("of the 15 smallest clients, where the identifier lowers MASE", int(lowers[size.index[-15:]].sum()))show("largest client", size.index[0])show("pooled MAE change from the largest client, kWh", contrib[size.index[0]])show("pooled MAE change, all clients, kWh", contrib.sum())# the decision rule keeps the identifier only if the mean per-client MASE is lower, not the pooled MAEshow("identifier kept", "yes" if per_client["identifier"].mean() < per_client["plain"].mean() else "no")
出力python client-identifier-check.py
first decision cutoff: 2014-11-25
last decision cutoff: 2014-12-03
clients: 30
windows: 4
scored hours: 2880
decision hours on a holiday: 0
MAE plain: 70.72
MAE identifier: 66.81
RMSE plain: 316.50
RMSE identifier: 303.68
mean MASE plain: 0.77
mean MASE identifier: 0.75
clients where the identifier lowers MASE: 23
of the 15 largest clients, where the identifier lowers MASE: 10
of the 15 smallest clients, where the identifier lowers MASE: 13
largest client: MT_370
pooled MAE change from the largest client, kWh: -3.80
pooled MAE change, all clients, kWh: -3.92
identifier kept: yes

識別子はクライアントごとの平均MASEを0.77から0.75へ下げ、30クライアントのうち23でMASEを下げる。

これらのウィンドウでは、プールしたMAEも70.72 kWhから66.81 kWhへ下がる。プールしたMAEは最大のクライアントに重みが偏るため、二つの誤差はクライアントを異なる重みで扱う。

プールした変化量-3.92 kWhのほとんどは一つのクライアントMT_370によるもので、そのうち-3.80 kWhを占める。

クライアントごとのMASEはすべてのクライアントに同じ重みを与えており、識別子は規模を問わず効果がある。大きい方から15クライアントのうち10、小さい方から15クライアントのうち13でMASEを下げる。大きなクライアントだけに効くわけではない。

出力された判定はyesであり、識別子は残され、最終モデルはそれを使う。差はわずかである。別のウィンドウでは、同程度のわずかな差で逆の符号になりうるため、判定は僅差でありウィンドウに依存する。別のウィンドウを持つ読者は、信頼する前に測り直すべきである。

識別子には、標準のカットオフでの代償がある。そこでは、最終モデルのクライアントごとの平均MASEは識別子ありで0.91、なしで0.98であるが、プールしたMAEは識別子ありで122.81 kWh、なしで119.03 kWhである。第7章では、その合計をこの結果と照らして確認しなければならない。この章の残りでは、識別子ありのモデルを使う。

実践ルール: クライアント識別子は、第5章の規則に従う一つの特徴量として扱う。判断用ウィンドウで、プールしたMAEを併記したうえで、クライアントごとの平均MASEを下げる場合に限って残す。判断が僅差であれば、そう明記し、別のウィンドウで測り直す。識別子が勝った場合は、その代償を書き留める。新しいクライアントは履歴ができるまで学習済みの分割を持たず、そのクライアントを予測する前にモデルを再学習しなければならない。

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

Apply the start rule to every client

最終変更:版2026.11.11

A series begins at its first reading. Before that, the meter reports zeros, and those zeros are not low use. Chapter 4 met this for one client. With thirty clients, three are late starters. MT_039 first reads on 2013-10-03, MT_179 on 2013-12-20, and MT_115 on 2014-01-14. A model fitted on their leading zeros learns a level near zero for them. The start rule drops every reading before a client's first reading. It finds that reading in the rows before the cutoff only.

The rule refuses a cutoff in two cases only: a client has no non-zero reading before the cutoff, or it has fewer than 48 hours of history since its first reading. It does not skip the client, because a skipped client leaves the total short. The rule does not catch a gap or a run of zeros in the middle of a series, and a meter replaced under the same id passes too, because its zeros are not leading. The scale catches a gap, because it refuses a series that is not one unbroken hourly series. Nothing in the forecast checks for one, so a gap there shows only as fewer training rows.

The leak check asks whether the rule reads only the past and refuses the right cutoffs. It runs nine cutoffs, refused or not, and poisons each from the cutoff on, once with zeros and once with a value no meter could record. The history must not change, and every accepted cutoff must hold all thirty clients.

start-rule-leak-check.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 合格
"""Checks that the start rule reads only rows before each cutoff, refuses the cutoffs the data's flag predicts, andremoves only leading zeros, on nine cutoffs. The same checks run on a deliberately broken history function, and eachmust fail there; the point rests on the refused, changed and missing counts. The checks are start_rule_checks in lib/panel.py."""import pandas as pdfrom lib.electricity import loadfrom lib.panel import ALL30, FEBRUARY_CUTOFFS, leaky_history, panel_history, start_rule_checksfrom lib.settings import EVAL_CUTOFFS, showraw = load(ALL30)# nine cutoffs: three around MT_179's and MT_115's first readings (refused), the February cutoffs and the standard cutoffsCHECKED = pd.DatetimeIndex(["2013-12-15", "2014-01-01", "2014-01-15", *FEBRUARY_CUTOFFS, *EVAL_CUTOFFS])def report(prefix, r):    show(f"{prefix}cutoffs checked", len(CHECKED))    show(f"{prefix}cutoffs refused by the start rule", r["refused"])    show(f"{prefix}cutoffs expected to be refused, from the flag", r["expected"])    show(f"{prefix}cutoffs where the refusal differs from the flag", r["mismatch"])    show(f"{prefix}cutoffs accepted", r["accepted"])    show(f"{prefix}accepted cutoffs with a client missing from the history", r["missing"])    show(f"{prefix}cutoffs whose history changes when the future is poisoned", r["changed"])# the book's history function, with the count of rows the rule removes switched onreal = start_rule_checks(raw, CHECKED, panel_history, removed_rows=True)report("", real)show("rows the start rule removes, accepted cutoffs", real["removed"])show("removed rows that are not zero", real["removed_nonzero"])# the deliberately broken history, which reads each first reading from the whole series, must fail every checkreport("broken version, ", start_rule_checks(raw, CHECKED, leaky_history))
出力python start-rule-leak-check.py
cutoffs checked: 9
cutoffs refused by the start rule: 3
cutoffs expected to be refused, from the flag: 3
cutoffs where the refusal differs from the flag: 0
cutoffs accepted: 6
accepted cutoffs with a client missing from the history: 0
cutoffs whose history changes when the future is poisoned: 0
rows the start rule removes, accepted cutoffs: 2064
removed rows that are not zero: 0
broken version, cutoffs checked: 9
broken version, cutoffs refused by the start rule: 1
broken version, cutoffs expected to be refused, from the flag: 3
broken version, cutoffs where the refusal differs from the flag: 2
broken version, cutoffs accepted: 8
broken version, accepted cutoffs with a client missing from the history: 2
broken version, cutoffs whose history changes when the future is poisoned: 2

The real rule passes all three checks. Its refusals match the data's own flag, which uses each first reading and the 48-hour rule: the rule refuses 3 of the nine cutoffs, the flag predicts 3, and 0 cutoffs differ from it.

Poisoning the future changes no history. Its history changes at 0 cutoffs, and 0 accepted cutoffs are missing a client.

The rule removes leading zeros and nothing else. Across the accepted cutoffs it drops 2064 rows, and 0 of them are not zero.

The same checks run on a deliberately broken version, which reads each first reading from the whole series, the leak the checks are written for. It fails each of them. Its refusals differ from the flag at 2 cutoffs, its history changes at 2, and 2 accepted cutoffs drop a client without a message. So a pass on the real rule means something.

The model runs with the start rule and without it, on the standard cutoffs and then the February cutoffs. The counts that differ, and each run's error, show what the rule does.

global-model-raw-starts.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 global model with the start rule and without it, on the February cutoffs, where a late starter's zeros enterthe history, and on the standard cutoffs, where the rule changes no row. The point rests on the February mean MASE linesand the count of forecast hours that differ; the scale lines compare the book's scale with a labelled counterfactual."""import numpy as npimport pandas as pdfrom lib.electricity import loadfrom lib.panel import (ALL30, FEBRUARY_CUTOFFS, IDENTIFIER_KEPT, LATE_STARTERS, late_starter_facts, mae_by_group,                       mase_by_run, scale_facts, with_and_without_start_rule)from lib.quirks import mask_clock_changesfrom lib.settings import EVAL_CUTOFFS, showraw = load(ALL30)df = mask_clock_changes(raw)[["unique_id", "ds", "y"]]        # clock-change hours are set to missing, so the scores leave them outfor label, value in late_starter_facts(raw, df).items():    show(label, value)standard = pd.to_datetime(EVAL_CUTOFFS)                       # the three standard cutoffs# two runs of the same model on the same cutoffs, differing only in their historiesscored = with_and_without_start_rule(df, standard, client_id=IDENTIFIER_KEPT)# compared with isclose, so a rounding difference between two runs does not count as a changed forecastshow("forecast hours that differ, standard", int((~np.isclose(scored["start"], scored["raw"])).sum()))# the February cutoffs, where the zeros of MT_115 and MT_179 enter the historyfeb = with_and_without_start_rule(df, FEBRUARY_CUTOFFS, client_id=IDENTIFIER_KEPT)show("scored hours, february", len(feb))show("forecast hours that differ, february", int((~np.isclose(feb["start"], feb["raw"])).sum()))for model in ["start", "raw"]:    for group, value in mae_by_group(feb, model).items():        show(f"MAE {group}, {model}, february", value)# both runs on one scale, read from the first February cutofffeb_mase = mase_by_run(raw, feb, ["start", "raw"])show("clients in MASE, february", int(feb_mase["start"].notna().sum()))for uid in LATE_STARTERS:    show(f"MASE {uid}, start, february", feb_mase.loc[uid, "start"])    show(f"MASE {uid}, raw, february", feb_mase.loc[uid, "raw"])for run in ["start", "raw"]:    show(f"mean MASE, {run}, february", feb_mase[run].mean())# 'counterfactual raw' keeps the zeros before each first reading, a scale the book does not use; 'start rule' is the book'sfor label, value in scale_facts(raw, standard, IDENTIFIER_KEPT).items():    show(label, value)
出力python global-model-raw-starts.py
first reading MT_039: 2013-10-03
first reading MT_115: 2014-01-14
first reading MT_179: 2013-12-20
zero share of history MT_115, 2014-02-01: 68
zero share of history MT_179, 2014-02-01: 23
zero share of history MT_115, 2014-02-15: 43
zero share of history MT_179, 2014-02-15: 0
zero share of history MT_115, 2014-02-28: 20
zero share of history MT_179, 2014-02-28: 0
forecast hours that differ, standard: 0
scored hours, february: 2160
forecast hours that differ, february: 2160
MAE late starters, start, february: 4.60
MAE other clients, start, february: 77.53
MAE MT_039, start, february: 4.64
MAE MT_115, start, february: 4.62
MAE MT_179, start, february: 4.54
MAE late starters, raw, february: 4.60
MAE other clients, raw, february: 77.95
MAE MT_039, raw, february: 4.57
MAE MT_115, raw, february: 4.68
MAE MT_179, raw, february: 4.53
clients in MASE, february: 30
MASE MT_039, start, february: 0.78
MASE MT_039, raw, february: 0.77
MASE MT_115, start, february: 0.90
MASE MT_115, raw, february: 0.91
MASE MT_179, start, february: 0.54
MASE MT_179, raw, february: 0.54
mean MASE, start, february: 0.70
mean MASE, raw, february: 0.71
MASE scale MT_039, start rule: 5.21
MASE scale MT_039, counterfactual raw: 3.28
MASE scale MT_115, start rule: 4.58
MASE scale MT_115, counterfactual raw: 2.22
MASE scale MT_179, start rule: 5.91
MASE scale MT_179, counterfactual raw: 3.04
mean MASE global, counterfactual raw scale, standard cutoffs: 1.01
mean MASE global, book scale, standard cutoffs: 0.91

At the standard cutoffs the rule matters less than the late starters might suggest. The three standard cutoffs have 8 weeks of history, reaching back to early November, and no client's history in that window holds a zero from before its first reading. So the rule changes no training row there, and 0 of the 2160 forecast hours change. The rule still changes the score through the MASE scale.

The February cutoffs, which Chapter 4 used for MT_115, are where the zeros enter the history. MT_115's history is 68 percent zeros on Feb 1, 2014, 43 percent on Feb 15 and 20 percent on Feb 28. MT_179's history is 23 percent zeros on Feb 1 and none after.

Here the forecasts change, because one model learns from all thirty clients at once: 2160 of the 2160 forecast hours in these three windows differ. Both runs are scored on the one book scale, read from Feb 1, 2014, so only the histories differ. The mean MASE is 0.70 with the rule and 0.71 without it.

Each late starter's MASE moves very little, and the direction is mixed. MT_039 scores 0.78 with the rule and 0.77 without it, and MT_115 scores 0.90 with the rule and 0.91 without.

MT_179 scores 0.54 with the rule and 0.54 without it, the same to two decimals.

The other 27 clients' MAE moves from 77.95 kWh without the rule to 77.53 kWh with it. The effect is small and mixed, and three windows are too few to call it. We keep the rule because the zeros are not demand, and because the scale depends on it.

You could instead mark the zeros as missing, as the clock rule does for the two clock-change hours in Chapter 3. That would be the wrong fix for this data. A zero before a first reading is the meter being silent, not a reading that is missing, and a missing value would still be a row the model learns from. The start rule removes the rows instead, and its check is simple to state: it removes only rows before the first reading, and every one of them is zero.

Working rule: Apply the start rule to every series that has leading zeros, and find each first reading from the rows before the cutoff. When the rule refuses a cutoff, stop the run and name the client and the cutoff. Do not fill the zeros, and do not publish a panel with a client missing. Judge the rule by the scale and by the windows where zeros enter the history, and expect the MAE effect to be small and mixed.

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

Score thirty clients on the same cutoffs

最終変更:版2026.11.11

The three standard cutoffs are Dec 29 to Dec 31, 2014, each at 00:00 on that day, with 24 hours forecast from each. For thirty clients that is 72 scored hours per client. Seasonal naive is the baseline Chapter 2 set. It takes each cutoff's own history, the 8 weeks before it, and copies the last day's readings forward. At the standard cutoffs no client's history holds a leading zero, so the global model and seasonal naive read the same readings. The comparison is fair because the inputs match, not because the methods are alike.

The headline is the mean per-client MASE, the measure Chapter 2 defines. The book uses one scale per client per backtest, the rule Chapter 2 sets, and the function book_scale in examples/lib/scoring.py builds it. The scale is the mean absolute change between each reading and the reading one day earlier, taken over every reading before the first scored cutoff. A late starter is counted from its first reading, and the clock-change readings are masked out. A client with no non-zero reading before the cutoff has no scale, so it is left out of MASE and reported, not treated as an error. Because the scale reads only readings before the scored windows, it is known at every cutoff and cannot leak. Each client counts once in the mean, so one large client cannot set the headline. The pooled MAE and RMSE follow as second lines. They show the error in kilowatt hours that the supplier pays, and they are weighted toward the large clients.

The scale is part of the score. MT_115's scale is 2.22 kWh if the zeros before its first reading are kept, and 4.58 kWh with the book's rule, which counts it from its first reading.

MT_039 and MT_179 move the same way. MT_039's scale rises from 3.28 to 5.21 kWh, and MT_179's from 3.04 to 5.91 kWh.

On the standard cutoffs the same forecasts score a mean MASE of 1.01 with the scale that keeps the zeros, and 0.91 with the book's scale. That difference is the scale, not the model. A score computed with a different scale rule is not comparable with one computed with the book's rule, so every score should record the rule it used.

The score below sets the global model beside seasonal naive on the three standard cutoffs.

global-model-thirty-clients.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 合格
"""Scores one global LightGBM model, with the identifier that client-identifier-check kept, against seasonal naive on thethree standard cutoffs, per client on the book's MASE scale. The point rests on the mean per-client MASE lines; the modelwithout the identifier is printed for reference only."""import pandas as pdfrom statsforecast import StatsForecastfrom statsforecast.models import SeasonalNaivefrom lib.backtest import forecast_windowsfrom lib.baselines import SEASONfrom lib.electricity import loadfrom lib.panel import ALL30, IDENTIFIER_KEPT, panel_windowsfrom lib.quirks import mask_clock_changesfrom lib.scoring import actual_hours, book_scale, left_out_facts, report_scores, score_windowsfrom lib.settings import EVAL_CUTOFFS, showraw = load(ALL30)df = mask_clock_changes(raw)[["unique_id", "ds", "y"]]        # clock-change hours are set to missing, so the scores leave them outcutoffs = pd.to_datetime(EVAL_CUTOFFS)                        # the three standard cutoffs, Dec 29 to Dec 31, 2014actual = actual_hours(df, cutoffs)# seasonal naive from each cutoff's own history: the baseline of Chapter 2naive = forecast_windows(StatsForecast(models=[SeasonalNaive(season_length=SEASON)], freq="h", n_jobs=1), df, cutoffs)global_fc = panel_windows(df, cutoffs, client_id=IDENTIFIER_KEPT)   # the identifier setting that client-identifier-check keptplain_fc = panel_windows(df, cutoffs, client_id=False, name="plain")  # the same model without the identifier, for referenceforecasts = naive.merge(global_fc, on=["unique_id", "ds"], validate="one_to_one").merge(    plain_fc, on=["unique_id", "ds"], validate="one_to_one")models = ["SeasonalNaive", "global", "plain"]# the book's scale, read from the readings before the first cutoff onlyscored, per_client = score_windows(actual, forecasts, models, book_scale(raw, cutoffs[0]))beats = per_client["global"] < per_client["SeasonalNaive"]    # per client: True where the global model's MASE is lowershow("clients scored", scored["unique_id"].nunique())show("windows", len(cutoffs))show("scored hours", len(scored))# a client with no non-zero reading before the first cutoff is left out of MASE, and is not an errorfor label, value in left_out_facts(raw, df, cutoffs[0]).items():    show(label, value)show("clients in MASE", per_client["global"].notna().sum())show("clients where global beats seasonal naive", int(beats.sum()))show("clients where seasonal naive wins", ", ".join(sorted(per_client.index[~beats])))report_scores(scored, per_client, models)
出力python global-model-thirty-clients.py
clients scored: 30
windows: 3
scored hours: 2160
clients left out of MASE: 0
clients with no reading before 2013-12-15, check: 2
clients with any row before 2013-12-15, broken count: 30
clients in MASE: 30
clients where global beats seasonal naive: 23
clients where seasonal naive wins: MT_001, MT_128, MT_141, MT_179, MT_217, MT_268, MT_294
MAE SeasonalNaive: 148.26
MAE global: 122.81
MAE plain: 119.03
RMSE SeasonalNaive: 780.48
RMSE global: 678.81
RMSE plain: 657.63
mean MASE SeasonalNaive: 1.18
mean MASE global: 0.91
mean MASE plain: 0.98

The example scores 30 clients on 3 windows, 2160 scored hours, and it counts 0 clients left out of MASE, which is zero: every client has a non-zero reading before the first cutoff, so every client is in the MASE table.

The count is only as good as its rule. At a cutoff of Dec 15, 2013, 2 clients have no reading yet, and counting any row before the cutoff would give 30, which reports no gap.

One global model beats seasonal naive on these cutoffs, for most clients and in total: its mean per-client MASE is 0.91 against 1.18, and it wins for 23 of the thirty clients. It loses for MT_001, MT_128, MT_141, MT_179, MT_217, MT_268, MT_294, and those clients are the first place to look when the model is refreshed.

The pooled figures point the same way. The MAE is 122.81 kWh against 148.26 kWh, and the RMSE is 678.81 kWh against 780.48.

The model without the identifier, printed for reference, has a mean MASE of 0.98 and an MAE of 119.03 kWh, which is the trade-off the identifier section describes.

The printed figures are means and counts, and a mean can hide one client that is far worse than the rest. When a figure changes, open the per-client table first.

The chapter does not explain why seasonal naive wins for those clients, and that is a reason not to report only the pooled figure. The result covers three windows in one week of one season, so it describes these cutoffs, not every day of the year. The longer test is the seven-window held-out week, which the rolling example in Chapter 10 uses.

Working rule: Score a global model per client on the same cutoffs as the baseline, with the MASE scale fixed before the first scored cutoff. Report the mean per-client MASE beside seasonal naive, and print the counts of clients and scored hours so a reader can check them. State any client left out of MASE and why. Read the pooled MAE and RMSE as the cost in kilowatt hours, not as the measure of model quality.

実行時間の見積もり

最終変更:版2026.11.11

バックテストにはモデルの当てはめ(フィット)という費用がかかる。実行する前に確認すべきなのは、その回数である。クライアントごとのモデルは、クライアント、ウィンドウ、手法の組み合わせごとに1回ずつ当てはめられるため、回数はクライアント数×ウィンドウ数×手法数となる。30クライアントを3ウィンドウで扱えば、クライアントごとの手法1つにつき90回の当てはめになる。グローバルモデルは、カバーするクライアントの数にかかわらず、ウィンドウと手法ごとに1回だけ当てはめられる。したがって同じ3ウィンドウなら当てはめは3回で済む。クライアントが増えるとグローバルモデルの個々の当てはめは大きくなるが、回数は増えない。

本書では、費用の大きいクライアントごとの手法に対して部分集合の規則を設けている。SUBSET8は8クライアントの部分集合であり、第4章はこの部分集合の上でクライアントごとの統計モデルを実行する。グローバルモデルは1回の当てはめで30クライアントすべてをカバーするため、30クライアントすべてを対象に、ALL30として実行する。部分集合は本書全体で固定されているので、ある章の数値を次の章の数値と並べて比較できる。ウィンドウ数も同じ考え方に従う。費用の大きい手法には3ウィンドウを用い、費用の小さい手法ではそれより多くしてよい。識別子の検査では、1ウィンドウにつきグローバルモデルの当てはめが2回かかる。識別子を含めたものと含めないものである。したがって4ウィンドウでは8回の当てはめになる。

クライアント数が増えたとき、この2種類の費用は異なる動きをする。クライアントごとの手法では、新しいクライアントが1つ増えるたびに当てはめが1回増える。グローバルモデルでは、各当てはめが読み込む行数が増えるために当てはめ1回が大きくなるが、回数は変わらない。

本書は所要時間を示さない。例は1スレッドで実行するため、本書の出力を記録したマシンでは出力が再現される。この選択は実行時間を犠牲にしている。所要時間はマシンに依存し、読者のマシンは異なる場合がある。数えるのは秒数ではなく、当てはめの回数である。

実践ルール: バックテストを実行する前に、当てはめの回数を数える。クライアントごとの手法ではクライアント数×ウィンドウ数×手法数、グローバルモデルではウィンドウ数×手法数である。回数が予算を超える場合は、部分集合かウィンドウ数を減らす。採点対象のウィンドウは決して減らしてはならない。減らした内容はスコアの横に書き残す。そうすれば、読者は同じ条件のもの同士を比較できる。

本番運用で起こりうる問題

最終変更:版2026.11.5

実行が停止することがある。基準時点より前に 0 でない読み取り値がないクライアント、または最初の読み取りから 48 時間に満たない履歴しかないクライアントがあると、開始規則はその基準時点を拒否する。規則は、そのクライアントを飛ばさずにエラーを送出する。クライアントを飛ばすと合計が不足し、第7章は各クライアントを合計して全体の値を求めるからである。本番では、実行を停止し、クライアントと基準時点を示して、担当者の判断を待つべきである。リーク検査は、本書のデータでも同じ拒否を示している。

1 つのモデルがすべてのクライアントを動かしている。2 月の基準時点では、後発クライアントのゼロによって予測時間が 2160 時間変わり、開始規則の節が示すように、他の 27 クライアントの MAE も動いた。1 つのクライアントの履歴、規則、特徴量のいずれを変更しても、パネル全体の予測が変わる。変更を加えたあとは、変更したクライアントだけでなく、すべてのクライアントを確認する。

尺度もスコアの一部である。同じ予測でも、最初の読み取り以前のゼロを尺度に含めるかどうかによって、平均 MASE は 1.01 にも 0.91 にもなる。尺度はスコアリングの節に示してある。規則はスコアごとに記録し、規則の変更はスコアの変更として扱う。

判断はずれていくことがある。識別子についての判断は、ホールドアウトした週の外にある 4 つの通常の窓に基づいており、その結論は僅差である。クライアントが加わる、抜ける、または規模が変わる場合には、判断をやり直すべきである。

欠けたクライアントは、表の中ではエラーとして現れない。29 クライアントのパネルも有効な表であり、その予測も予測らしく見える。採点されるクライアント数や時間数が想定より少ない実行、グローバルモデルが季節ナイーブを上回るクライアント数が実行ごとに大きく変わる場合は、停止すべき兆候である。プールした MAE は変わらないのに、特定の 1 クライアントの MASE が急に跳ね上がる場合も同様である。

実践ルール: 更新のたびに、スコアを読む前に、件数(クライアント数、窓の数、採点した時間数、拒否した基準時点、MASE から除外したクライアント)を出力して確認する。そのうえで、クライアントごとの平均 MASE を季節ナイーブと並べて報告する。拒否が 1 件でもあれば実行を停止し、不足したパネルから作った合計は公表しない。

この章で下した判断

最終変更:版2026.11.5

第7章は、この章が引き渡すものから始まる。引き渡されるのは、標準の各カットオフにおける30クライアント分の予測である。これらは、クライアント識別子と開始規則を適用した1つのモデルで作成し、本書の唯一の MASE の尺度で採点したものである。識別子を残すことは client-identifier-check での判断によって決まり、examples/lib/panel.py はその判定を IDENTIFIER_KEPT に保持している。これらのカットオフでは、識別子を用いるとプールした誤差が悪化する。そのため、第7章ではクライアント別の予測に頼る前に、合計を確認するべきである。

  • 1つのグローバルな LightGBM モデルが30クライアントすべてを対象とする。ラグは24と168とし、カレンダー特徴量と祝日特徴量は用いない。各クライアントの目的変数は、そのウィンドウの履歴のみからスケーリングする。このスケーリングは第5章で確定したものである。
  • クライアント識別子は残す。この判断には、2014年11月25日から12月3日までの通常の4つのウィンドウを用いた。これらはホールドアウトした週の外にあり、ポルトガルの祝日を含まない。これは、設定を選ぶための本書の規則が求めるとおりである。これらのウィンドウでの平均 MASE は 0.77 から 0.75 に変わる。識別子の節が示すように、この判定は僅差である。
  • 開始規則はすべてのクライアントに適用する。開始できないカットオフは、そのクライアントを飛ばさずに拒否する。
  • 各パネル履歴の時計変更時の時間帯は、その履歴のみから補完する。したがって、時計変更をまたぐローリングウィンドウも、拒否されずに適合される。第10章のローリングウィンドウはこれに依存している。
  • 見出しの数値は、30クライアントすべてにわたるクライアント別 MASE の平均である。尺度は本書で唯一のもの(第2章で定め、book_scale で計算する)を用い、同じカットオフでの季節ナイーブ法と並べて示す。カットオフより前にゼロでない観測値が1つもないクライアントは、MASE から除外し、その旨を報告する。プールした MAE と RMSE は第2の指標として続く。標準のカットオフでは、どのクライアントも最初のカットオフより前に観測値があるため、除外されるクライアントはない。
  • モデルは1スレッドで固定シードにより動作するため、本書の出力を記録したマシンでは出力が再現する。本書は他のマシンでは検証していない。

この版における本章

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

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

この節を引用する

形式

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

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

このページの内容

全10章中の第6章: 1つのモデルで多数のクライアントを予測する

  1. One model for many clients
  2. 各クライアントを識別する
  3. Apply the start rule to every client
  4. Score thirty clients on the same cutoffs
  5. 実行時間の見積もり
  6. 本番運用で起こりうる問題
  7. この章で下した判断

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