예측 불확실성 정량화
읽는 데 약 53분분 걸린다, 7절에 4개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.11판을 번역한 것이다. 원문 읽기
이 장에서는 하루 앞 예측마다 범위를 설정하여, 구매가 그 예측에 의존할 수 있는지 판단할 수 있게 한다. 평가하는 날보다 앞선 날들을 사용해 예측 구간을 보정하고, 그 구간이 얼마나 자주 실제 값을 포함하는지 측정하며, 오류에 따르는 두 가지 비용을 바탕으로 구매할 수준을 선택한다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Why one number is not enough
The forecasts so far give one number for each client and hour, and a single number is not enough to buy on. The supplier cannot buy an expected value. It buys an amount of power a day ahead for each hour, so it needs a range around each forecast. Each kWh it buys is either used or not. Buying short means buying the rest later at a premium, and buying long means paying for power that nobody uses. The two errors cost different amounts, so the right purchase is usually not the forecast itself. Take one hour. Suppose the forecast is 100 kWh. If the reading turns out 10 kWh higher, the supplier is short and pays the short cost on those 10 kWh. If it turns out 10 kWh lower, the supplier has 10 kWh it pays for and does not use. When the short cost is three times the unused cost, a purchase above the forecast costs less on average, because it makes the expensive error less likely. How far above the forecast the purchase should sit depends on that ratio, and on how wide the errors are.
This chapter states two costs as assumptions. A kWh bought short costs 3.00 cost units, and a kWh bought and not used costs 1.00. These numbers are illustrative. They are not prices, and the book does not claim that any real supplier faces them. A later section shows how they set the purchase.
A prediction interval gives a lower and an upper bound for each hour. A prediction interval's level, such as 80 or 95, is the share of readings the bounds should contain. The share of readings the bounds contain is the coverage, and coverage belongs to many forecasts made the same way, not to one. One day's band either contains the readings or it does not. Across the 72 hours of three days, the share inside the band is a measurement. Across a year of days, it becomes a track record. A 95 percent band whose hours fall inside it 90 percent of the time has undercovered, but no single day shows it. Only the average over many hours shows it, and that average is what we measure.
Quantiles connect the bands to the costs. The lower bound of a central 80 percent interval is the 0.1 quantile of the forecast's distribution, the value that the reading falls below one time in ten. The upper bound is the 0.9 quantile. The purchase that minimises the expected cost is also a quantile, and Choose the level from the cost of error derives which one.
In the case, the range that matters is the total's, because the total is what the supplier buys. Chapter 6 forecast the thirty clients with one global model, and the total is the hourly sum of those forecasts. Each client has its own range, but the total's range cannot be read off the clients' ranges by adding them. Choose the level from the cost of error compares the two.
Working rule: Ask for a range wherever the costs of the two errors differ, and choose its level from those costs rather than from a number that looks reassuring. Report coverage as the share of hours inside the band over many windows, never as the chance that one day falls inside.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Build intervals from residuals
A range needs bounds, and the simplest bounds come from past errors. A residual is the error of an earlier forecast: the reading minus the forecast, e = y - f. Conformal prediction builds a band from the residuals of forecasts made the same way on earlier days. Take the residuals of a set of calibration windows, group them by horizon step, and read off the quantiles you need. A day-ahead forecast made at 00:00 has one horizon step for each hour of the day, so the group is the hour alone. For a level L in percent, the bounds for a forecast f made at a given step are:
lower = f + Q((1 - L/100) / 2)
upper = f + Q((1 + L/100) / 2)
where Q(p) is the empirical p-quantile of the calibration residuals at that step. The method assumes no model of the errors. It only assumes that the calibration residuals resemble the residuals to come, which a later section tests. A calibration window is a cutoff whose residuals size the bands. It always comes before the cutoffs being forecast, and it is never one of the windows that are scored.
The library that does this for the book's model is mlforecast, at version 1.1.0. Its class PredictionIntervals takes a number of windows, a horizon and a method, and it has four conformal methods: conformal_error, conformal_distribution, and their weighted versions. The two unweighted methods score the absolute residuals, |y - f|, so their bounds are symmetric around the forecast (mlforecast 1.1.0, mlforecast/conformal_prediction.py, function compute_conformity_scores). The default, conformal_distribution, works one client and one horizon step at a time. For each client and step it takes the calibration windows' absolute residuals, makes the paths of the forecast plus and minus each one, and reads the quantiles of those paths. Nothing is pooled across clients. The statistical library, statsforecast at version 2.1.1, names its interval class ConformalIntervals, not PredictionIntervals.
To see what the library does with a short calibration history, run its class with three calibration windows. It scores the three standard cutoffs, Dec 29 to Dec 31, 2014, each at 00:00. Those are the held-out week's last three days, and the days this chapter scores. mlforecast refits the global model at each cutoff and calibrates each one on the three before it.
1"""mlforecast's own conformal intervals, with three calibration windows, refitted at each of the three standard cutoffs.2Compare the coverage at 80 and 95 with their labels, and with the highest coverage three windows allow."""3import pandas as pd45from lib.electricity import load6from lib.intervals import builtin_intervals, design_coverage, symmetric_ceiling7from lib.panel import ALL308from lib.quirks import mask_clock_changes9from lib.settings import EVAL_CUTOFFS, show1011raw = load(ALL30)12# Every clock-change hour (four changes, 2013 and 2014) is masked as NaN. builtin_intervals keeps only rows from Oct 27, 2014 on, so no masked hour is in a window.13df = mask_clock_changes(raw)[["unique_id", "ds", "y"]]14# One row per client and hour. The bounds are columns named by model and level, such as LGBMRegressor-lo-80.15cv = builtin_intervals(df, pd.to_datetime(EVAL_CUTOFFS))1617show("scored hours", len(cv))18show("calibration windows per cutoff", 3)19show("residuals per client and hour", 3)20# Ceiling of a band of plus and minus n absolute residuals, n / (n + 1), with n = 3: at most 3 of the 4 places a new one can take.21show("highest coverage three windows allow, any level", symmetric_ceiling(3), 3)22for level in (80, 95):23 # Simulated under exchangeable normal errors, with mlforecast's construction, to set against the measured coverage.24 show(f"simulated coverage at {level}, exchangeable errors", design_coverage(level, 3, "builtin"), 3)25for level in (80, 95):26 lo, hi = cv[f"LGBMRegressor-lo-{level}"], cv[f"LGBMRegressor-hi-{level}"]27 inside = (cv["y"] >= lo) & (cv["y"] <= hi)28 show(f"coverage at {level}", inside.mean(), 3)29 show(f"mean width at {level}", (hi - lo).mean())30 if level == 80:31 # The by-day lines are printed for the 80 level only. Each hour is grouped by its calendar day.32 day = cv["ds"].dt.floor("D")33 for d, share in inside.groupby(day).mean().items():34 show(f"coverage at 80 on {d:%Y-%m-%d}", share, 3)35 for d, err in (cv["y"] - cv["LGBMRegressor"]).abs().groupby(day).mean().items():36 show(f"mean absolute error on {d:%Y-%m-%d}", err)
python conformal-three-windows.pyscored hours: 2160
calibration windows per cutoff: 3
residuals per client and hour: 3
highest coverage three windows allow, any level: 0.750
simulated coverage at 80, exchangeable errors: 0.656
simulated coverage at 95, exchangeable errors: 0.732
coverage at 80: 0.690
mean width at 80: 281.07
coverage at 80 on 2014-12-29: 0.756
coverage at 80 on 2014-12-30: 0.676
coverage at 80 on 2014-12-31: 0.637
mean absolute error on 2014-12-29: 114.62
mean absolute error on 2014-12-30: 94.42
mean absolute error on 2014-12-31: 163.37
coverage at 95: 0.750
mean width at 95: 355.39
The output shows the failure before any fix: across the 2160 client-hours, the bands at the 80 level cover 0.690 and at the 95 level 0.750. Both fall short of their labels, and the bands at 80 are 281.07 kWh wide on average.
The design sets a ceiling, and the 95 result sits on it. With three windows, each client and hour has three absolute residuals, and the band reaches no further than the largest of them. For exchangeable errors, the test error is the largest of four absolute errors one time in four, so the band misses it that often. The highest coverage three windows allow is 0.750, at any level. Under the same exchangeable assumption, the band's expected coverage is 0.656 at 80 and 0.732 at 95. The simulation draws normal errors, with the same construction. The measured figures are a little above those expected values, so the calibration windows did not have smaller errors than the scored days. Calm calibration windows would push coverage below the expected value, not above it. The shortfall is the construction's.
The coverage by day shows where the shortfall sits. At the 80 level it is 0.756 on Dec 29, 0.676 on Dec 30 and 0.637 on Dec 31. The forecast errors on those days were 114.62, 94.42 and 163.37 kWh on average. Dec 31 has the largest errors and the lowest coverage, and three days cannot separate day-to-day variation from the design.
A second problem comes from the calibration. Each cutoff calibrates only on days before it: the bands for Dec 31 use Dec 28, 29 and 30. But Dec 29 and Dec 30 are scored days too. So the three scored windows are not independent, because one window's calibration contains the readings of another scored window. No band uses its own day's readings, and the rule is right for operation, where those readings are known. For a test it weakens the result. Fixing it would need a separate calibration fit for each cutoff, which is more than a one-argument change, so the chapter's own bands use a fixed calibration set instead, as Calibrate on earlier windows shows.
Working rule: Build each band from the residuals of windows that come before its cutoff, and check the coverage it reaches on windows it did not use before you trust it. Read the level a design can reach before you read the coverage. Three residuals per client and hour cannot reach either label, so the fix is a larger calibration set, not a different reading of the output.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Calibrate on earlier windows
The calibration windows must come before the windows you score, and they must not share a target hour with them. The book adds one more rule: a calibration window must not fall on a Portuguese public holiday, because a holiday's load follows the calendar rather than the week before it. The rule applies to the decision windows as well. The held-out evaluation calibrates on twelve ordinary days, Dec 9 to 20, 2014, which end four days before the held-out week. Both examples in this section print the holiday hours and the shared hours in their calibration, and both counts are zero.
Twelve windows with thirty clients give 360 residuals for each hour of the day. They come from twelve days, though, and the thirty clients share each day's weather and calendar. So a day-level error is still a sample of twelve. The pooled residuals have a second problem. The clients differ enormously in size. In the scored week the largest client, MT_370, averages 17499.81 kWh an hour over the three scored days. Pooled residuals in kWh are dominated by such clients, so the bands fit the large clients and misfit the small ones. The fix is to divide each client's residuals by that client's scale before pooling, and multiply the bound back by the scale of the client being forecast. The scale is the seasonal naive error on the history before the first calibration cutoff, the same kind of scale the book uses for MASE. With the scale, the thirty clients count alike.
Two choices in this design were made on the decision windows, not on the held-out evaluation. The decision windows are the four cutoffs from Nov 25 to Dec 3, 2014. Their calibration is Nov 9 to 20, 2014, twelve holiday-free days that end four days before the first decision cutoff, the same shape as the held-out design. The windows are scored on their own, and the held-out evaluation is not read. The choices are judged by the interval score and the lowest client's coverage. The interval score adds a band's width to a penalty for each reading that misses the band, the penalty growing with the distance of the miss and scaled by 2 over the miss rate (Gneiting and Raftery (2007), eq. 43). Those windows settle both choices, as the measurements below show.
1"""The two calibration choices, scaling each client's residuals and the finite-sample levels, decided on the four decision2windows (Nov 25 to Dec 3, 2014), with calibration on Nov 9 to 20. Compare the lowest client's coverage and the interval scores printed for each variant;3the standard cutoffs are not read."""4from lib.baselines import seasonal_scale5from lib.electricity import load6from lib.intervals import DECISION_CAL, bounds, calibration_facts, coverage, interval_score, paired, total_of7from lib.panel import ALL30, DECISION_CUTOFFS8from lib.quirks import mask_clock_changes9from lib.scoring import book_scale10from lib.settings import show1112raw = load(ALL30)13# Every clock-change hour (four changes, 2013 and 2014) is masked as NaN, as in every example of this chapter.14df = mask_clock_changes(raw)[["unique_id", "ds", "y"]]15# One row per client and hour, with the forecast f, the reading y and the residual e.16cal, sc = paired(df, DECISION_CAL), paired(df, DECISION_CUTOFFS)17# Each client's MASE-style scale, from the history before the first calibration cutoff.18scale = seasonal_scale(book_scale(raw, DECISION_CAL[0]))1920for label, value in calibration_facts(df, DECISION_CUTOFFS, DECISION_CAL).items():21 show(label, value)22show("residuals per hour of the day", len(cal) // 24)23variants = (("unscaled", None, False), ("scaled", scale, False),24 ("unscaled, finite", None, True), ("scaled, finite", scale, True))25for name, s, fin in variants:26 for level in (80, 95):27 # scale=None pools the raw kWh residuals; finite=True applies the (n + 1) quantile correction.28 lo, hi = bounds(sc, cal, level, scale=s, finite=fin)29 show(f"{name}, coverage at {level}", coverage(sc["y"], lo, hi), 3)30 show(f"{name}, interval score at {level}", interval_score(sc["y"], lo, hi, level))31 lo, hi = bounds(sc, cal, 80, scale=s, finite=fin)32 # Coverage per client, then the lowest of the thirty clients.33 show(f"{name}, lowest client coverage at 80", ((sc["y"] >= lo) & (sc["y"] <= hi)).groupby(sc["unique_id"]).mean().min(), 3)34# One series, so no scale: the scale exists only to pool clients of different size.35tcal, tsc = total_of(cal), total_of(sc)36for name, fin in (("total", False), ("total, finite", True)):37 lo, hi = bounds(tsc, tcal, 80, finite=fin)38 show(f"{name}, coverage at 80", coverage(tsc["y"], lo, hi), 3)39 show(f"{name}, interval score at 80", interval_score(tsc["y"], lo, hi, 80))
python conformal-decision-windows.pycalibration windows: 12
holiday hours in calibration: 0
calibration hours shared with scored: 0
residuals per hour of the day: 360
unscaled, coverage at 80: 0.809
unscaled, interval score at 80: 603.88
unscaled, coverage at 95: 0.957
unscaled, interval score at 95: 1950.32
unscaled, lowest client coverage at 80: 0.021
scaled, coverage at 80: 0.834
scaled, interval score at 80: 336.72
scaled, coverage at 95: 0.954
scaled, interval score at 95: 581.28
scaled, lowest client coverage at 80: 0.365
unscaled, finite, coverage at 80: 0.811
unscaled, finite, interval score at 80: 604.19
unscaled, finite, coverage at 95: 0.959
unscaled, finite, interval score at 95: 1961.48
unscaled, finite, lowest client coverage at 80: 0.021
scaled, finite, coverage at 80: 0.835
scaled, finite, interval score at 80: 337.31
scaled, finite, coverage at 95: 0.956
scaled, finite, interval score at 95: 592.35
scaled, finite, lowest client coverage at 80: 0.375
total, coverage at 80: 0.948
total, interval score at 80: 9268.36
total, finite, coverage at 80: 0.990
total, finite, interval score at 80: 10724.99
Scaling wins on the two measures the variants were judged by, and loses only on the pooled coverage at 80. The worst-covered client's coverage at 80 rises from 0.021 to 0.365, and the interval score at 80 falls from 603.88 to 336.72. It falls at 95 as well, as the output shows.
We judged the variants by these two measures because the pooled figure hides clients. We chose them after seeing the decision numbers, so the pooled figure is reported beside them. At 80 the pooled coverage is closer to its label without the scale, at 0.809 against 0.834. The scale stays.
The finite-sample levels stay out of the bands. Each new residual is one more among n + 1, so the finite-sample levels move outward a little: each quantile level moves to floor((n + 1) * a) / n for the lower bound and ceil((n + 1) * (1 - a)) / n for the upper, where n is the number of residuals and a the tail share. Their effect on the scaled coverage at 80 is small, from 0.834 to 0.835, and the interval score at 80 gets worse, from 336.72 to 337.31. It gets worse at 95 too, as the output shows. The correction widens the bands and does not help, so the bands do not use it.
The held-out evaluation applies the same design to the standard cutoffs, which are the days the rest of the chapter scores.
1"""Conformal bands for every client, calibrated on twelve holiday-free days before the scored week, with each client's2residuals scaled first. Read the coverage and interval score at 80 and 95 first; the unscaled, three-day and3finite-sample lines are printed for comparison."""4import pandas as pd56from lib.baselines import seasonal_scale7from lib.electricity import load8from lib.intervals import CAL_CUTOFFS, bounds, calibration_facts, coverage, interval_score, paired9from lib.panel import ALL3010from lib.quirks import mask_clock_changes11from lib.scoring import book_scale12from lib.settings import EVAL_CUTOFFS, show1314raw = load(ALL30)15df = mask_clock_changes(raw)[["unique_id", "ds", "y"]]16scored_cutoffs = pd.to_datetime(EVAL_CUTOFFS)17cal, sc = paired(df, CAL_CUTOFFS), paired(df, scored_cutoffs)18# The scale is read from the history before the first calibration cutoff, as the book's MASE scale is.19scale = seasonal_scale(book_scale(raw, CAL_CUTOFFS[0]))20# The largest client is the one with the highest mean reading over the scored windows.21big = sc.groupby("unique_id")["y"].mean().idxmax()2223for label, value in calibration_facts(df, scored_cutoffs).items():24 show(label, value)25show("calibration residuals per hour of the day", len(cal) // 24)26show("largest client", big)27show("mean hourly load of the largest client", sc.groupby("unique_id")["y"].mean().max())28for level in (80, 95):29 lo, hi = bounds(sc, cal, level, scale=scale)30 show(f"coverage at {level}", coverage(sc["y"], lo, hi), 3)31 show(f"mean width at {level}", (hi - lo).mean())32 show(f"interval score at {level}", interval_score(sc["y"], lo, hi, level))33lo, hi = bounds(sc, cal, 80, scale=scale)34per_client = ((sc["y"] >= lo) & (sc["y"] <= hi)).groupby(sc["unique_id"]).mean()35show("lowest client coverage at 80", per_client.min(), 3)36# No scale here: the pooled residuals stay in kWh, which is what lets the large clients set the bands.37lo, hi = bounds(sc, cal, 80)38unscaled = ((sc["y"] >= lo) & (sc["y"] <= hi)).groupby(sc["unique_id"]).mean()39show("largest client coverage at 80, unscaled residuals", unscaled[big], 3)40# The three calibration days nearest the scored week: Dec 18, 19 and 20, 2014.41recent = cal[cal["cutoff"] >= "2014-12-18"]42lo, hi = bounds(sc, recent, 80, scale=scale)43show("coverage at 80 from three calibration days", coverage(sc["y"], lo, hi), 3)44lo, hi = bounds(sc, cal, 80, scale=scale, finite=True)45show("coverage at 80 with finite-sample levels", coverage(sc["y"], lo, hi), 3)
python conformal-earlier-windows.pycalibration windows: 12
holiday hours in calibration: 0
calibration hours shared with scored: 0
calibration residuals per hour of the day: 360
largest client: MT_370
mean hourly load of the largest client: 17499.81
coverage at 80: 0.739
mean width at 80: 267.62
interval score at 80: 673.89
coverage at 95: 0.902
mean width at 95: 532.00
interval score at 95: 1326.80
lowest client coverage at 80: 0.472
largest client coverage at 80, unscaled residuals: 0.000
coverage at 80 from three calibration days: 0.711
coverage at 80 with finite-sample levels: 0.741
The scaled bands still fall short of both labels on the standard cutoffs: they cover 0.739 of client-hours at 80 and 0.902 at 95. Their mean widths are 267.62 kWh and 532.00 kWh.
The scores are 673.89 at 80 and 1326.80 at 95. They are in kWh, so the large clients dominate them. Lower is better, and the score rewards a band that is both narrow and right.
The pooled bands still have to be read per client. The lowest client coverage at 80 is 0.472, for the client the scaled bands fit least well. With unscaled residuals, the largest client is covered in 0.000 of its hours at 80. The pooled kWh bands were set by the large clients, and they miss the largest client entirely.
Two more checks on the standard cutoffs test the design. Calibrating on only the three days nearest the scored week, Dec 18 to 20, gives 0.711 at 80, against 0.739 with all twelve. Three days are a smaller sample, and the coverage is a little lower. The finite-sample levels give 0.741 at 80, a small change that agrees with the decision windows: the correction does little for the client bands.
Working rule: Calibrate on windows that come before the scored ones, with no holiday in them, and scale each client before pooling its residuals. Make each design choice on windows that are not the ones you report. Report how many windows and residuals went into the bands and the coverage they gave on the scored days, even when that coverage falls short of the level.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Measure coverage on held-out days
Coverage is measured on days that the calibration never used. The standard cutoffs give three days, and each day gives 24 hours for each client, so the 2160 client-hours are not that many independent observations. The thirty clients share the calendar and the weather, so the hours of one day agree with one another. For day-level errors the sample is three days, which cannot measure a coverage level. Three days can show that a band fell short on those days, but they cannot say by how much a band falls short over a longer period.
The supplier buys the total, so the total's coverage matters most. Its bands are built from its own residuals over the same twelve days, with the quantiles read directly, and are offered at 80 only, because twelve residuals cannot support 95. With signed bounds, the band from the smallest residual to the largest covers at most 0.846 of the time, if the residuals are exchangeable, and a 95 band, or a 90 band, asks for more.
The total's bands cover 0.667 of its 72 scored hours at 80. For exchangeable errors, the same construction covers 0.682, so most of the gap to 80 comes from the twelve-residual sample. The section on cost puts these bands to use.
The total's errors vary by day. The mean absolute error of the total was 2415.51 kWh on the calibration windows and 2985.88 kWh on the scored days. Dec 31 accounts for most of the gap between the scored days and the calibration windows.
| Scored day | Error of the total, kWh | Coverage at 80 |
|---|---|---|
| Dec 29, 2014 | 2448.53 | 0.625 |
| Dec 30, 2014 | 2149.78 | 0.708 |
| Dec 31, 2014 | 4359.32 | 0.667 |
The coverage does not follow the errors. Dec 29 has the lowest coverage with a middle-sized error, and Dec 31 has the largest error with a middle-sized coverage. Each day has 24 hours, and three days are too few to tell the two apart.
The finite-sample levels would change the total's figure. On the scored days they give 0.736 at 80. The choice was made on the decision windows, where the correction widened the total's bands and worsened their interval score, so the bands do not use it. The decision windows also show that the direction of the gap is not fixed. There the total's 80 bands covered 0.948 of hours, more than their label, and the finite levels pushed that to 0.990.
Angelopoulos and Bates (2022) show that split conformal prediction covers the test point with probability at least 1 - alpha when the calibration and test points are independent and identically distributed, or more generally exchangeable. They also note that adjacent points in a time series are not exchangeable, using a temperature series as the example. The same holds for hourly load: each hour carries the one before it, and a day's hours share the weather and the calendar. Barber and co-authors (2023) call the loss in coverage when exchangeability fails a coverage gap. Their bound does not assume a particular joint distribution. It is small when recent calibration points are weighted in a way that matches the test point's distribution, as in slow drift. That result is theoretical, and this chapter does not test it. A 2026 preprint, a survey of conformal methods for dependent series, states that temporal dependence violates the exchangeability assumption. It is not peer reviewed, and we cite it only for that point.
So the book promises nothing about coverage that it does not measure. The coverage in this chapter is what three days showed, under the calibration described in Calibrate on earlier windows.
Working rule: Report coverage on windows that the calibration never used, with the number of windows and the coverage of each. Keep the same measure in a running log once the forecast runs every day, as Chapter 10 does. Read three scored days as a warning, not as a measurement of the level you were promised.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Choose the level from the cost of error
The supplier buys one amount for each hour, and the costs of the two errors set that amount. Let cu be the cost of one kWh bought short and co the cost of one kWh bought and not used. Let F be the distribution of demand. Differentiating the expected cost with respect to the purchase q gives co F(q) - cu (1 - F(q)), which is zero where F(q) = cu / (cu + co), the smallest expected cost. The level cu / (cu + co) is the critical fractile of the newsvendor model. The HKUST IEEM 101 notes on the newsvendor model give the same proof, writing the cost of excess as c0. This chapter writes it co. The purchase is therefore the quantile at level tau = cu / (cu + co).
With the illustrative costs from Why one number is not enough, tau is 0.75. The rule says to buy the quantile of the demand at that level, for each hour. The quantile at level tau is the purchase that minimises the quantile loss at that level, as Gneiting and Raftery (2007) show. The quantile loss is tau * (y - q) when the reading y is at or above the purchase q, and (1 - tau) * (q - y) when it is below. The quantile loss is not a cost in kWh or in money. It is the rule that the quantile minimises, and it has the same shape as the supplier's cost. Multiplying it by cu + co gives the cost exactly, which the example prints beside the mean cost.
Does buying at the critical fractile cost less than buying at the median or higher, on days the bands never saw? Below, the purchase is set for each hour from these costs, and the scored days answer the question. The level 0.95 is not offered, as Measure coverage on held-out days explains.
1"""The buy level for the total, set from the two costs: the critical fractile, cu / (cu + co), is the quantile that minimises2the expected cost. Compare the mean cost and the hours short at each level; the costs are illustrative, not prices."""3import pandas as pd45from lib.electricity import load6from lib.intervals import CAL_CUTOFFS, COST_EXCESS, COST_SHORT, buy_report, critical_fractile, paired7from lib.panel import ALL308from lib.quirks import mask_clock_changes9from lib.settings import EVAL_CUTOFFS, show1011raw = load(ALL30)12# Every clock-change hour (four changes, 2013 and 2014) is masked as NaN, as in every example of this chapter.13df = mask_clock_changes(raw)[["unique_id", "ds", "y"]]14# Calibration on Dec 9 to 20, 2014; scored on the three standard cutoffs.15pairs_cal, pairs_sc = paired(df, CAL_CUTOFFS), paired(df, pd.to_datetime(EVAL_CUTOFFS))1617show("cost of a kWh short", COST_SHORT)18show("cost of a kWh unused", COST_EXCESS)19# The quantile level cu / (cu + co), from the two costs printed above.20show("critical fractile", critical_fractile())21# buy_report returns the printed rows as (label, value, decimal places).22for label, value, digits in buy_report(pairs_cal, pairs_sc):23 show(label, value, digits)
python buy-ahead-level-by-cost.pycost of a kWh short: 3.00
cost of a kWh unused: 1.00
critical fractile: 0.75
scored hours: 72
residuals per hour for the total: 12
highest coverage the total's residuals allow: 0.846
simulated coverage at 80, exchangeable errors: 0.682
mean absolute error of the total, calibration days: 2415.51
mean absolute error of the total, scored days: 2985.88
total coverage at 80: 0.667
total coverage at 80 with finite-sample levels, not used: 0.736
total coverage at 80 on 2014-12-29: 0.625
total coverage at 80 on 2014-12-30: 0.708
total coverage at 80 on 2014-12-31: 0.667
total mean absolute error on 2014-12-29: 2448.53
total mean absolute error on 2014-12-30: 2149.78
total mean absolute error on 2014-12-31: 4359.32
mean cost at 0.50: 5087.95
hours short at 0.50: 0.528
mean cost at 0.75: 3843.61
hours short at 0.75: 0.403
mean cost at 0.90: 3667.43
hours short at 0.90: 0.222
quantile loss at critical fractile, times both costs: 3843.61
mean hourly total bound from the total: 31983.95
mean hourly total bound from the sum of client bounds: 32388.77
hours short at critical fractile, sum of client bounds: 0.306
mean cost at critical fractile, sum of client bounds: 3729.17
The identity holds: multiplied by the sum of the two costs, the quantile loss at the critical fractile is 3843.61, the same as the mean cost at that level, 3843.61. The rule is correct as arithmetic.
| Level | Mean cost | Hours short |
|---|---|---|
| 0.50 | 5087.95 | 0.528 |
| 0.75, the critical fractile | 3843.61 | 0.403 |
| 0.90 | 3667.43 | 0.222 |
The result on the scored days is less comfortable. The rule chose the critical fractile, and on these three days 0.90 cost less, at 3667.43 against 3843.61. At the critical fractile the purchase was short in 0.403 of the hours, where a calibrated level would fall short in one hour in four. That is the coverage shortfall from Measure coverage on held-out days seen as money. We do not move the level to 0.90. The three scored days are the test, and a level chosen because it wins on them has been chosen on the test. The honest reading is that the bands were too narrow here, so the purchase was too low, and that the level is right only when the bands are.
Should the purchase follow the clients' bounds instead? Summing each client's bound at the critical fractile gives a bound of 32388.77 kWh an hour, against 31983.95 from the total's own residuals. Summed quantiles equal the total's quantile when the errors move together perfectly. For an upper quantile, with errors that partly cancel, the sum usually sits above it, as it does here.
On the scored days the summed bound did better, with hours short at 0.306 against 0.403, and a mean cost of 3729.17 against 3843.61. That advantage comes from its higher level, not from a better calibration, and the scored days cannot show that it holds in general. We keep the total's own bound, because the purchase is made against the total's residuals, and we do not switch to the bound that did better here.
Working rule: Set the buy level from the two costs, as tau = cu / (cu + co), fix it before you score the days, and calibrate the total's bands on the total's own residuals. Show the realised cost at other levels as a check, but never move the level to whichever one would have won on the days you score.
운영에서 잘못되는 것들
- 보정 시즌과 평가 시즌은 다르다. 휴일은 보정에서 제외하며, 이렇게 하면 테스트가 공정하게 유지된다. 그러나 총량의 오차는 구간마다 달라지고, 평가 대상 날짜의 오차가 보정 구간의 오차보다 클 수 있다. 평온한 시기에 보정한 구간은 더 어려운 시기를 놓친다. 이를 알아차리려면 매일 커버리지를 명목 수준과 비교하고 이동 평균을 지켜보아야 한다. 커버리지가 일주일 동안 표시된 수준 밑으로 떨어지면 그것이 징후이며, 가장 먼저 살펴볼 곳은 그 주의 오차이다.
- 풀링한 구간은 고객을 가린다. kWh 단위로 풀링한 구간은 가장 큰 고객이 좌우한다. 스케일링하지 않은 잔차를 쓰면 가장 큰 고객의 구간은 80에서 그 고객의 시간대 중 0.000를 덮는다. 스케일링한 잔차를 쓰면 80에서 가장 낮은 고객 커버리지는 0.472이므로, 스케일링한 풀도 구간을 벗어나는 고객을 가린다. 풀링한 수치만 보지 말고 고객별 커버리지를 읽어야 한다.
- 사흘은 말해 주는 것이 적다. 평가 대상 사흘의 커버리지 수치는 발견처럼 보일 수 있지만, 실제로는 일 단위 오차를 세 번 관측한 것이다. 많은 구간에 걸친 커버리지를 사용하고, 짧은 기간의 결과는 결과가 아니라 살펴볼 이유로 다루어야 한다.
- 의존성은 단순한 보장을 깨뜨린다. 시간별 부하는 자기상관이 있으며, 이웃한 시간의 보정 잔차는 서로 독립이 아니다. 그러므로 구간에는 교과서 정리가 주는 보장이 없다. 날씨나 달력이 바뀌면 커버리지가 변할 수 있고, 그런 일이 생겼음을 알려 주는 것은 측정한 커버리지뿐이다. 오차가 같은 부호를 갖는 날이 이어지는 것은 주의해야 할 패턴이며, 누적 기록에서 이것이 드러난다.
- 총량은 시간당 잔차가 적다. 보정 구간 하나는 각 시간에 총량의 잔차를 하나만 준다. 그래서 구간이 열두 개면 잔차도 열두 개이다. 부호 있는 잔차를 쓸 때 열두 개의 잔차가 허용하는 가장 높은 커버리지는 0.846이므로 총량의 구간은 80에서 멈추며, 구간을 제시하기 전에 수준 점검을 먼저 해야 한다. 보정 구간을 더 늘리면 총량의 표본이 커지지만, 각 구간은 평가 주 이전의 평범한 날이어야 한다.
- 롤링 보정은 평가하는 날을 사용할 수 있다. Build intervals from residuals의 내장 규칙은 각 기준 시점을 그 앞의 세 기준 시점으로 보정한다. 운영에서는 그 값들이 이미 알려져 있으므로 문제가 없다. 그러나 테스트에서는 평가 구간들이 서로에게 의존하게 된다. 보정 집합은 고정하고, 모든 평가 구간보다 앞선 것으로 유지해야 한다.
이 장에서 내린 결정
- 보정 구간. 보류 주간 이전의 평범한 12일, 즉 2014년 12월 9일부터 20일까지이다. 휴일은 제외하며, 보정에 쓴 시간대는 채점하지 않는다. 의사결정 구간도 열두 날로, 2014년 11월 9일부터 20일까지이다. 이 길이는 결과가 아니라 선택이다. 열두 날이 가장 좋은 길이라는 점을 데이터가 보여 주지는 않는다.
- 합치기 전의 척도 조정. 각 고객의 잔차는 첫 번째 보정 기준 시점 이전 이력에서 구한 계절 나이브 오차로 나눈다. 이는 이 책이 MASE에 쓰는 척도와 같다. 이 선택은 의사결정 구간에서 정해졌으며, 총량에는 척도가 필요 없다.
- 구간에 유한 표본 보정을 쓰지 않는다. 이 보정은 고객과 총량 모두에 대해 의사결정 구간에서 시험했으나 구간 점수를 개선하지 못했다. 이 보정은 잔차 집합이 어떤 수준을 뒷받침할 수 있는지 읽어 내는 데에만 쓴다.
- 부호 있는 잔차. 구간과 구매 분위수는 부호 있는 잔차를 사용하므로 하한과 상한이 대칭일 필요가 없다. mlforecast의 conformal 방법은 절대 잔차를 사용하며 대칭 구간을 준다. Build intervals from residuals의 내장 실행은 비교를 위해 넣은 것이다.
- 구매는 총량을 대상으로 한다. 구매 수준과 그 분위수는 총량의 잔차로 정한다. 고객별 구간은 예측을 읽기 위한 것이지 구매를 위한 것이 아니다.
- 비용은 가정이다. 3.00와 1.00이라는 비용은 Why one number is not enough에 밝혀 두었으며, 측정한 값이 아니라 판단에 따른 것이다.
- 통계 라이브러리의 구간 클래스. statsforecast의 클래스는
ConformalIntervals이다. 이 이름은 mlforecast의PredictionIntervals와 다르며, 이 장은 각 라이브러리에 그 라이브러리의 이름을 쓴다. - 세 번째 예제. 구매 결정에는 별도의 측정이 필요했으므로
buy-ahead-level-by-cost를 추가했고, 보류 평가가 쓰지 않는 구간에서 설계상의 선택을 내리기 위한conformal-decision-windows도 함께 추가했다. - 휴일 포괄 범위는 주장하지 않는다. 2014년 12월 25일은 보류 주간에 들어 있지만 보정 구간과 채점 구간 모두의 바깥에 있다. 이 책은 구간이 휴일 당일을 얼마나 포괄하는지에 대해 아무것도 보고하지 않는다.
- 수준보다 구간이 먼저이다. 구매 수준은 그 아래에 놓인 구간만큼만 좋고, 밴드는 그것을 정한 윈도우만큼만 좋다.
이 판의 이 장
2026.11.11판예제 통과 2026년 11월 20이 장에서 4개 예제개 중 4개가 통과한다
영어판 2026.11.11판을 번역한 것이다.