내일의 수요 예측하기
읽는 데 약 45분분 걸린다, 7절에 3개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.11판을 번역한 것이다. 원문 읽기
이 장에서는 내일의 수요에 대한 첫 예측과, 이후의 모든 예측이 넘어서야 하는 단순한 기준선을 만든다. 한 고객의 시간별 수요를 불러오고, 계절성 단순 기준선과 통계 모델 하나로 다음 날을 예측한 뒤, 두 예측을 같은 7일에 대해 채점한다. 결과는 의도적으로 거칠다. 예측 구간도 없고, 튜닝도 없으며, 판단의 근거도 고객 한 명뿐이다. 이후의 각 장에서 그중 한 부분씩을 탄탄하게 다진다. 필요한 것은 Python, pandas, 표본의 평균, 그리고 오차가 무엇인지에 대한 이해뿐이며, 핵심 용어는 처음 나올 때 한 줄로 정의한다.
내일의 전기는 오늘, 하루가 시작되기 전에 한 시간 단위로 구매해야 한다. 전기를 구매하는 쪽은 고객이 그 시간마다 얼마나 사용할지에 대한 예측이 필요하며, 예측이 빗나가는 시간마다 구매 계획은 잘못된 수치를 기준으로 짜인다. 따라서 어떤 방법이든 신뢰하기 전에 두 가지 질문에 답해야 한다. 구매 이전에 기록된 측정값만으로 만든 예측은 고객이 실제로 사용한 양에 가까운가? 그리고 누구나 만들 수 있는 가장 단순한 예측, 즉 어제를 그대로 베끼는 예측보다 나은가?
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
The case and its data
This book follows one case throughout: an electricity supplier that buys power a day ahead for its clients, which we call the supplier.
The supplier commits to its purchases before the day starts, and it needs a range as well as a single number, because buying too little costs more than buying too much. This book builds the forecast that such a purchase starts from. A forecast here is the expected demand of one client in each hour, made from readings recorded before the forecast was made.
Three terms fix what a forecast is. The moment a forecast is made is its cutoff. A forecast uses only the readings before its cutoff, and it reaches forward a fixed number of hours, its horizon. A window is one cutoff with its horizon and the forecast it produces. Here the horizon is 24 hours, so each window covers one day: the 24 hours that start at its cutoff.
The timing matters as much as the method. Every window in this book has its cutoff at 00:00 on the day it predicts, so the last reading it can use is the one for 23:00 on the day before. The case buys before the day starts, so a midnight cutoff is a simplification. The book keeps it so that each window needs only the day before. A supplier that buys earlier would cut earlier and forecast further ahead. A forecast that reads one hour past its cutoff would use information the supplier does not have when it buys, and its score would flatter it.
The data is public. It is the ElectricityLoadDiagrams20112014 dataset from the UCI Machine Learning Repository, by Trindade (2015), with the DOI 10.24432/C58C86. It is licensed under CC BY 4.0. The book ships a cut of it, electricity_hourly.csv.gz, with the licence beside it in the same folder. The data card gives the source, the cut and its limits.
The raw file holds 370 clients, with a reading every 15 minutes. The cut averages the four readings of each hour, which gives the energy used in that hour in kWh, and it keeps two whole years, 2013 and 2014. One client, MT_223, has no non-zero reading in that window, so the cut drops it. The 369 clients that remain are sorted by id, and 30 are kept at evenly spaced positions. A reader who cuts the raw file must drop MT_223 and take the same 30 evenly spaced positions, or the counts in this book will not match.
The clients have anonymous ids such as MT_014. The dataset does not say what they are, so the book calls them clients. It does not describe them as companies or households.
Two groups of clients recur through the book. The thirty clients are every client in the cut. The 8 clients of SUBSET8 are every fourth client of the thirty, starting with the second. Later chapters use that subset where a full run would take too long, and it includes one client that starts late. The lead client, MT_014, is the first client of SUBSET8. This chapter and its single-client examples use it.
The test period is the last week of 2014, from Dec 25 to Dec 31, 2014. The forecasts in this chapter are scored on it, and it is called the held-out week. Each forecast uses only readings from before its cutoff, so no forecast learns from the day it predicts. The week is not quiet. Dec 25, 2014 is Christmas Day, a national holiday in Portugal, where the data's clock is set. This chapter scores the week as it is, and the scores show what the holiday does. Chapter 5 tests a holiday flag on holiday windows and does not keep it, so the book does not repair the holiday here. Chapter 10 shows its cost.
A forecast says what demand is likely to be. It does not say why. The data records how much each client used. It cannot say what demand would have been under a different price or contract. That is a causal question, and it needs a different design.
Working rule: Check the cut against the data card before any forecast is made. The file should hold 30 clients, and the example counts how many of them have a full two years of hourly rows. Those counts should match the card. Confirm that MT_223 is missing and explained. A cut that does not match the card is different data, and every number computed from it describes that data, not this one.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Load one client's hourly demand
A time series is a sequence of readings in time order. In the book's file, each row is one client in one hour, and each client's hours are in time order. To load one client, keep that client's rows. The helper load in examples/lib/electricity.py does that and returns four columns. unique_id names the client. ds is the hour. y is the energy used in that hour, in kWh. quirk tells you whether the row needs special handling.
The ds column is the start of the hour, in local clock time with no time zone. The data card gives this label, and the book's examples treat the index as one naive hourly index. Each row's quirk is one of four labels:
normalis an ordinary hour.before_first_readingis an hour before a client's first non-zero reading. Only a late-starting client has these rows.clock_change_gapis 01:00 on a March clock-change day. The dataset's note says it reads zero for every client. The data card measures it: of 57 such hours with non-zero neighbours, 55 read below 5% of them.clock_change_repeatis 01:00 on an October clock-change day. It holds about two hours of energy under one label.
The book keeps every value as the meter recorded it. Nothing is filled, smoothed, removed or rescaled. A zero in a gap hour and a doubled October hour are therefore still in the file, flagged but not corrected. Chapter 3 decides what each flagged row means for a model. This chapter only needs to know the labels exist, and to check that none of them falls inside the windows it scores.
The lead client has readings in every hour of the window, so none of its rows are before_first_reading. Over the two years it has 17516 ordinary rows. It has 2 gap rows and 2 repeat rows, one of each in each year.
1"""Loads the lead client's hourly demand, counts its quirk labels, and checks the eight-week history before each2held-out cutoff. The point rests on the last printed line: no history holds a clock-change row."""3from lib.backtest import held_out_cutoffs, history_before4from lib.electricity import load5from lib.settings import LEAD, show678def fmt(ts):9 return ts.strftime("%Y-%m-%d %H:%M")101112FULL_ROWS = 2 * 365 * 24 # two years of hours; 2013 and 2014 are not leap years1314everyone = load()15show("clients in the file", everyone["unique_id"].nunique())16show(f"clients with {FULL_ROWS} rows", int((everyone.groupby("unique_id").size() == FULL_ROWS).sum()))1718df = load([LEAD])19show("rows", len(df))20show("first reading", fmt(df["ds"].min()))21show("last reading", fmt(df["ds"].max()))22for quirk in ["normal", "before_first_reading", "clock_change_gap", "clock_change_repeat"]:23 show(f"{quirk} rows", int((df["quirk"] == quirk).sum()))2425# history_before keeps the HISTORY_HOURS hours (eight weeks) before each cutoff, and raises if a count is off.26windows = [history_before(df, cutoff) for cutoff in held_out_cutoffs()]27show("history rows per window", min(len(w) for w in windows))28show("longest history rows", max(len(w) for w in windows))29show("first history reading", fmt(windows[0]["ds"].min()))30# Counts only the two clock-change labels.31show("clock-change rows in held-out histories",32 sum(int(w["quirk"].isin(["clock_change_gap", "clock_change_repeat"]).sum()) for w in windows))
python load-lead-client.pyclients in the file: 30
clients with 17520 rows: 30
rows: 17520
first reading: 2013-01-01 00:00
last reading: 2014-12-31 23:00
normal rows: 17516
before_first_reading rows: 0
clock_change_gap rows: 2
clock_change_repeat rows: 2
history rows per window: 1344
longest history rows: 1344
first history reading: 2014-10-30 00:00
clock-change rows in held-out histories: 0
The file holds 30 clients. The lead client has 17520 rows, from 2013-01-01 00:00 to 2014-12-31 23:00.
Two years of hours is 17520 rows for each client, and 30 of 30 clients have exactly that many, so no hour is missing from the file for those clients. A window with fewer hours than its history should hold has a gap, and the gap would be the first thing to explain. Check the client count and the row count against the card.
A forecast needs history. The book's history is 8 weeks, which is 1344 hours, and each cutoff in the held-out week gets exactly that much before it. The shortest history has 1344 rows, and the longest has 1344.
For the first cutoff of the held-out week, the history begins at 2014-10-30 00:00. That is after the clock change of Oct 26, 2014, which the data card dates. So none of the 7 histories holds a clock-change hour, and the example counts 0 clock-change rows across all seven.
The rest of this chapter can leave the clock-change rows alone for that reason. Chapter 3 meets them, and Chapter 4 meets the late starter.
Working rule: Choose the client and the window first, then count the quirks in that window's history before any model sees it. If a history holds a clock-change label or a before_first_reading row, do not hand it to a model unchanged, because the model will read the label's value as demand. Chapter 3 and Chapter 4 give the rules for those rows. A window that holds neither can use its rows as they are, as this chapter does.
계절성 단순 예측으로 다음 날 예측하기
첫 번째 예측은 만들기 가장 간단한 예측이며, 이후의 모든 예측은 이 예측을 능가해야 한다. 이 예측은 사례와 데이터의 기준 시점과 예측 구간, 그리고 클라이언트 하나 불러오기에서 설명한 이력을 사용한다.
계절성 단순 예측은 미래의 각 값이 같은 계절에 마지막으로 관측된 값과 같다고 본다. Hyndman과 Athanasopoulos는 임의의 길이 m의 계절에 대해 이를 정의한다. 미래 값의 예측은 한 계절 전에 관측된 값이다(Hyndman and Athanasopoulos, Forecasting: Principles and Practice, ch. 5). 시간 단위 데이터에 일 주기를 적용하면 계절은 24시간이므로, 내일 어느 시각의 예측은 오늘 같은 시각의 측정값이다. 이 책의 표기로는 시각 t의 예측이 y(t - 24)이다.
이 규칙에는 적합시키는 것이 하나도 없다. 예측은 데이터의 복사본이므로 추정 단계가 필요하지 않다. 또한 어떤 기준 시점에서든 기준 시점보다 앞선 데이터를 읽지 않는다. 기준 시점부터 그 23시간 뒤까지의 각 시각에서 t - 24은 기준 시점 24시간 전부터 기준 시점 직전 시각 사이에 놓이므로, 복사에는 이력만 쓰인다.
보류한 한 주에는 7개의 윈도가 있다. 윈도는 2014년 12월 25일부터 12월 31일까지 하루에 하나씩이며, 각각 00:00에 만든다. 공급자의 질문은 MT_014의 내일 수요이다. 12월 25일의 예측은 12월 24일의 각 시각 측정값을 복사하며, 같은 규칙이 한 주의 나머지 날에도 전날로부터 예측을 만든다.
12월 25일 00:00의 윈도를 구체적인 사례로 들어 보자. 이 윈도의 12월 25일 00:00 예측은 12월 24일 00:00의 측정값이고, 12월 25일 23:00 예측은 12월 24일 23:00의 측정값이다. 이력의 1344시간 중 이 방법이 쓰는 것은 마지막 24시간뿐이다. statsforecast의 _seasonal_naive가 마지막 계절의 값을 반복하기 때문이다(statsforecast 2.1.1, statsforecast/utils.py). 그래도 예제는 이력 전체를 넘긴다. 이력을 더 많이 쓰는 모델에도 같은 호출을 쓰며, 이력 길이가 하나인 호출 하나면 배워야 할 형태가 둘이 아니라 하나이기 때문이다.
왜 주가 아니라 하루인가? 168시간의 계절은 한 주 전 같은 요일의 같은 시각을 복사하며, 주간 리듬이 있는 시계열에는 이것도 타당한 기준선이다. 이 장이 일 단위 계절을 쓰는 이유는 질문이 다음 날이고, 사례에 필요한 것이 하루 앞 예측이기 때문이다.
1"""Forecasts the lead client's next day with seasonal naive for each day of the held-out week, then scores it.2The point rests on the MAE and RMSE lines, which score a copy of yesterday, and on the missing forecasts line."""3import pandas as pd4from statsforecast import StatsForecast5from statsforecast.models import SeasonalNaive67from lib.backtest import forecast_windows, held_out_cutoffs, scoring_counts, score_windows, window_mae8from lib.electricity import load9from lib.settings import HORIZON, LEAD, show101112def day_mean(day):13 return df[df["ds"].dt.normalize() == pd.Timestamp(day)]["y"].mean()141516# statsforecast reads a frame with three columns: the series id, the time and the value.17df = load([LEAD])[["unique_id", "ds", "y"]]18# season_length 24 is the daily cycle of hourly data; freq "h" is pandas' code for hourly steps; one job runs in one process.19sf = StatsForecast(models=[SeasonalNaive(season_length=24)], freq="h", n_jobs=1)20forecasts = forecast_windows(sf, df, held_out_cutoffs())21scores = score_windows(df, forecasts, "SeasonalNaive")22counts = scoring_counts(df, forecasts, "SeasonalNaive")2324show("horizon hours", HORIZON)25show("windows", counts["windows"])26show("scored hours", counts["scored_hours"])27show("missing forecasts", counts["missing_forecasts"])28# The readings at the forecast hours, which are the hours the scores cover.29show("mean demand", df[df["ds"].isin(forecasts["ds"])]["y"].mean())30show("mean demand 2014-12-24", day_mean("2014-12-24"))31show("mean demand 2014-12-25", day_mean("2014-12-25"))32show("MAE", scores["mae"])33show("RMSE", scores["rmse"])34for day, mae_day in window_mae(df, forecasts, "SeasonalNaive").items():35 show(f"MAE {day:%Y-%m-%d}", mae_day)3637# The check is run on a history with one hour removed, to show it refuses a short history.38cutoff = held_out_cutoffs()[0]39gap = df[df["ds"] != cutoff - pd.Timedelta(hours=1)] # drops the hour just before the first cutoff40try:41 forecast_windows(sf, gap, [cutoff]) # history_before raises ValueError unless every client has exactly HISTORY_HOURS rows before the cutoff.42 refused = "no"43except ValueError:44 refused = "yes"45show("history with one hour removed refused", refused)
python seasonal-naive-next-day.pyhorizon hours: 24
windows: 7
scored hours: 168
missing forecasts: 0
mean demand: 46.62
mean demand 2014-12-24: 47.58
mean demand 2014-12-25: 38.40
MAE: 8.36
RMSE: 10.87
MAE 2014-12-25: 9.41
MAE 2014-12-26: 12.16
MAE 2014-12-27: 5.10
MAE 2014-12-28: 11.16
MAE 2014-12-29: 8.68
MAE 2014-12-30: 5.26
MAE 2014-12-31: 6.75
history with one hour removed refused: yes
각 예측은 이후의 측정값과 비교해 채점하며, 채점 대상 168시간 모두에 예측이 있다. 이 시간들의 평균은 46.62 kWh이며, 이 장의 모든 오차는 이 수준을 기준으로 읽어야 한다.
계절성 단순 예측은 기준선이며, 일 주기가 시계열을 지배할 때는 강력한 기준선이 될 수 있다. 약점은 하루만 복사한다는 점이다. 평소와 다른 날이 다음 날의 예측이 되며, 이 방법에는 그것을 평균으로 상쇄할 방법이 없다.
작업 규칙: 일 주기가 있는 시간 단위 시계열을 비교할 때는 항상 계절성 단순 예측을 포함한다. 적합이 필요 없으므로 모든 윈도에서 추가 비용 없이 실행된다. 같은 윈도에서 이 예측을 능가하지 못하는 모델은 추가 작업이 정당하다는 것을 입증하지 못한 것이다. 점수를 읽기 전에 예측에 결측값이 있는지 확인한다. 마지막 계절의 결측 측정값이 결측 예측이 되기 때문이다. 3장에서 어떤 모델이든 실행하기 전에 그 시간들을 채우는 규칙을 다룬다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Forecast the next day with one model
The baseline above answers what a forecast gets with no model at all. The question here is whether a fitted model does better on the same 7 windows, and the model is AutoETS. statsforecast 2.1.1 describes AutoETS as selecting the best ETS (error, trend and seasonality) form with an information criterion (statsforecast/models.py, class AutoETS). The criterion AutoETS uses is AICc, the Akaike information criterion corrected for small samples. It is set in ets_f, in statsforecast/ets.py, and AutoETS offers no other.
The model string sets which forms the model may take, with one letter each for error, trend and season. Z lets AICc choose, and A fixes the form to additive. This chapter uses ZZA: AICc chooses the error and the trend, and the season is additive, so every candidate has a daily cycle. The default, ZZZ, also lets AICc choose the season. On this client and these 7 cutoffs it chose no season in every window, a flat form, ETS(A,N,N), so its forecast is one value repeated for the day. This chapter asks whether a model with the daily cycle beats a copy of yesterday, so it does not use that form. Other seasonal forms score differently on this week, and Chapter 4 looks at the forms and the choice.
A fit does three things, and each one matters for what the score means. At a cutoff, AutoETS reads the 1344 hours before it and compares the candidate forms, keeping the one with the lowest AICc. AICc rewards a close fit to the history and charges for each parameter the form uses, so a form with more parameters must fit much better to win. The model then projects that form 24 hours ahead. The held-out week therefore means 7 separate selections, not one. In this week 7 windows chose ETS(A,N,A): additive error, no trend and an additive daily season. The 7 fits still differ in their parameters. The book does not quote them, because each is a detail of one fit, and a reader should not take it as a finding.
The comparison is fair only when nothing else changes. It uses the same 7 cutoffs and the same 1344 hours of history before each one, and it refits the model at every cutoff using only the history before that cutoff. Only the model differs from the baseline.
1"""Forecasts the lead client's next day with AutoETS for each day of the held-out week, then scores it.2The point rests on the MAE and RMSE lines, read against the seasonal naive example, and on the form counts."""3import numpy as np4from statsforecast import StatsForecast5from statsforecast.models import AutoETS67from lib.backtest import chosen_forms, forecast_windows, held_out_cutoffs, scoring_counts, score_windows, window_mae8from lib.electricity import load9from lib.settings import HORIZON, LEAD, SEED, show1011# Seeded by convention. AutoETS's point forecast draws no random numbers, so this line changes nothing here.12np.random.seed(SEED)13# statsforecast reads a frame with three columns: the series id, the time and the value.14df = load([LEAD])[["unique_id", "ds", "y"]]15# model="ZZA": AICc chooses the error and trend forms; the seasonal form is fixed to additive, so every form has a day cycle.16sf = StatsForecast(models=[AutoETS(season_length=24, model="ZZA")], freq="h", n_jobs=1)17forecasts = forecast_windows(sf, df, held_out_cutoffs())18scores = score_windows(df, forecasts, "AutoETS")19counts = scoring_counts(df, forecasts, "AutoETS")20# chosen_forms refits at each cutoff to read the form each fit picked; the forecasts above do not report it.21forms = chosen_forms(sf, df, held_out_cutoffs())2223show("horizon hours", HORIZON)24show("windows", counts["windows"])25show("scored hours", counts["scored_hours"])26show("missing forecasts", counts["missing_forecasts"])27for form, n in forms.items():28 show(f"windows that chose {form}", n)29show("MAE", scores["mae"])30show("RMSE", scores["rmse"])31for day, mae_day in window_mae(df, forecasts, "AutoETS").items():32 show(f"MAE {day:%Y-%m-%d}", mae_day)
python autoets-next-day.pyhorizon hours: 24
windows: 7
scored hours: 168
missing forecasts: 0
windows that chose ETS(A,N,A): 7
MAE: 8.86
RMSE: 10.91
MAE 2014-12-25: 13.51
MAE 2014-12-26: 11.21
MAE 2014-12-27: 4.17
MAE 2014-12-28: 10.03
MAE 2014-12-29: 9.53
MAE 2014-12-30: 6.33
MAE 2014-12-31: 7.25
The counts match the baseline's, so the two scores cover the same 168 hours, and all 7 windows chose the same form. The model makes 7 fits, one at each cutoff, and each sees only what was known at its cutoff. The next section sets the scores side by side.
Working rule: Add a model only with a baseline it has to beat on the same windows. Refit the model at each cutoff, using history from before that cutoff only. A model fitted once on the whole series and then scored on that series has seen the answers, and its score is not a forecast score.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Score both on a held-out week
Both examples have now made 7 day-ahead forecasts, from the two sections above. A score turns the errors of a set of forecasts into one number. The error of an hour is the actual demand minus the forecast. This chapter uses two scores. The mean absolute error, MAE, is the average size of the miss: MAE = mean(abs(actual - forecast)). The root mean squared error, RMSE, is RMSE = sqrt(mean((actual - forecast)^2)). Both are in kWh, and they answer different questions. Hyndman and Athanasopoulos, in Forecasting: Principles and Practice, ch. 5, note that a forecast minimising MAE is a forecast of the median, and one minimising RMSE is a forecast of the mean. Because RMSE squares each error, a few large misses raise it more than they raise MAE.
Both scores come from utilsforecast (0.2.17). Its mae is the mean of the absolute errors, and its rmse is the square root of the mean of the squared errors (utilsforecast/losses.py, functions mae and rmse). The scores pool the 168 scored hours. Each hour counts once, and each of the 7 windows contributes 24 of them.
Read the table against the mean demand of 46.62 kWh an hour: a lower number means forecasts closer to the readings.
| Model | MAE (kWh) | RMSE (kWh) |
|---|---|---|
| SeasonalNaive | 8.36 | 10.87 |
| AutoETS | 8.86 | 10.91 |
AutoETS's errors are higher than the baseline's on both scores, as the table shows, with MAE at 8.86 kWh against 8.36. The MAE is the number to plan with, because it is the typical miss in each hour. RMSE is always at least MAE. For normal errors RMSE is about 1.25 times MAE, so a ratio well above that means a few large misses. This section reads the two scores together and goes no further, because one client over one week cannot show the spread of the misses.
Both models do worst around Christmas, but on different days. The daily lines show where: the baseline's worst day is Dec 26, the day after Christmas, when it copies Christmas Day, at 12.16 kWh an hour, the largest of the 7. AutoETS's worst day is Dec 25 itself, at 13.51 kWh, against 9.41 for the baseline. A gap of this size on one client over one week is not a verdict. Seven forecasts make a small sample, and a ranking built on one week can flip on the next. Chapter 3 backtests seasonal naive over a year of Sunday cutoffs.
The score also has to match the decision, and the purchase is lopsided: as the case says, buying too little costs more than buying too much. MAE and RMSE treat a miss in either direction alike, because they use the size of each miss and not its sign. That is enough for this chapter, which asks whether a forecast is close. It is not enough for the purchase. Chapter 8 builds ranges for that decision, and scores them against what happened.
Working rule: Score each model on forecasts it made without the scored hours in its history, over more than one day, and report the number of windows and hours behind each score. Compare models only on the same windows. Read MAE and RMSE together. If they disagree about which model is better, look at the largest misses in the windows before you choose, because a few large misses can decide the result.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
What goes wrong in production
The forecasts and scores above can go wrong in 5 ways, and only some of them print an error. The cutoff rule and the seasonal naive rule say what each window must hold.
The first failure is a label that is off by an hour, and no score in this chapter detects it. If a reader takes ds as the end of its hour rather than the start, the forecasts and the readings they are scored against carry the same shift, so the score does not change. The error is in the purchase instead: the forecast would cover different hours from the ones the supplier buys for. The data card fixes the label, so it is the first thing to check when a forecast is moved to new data.
Leakage flatters a window whose history includes the hours it predicts, and nothing in the score says so. Hewamalage, Ackermann and Bergmeir (2022) warn that rolling-origin evaluation is prone to this leak when it is not done with care. The checks here are the cutoff rule and the history length. Each history must end before its cutoff and hold 1344 rows. history_before raises an error when a history is short or long. A history with one hour removed is refused: the check at the end of the seasonal naive example prints yes for it.
Seasonal naive copies yesterday, so an unusual day becomes tomorrow's forecast, and the held-out week holds one. Dec 25, 2014 is Christmas Day, and the lead client's mean demand that day is 38.40 kWh an hour, against 47.58 kWh on Dec 24. The window for Dec 26 copies that day, so it has the largest MAE of the 7 windows, 12.16 kWh. That is the failure, and the scores show it. One holiday is too few to measure a holiday effect, so the book leaves it alone, as the case and its data explains. Chapter 10 shows its cost.
A missing reading gets through unchecked. The statsforecast seasonal naive does not check its input. It repeats the last season's values, so a missing value in that season becomes a missing forecast (statsforecast 2.1.1, statsforecast/utils.py, function _seasonal_naive). The seasonal naive example counts missing forecasts, 0 here, because a hole in the forecast is an hour the score does not describe. Chapter 3 fills the hours that need filling, from data before the cutoff, before any model runs.
Last, the window itself can flatter the method. A week with no unusual days can make almost any forecast look good, and a week with one can make every forecast look bad. The held-out week has a holiday in it, and it is still one week for one client, so its scores describe that week more than the method. The fix is breadth: compare models on several windows of different kinds before you trust a ranking.
Working rule: Before you trust a score, check three things in this order: each window's first forecast hour is its cutoff, each history ends before its cutoff and holds the full history length, and no forecast is missing. The helpers raise an error for the first two, and the examples print the third. A score counts as a finding only after all three pass.
이 장에서 내린 결정
이 장에서는 아홉 가지를 선택했다. 대부분은 examples/lib/settings.py의 설정이므로, 이후 판에서 설정 하나를 바꾸면 그 설정을 쓰는 모든 장에 그 변경이 적용된다. 나머지는 데이터 카드나 이 장에 적혀 있다. 2장은 이 두 예측과 두 점수에서 출발하여, 둘 중 어느 하나라도 그에 따라 행동할 만큼 충분히 좋은지 묻는다.
- 각 윈도의 기준 시점(cutoff)은 그 윈도가 예측하는 날의 00:00이고 예측 구간(horizon)은 24시간이므로, 각 윈도는 그 하루를 포함한다.
- 각 기준 시점 이전의 이력은 1344시간이며, 이는 8주에 해당한다.
- 대표 클라이언트는
MT_014이다. 평가에서 제외한 주(held-out week)는 2014년 12월 25일부터 12월 31일까지이며, 윈도는 7개, 채점 대상 시간은 168시간이다. - 점수는 MAE와 RMSE이며, 채점 대상 시간 전체에 걸쳐 합산하여 소수점 둘째 자리까지 출력한다.
- 모델은 주기가 24시간인 계절성 나이브(seasonal naive)와, 모델 문자열이
ZZA이고 주기가 24시간인 AutoETS이다. 각 실행은 작업 하나로 statsforecast를 사용한다. 두 점 예측 모두 난수를 쓰지 않으므로, 관례에 따라 AutoETS 예제가 설정하는 시드는 그 예측에 아무 영향도 주지 않는다. - 데이터 카드에 설명한 대로, 이 절단(cut)은
MT_223을 제외하고 클라이언트 30개를 남긴다. - 이 장의 어떤 이력에도 시계 변경(서머타임 전환) 행과 늦게 시작한 클라이언트의 행이 들어 있지 않으므로, 이 행들은 그대로 둔다. 이 행들은 3장과 4장에서 다룬다.
- 본문이 인용하는 모든 수치는 해당 예제의 기록된 출력에 있는 이름 붙은 줄에 연결되어 있으므로, 본문과 출력이 모르는 사이에 어긋날 수 없다.
- 이 장은 클라이언트 하나의 예측만 만들고 예측 범위는 다루지 않는다. 예측 범위는 8장에서 시작한다.
이 판의 이 장
2026.11.11판예제 통과 2026년 11월 20이 장에서 3개 예제개 중 3개가 통과한다
영어판 2026.11.11판을 번역한 것이다.