Keep the forecast running
읽는 데 약 44분분 걸린다, 7절에 5개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.11판을 번역한 것이다. 원문 읽기
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Once a forecast runs every day, the question changes from whether it scored well to whether it still holds on the day it's used. This chapter builds the loop that answers that question. You'll refit a forecast on a schedule, log each day's forecast before its readings exist, check that the log used only what had arrived, score the readings as they come in, flag a day whose error is out of line with the backtest, and say when a model should be retired.
The stake is the next buying round. The supplier commits to power for the next day from the forecast, so a forecast that has gone wrong without anyone noticing costs money in that purchase. This chapter does not reduce that risk to zero. It makes the risk visible on the day it appears, using only what the supplier knew at the time.
The earlier chapters checked the supplier's forecast on past data. Each method was scored after the fact on the last days of 2014, with every reading in hand. In operation the order runs the other way. The supplier buys power for Dec 29, 2014 from a forecast made at 00:00 on Dec 29, the day's cutoff, using only what it knows at that time, and it learns what happened a day later. A forecast that held up on the backtest can drift. The clients change, a holiday falls inside the window, or a meter feed stops for a few hours. The supplier needs to see that before the next buying round, not in a review at the end of the quarter.
This chapter runs the loop for the last seven days of 2014, from Dec 25 to Dec 31. Each day gets one forecast for each of the thirty clients, made from its own midnight cutoff. Every time in this chapter is a data time. A cutoff is 00:00 of its day, and a reading arrives at the end of its hour. The decision and calibration runs start on Nov 25 and Dec 9, 2014, and the refit cycle is anchored to Monday, Nov 24, 2014. All of these start after Jan 16, 2014. That is the first midnight at which the start rule admits all thirty clients into one model: MT_115's first reading is at 00:00 on Jan 14, 2014, and the rule needs 48 hours of history from it, as Chapter 6 sets out.
A forecast says what the readings will do. It does not say why they do it. The loop can tell the supplier that demand has moved away from the forecast. It cannot tell the supplier which habit, price or weather caused the move, and this chapter does not try. A forecast that holds up is not a causal claim, and no flag in this chapter turns into one.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Refit on a schedule
A refit re-estimates the model's parameters on the history known at a cutoff. Between refits, the model keeps its trees. Each forecast still reads the most recent readings to build its lag inputs, so the forecast reflects the last hours even when the trees do not.
One detail is often missed. mlforecast 1.1.0 fits each client's scaling again whenever it predicts from a new history: predict with new_df fits the target transforms on that history (forecast.py lines 1374 to 1412, and core.py lines 536 to 540 of the pinned release). Each client's mean and spread therefore come from the history known at every cutoff, and only the trees wait for a refit. That is not leakage, because that history is known at the cutoff.
The word needs one caution. In Hyndman and Athanasopoulos's Forecasting: Principles and Practice, 3rd ed. (FPP3), refit() applies a fitted model without re-estimating it (FPP3, Chapter 13). Here, "refit" means re-estimating the trees.
A refit must not use the readings it is about to forecast. A refit at cutoff c may read only readings that arrived by c. The loop enforces this by construction. The history for a refit, and for every forecast, holds only readings that had arrived by the cutoff, so the actuals of the day being forecast are never in it.
The cadence is the choice that remains. We considered two cadences, a refit every day or a refit every seven days. Both forecast every day from its own cutoff, with the same global model from Chapter 6: one scaled LightGBM over the thirty clients, with lags of 24 and 168 hours and the client identifier. The global model runs here because it is the best choosable model on the decision windows: the recorded models in Chapter 9 have no forecasts there, so they cannot be chosen. They differ only in how often the trees are re-estimated. The weekly cycle is anchored to Monday, Nov 24, 2014, so its refits fall on Mondays: Nov 24, Dec 1, Dec 8 and so on. A run's refit dates therefore do not depend on the day the run starts. Each forecast uses the model fitted on the Monday on or before its cutoff.
We choose between the cadences on the four ordinary decision windows, Nov 25, Nov 26, Dec 2 and Dec 3, 2014. None of them is a Portuguese holiday, and the held-out week is not used. The rule is the lower mean MASE on those windows. Every run in this chapter uses one scale per client, read from readings before Nov 25, 2014 under the rule in Chapter 2. The decision windows, the calibration windows and the held-out week share that yardstick. The decision and calibration histories reach back over the clock change of Oct 26, 2014. The loop fills that 01:00 hour from the hours either side, as Chapter 3 does.
Both cadences run on the four decision windows. Because the weekly model is one or two days old there, a model of each age from 0 to 6 days also forecasts those days.
1"""Choose the refit cadence on the four decision days, Nov 25 to Dec 3, 2014: a refit every day or every seven days on2Mondays, with the global model from Chapter 6. The cadence with the lower `mean MASE` line is the one the rule takes, and3the `model aged` lines show how far a model's age alone moves that score. The held-out week is not used."""4import pandas as pd56from lib.electricity import load7from lib.panel import ALL308from lib.running import DECISION_DAYS, daily_mase, feed, fit_at, forecast_at, prepare, run_days, scale_from, with_actuals9from lib.settings import show1011raw = load(ALL30)12df = prepare(raw)13scale = scale_from(raw) # one MASE scale, read before Nov 25, used by every run in the chapter14show("decision days", len(DECISION_DAYS))15# feed returns (train, known, pending count, read_by); [0] is train16show("rows read by one refit", len(feed(df, DECISION_DAYS[0])[0]))17names = {1: "daily", 7: "weekly"} # the keys are the refit interval in days18means = {}19for every in names:20 scored = with_actuals(run_days(df, DECISION_DAYS, refit_every=every), df) # refit_every: a refit every this many days21 means[every] = daily_mase(scored, scale).mean() # the mean over the four decision days of each day's MASE22 show(f"refits, {names[every]}", scored["refit"].nunique()) # the distinct refit days the decision days use23 show(f"MAE, {names[every]}", scored["ae"].mean())24 show(f"mean MASE, {names[every]}", means[every], digits=3)25show("mean MASE, daily minus weekly", means[1] - means[7], digits=3) # positive when the weekly cadence has the lower mean26show("chosen cadence", names[min(means, key=means.get)]) # the lower mean wins; the close-call tie-break is made in the prose27models = {}28for age in range(7):29 parts = []30 for day in DECISION_DAYS:31 fit_day = day - pd.Timedelta(days=age) # a model aged `age` days, fitted that many days before the decision day32 if fit_day not in models: # a model is fitted once and reused by every decision day it serves33 models[fit_day] = fit_at(df, fit_day)[0] # fit_at returns (model, read_by); [0] is the model34 # forecast_at returns (forecast, pending count, read_by); the first is the forecast35 part, _, _ = forecast_at(models[fit_day], df, day)36 parts.append(part.assign(cutoff=day)) # daily_mase groups each forecast by its cutoff37 show(f"mean MASE, model aged {age} days", daily_mase(with_actuals(pd.concat(parts), df), scale).mean(), digits=3)
python refit-cadence-decision.pydecision 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
On the decision windows the weekly cadence has the lower mean MASE, by 0.008, and it needs half as many fits on those four days: the daily cadence runs 4 refits, and the weekly cadence 2. Each refit reads 40320 rows, which is thirty clients times 1,344 hours of history. In operation a weekly cadence needs one seventh of the fits.
A model up to six days old scores near a fresh one on the decision windows, and that is all the age check claims. Its mean MASE runs from 0.741 at three days, the lowest of ages 0 to 6, to 0.758 at five, the highest, with a fresh model at 0.754. Age shows no trend, and the spread across all seven ages is wider than the gap between the two cadences. That gap is small, and four days cannot separate the cadences, so the example does not show that weekly is better. A reader with a larger model or a longer horizon should run the same check on their own decision windows.
The rule picks weekly, because its mean is lower. That gap sits inside the spread that model age alone produces, so the two cadences are close. When they are, the working rule takes the one with fewer refits, and the book says so here: weekly.
Working rule: Choose the refit cadence on ordinary days that come before the held-out week, scored on one scale that was read before the first of those days. Take the cadence with the lower mean MASE, and when the two are close, take the one with fewer refits and say so. Never refit on readings from the day you are forecasting.
실제값이 도착하기 전에 모든 예측을 기록한다
예측 로그는 클라이언트와 시간마다 한 행씩 두는 표이다. 각 행에는 예측을 만든 시점인 컷오프, 행을 기록한 시각, 클라이언트, 시간, 예측값, 예측의 하한과 상한, 모델의 재적합일, 아래에서 설명하는 두 가지 도착 시각, 그리고 해당 예측을 위해 채운 측정값의 개수가 들어 있다. 로그가 하는 일은 하나이다. 그 시점에 예측이 무엇이라고 말했는지, 그리고 예측을 만들 때 루프가 무엇을 볼 수 있었는지를 증명한다. 로그가 없으면 나중의 보고서가 실제로 만들어진 예측을 사용했는지, 아니면 더 새로운 모델과 실제값으로 사후에 다시 만든 예측을 사용했는지 아무도 알 수 없다. 다시 만든 로그는 위장된 누수이다. 예측이 무엇이었어야 했는지를 이미 알고 있기 때문이다.
각 행의 구간은 8장에서 구간을 만드는 방식과 같게 만든다. 구간은 예측값에 같은 시간대의 스케일링된 잔차를 더한 것이며, 잔차는 2014년 12월 9일부터 12월 20일까지의 보정 구간에서 가져온다. 이 구간은 모든 홀드아웃 날짜보다 앞서 있고 주가 시작되기 전에 고정된다. 각 시간대의 잔차는 서른 개 클라이언트에 걸쳐 합산하므로 시간대마다 열두 개가 아니라 360개가 있다. 8장의 클라이언트별 구간도 같은 잔차를 합산하며 95% 수준에서도 제시한다. 이 루프는 80% 수준만 기록하는데, 마지막 절의 폐기 트리거가 80% 구간을 읽으므로 수준을 하나로 두면 로그와 트리거가 일치하기 때문이다. 구간은 기록된 예측과 고정된 보정 잔차로 계산하므로, 구간이 다루는 날의 측정값을 읽을 필요가 없다.
검사가 실패할 수 없다면 로그가 증명하는 바는 겉보기보다 적다. 규칙은 모델과 예측이 만들어진 시점까지 도착한 측정값만 읽어야 한다는 것이다. 그래서 로그는 각 행에 두 가지 도착 시각을 기록한다. fit_read_by는 모델을 적합하는 데 쓴 측정값 중 가장 나중에 도착한 시각이며, 모델의 재적합일보다 늦어서는 안 된다. read_by는 예측이 읽은 측정값 중 가장 나중에 도착한 시각이며, 컷오프보다 늦어서는 안 된다. written_at를 측정값의 도착 시각과 비교하는 것으로는 이를 검사할 수 없다. 재생은 written_at를 컷오프로 기록하므로, 그 비교는 어떤 코드에서도 통과하기 때문이다. 운영 환경에서는 written_at가 추가 전용 저장소의 시계에서 나온다. 재생은 이를 표기만 할 수 있다. 두 검사는 홀드아웃 주의 모든 행에서 실행하며, 모델의 검사는 의도적으로 누수를 넣은 주에서도 다시 실행하는데, 여기서는 누수를 반드시 잡아내야 한다.
1"""Runs the held-out week, Dec 25 to Dec 31, 2014: one forecast a day from its own midnight cutoff, with the weekly refit2cycle and the late-data fill, each logged when it is made. The `log rows` lines show both arrival checks pass, and the3leaky run fails the first. The `MAE` and `coverage 80` lines give each day's mean absolute error and how often its 80%4band held. The 80% bands use calibration days Dec 9 to Dec 20, 2014, earlier than every scored day."""5import pandas as pd67from lib.electricity import load8from lib.panel import ALL309from lib.running import CAL_DAYS, HELD_OUT_DAYS, REFIT_EVERY, band, coverage_by_day, prepare, run_days, scale_from, with_actuals10from lib.settings import show1112raw = load(ALL30)13df = prepare(raw)14scale = scale_from(raw)15cal = with_actuals(run_days(df, CAL_DAYS), df) # the residuals that set the bands, from days earlier than the week16bands = band(with_actuals(run_days(df, HELD_OUT_DAYS), df), cal, scale)17# leak=True refits each day's model on the next day's readings18leaky = with_actuals(run_days(df, HELD_OUT_DAYS, leak=True), df)19# refit dates in the week; the Dec 22 refit is dated before it20in_week = sorted({d for d in bands["refit"] if d >= HELD_OUT_DAYS[0]})21show("refit every (days)", REFIT_EVERY)22show("refit days in the week", ", ".join(f"{d:%Y-%m-%d}" for d in in_week))23show("models used in the week", bands["refit"].nunique())24show("log rows", len(bands))25# hour 0 holds 12 calibration days times 30 clients26show("calibration residuals per hour, pooled over clients", cal.dropna(subset=["e"]).groupby("hour").size().iloc[0])27# a model may read only readings that had arrived by its refit day28show("log rows whose model read only readings in by its refit day", int((bands["fit_read_by"] <= bands["refit"]).sum()))29# a forecast may read only readings that had arrived by its cutoff30show("log rows whose forecast read only readings in by its cutoff", int((bands["read_by"] <= bands["cutoff"]).sum()))31show("leaky log rows whose model read only readings in by its refit day", int((leaky["fit_read_by"] <= leaky["refit"]).sum()))32# a reading arrives at the end of its hour, so any other arrival is late33show("readings that arrived late", int((bands["arrives"] != bands["ds"] + pd.Timedelta(hours=1)).sum()))34# every row of a cutoff has the same count, so the first row gives it35show("forecast inputs filled, Dec 29", int(bands.loc[bands["cutoff"] == "2014-12-29", "filled"].iloc[0]))36# the last of Dec 28's readings to arrive37done = bands.loc[bands["cutoff"] == "2014-12-28", "arrives"].max()38show("Dec 28 complete at", f"{done:%H:%M on %b %d, %Y}")39mae = bands.groupby("cutoff")["ae"].mean()40cov = coverage_by_day(bands)41for day in mae.index:42 show(f"MAE {day:%Y-%m-%d}", mae[day])43for day in cov.index:44 show(f"coverage 80 {day:%Y-%m-%d}", cov[day], digits=3)45show("leaky MAE 2014-12-25", leaky.loc[leaky["cutoff"] == "2014-12-25", "ae"].mean())
python rolling-refit-seven-days.pyrefit 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
로그는 5040개의 행을 가지며, 이는 서른 개 클라이언트의 24시간을 7일 동안 기록한 것이다. 이 중 5040개 행이 모델의 도착 검사를 통과하고, 5040개 행이 예측의 도착 검사를 통과한다. 이 주에는 두 모델을 쓴다. 12월 22일 월요일에 적합한 모델은 12월 25일부터 28일까지를 맡고, 12월 29일 월요일에 다시 적합한 모델은 12월 29일부터 31일까지를 맡으므로, 재적합은 주 안에서 일어난다.
한 번도 실패하지 않는 검사는 알려 주는 바가 적으므로, 이 주는 누수를 넣은 채로도 실행한다. 이 실행에서는 각 날의 모델을 다음 날의 측정값으로 다시 적합하므로 모델이 예측 대상인 날을 이미 본 상태가 되고, 모델의 검사는 모든 행에서 실패한다. 통과한 행은 0개이다. 누수는 예측도 실제보다 좋아 보이게 만든다. 12월 25일의 MAE는 351.79 kWh로, 누수 없는 실행의 447.59 kWh와 대비된다. 남겨 두어야 할 것은 이 검사이다. 재적합을 다음 날의 측정값으로 옮기는 수정이 가해지면 출력되는 개수가 0이 되고, 그러면 기록된 출력이 실패한다.
작업 규칙: 각 예측의 행은 컷오프 시점에, 그때까지 도착한 측정값으로 기록하고, 재적합일과 두 도착 시각을 함께 남긴다. 과거 로그를 더 새로운 모델이나 실제값으로 다시 만들어서는 안 된다. 어떤 날의 행이 사라졌다면 로그에서 그 날을 누락으로 표시하고, 나중에 채워 넣지 않는다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Score the log as actuals arrive
A reading scores the forecast logged for its hour when it arrives. The day's score is its daily MASE. The daily MASE takes each client's mean absolute error over the day's 24 hours, divides it by the client's scale, and averages the results over the thirty clients:
daily MASE = mean over clients of (MAE over the day's 24 hours / scale)
The scale is the one set in the refit section, read from before Nov 25, 2014, and it does not change from day to day. A reading enters the score for its own day, and only after it has arrived, so the score never uses a value the supplier did not have at the time. That is the second half of the leakage rule in the log section. A day is scored once its last reading is in. For Dec 29, that is 00:00 on Dec 30.
Most days arrive whole. The held-out week has one day that does not. The lead client's last six readings of Dec 28, 2014, from 18:00 to 23:00, arrive at 09:00 on Dec 29. That is nine hours after the Dec 29 cutoff, so the Dec 29 forecast has to be made without them. The rule for this case is the book's own choice, and no source supports it:
- A reading that has not arrived at a cutoff is left out of that day's refit.
- For the forecast at that cutoff, the missing value is filled with the reading of the same hour a week earlier, which had arrived. The log counts how many values were filled.
- The forecast is not redone when the reading arrives.
- The reading is scored when it arrives, and its day is scored once its last reading is in.
The first option tried was to leave the missing values as they were. The library refused them. At the pinned version, 1.1.0 raised this error when the forecast was made:
ValueError: y column contains null values.
There are two ways to fill the gap. Forward fill repeats the last reading that arrived. That flattens the evening, because the lead client's 18:00 to 23:00 values all become the 17:00 value, and lag 24 carries that flat evening into the next day's evening forecast. Filling from the same hour a week earlier keeps the evening's shape. We picked the fill on the decision windows, not the held-out week. There the same six readings are made late before each decision cutoff, and both fills forecast from them.
1"""Chooses how a late reading is filled on the decision windows, Nov 25 to Dec 3, 2014: the lead client's last six readings2of the day before arrive at 09:00 on each cutoff day, as the Dec 28 readings do in the held-out week. The3`MAE, lead client hours 18 to 23` lines decide between forward fill and a fill from the same hour a week earlier; only4those hours change, because lag 24 reads them, and the held-out week is not used."""5import pandas as pd67from lib.electricity import load8from lib.panel import ALL309from lib.running import DECISION_DAYS, LATE_CLIENT, feed, late_copy, prepare, run_days, with_actuals10from lib.settings import show1112raw = load(ALL30)13df = prepare(raw)14# feed returns (train, known, pending count, read_by); [2] is the pending count15show("readings late for each decision cutoff", feed(late_copy(df, DECISION_DAYS[0]), DECISION_DAYS[0])[2])16errors = {}17for rule in ("forward", "week"):18 parts = []19 for day in DECISION_DAYS:20 # the day before's last six readings arrive at 09:00 on this day, after its cutoff, so the fill applies21 scored = with_actuals(run_days(late_copy(df, day), [day], fill=rule), df)22 # 18:00 to 23:00 of the day scored, which lag 24 reads from the day before23 parts.append(scored.loc[(scored["unique_id"] == LATE_CLIENT) & (scored["hour"] >= 18), "ae"])24 errors[rule] = pd.concat(parts).mean()25 show(f"hours scored, {rule} fill", len(pd.concat(parts)))26 show(f"MAE, lead client hours 18 to 23, {rule} fill", errors[rule])27show("chosen late fill", min(errors, key=errors.get))
python late-fill-decision.pyreadings 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
The week-earlier fill is the more accurate of the two. Over the lead client's hours from 18:00 to 23:00, across 24 forecast hours, its mean absolute error is 5.03 kWh, against 7.92 kWh with forward fill. The book uses it in every run.
The held-out week shows the rule at work. 6 readings arrived late, and the Dec 29 forecast filled 6 inputs. The Dec 29 refit left the same six readings out, so the branch that leaves a reading out of a refit runs in this week too. Dec 28 was complete at 09:00 on Dec 29, 2014.
A single day's MAE does not say whether the day was bad, because the level of demand changes from day to day. That is why the flag in the next section divides by a reference.
Working rule: Score each day when its last reading arrives, against the forecast logged at its cutoff, on the chapter's one scale. When a reading arrives late, score it then, count it in the log, and leave the logged forecast alone. Never change a forecast after its cutoff, even when the change would improve the score.
백테스트에 비추어 드리프트 표시하기
지난 절의 일별 점수에는 어떤 날이 기준에서 벗어났는지 알려 주는 선이 필요하다. 표시는 그날에 대한 질문이지 판정이 아니다. 이 규칙은 하루의 일별 MASE가 모델이 이전에 보인 성능과 어긋나는지를 묻는다. 일별 MASE가 기준값의 두 배를 넘으면 그날에 표시를 한다. 기준값은 2014년 12월 9일부터 12월 20일까지 보정 윈도의 일별 MASE 중앙값이다. 이 날들은 표시가 판단하는 모든 날보다 앞선다. 이 중 포르투갈 공휴일은 하루도 없다. 다만 12월 9일의 lag-24 값은 국경일인 12월 8일 성모 무염시태 대축일까지 거슬러 올라간다. 이 영향은 하루치에 불과하며 중앙값이 이를 완화한다.
2배라는 계수는 이 책의 경험칙이다. 이런 종류의 표시에 대해 발표된 임계값은 알려진 것이 없으므로 이 수치는 우리가 정한 것이며, 그렇게 밝혀 둔다. 우리는 이 값을 결정 윈도에서 확인했다. 결정 윈도의 평범한 날 4일은 알려진 원인 없이 표시가 작동하는지를 시험한다.
1"""Flags drift against the backtest: a day is flagged when its daily MASE is above FLAG_FACTOR times the reference, the2median daily MASE of the calibration days, Dec 9 to Dec 20, 2014, which are earlier than the held-out week. The3`largest decision day` and `decision days flagged` lines show the ordinary days staying under the line, and the `MASE`4and `held-out days flagged` lines show which held-out days cross it."""5from lib.electricity import load6from lib.panel import ALL307from lib.running import (CAL_DAYS, DECISION_DAYS, FLAG_FACTOR, HELD_OUT_DAYS, daily_mase, flagged, prepare, run_days,8 scale_from, with_actuals)9from lib.settings import show1011raw = load(ALL30)12df = prepare(raw)13scale = scale_from(raw)14reference = daily_mase(with_actuals(run_days(df, CAL_DAYS), df), scale).median() # the median, not the mean, so one unusual calibration day moves it little15show("reference, median daily MASE", reference)16show("flag above, MASE", FLAG_FACTOR * reference) # FLAG_FACTOR is 2, the chapter's rule of thumb17decision = daily_mase(with_actuals(run_days(df, DECISION_DAYS), df), scale)18show("largest decision day, times the reference", decision.max() / reference)19show("decision days flagged", len(flagged(decision, reference)))20held = daily_mase(with_actuals(run_days(df, HELD_OUT_DAYS), df), scale)21for day, value in held.items():22 show(f"MASE {day:%Y-%m-%d}", value)23show("held-out days flagged", len(flagged(held, reference)))24show("flagged held-out days", ", ".join(f"{day:%Y-%m-%d}" for day in flagged(held, reference)))
python drift-flag-rolling.pyreference, 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일과 26일이다. 이 두 날의 일별 MASE는 4.62과 2.00이며, 표시선은 1.43이다. 그다음은 12월 31일 새해 전날이고, 선 아래에 있다.
두 표시 모두 알려진 원인이 있다. 12월 25일은 포르투갈의 공휴일인 크리스마스이다. 모델에는 공휴일 입력이 없다. 5장은 부분집합의 결정 윈도에서 달력 열과 공휴일 열을, 그중 공휴일 열도 포함해 시험했으나 단순 lag를 이기는 것이 없었고, 그래서 6장은 전역 모델에 그런 열을 주지 않았다. 12월 26일은 포르투갈의 공휴일이 아니지만, 그날의 lag-24 값은 12월 25일이다. 12월 26일 각 시간의 예측은 12월 25일 같은 시간을 읽으므로 공휴일의 패턴이 다음 날로 이어진다. 이는 드리프트가 아니라 달력 효과이며, 루프는 둘을 구별하지 못한다. 루프는 날을 표시할 뿐이다. 사람이 각 표시를 읽고 달력을 확인한다.
하루만으로는 판정이 되지 않는다. 높은 날 하루는 공휴일, 폭풍, 잘못 입력된 값에서 나올 수 있다. 달력상의 원인 없이 표시가 이틀 연속 나오면 모델을 살펴볼 이유가 된다. 그때 무엇을 할지는 다음 절에서 다룬다.
작업 규칙: 일별 MASE가 앞선 보정 윈도 중앙값의 두 배를 넘는 날에 표시하고, 달력상의 원인으로 설명되는지 묻는다. 원인이 있으면 표시 옆에 기록한다. 설명되지 않는 표시가 이틀 연속 나오면 모델 폐기 점검의 시작으로 보되, 모델이 고장 났다는 증거로 여기지는 않는다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Know when to retire a model
Retiring a model means stopping its use and replacing it. A refit is the lighter move, and it comes first. This chapter names three triggers for either move, and each one reads a number the loop already logs. The first retirement trigger is sustained drift: flags on consecutive days with no calendar cause. The second retirement trigger is an uncovered band: the 80% band covers well under 80% of readings on several days. The third is a change in a library the model depends on.
The second trigger needs a sense of what ordinary coverage looks like. On the ordinary days, Dec 27 to Dec 31, coverage at 80% stays between 0.701 and 0.790. Dec 29, when the late readings arrive, and Dec 31, New Year's Eve, count as ordinary days here. Dec 25 is lower, at 0.232, and Dec 26 is at 0.431, for the reason the flags gave. Dec 25 is the holiday, and Dec 26 reads it through lag 24. The bands are a little narrow even on ordinary days, as Chapter 8 found. So a day between 0.70 and 0.80 is normal here, and a day far below that is not.
To show what the flags and bands do, the chapter stages a change. It is invented for the test, not a fact about the supplier's data. From Dec 27, 2014, every reading of all thirty clients is multiplied by 0.6, as if demand had dropped by 40%. The held-out week then runs on the changed readings, with the same cadence, reference, rule and bands as before.
1"""Shows how a change appears in the flags: a stated test, not a fact about the data, in which every reading from Dec 27,22014 is multiplied by 0.6, as if demand had dropped by 40%. The calibration windows are earlier than the change, so the3reference and bands are fixed before it happens. The `held-out days flagged` and `coverage 80` lines show what the flags4and bands do, with the same cadence, reference, rule and bands as the held-out runs in drift-flag-rolling and5rolling-refit-seven-days."""6import pandas as pd78from lib.electricity import load9from lib.panel import ALL3010from lib.running import (CAL_DAYS, HELD_OUT_DAYS, band, coverage_by_day, daily_mase, flagged, prepare, run_days,11 scale_from, with_actuals)12from lib.settings import show1314raw = load(ALL30)15df = prepare(raw)16scale = scale_from(raw)17cal = with_actuals(run_days(df, CAL_DAYS), df) # calibration windows come before the change, so the reference is fixed before it18reference = daily_mase(cal, scale).median()19changed = df.copy()20after = changed["ds"] >= pd.Timestamp("2014-12-27") # the first changed day, Dec 27, from its midnight on21changed.loc[after, "y"] = changed.loc[after, "y"] * 0.6 # a stated test: every reading from Dec 27 at 60%, as if demand fell 40%22held = with_actuals(run_days(changed, HELD_OUT_DAYS), changed) # the changed readings go through the same loop, refits included2324show("reference, median daily MASE", reference)25mase = daily_mase(held, scale)26for day, value in mase.items():27 show(f"MASE {day:%Y-%m-%d}", value)28show("held-out days flagged", len(flagged(mase, reference)))29cov = coverage_by_day(band(held, cal, scale)) # the bands use the unchanged calibration days, as in the held-out run30for day, value in cov.items():31 show(f"coverage 80 {day:%Y-%m-%d}", value, digits=3)
python drift-after-a-change.pyreference, 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
All 7 held-out days are flagged. Dec 25 and Dec 26 are flagged for Christmas and its echo, as before, and each day from Dec 27, the first changed day, is flagged too. On Dec 27 the daily MASE is 4.74, and coverage falls to 0.078 that day, the lowest of the week.
One scheduled refit did not clear the flags. The refit on Monday, Dec 29, is the only step in this test that refits on changed readings, and it read Dec 27 and Dec 28 at the lower level. Its daily MASE fell by about 40%, from 2.93 on Dec 28 to 1.68 on Dec 29, but Dec 30 and Dec 31 stayed above the line. Coverage recovered to 0.328 on Dec 29 and 0.333 on Dec 31, still far below 80%.
A run of flags like this, with coverage that low, is a case for an early refit, and the book's rule is to refit early. We did not test an early refit on a day of its own, so that rule is a rule of thumb and not a measured result.
The third trigger is a library change. Libraries release often, and a later release can change an output even when the code stays the same. The loop depends on 1.1.0 and 4.7.0. Prophet, which Chapter 9 pins at 1.5.0, is not part of this loop, but it is another pinned library, and its release history shows how often such a library moves (PyPI release history). A release is a reason to run this chapter's checks again. It is not, by itself, a reason to retire a model.
These checks are the forecast log, the flags and the coverage of the bands. They are not a monitoring system. A monitoring system covers alerts, dashboards, data quality across many feeds and the people who respond. A later book on monitoring models in production can continue this case, and this chapter ends where that book would begin.
Working rule: Refit early when flags run on several days in a row with no calendar cause, or when the 80% band covers far below 80% of readings on several days, and record the trigger with the log. Retire the model when an early refit does not clear the flags. Re-run this chapter's checks when a pinned library is released, and keep the pins until the checks pass on the new version.
운영 환경에서 잘못되는 것들
피드는 이력 중간에서 끊길 수 있다. 루프는 피드가 전달하지 않은 측정값을 채우지 않는다. 중간에 빈 구간이 있으면 모든 지연값이 어긋나므로, 코드는 오류를 발생시킨다. 채우는 것은 시계 변경 시간대뿐이며, 이는 3장의 규칙을 따른다. 이력의 끝에서 여전히 빠져 있는 측정값은 다른 경우이며, 이는 늦게 도착하는 데이터 규칙이 처리한다.
재적합에서 누수가 생길 수 있다. 재적합이 예측하려는 날의 측정값을 읽으면, 백테스트는 실제 운영 결과보다 좋게 보인다. 같은 날짜에 대해 운영 MASE가 백테스트의 MASE보다 훨씬 높게 나타나므로 이를 알아챌 수 있다. 루프는 이력 규칙으로 이를 방지하며, 루프를 다시 작성할 때 반드시 유지해야 할 것이 이 규칙이다. 3장의 누수 검사인 시프트 테스트와 7장의 누수 검사인 오염 검사도 유지한다. 오염 검사는 기준 시점 이후의 모든 측정값에 잘못된 값을 덮어쓴 다음, 그 기준 시점의 재적합과 예측이 변하지 않는지 확인한다.
고객 서른 곳의 평균에 건 플래그는 한 고객의 변화를 가릴 수 있다. 한 고객에게 큰 변화가 생겨도 일별 MASE는 그 고객의 일별 MASE 변화량을 서른으로 나눈 만큼만 움직인다. 스트레스 예제는 모든 고객을 한꺼번에 움직이므로 플래그가 작동한다. 고객 한 곳만 바뀌는 경우는 시험하지 않았다. 그 고객 자신의 MASE가 보정 중앙값보다 훨씬 높게 나타나므로 이를 알아챌 수 있다. 이것이 우리가 가장 먼저 메우고자 하는 빈틈이며, 각 고객 자신의 MASE에 두 번째 플래그를 두는 방법을 생각할 수 있다.
버전을 고정한 라이브러리도 고정 버전을 갱신하면 동작이 바뀔 수 있다. 채점 절의 널 값 오류는 mlforecast 1.1.0의 동작이다. 이후 버전은 빈 구간을 채우거나 버리거나 받아들일 수 있고, 그러면 예측이 달라진다. 고정 버전을 갱신하는 것은 예측을 바꾸는 일이며, 검사를 다시 실행해야 한다.
마지막 실패는 사후에 작성한 로그이다. 예제 어디에도 팀이 나중에 로그를 다시 만드는 것을 막는 장치는 없으며, 다시 만든 출력은 올바르게 보일 것이다. 두 도착 열과 그 검사가 이를 드러낸다. 이 검사를 없애면 로그는 더 이상 아무것도 증명하지 못한다.
작업 규칙: 모든 실행에서 세 가지 검사를 유지한다. 각 재적합과 예측에서 미래를 배제하는 이력 규칙, 각 로그 행의 두 도착 검사, 그리고 3장과 7장의 누수 검사이다. 이 중 하나라도 실패하면 루프를 멈추고, 다음 예측 전에 원인을 고친다. 이력이나 로그를 손으로 고치지 않는다. 손으로 고치는 것은 검사가 잡아내기 위해 존재하는 바로 그런 종류의 변경이기 때문이다.
이 장에서 내린 결정
- 재적합 주기: 7일마다, 월요일에 한다. 결정 구간에서 평균 MASE는 주간 주기가 더 낮았으며, 그 차이는 0.008이다. 이 차이는 모델의 나이만으로도 생기는 변동 폭 안에 들기 때문에 동점 처리 규칙을 적용하고, 이 책은 재적합 횟수가 더 적은 주기를 택한다.
- 하나의 MASE 척도: 2014년 11월 25일 이전의 측정값에서 읽어 내며, 2장의 규칙에 따라 이 장의 모든 실행에 사용한다. 따라서 결정일, 보정 구간, 보류한 날이 하나의 기준으로 채점되고, 채점 대상인 시간은 어느 것도 이 척도를 정하는 데 쓰이지 않는다.
- 경보 규칙: 어떤 날의 MASE가 보정 구간(2014년 12월 9일~12월 20일)의 일별 MASE 중앙값의 두 배를 넘으면 그날에 경보를 표시한다. 2라는 배수는 경험칙으로 밝혀 둔 값이며, 일반적인 결정 구간보다 여유가 있다는 이유로 유지한다.
- 구간: 80%만 쓴다. 폐기(은퇴) 트리거가 이 수준을 읽기 때문이며, 8장은 95%도 제시한다. 구간은 보정 구간 열두 개에서 같은 시간대의 척도화된 잔차를 서른 고객에 걸쳐 모은 값으로 만들며, 보류한 주 이전에 고정한다. 총량 예측, 총량 구간, 구매 분위수는 기록하지 않는다. 따라서 기록은 고객별 예측을 점검할 뿐, 8장에서 총량을 기준으로 하는 구매는 점검하지 않는다. 총량을 기준으로 구매하는 공급업체라면 그 분위수를 기록에 추가해야 한다.
- 늦게 도착한 측정값: 재적합에서는 제외하고, 예측에서는 한 주 전 같은 시간의 값으로 채우며, 기록에 그 수를 센다. 도착하면 채점하고, 이미 낸 예측을 다시 만드는 데에는 쓰지 않는다. 이 채움 방식은 결정 구간에서 골랐다. 이 규칙은 출처가 없으며 이 책 자체의 규칙이다.
- 범위: 서른 고객에 대한 7일이다. 한 주에는 공휴일, 늦게 도착한 측정값, 그 주 안에 드는 주간 재적합이 들어 있으므로 각 규칙이 드러난다. 더 긴 실행이라면 평범한 날이 얼마나 자주 경보 대상이 되는지를 측정하겠지만, 이 장은 이를 측정하지 않는다.
- 모니터링의 경계: 이 장의 점검만 다룬다. 이 점검을 시간에 걸쳐 감시하는 모니터링 시스템은 이 책의 범위 밖이다.
- 독자의 사례: 이 책의 마지막 결정은 작업을 독자에게 돌려준다. 공급업체의 사례는 여기서 끝나며, 주간 재적합, 각 예측이 읽은 내용을 점검하는 기록, 측정값이 도착하는 대로 하는 채점, 백테스트에 대한 경보가 그 결과다. 독자의 사례에서는 이 결정들을 독자의 데이터로 다시 내려야 한다. 재적합 주기는 평범한 결정 구간에서, 늦은 데이터 규칙은 실제로 받는 피드에서, 경보 배수는 보정 구간에서, 구간 수준은 구매 규칙이 요구하는 값에서 정한다. 각 결정은 보류한 주보다 앞선 날들에서 내린다.
이 판의 이 장
2026.11.11판예제 통과 2026년 11월 20이 장에서 5개 예제개 중 5개가 통과한다
영어판 2026.11.11판을 번역한 것이다.