모델이 넘어야 할 기준선 정하기
읽는 데 약 43분분 걸린다, 7절에 2개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.11판을 번역한 것이다. 원문 읽기
이 장에서는 한 고객의 하루 전 예측에 대해 나이브(naive), 계절 나이브(seasonal naive), 주 평균(average of weeks)의 세 가지 기준선을 계산한다. 그리고 예측 주 이전의 측정값만 읽는 척도를 사용해 MASE로 고객의 오차를 척도화한다.
Chapter 1은 검증용으로 떼어 둔 주에 대한 두 개의 점수로 끝났다. 그러나 kWh 단위의 오차는 그 자체로는 아무 의미가 없으므로, 두 점수는 아직 판단할 수 없다. 각 시간대의 예측에 따라 전력을 구매하는 공급자는 각 모델의 오차를 같은 시간대에서 가장 단순한 예측이 받는 점수와 견주어야 하고, 고객의 수요가 하루에서 다음 날로 넘어갈 때 얼마나 변하는지와도 견주어야 한다. 이 장은 이 두 가지 비교를 구성한다. 공급자가 모델이 비용만큼의 가치가 있다고 말하려면 먼저 이 비교가 필요하다.
모든 오차는 한 시간에 대한 킬로와트시 단위의 빗나감이며, 여기서의 점수는 그 빗나감을 시간별로 평균한 값이다. 기준선의 점수도 같은 종류의 수치이다. 그 점수는 가장 단순한 규칙이 하루 중 평균적인 한 시간에 얼마의 킬로와트시 오차를 남기는지를 나타내며, 그 수치를 넘지 못하는 모델은 추가 비용을 치를 만한 자격을 얻지 못한 것이다. 그러므로 각 점수는 다른 행의 점수와 비교할 뿐 아니라 대표 고객의 평균 수요와도 견주어 읽는다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Why a baseline comes first
A baseline is a forecast that needs no fitting. It copies a value the history already holds, so it costs almost nothing to run, and it sets a bar that any model has to clear. A model earns its place only by beating a forecast that cost nothing. Fitting time, tuning and keeping a model running are all costs, and the baseline's score measures what those costs buy.
Three terms matter here. The cutoff is the hour at which a forecast is made. The cutoff is the first hour the forecast covers, and the history is every reading before the cutoff. The horizon is how far ahead a forecast reaches, here 24 hours. A window is one cutoff together with the horizon it covers, and a backtest is the score of many windows, each made as it would have been made on its day.
The comparison has to be fair, or it measures the setup and not the model. A baseline scored on different hours, with a different history or a different scoring routine, says nothing about the model beside it. So every method in this chapter takes its cutoffs from held_out_cutoffs(), the seven daily cutoffs at 00:00 of the held-out week, reads its history through history_before(), which takes the eight weeks of hours before a cutoff, and is scored by the same code. These are the seven windows Chapter 1 used.
Working rule: Score every baseline on the same windows, histories and scoring code as the model it will be compared with, and count each baseline's missing forecasts before you read its score. A model that beats a baseline scored on different hours has not beaten it.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Three baselines to beat
Each baseline copies the history in a different way. Naive carries the last hour it has seen forward across the whole day. Seasonal naive copies the day before, hour for hour. Average of weeks takes the mean of that hour on that weekday over the four weeks before.
Every rule covers the 24 hours after a cutoff. Call the cutoff T, the hour at which the forecast is made, and let k run from 0 to 23 across the hours the forecast covers. The three rules are these:
- Naive repeats the last reading before the cutoff:
forecast(T + k) = y(T - 1). - Seasonal naive repeats the reading one day earlier:
forecast(T + k) = y(T + k - 24). - Average of weeks takes the mean of the same hour on the same weekday over the four weeks before:
forecast(T + k) = (y(T + k - 168) + y(T + k - 336) + y(T + k - 504) + y(T + k - 672)) / 4.
The lags are in hours, so 168 is one week. Every reading a rule uses comes from before the cutoff: naive's is the hour before it, seasonal naive's are the 24 hours before it, and average of weeks reaches back one to four weeks. Take the window at 00:00 on Dec 25, 2014 as a worked case. Naive gives every hour of Dec 25 the reading at 23:00 on Dec 24, so the forecast is flat. Seasonal naive gives 00:00 on Dec 25 the reading at 00:00 on Dec 24, and so copies the whole previous day's shape. Average of weeks gives 00:00 on Dec 25 the mean of the 00:00 readings on Dec 18, Dec 11, Dec 4 and Nov 27. That mean smooths out one unusual day, but it also averages in any level change across the four weeks.
Each rule fails in a known way. Naive gives every hour of the day the same value, so it cannot follow the daily peak at all. Seasonal naive copies one day, so an unusual day is copied into the forecast for the next day, as the per-day errors later in this section show on the held-out week. Average of weeks needs four clean weeks, and a holiday in any of them enters the mean with the same weight as an ordinary day. A baseline's score therefore describes its rule on the windows it was run on, and these failures show up only on the windows where they happen.
Naive and seasonal naive come from statsforecast (2.1.1), whose classes Naive and SeasonalNaive are in statsforecast/models.py. The seasonal naive rule is the one Hyndman and Athanasopoulos give for seasonal data: the forecast is the last observed value from the same season. Average of weeks is not a library method, so examples/lib/baselines.py computes it in pandas, where the rule can be read, and each window reads only its own history. A lag missing from that history raises an error instead of being skipped. One script scores all three rules through those seven windows, and its first lines count the windows, scored hours and missing forecasts, so you can check them before you read a score.
1"""Score the three baselines for the lead client over the held-out week, on the same seven windows. The point rests on the missing-forecasts line, which must be zero for the scores to compare, and on the three MAE lines."""2import pandas as pd34from lib.backtest import held_out_cutoffs, score_windows, window_mae5from lib.baselines import BASELINES, baseline_forecasts6from lib.electricity import load7from lib.settings import LEAD, show89cutoffs = held_out_cutoffs() # seven daily cutoffs at 00:00; every baseline uses these same windows10df = load([LEAD])[["unique_id", "ds", "y"]] # unique_id, ds and y only: the baselines read no other column11forecasts = baseline_forecasts(df, cutoffs) # one row per forecast hour, one column per baseline; each window reads its own history12labels = ["naive", "seasonal naive", "average of weeks"] # printed names, in the order of BASELINES, which the loops below zip with1314show("windows", len(cutoffs))15show("scored hours", len(forecasts))16show("missing forecasts", int(forecasts[BASELINES].isna().sum().sum())) # NaN marks a forecast that could not be made; the two sums count them over every column17show("mean demand", df[df["ds"].isin(forecasts["ds"])]["y"].mean()) # the mean over the scored hours only, not over the whole history18for model, label in zip(BASELINES, labels):19 show(f"{label} MAE", score_windows(df, forecasts, model)["mae"]) # pooled over every scored hour; the result is keyed by metric name20for model, label in zip(BASELINES, labels):21 per_window = window_mae(df, forecasts, model) # one MAE per window, keyed by the day its forecast hours fall on22 show(f"{label} worst window MAE", per_window.max())23 show(f"{label} worst window", per_window.idxmax().strftime("%b %d, %Y"))24 for day in ["2014-12-25", "2014-12-26"]: # Dec 25 is the holiday and Dec 26 the day after: the two windows the prose reads25 show(f"{label} MAE {pd.Timestamp(day):%b %d} window", per_window[pd.Timestamp(day)]) # windows are keyed by midnight of their day, so a Timestamp at 00:00 finds one
python naive-baselines-held-out-week.pywindows: 7
scored hours: 168
missing forecasts: 0
mean demand: 46.62
naive MAE: 8.16
seasonal naive MAE: 8.36
average of weeks MAE: 8.96
naive worst window MAE: 11.01
naive worst window: Dec 30, 2014
naive MAE Dec 25 window: 5.84
naive MAE Dec 26 window: 10.36
seasonal naive worst window MAE: 12.16
seasonal naive worst window: Dec 26, 2014
seasonal naive MAE Dec 25 window: 9.41
seasonal naive MAE Dec 26 window: 12.16
average of weeks worst window MAE: 22.09
average of weeks worst window: Dec 25, 2014
average of weeks MAE Dec 25 window: 22.09
average of weeks MAE Dec 26 window: 12.33
The three scores are comparable only because they cover the same hours: 168 scored hours in 7 windows, one for each hour of the seven days, and 0 missing forecasts across the three rules. That count is the one the working rule in the first section asks for, and zero is the only value that lets the three be compared on the same hours.
Read each error below against the lead client's mean demand of 46.62 kWh. Each score below is a MAE, the mean absolute miss in kWh that Chapter 1 defines. The three baselines score:
- naive: 8.16 kWh
- seasonal naive: 8.36 kWh
- average of weeks: 8.96 kWh
The simplest rule has the lowest error on this week, and average of weeks, which averages four weeks, is the weakest. Nothing here explains that order, and this is one client and one week, so it is a result for this week only. Chapter 3 is where the book backtests seasonal naive across many cutoffs.
The totals hide where the errors sit. The week begins on Dec 25, 2014, a Portuguese national holiday, and its first window is where the rules part company. Naive has the lowest error on it, at 5.84 kWh, against 9.41 kWh for seasonal naive. Average of weeks is worse still, and its largest error of the week falls on that window, at 22.09 kWh, because its four lags are ordinary days and the holiday has no match among them.
The day after the holiday is where copying costs seasonal naive. Its largest error of the week falls on Dec 26, 2014, at 12.16 kWh, because that window copies the holiday's pattern. On that day naive is still the lowest, at 10.36 kWh.
We recommend reporting all three baselines every time. Use seasonal naive as the main reference for MASE, because it carries the daily cycle that makes hourly demand predictable, and keep naive beside it, because on some weeks the flat rule is the stronger one.
Working rule: Start from naive and seasonal naive, both from the library, and add average of weeks when the series has a weekly rhythm worth testing. Check one forecast by hand against its formula before you rely on a baseline: pick one cutoff, compute one hour from the readings in its history, and compare the result with the forecast.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Scale errors with MASE
A kilowatt-hour error means different things for different clients. A miss of 8.36 kWh an hour is small for a client that uses 46.62 kWh an hour, and the same miss would be large for a hypothetical client that uses 4 kWh an hour. Scaling the error removes that difference. A scaled error divides each absolute error by a scale, the typical error of a simple method on the same client's own history. MASE, the mean absolute scaled error, is the mean of the scaled errors. Hyndman and Koehler introduced it in a 2006 paper in the International Journal of Forecasting. The link is the authors' preprint, dated 2005. They noted that the scaled error does not depend on the units of the data, so the same number can be read across clients of very different size. This chapter scores one client, so that comparison across clients is the reason for the scale, not a result shown here.
The 2006 paper scales by the one-step naive error: the mean absolute difference between each reading and the one before it. That is the natural scale for non-seasonal series. For hourly demand, this book uses the seasonal form that Hyndman and Athanasopoulos give for seasonal data, because the comparison a reader wants is with seasonal naive: under the seasonal scale, the denominator is seasonal naive's error on the client's own history. A MASE below 1 then says the forecast's error on the scored hours is smaller than seasonal naive's error on that history. A one-step scale would compare it with a method this book does not use for hourly demand.
The two formulas are these:
scale = mean of |y(t) - y(t - 24)|over every reading t before the first test day, with the pairs that touch a masked clock-change hour left outMASE = mean of |actual(t) - forecast(t)| / scaleover the scored hours
The scale reads every reading before the first test day, 17352 hours, about two years. That is longer than each window's eight-week history, and a longer history gives a steadier estimate of the client's usual swing. One scale for the week also means every window is read against the same number. The function seasonal_scale in examples/lib/baselines.py computes it for one client or for many, and returns one value per client. To see whether the cut matters, score the three baselines on the held-out week twice: with the scale from history, and with the scale from the whole series, both with the clock-change readings masked.
1"""Score the lead client's held-out week in MASE with a scale from history and with one from the whole series, both with the clock-change readings masked. The point rests on the two last-reading lines, which show where each scale stops, and on the MASE ratio lines."""2import pandas as pd34from lib.backtest import held_out_cutoffs5from lib.baselines import BASELINES, baseline_forecasts, mase_scores, scale_history, seasonal_scale6from lib.electricity import load7from lib.quirks import mask_clock_changes8from lib.settings import HELD_OUT_WEEK, LEAD, show910LABELS = ["naive", "seasonal naive", "average of weeks"] # printed names, in the order of BASELINES11first_day = pd.Timestamp(HELD_OUT_WEEK[0]) # the first test day: the history scale may read only readings before it1213full = load([LEAD]) # every reading of the lead client, with the quirk column that marks clock-change hours14df = full[["unique_id", "ds", "y"]] # the three columns the baselines and mase_scores read; quirk is for masking only15forecasts = baseline_forecasts(df, held_out_cutoffs()) # the same windows and history rule as naive-baselines-held-out-week.py16history = scale_history(full, first_day) # keeps only rows strictly before the first test day, so no test hour reaches this scale17masked_history = mask_clock_changes(history) # clock-change hours set to NaN, so the pairs that touch them drop out of the mean18masked_whole = mask_clock_changes(full) # the same masking on the whole series, so the test week is the only difference19test_rows = len(full[full["ds"] >= first_day]) # readings from the first test day on: the test week's rows2021show("scale rows from history", len(history))22show("last scale reading from history", history["ds"].max().strftime("%b %d, %Y %H:%M")) # this must be the hour before the first test day; the line is the check23show("scale rows from whole series", len(full))24show("last reading of whole series", full["ds"].max().strftime("%b %d, %Y %H:%M"))25show("test week share of whole-series rows in percent", 100 * test_rows / len(full), digits=3)26show("clock-change rows in scale history", int(history["quirk"].ne("normal").sum())) # every quirk but normal; for the lead client these are the clock-change hours, as it has no late start27show("test week own mean day-to-day difference", seasonal_scale(full[full["ds"] >= first_day - pd.Timedelta(hours=24)]).loc[LEAD], digits=4) # starts 24 hours early, so its first pair is the first test day against the day before28show("scale from history as recorded", seasonal_scale(history).loc[LEAD], digits=4) # seasonal_scale returns one value per client, so .loc picks the lead client; the clock-change pairs are kept here29show("scale from history clock changes masked", seasonal_scale(masked_history).loc[LEAD], digits=4) # pairs with a NaN are left out of the mean30show("scale from whole series clock changes masked", seasonal_scale(masked_whole).loc[LEAD], digits=4)3132hist = mase_scores(df, forecasts, BASELINES, masked_history).loc[LEAD] # the scale comes from the rows passed as train, not from df; that choice is what this example tests33whole = mase_scores(df, forecasts, BASELINES, masked_whole).loc[LEAD]34for model, label in zip(BASELINES, LABELS):35 show(f"{label} MASE from history scale", hist[model])36 show(f"{label} MASE from whole-series scale", whole[model])37 show(f"{label} MASE ratio whole-series over history", whole[model] / hist[model], digits=4) # both MASEs share the same errors, so this ratio is the history scale over the whole-series scale38show("seasonal naive MASE from history scale at four decimals", hist["SeasonalNaive"], digits=4) # two decimals hide the leak, so the last two lines print four39show("seasonal naive MASE from whole-series scale at four decimals", whole["SeasonalNaive"], digits=4)
python mase-scale-leak-check.pyscale rows from history: 17352
last scale reading from history: Dec 24, 2014 23:00
scale rows from whole series: 17520
last reading of whole series: Dec 31, 2014 23:00
test week share of whole-series rows in percent: 0.959
clock-change rows in scale history: 4
test week own mean day-to-day difference: 8.3607
scale from history as recorded: 7.1121
scale from history clock changes masked: 7.1005
scale from whole series clock changes masked: 7.1126
naive MASE from history scale: 1.15
naive MASE from whole-series scale: 1.15
naive MASE ratio whole-series over history: 0.9983
seasonal naive MASE from history scale: 1.18
seasonal naive MASE from whole-series scale: 1.18
seasonal naive MASE ratio whole-series over history: 0.9983
average of weeks MASE from history scale: 1.26
average of weeks MASE from whole-series scale: 1.26
average of weeks MASE ratio whole-series over history: 0.9983
seasonal naive MASE from history scale at four decimals: 1.1775
seasonal naive MASE from whole-series scale at four decimals: 1.1755
The scale from history is 7.1005 kWh, the average gap between each hour and the same hour the day before, and it reads against the mean demand the way an MAE does. A scale that is a large share of the mean says the client's own day-to-day swing is large, and every error for that client is read against that swing. Dividing seasonal naive's MAE of 8.36 kWh by the scale gives its MASE, 1.18. utilsforecast's mase, reached through the helper mase_scores, computes this MASE by dividing the same MAE by the same seasonal scale (utilsforecast 0.2.17, utilsforecast/losses.py, function mase), so the division by hand gives the same figure.
utilsforecast (0.2.17) computes MASE with its mase function in utilsforecast/losses.py. The function takes its scale from the train_df it is given, and it shifts that frame by rows, not by time, so a missing hour moves every later lag and nothing reports it. It also needs sorted input. Its time filter runs only when the scored frame has a cutoff column (function _create_train_with_cutoffs). So the library does not decide which readings the scale may read. The caller does, and the next section is about that choice.
Working rule: Report MASE beside MAE whenever the clients you compare differ in size, and say in the same sentence which history the scale comes from. Read MASE as a ratio of two mean errors, one from the scored hours and one from the history. It is not a percentage gain over seasonal naive, even when the MASE is well below 1.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Take the MASE scale from history
A scale describes the history before the first test day, not the series as a whole. If the scale reads the whole series, it also reads the hours the forecast is scored on, so the held-out week enters the denominator of its own error. That is a leak, and it raises no error. The MASE it produces looks like any other. The rule in this book is that a scale reads only the readings before the first test day of the week it scores, which for the held-out week is Dec 25, 2014.
A whole-series scale looks like the safer choice, because it uses more readings. It uses more readings from the wrong period. The extra readings are the ones the forecast is judged on, so the scale is no longer a measure of what was known at the cutoff. More data does not fix that. Only the cut does.
The script in the previous section prints the rows each scale reads, and those lines are the check. The history scale reads 17352 readings, and its last reading is Dec 24, 2014 23:00, the hour before the first test day. A later date there would mean test hours reached the scale.
The whole-series scale reads 17520 readings, through Dec 31, 2014 23:00, which covers the whole held-out week. Both scales have their clock-change readings masked, so the held-out week is the only difference between them.
The whole-series scale is the larger one, so every MASE computed with it is smaller. At two decimals both scales give seasonal naive 1.18, so the leak does not show. At four decimals it does, with seasonal naive's MASE at 1.1775 against 1.1755, and the factor below is the lesson, not the rounding.
The scales are 7.1005 kWh from history and 7.1126 kWh from the whole series, and the same factor, 0.9983, shrinks each of the three rules.
The leak is small on this week because the held-out week is a small share of the series. It makes up 0.959 percent of the whole-series readings, so the whole-series scale is roughly the history scale moved toward the held-out week's own swing by that share. The held-out week's own mean day-to-day difference is 8.3607 kWh, against 7.1005 kWh for the history, so the week swings more than the history does. The share times that gap is the leak, and the ratio above is its size. The leak grows in two ways. It grows when more of the scale's rows are test hours, as in a test period much longer than one week, such as the year of cutoffs in Chapter 3. It also grows when the held-out week's swing sits further from the history's. A quieter week would pull the whole-series scale down and make every MASE larger, so the same leak can flatter a model in one week and penalise it in another.
The clock changes are a second, smaller point, and this chapter handles them as Chapter 3 does. The history holds 4 clock-change readings: the two gap hours and the two repeat hours of the March and October changes in 2013 and 2014. The gap hours read zero, and the repeat hours hold the energy of two, as the data card describes; Chapter 3 shows the effect. Kept as recorded, those pairs give a scale of 7.1121 kWh. Masked, the scale is 7.1005 kWh, because the pairs that touch a masked reading drop out of the mean. A masked reading is neither zero nor a copy; it is missing. The chapter's scale masks them, and Chapter 3 gives the reason, which sets them to missing in every training set and every score.
Working rule: Pass a scale only the readings before the first test day, mask its clock-change readings, and print the last reading it uses. Check that this reading is the hour before the first test day. A small difference between the two scales does not show the procedure is right. The row check does.
기준선의 점수 읽기
MASE는 예측의 오차를 고객 자신의 이력에서 계절 순진 예측이 낸 오차와 비교한다. 값이 1보다 작으면 채점한 시간대에서 예측의 오차가 그 이력에서 계절 순진 예측이 낸 오차보다 작다. 1보다 크면 더 크다. Hyndman과 Koehler는 논문에서 1단계 스케일을 두고 이렇게 읽는다고 설명하며, 계절 스케일에서도 계산은 같다. 이 책은 좋은 점수의 기준값을 제시하지 않는다. 무엇이 좋은 점수인지는 예측이 빗나갈 때 공급자가 치르는 비용에 달려 있으며, 그 비용은 공급자가 알고 이 책은 모른다.
표는 세 기준선을 한 행씩 나란히 보여 준다. MAE의 단위는 kWh이고, MASE는 시계 변경을 가린 이력 스케일을 사용한다. 이전 절의 누수는 소수 둘째 자리에서는 드러나지 않으므로, 표에는 MASE 열이 하나만 있다.
| 기준선 | MAE (kWh) | MASE |
|---|---|---|
| 순진 예측 | 8.16 | 1.15 |
| 계절 순진 예측 | 8.36 | 1.18 |
| 주 평균 | 8.96 | 1.26 |
세 MASE 값은 모두 1보다 크므로, 모든 기준선은 이력에서 계절 순진 예측이 보인 전형적인 오차보다 더 크게 빗나갔다. 계절 순진 예측 자체의 경우에는 그 주의 일간 변동이 이력의 변동보다 컸다. 이 기준선의 MAE는 검증용으로 떼어 둔 주 자체의 일간 차이인 8.3607 kWh와 같고, 이력의 값은 7.1005 kWh이다. 순진 예측과 주 평균의 경우 스케일은 두 방법을 각자의 과거가 아니라 계절 순진 예측과 비교한다. 따라서 이 표는 두 규칙이 이력에서 어떤 성적을 냈는지는 알려 주지 않는다. 그 주는 국경일로 시작하며, 앞선 절은 주 평균에서 오차가 가장 큰 구간이 휴일 구간임을 보여 준다. 이 책은 여기서 나머지 요일을 검증하지 않는다.
두 척도에서 순서는 같아서, 순진 예측이 첫째, 계절 순진 예측이 둘째, 주 평균이 셋째이다. 이 일치는 발견이 아니다. MASE는 모든 MAE를 같은 스케일로 나누므로, 한 고객에 대해서는 MAE와 MASE의 순서가 달라질 수 없다.
이 표는 공급자의 질문도 던진다. 가장 단순한 규칙으로 전력을 구매해도 충분한가라는 질문이다. 그 답은 한 시간의 오차가 얼마의 비용인가에 달려 있고, MASE는 그 비용을 값으로 매기지 않는다. MASE가 공급자에게 주는 것은 되풀이할 수 있는 비교이다. 이후의 모델도 같은 보조 함수로 채점할 수 있으므로, 그 MASE는 단위를 바꾸지 않고 이 행들 옆에 놓인다.
표는 다음 순서로 읽는다. 첫째, 앞선 절에서 모든 행이 같은 시간대를 채점하고 누락된 예측이 없는지 확인한다. 둘째, MASE 열을 1과 비교해 읽는다. 셋째, 각 행을 교과서에 나온 수치가 아니라 다른 행과 비교한다. 가장 좋은 행과 비슷한 수준에 그친 적합 모델은 많은 것을 보여 주지 못했고, 인쇄된 반올림 오차보다 작은 차이로 앞선 모델은 아무것도 보여 주지 못했다.
작업 규칙: 각 기준선의 MASE를 1과 비교하고 다른 기준선과도 비교하며, 한 주의 결과만으로 우승자를 정하지 않는다. 모델이 더 낫다고 인정되려면 둘 이상의 구간 집합에서 가장 좋은 기준선을 이겨야 하고, 그 차이가 인쇄된 점수의 반올림 오차보다 커야 한다.
운영 환경에서 무엇이 잘못되는가
기준선을 다른 시간대에서 채점하거나 다른 이력으로 채점하면, 비교는 더 이상 그 말이 뜻하는 바를 나타내지 못한다. 어떤 팀은 모델을 1년치 예측 시점으로 채점하고 기준선은 1주치로만 채점할 수 있다. 모델에는 기준선보다 긴 이력을 줄 수도 있다. 그러면 비교는 설정을 측정할 뿐인데, 출력된 숫자는 증거처럼 보인다. 이 장에서 쓰는 점검이 바로 그것이다. 모든 방법은 예측 시점을 held_out_cutoffs에서, 이력을 history_before에서 가져오며, 실행마다 누락된 예측의 개수를 출력한다.
척도의 누수는 다른 MASE와 다를 바 없어 보이는 MASE를 남기고, 오류도 일으키지 않는다. 이 장에서는 이 누수가 모든 계절 naive MASE에 0.9983를 곱하는데, 소수 둘째 자리까지만 보면 이 변화는 드러나지 않는다. 다른 주에서 더 큰 누수가 생겨도 지면에서는 똑같이 보일 것이다. 점검 수단은 출력된 행 수와 척도가 사용하는 마지막 관측값이며, 둘 다 한 줄의 출력에 있으므로 검토자가 아무것도 다시 실행하지 않고 읽을 수 있다.
계절 지연에 공백이 있으면 어떤 출력에도 표시되지 않는 잘못된 척도가 나온다. 한 시간이 빠져 있으면 24행의 지연은 25시간 전에 닿으므로, 다음 날의 각 쌍은 엇갈린 시간끼리 비교한다. 라이브러리의 mase에는 공백을 확인하는 기능이 없다. 보조 함수 seasonal_scale는 각 고객의 시간이 끊김 없이 이어지는지 확인하고, mase_scores는 라이브러리가 척도의 행을 읽기 전에 같은 확인을 그 행들에 수행한다. 이 확인은 assert 문 대신 오류를 발생시키는데, Python이 -O 아래에서는 assert 문을 제거하기 때문이다. 채점 대상 시간은 관측값의 존재 여부와 중복만 확인한다. 운영 환경의 실행에서는 어떤 척도를 계산하기 전에 피드에 들어온 시간 수를 세어야 한다. 보조 함수 안의 확인은 문제가 이미 척도에 반영된 뒤에 보고하기 때문이다.
계절 지연을 잘못된 주기에 맞춰 고를 수도 있다. 24의 지연은 일 단위 주기를 가진 시간별 수요에 적합하다. 일별 데이터는 주 단위 주기를 가지며, 주 단위 리듬을 가진 시간별 데이터에는 대신 168의 지연이 필요할 수 있다. 잘못된 계절로 계산한 척도도 여전히 하나의 숫자이므로 출력에서는 실수를 알아볼 수 없다. 점검 방법은 본문에서 척도 옆에 계절을 명시하고, 척도를 사용하기 전에 그것이 데이터의 주기와 맞는지 확인하는 것이다.
보류된 주에서 설정을 고르면 비교가 훼손된다. 주별 평균에는 선택이 하나 들어 있다. 몇 주를 평균할 것인가이다. 보류된 주에서 가장 좋은 점수가 나온다는 이유로 이 수를 고르면, 기준선이 평가받는 바로 그 주에 맞춰 적합된 것이므로 모델과의 비교는 더 이상 공정하지 않다. 이 책은 어떤 점수도 출력하기 전에 4주로 정했고, 이 장에서도 모든 구간에 그 값을 유지한다. 이 값을 바꾸려면 장 끝의 결정 목록에 적어야 하며, 점수를 보기 전에 바꿔야 한다.
작업 규칙: 기준선의 입력과 그 척도의 입력은 다음 순서로 점검한다. 모든 방법에 같은 구간을 쓰는지, 척도가 이전 관측값만 읽고 마지막 관측값이 출력되는지, 계절 지연에 끊김 없는 시간별 이력이 있는지, 계절이 데이터의 주기와 일치하는지 확인한다. 각 점검은 한 줄의 출력이나 하나의 개수로 이루어지며, 점검에 실패하면 문제를 고칠 때까지 비교를 중단한다.
이 장에서 내린 결정
이 장의 내용은 일곱 가지 선택으로 정해졌고, 마지막 선택은 3장으로 넘기는 인계 사항이다. 대부분은 기준선 도우미 함수가 있는 examples/lib/baselines.py에 있으므로, 그곳을 고치면 그 함수를 호출하는 모든 장에 반영된다. 이력 길이와 예측 구간은 examples/lib/settings.py의 설정이며, 1장에서 쓴 것과 같다. 따라서 이 장의 어떤 기준선도 옆에 놓인 예측과 다른 이력을 읽지 않는다.
- MASE의 척도는 계절 척도이며, 시차는 24시간이다. 2006년 논문의 한 단계 척도는 쓰지 않는다.
- 척도는 2014년 12월 25일 이전의 모든 관측값으로 구한, 보류한 주에 대한 고객별 숫자 하나다. 앞서 설명했듯이 이 척도는 각 윈도의 이력보다 길다. 프레임에 컷오프 열이 있으면 utilsforecast는 컷오프마다 척도를 받을 수 있지만, 이 장은 그 옵션을 쓰지 않는다. 그 옵션을 추가한다면, 그 필터가
ds <= cutoff를 유지하므로 컷오프 시각 자체가 포함된다는 점을 알아야 한다. 이 책에서 컷오프는 예측이 다루는 첫 시간이며, 그 시간의 관측값은 이력이 아니다. 따라서 이 책의 컷오프로 만든 컷오프 열은 먼저 한 시간 앞으로 당겨야 한다. - 주 평균은 각 예측일 이전의 네 주를 쓰고, pandas로 계산하며, 자신의 8주 이력만 읽는다.
- 나이브와 계절 나이브는 statsforecast의 클래스다. 점수는 그 주에 채점된 모든 시간에 걸쳐 합산하며 소수점 둘째 자리까지 출력한다.
- 척도는 3장의 규칙에 따라 시계 변경 관측값 4개를 마스킹한다. 그러면 출력되는 이력 척도는 7.1005 kWh다.
- 기준선은 난수를 쓰지 않으므로 예제에서 시드를 설정하지 않는다.
- 3장은 계절 나이브와 이 도우미 함수들을 그대로 가져가 1년치 일요일 컷오프에 대해 실행한다. 이때 고객별 척도 하나는 이 장이 정한 규칙대로 첫 컷오프 이전의 모든 관측값으로 구한다. 한 주만으로는 이 검증을 할 수 없다.
이 판의 이 장
2026.11.11판예제 통과 2026년 11월 20이 장에서 2개 예제개 중 2개가 통과한다
영어판 2026.11.11판을 번역한 것이다.