Probabilistic forecasting and its evaluation
Useful forecasts describe distributions. This lesson develops sharpness subject to calibration, proper scoring rules, quantile forecasts, PIT diagnostics, rolling-origin evaluation, scaled metrics, Diebold-Mariano comparison and forecast combination.
After this lesson you can
- Demonstrate that a scoring rule is proper and select one suited to the use: logarithmic, CRPS, pinball or intervals.
- Calculate normal CRPS in closed form and from samples.
- Diagnose calibration with PIT histograms and coverage, and distinguish calibration from sharpness.
- Design a leakage-free rolling-origin evaluation with suitable baselines.
- Compare forecasters with Diebold-Mariano and combine forecasts by averaging quantiles and estimated weights.
Before you start
- 26ARIMA forecasting and prediction intervalsForecasting baselinesState space forecastingVolatility forecasting and evaluationMean ergodicity of a stationary series
- 11k-fold cross-validationStratified, grouped and temporal splitsRegression loss functionsStatistical functional elicited by a loss
- 04Probability integral transform and inverse transform sampling
- 07Logarithmic scoring ruleKullback-Leibler divergence (relative entropy)
How uncertain is the future?
Deciding how much inventory to buy, capacity to reserve or capital to risk requires more than a central value. The same mean can correspond to a narrow distribution or one with a considerable loss tail. A predictive distribution assigns probabilities to future outcomes conditional on information available at the forecast origin. Before evaluating it, check what information it used and for which horizon.
In the first experiment, change a predictive distribution’s bias and spread and compare its PIT histogram, coverage and scores. An overly wide interval can overcover, but that does not mean it is calibrated. Comparing a calibrated marginal distribution with a better-informed conditional distribution shows that even correct marginal calibration can coexist with low sharpness.
Scores that reward telling the truth
A proper scoring rule assigns loss to the announced distribution and outcome . It is proper if, for every true distribution in the class considered, . It is strictly proper if equality implies . In this lesson lower values are better; other sources use the opposite convention.
Logarithmic loss is strictly proper under the necessary domination and integrability conditions: the expected loss difference is the Kullback-Leibler divergence . It severely penalizes assigning very low density to the observation and requires a well-defined density. Changing scale requires transforming the density with the Jacobian.
CRPS evaluates the entire cumulative distribution function:
If are independent with law and have finite first moment, it is also . To show propriety, take expectation under : . The expected loss difference is , zero only when the distributions coincide. In higher dimensions, the energy score replaces absolute value with Euclidean norm in the expectation representation; it is proper under moment assumptions, although it can be insensitive to certain dependence errors.
For , , , standard density and CDF :
The score of a central interval at level adds width and penalizes observations outside it: It evaluates that interval, not the entire distribution. Nominal coverage alone does not demonstrate full calibration.
Quantiles and asymmetric decisions
The pinball loss of quantile for is . Underestimation and overestimation have different costs. The expected minimum is any satisfying ; with atoms or empirical data there may be multiple minimizers.
CRPS is also for distributions with finite first moment. Quadrature with a few quantiles only approximates it. Separately fitted quantiles can cross, contradicting their order; use a model with monotonicity constraints or rearrangement and reevaluate calibration and loss.
Diagnose before declaring victory
For a continuous predictive CDF , the probability integral transform is . Under a correct conditional forecast, each is uniform. A U-shaped histogram often suggests a distribution that is too narrow; central concentration suggests overdispersion. Bias can produce asymmetry. These shapes are diagnostics, not unique proofs of their cause. For discrete distributions, randomize PIT within the jump; a uniform marginal histogram does not guarantee conditional calibration, and PITs at overlapping horizons can be dependent.
A quantile reliability diagram compares each announced level with the frequency of . The diagonal is the marginal target. This parallels classification probability calibration, although here an ordered family of thresholds is evaluated. The interactive shows this comparison alongside PIT.
Interval coverage is compared with its announced level, but an excessively wide forecast can overcover. Gneiting and Raftery propose seeking sharpness subject to calibration: among valid forecasts we prefer to concentrate the distribution as much as the available information permits. A climatological distribution ignoring a predictive covariate can be well calibrated marginally and less sharp than a correctly conditioned one.
Rolling origins and comparable scales
In rolling-origin evaluation, each model is fitted on data before the origin and evaluated on later observations. An expanding window retains the past; a sliding one discards older data. For multiple horizons record origin, horizon and target date, since errors overlap. Imputation, transformations, hyperparameter selection and combination weights must be learned without looking ahead. Reserve a later segment if using earlier origins to choose the procedure.
Scaled metrics compare errors with a scale calculated only on training data. For seasonal period , MASE divides mean absolute test error by the training mean of ; RMSSE does the same with squares and takes the square root. If that denominator is zero, the metric is undefined. MAPE is problematic with zero or near-zero values; sMAPE also does not eliminate all difficulties with small denominators.
M4 compared 61 methods on 100,000 series. Organizers highlighted that the best results mainly combined statistical methods. M5 Accuracy used a 28-day horizon and weighted RMSSE; its winner equally weighted six models with different approaches and training sets. M5 Uncertainty requested nine quantiles for 42,840 hierarchical series. Results depend on the dataset and loss: they do not imply one method wins in every application.
Comparing and combining
The Diebold-Mariano test works with loss differences . Under the zero-mean hypothesis and suitable stationarity, moment and weak-dependence conditions, the statistic divides by an estimate of its standard error based on long-run variance. Use a HAC estimate and declare its bandwidth: overlapping horizons create dependence, but taking lags does not necessarily capture all dependence. A large p-value does not prove equality, and with few dates the normal approximation can be poor.
Combining CDFs as a mixture and averaging quantiles are different operations. Nonnegative weights summing to one produce a valid CDF in the first case and preserve quantile ordering in the second. Fitting weights on evaluation data leaks the future; use an earlier validation window and retain a later test.
The same available-information principle appears in walk-forward strategy validation, where costs and execution rules must also be incorporated. Adaptive conformal inference addresses intervals under temporal dependence with its own conditions and guarantees: coverage is not guaranteed for every dependent series. Practical significance reminds us that a statistically detectable difference may be too small to justify an operational change.
Lab: scores from scratch
The empirical CRPS formula uses every pair from a sample of size . Sorting first reduces cost to : if , half the mean pairwise distance is . This is the exact score of the empirical distribution, with denominator ; replacing it by constructs another Monte Carlo estimator.
import numpy as np
from scipy.special import ndtr
from scipy.stats import norm
def crps_normal(mu, sigma, y):
mu,sigma,y=np.broadcast_arrays(mu,sigma,y)
if np.any(~np.isfinite(mu)) or np.any(~np.isfinite(sigma)) or np.any(~np.isfinite(y)) or np.any(sigma<=0):
raise ValueError("parámetros finitos y sigma positiva")
z=(y-mu)/sigma
phi=np.exp(-z*z/2)/np.sqrt(2*np.pi)
return sigma*(z*(2*ndtr(z)-1)+2*phi-1/np.sqrt(np.pi))
def crps_muestra(samples,y):
x=np.sort(np.asarray(samples,dtype=float))
if x.ndim!=1 or not len(x) or not np.all(np.isfinite(x)) or not np.isfinite(y):
raise ValueError("muestra unidimensional no vacía y datos finitos")
m=len(x); pesos=2*np.arange(1,m+1)-m-1
return np.mean(np.abs(x-y))-np.dot(pesos,x-x[0])/(m*m)
def pinball(y,q,tau):
e=np.asarray(y)-np.asarray(q)
return np.maximum(tau*e,(tau-1)*e)
rng=np.random.default_rng(2622)
observaciones=rng.normal(size=1000)
pit=ndtr(observaciones)
print("PIT por décimas:",np.histogram(pit,bins=np.linspace(0,1,11))[0])
print("cobertura nominal 90 % y CRPS medio:",
np.mean(np.abs(observaciones)<=norm.ppf(.95)),
crps_normal(0,1,observaciones).mean())
muestra=rng.normal(size=4000)
rejilla=np.array([-2.,-1.5,-.5,0.,.5,1.5,2.])
print("CRPS normal en una rejilla de observaciones:",list(map(float,crps_normal(0,1,rejilla))))
print("aproximación empírica en y=0.5:",crps_muestra(muestra,.5))
desplazada=muestra[:999]+1e14
print("error de invariancia al centrar los datos:",
abs(crps_muestra(desplazada,1e14)-crps_muestra(desplazada-desplazada[0],1e14-desplazada[0])))
print("cuantiles empíricos y pérdidas medias:",
[(t,np.quantile(observaciones,t),pinball(observaciones,np.quantile(observaciones,t),t).mean()) for t in (.1,.5,.9)])To distinguish lack of calibration from lack of information, let be independent standard normals and . The forecast conditional on is ; if we ignore , the correct marginal is , where the second parameter is variance. Both are calibrated given their respective information, but the second discards a useful signal. If is announced instead, central coverage is excessive and its PIT is not uniform.
x=rng.normal(size=4000); y_sim=x+rng.normal(size=4000)
for nombre,mu,sigma in [("condicional",x,1.),("marginal",np.zeros_like(x),np.sqrt(2)),("demasiado ancha",x,2.)]:
u=ndtr((y_sim-mu)/sigma)
cobertura=np.mean(np.abs(y_sim-mu)<=norm.ppf(.95)*sigma)
logscore=np.mean(-norm.logpdf(y_sim,loc=mu,scale=sigma))
print(nombre,"cobertura, CRPS, log-score, PIT por cuartiles:",
cobertura,crps_normal(mu,sigma,y_sim).mean(),logscore,np.histogram(u,bins=np.linspace(0,1,5))[0])
niveles=np.arange(1,10)/10
frecuencias=[np.mean(y_sim<=x+norm.ppf(t)) for t in niveles]
print("fiabilidad condicional, nivel y frecuencia:",list(zip(niveles,frecuencias)))Evaluating forecasts across series
We reuse the monthly AirPassengers series from the SARIMA lesson and quarterly real GDP from the statsmodels macroeconomic dataset. These are examples to run the protocol, not a representative competition. Each origin uses only its past, and horizons are evaluated on the original scale.
We define two origins per series with horizon three. Models and hyperparameters are fixed for this example before evaluation. The seasonal naive forecast uses the last cycle as its mean and spread based on training seasonal differences. For ETS we use a normal approximation with constant residual deviation, not an exact ETS interval. SARIMA and the structural model use predictive variance supplied by their state-space representation. In every case the bands are conditional on the fitted model and omit some parameter uncertainty.
import statsmodels.api as sm
import warnings
from statsmodels.tools.sm_exceptions import ConvergenceWarning
warnings.filterwarnings("ignore",category=ConvergenceWarning)
pasajeros = np.array([112,118,132,129,121,135,148,148,136,119,104,118,115,126,141,135,125,149,170,170,158,133,114,140,145,150,178,163,172,178,199,199,184,162,146,166,171,180,193,181,183,218,230,242,209,191,172,194,196,196,236,235,229,243,264,272,237,211,180,201,204,188,235,227,234,264,302,293,259,229,203,229,242,233,267,269,270,315,364,347,312,274,237,278,284,277,317,313,318,374,413,405,355,306,271,306,315,301,356,348,355,422,465,467,404,347,305,336,340,318,362,348,363,435,491,505,404,359,310,337,360,342,406,396,420,472,548,559,463,407,362,405,417,391,419,461,472,535,622,606,508,461,390,432], dtype=float)
macro = np.asarray(sm.datasets.macrodata.load_pandas().data["realgdp"],dtype=float)
series = {"pasajeros":(pasajeros,12), "pib":(macro,4)}
origenes = {nombre:(len(v)-6,len(v)-3) for nombre,(v,m) in series.items()}
resultados = []
def registrar(nombre, metodo, origen, media, sigma):
serie,m=series[nombre]; train=serie[:origen]
real=serie[origen:origen+len(media)]
dif=train[m:]-train[:-m]
escala=np.mean(np.abs(dif)); escala2=np.mean(dif*dif)
for h,(pred,sd,obs) in enumerate(zip(media,sigma,real),1):
resultados.append((nombre,metodo,origen,h,float(obs),float(pred),float(sd),float(escala),float(escala2)))
for nombre,(serie,m) in series.items():
for origen in origenes[nombre]:
train=serie[:origen]; dif=train[m:]-train[:-m]
media=train[-m:][:3]; sigma=np.repeat(np.std(dif,ddof=1),3)
registrar(nombre,"ingenuo",origen,media,sigma)
print("nombres, longitudes y orígenes:",
[(k,len(v),origenes[k]) for k,(v,m) in series.items()])
print("primeras predicciones ingenuas:",resultados[:3])from statsmodels.tsa.holtwinters import ExponentialSmoothing
convergencia_ets=[]
for nombre,(serie,m) in series.items():
for origen in origenes[nombre]:
train=serie[:origen]
fit=ExponentialSmoothing(train,trend="add",seasonal="add",seasonal_periods=m,
initialization_method="estimated").fit(optimized=True)
media=np.asarray(fit.forecast(3))
sigma=np.repeat(np.std(fit.resid,ddof=1),3)
registrar(nombre,"ETS",origen,media,sigma)
convergencia_ets.append(bool(fit.mle_retvals.get("success",False)))
print("pronósticos ETS registrados y convergencia:",
sum(r[1]=="ETS" for r in resultados),convergencia_ets)from statsmodels.tsa.statespace.sarimax import SARIMAX
convergencia_sarima=[]
for nombre,(serie,m) in series.items():
for origen in origenes[nombre]:
train=serie[:origen]
fit=SARIMAX(train,order=(0,1,1),seasonal_order=(0,1,1,m),
trend="n",enforce_stationarity=False,enforce_invertibility=False).fit(disp=False,maxiter=40)
pred=fit.get_forecast(3)
registrar(nombre,"SARIMA",origen,np.asarray(pred.predicted_mean),
np.sqrt(np.maximum(np.asarray(pred.var_pred_mean),1e-12)))
convergencia_sarima.append(bool(fit.mle_retvals.get("converged",False)))
print("convergencia SARIMA por origen:",convergencia_sarima)from statsmodels.tsa.statespace.structural import UnobservedComponents
convergencia_estructural=[]
for nombre,(serie,m) in series.items():
for origen in origenes[nombre]:
train=serie[:origen]
fit=UnobservedComponents(train,level="local linear trend",seasonal=m).fit(disp=False,maxiter=40)
pred=fit.get_forecast(3)
registrar(nombre,"estructural",origen,np.asarray(pred.predicted_mean),
np.sqrt(np.maximum(np.asarray(pred.var_pred_mean),1e-12)))
convergencia_estructural.append(bool(fit.mle_retvals.get("converged",False)))
print("convergencia estructural por origen:",convergencia_estructural)A convergence warning is part of the result, not a detail to hide. If the optimizer does not converge, increase iterations, examine identification and scale, or discard that fit before drawing conclusions. This lab uses few origins so you can run it in the browser.
We calculate MASE and RMSSE with scales corresponding to each origin, normal CRPS and coverage. A zero scale is explicitly excluded as undefined. To avoid mixing errors in different units, we summarize each series separately.
for nombre in series:
for metodo in ("ingenuo","ETS","SARIMA","estructural"):
filas=[r for r in resultados if r[0]==nombre and r[1]==metodo]
obs=np.array([r[4] for r in filas]); mu=np.array([r[5] for r in filas])
sd=np.array([r[6] for r in filas]); esc=np.array([r[7] for r in filas])
esc2=np.array([r[8] for r in filas])
mase=np.mean(np.abs(obs-mu)/esc) if np.all(esc>0) else np.nan
rmsse=np.sqrt(np.mean((obs-mu)**2/esc2)) if np.all(esc2>0) else np.nan
cobertura=np.mean(np.abs(obs-mu)<=norm.ppf(.95)*sd)
print(nombre,metodo,"MASE, RMSSE, CRPS, cobertura:",
mase,rmsse,np.mean(crps_normal(mu,sd,obs)),cobertura)To compare dependent losses we estimate long-run variance with Bartlett weights. The implementation uses divisor for each autocovariance and an explicit bandwidth. Besides a simulation, we compare the seasonal naive forecast with the average of the two previous cycles on AirPassengers, at a one-step horizon and with each origin’s own training scale. Methods and period are fixed before evaluation. The small sample and test assumptions limit interpretation of the p-value.
def diebold_mariano(d, lag):
d=np.asarray(d,dtype=float); n=len(d)
if n<3 or not 0<=lag<n:
raise ValueError("n y ancho de banda inválidos")
centrado=d-d.mean()
var=np.dot(centrado,centrado)/n
for k in range(1,lag+1):
gamma=np.dot(centrado[k:],centrado[:-k])/n
var+=2*(1-k/(lag+1))*gamma
if var<=0:
raise ValueError("varianza de largo plazo no positiva")
estadistico=d.mean()/np.sqrt(var/n)
return estadistico,2*norm.sf(abs(estadistico)),var
innovaciones=rng.normal(size=180)
d=np.zeros(len(innovaciones))
for t in range(1,len(d)):
d[t]=.55*d[t-1]+innovaciones[t]
print("DM, p bilateral y varianza HAC de la simulación:",diebold_mariano(d,4))
perdidas_a=[]; perdidas_b=[]
for origen in range(108,len(pasajeros)):
train=pasajeros[:origen]
escala=np.mean((train[12:]-train[:-12])**2)
real=pasajeros[origen]
a=train[-12]
b=(train[-12]+train[-24])/2
perdidas_a.append((real-a)**2/escala)
perdidas_b.append((real-b)**2/escala)
d_real=np.array(perdidas_a)-np.array(perdidas_b)
print("orígenes reales, diferencia media de pérdidas y DM HAC:",
len(d_real),d_real.mean(),diebold_mariano(d_real,4))Finally, we combine ETS and SARIMA quantiles. The first origin chooses a weight from a small grid by minimizing mean pinball loss for three quantiles; the second is reserved to evaluate that weight. This demonstrates temporal separation, not reliable selection with so few observations.
taus=np.array([.1,.5,.9])
for nombre in series:
primero,segundo=origenes[nombre]
def bloques(metodo,origen):
return sorted([r for r in resultados if r[0]==nombre and r[1]==metodo and r[2]==origen],key=lambda r:r[3])
def combinados(origen,peso):
a,b=bloques("ETS",origen),bloques("SARIMA",origen)
obs=np.array([r[4] for r in a])
qa=np.array([r[5]+r[6]*norm.ppf(taus) for r in a])
qb=np.array([r[5]+r[6]*norm.ppf(taus) for r in b])
return obs,peso*qa+(1-peso)*qb
candidatos=np.linspace(0,1,5)
perdidas=[]
for peso in candidatos:
obs,q=combinados(primero,peso)
perdidas.append(pinball(obs[:,None],q,taus).mean())
peso=candidatos[np.argmin(perdidas)]
obs,q=combinados(segundo,peso)
print(nombre,"peso ETS validado, pérdida en siguiente origen:",
peso,pinball(obs[:,None],q,taus).mean())Exercises
Step 1 of 2. Which expressions give the one-sided derivatives of expected loss with respect to q?
Step 1 of 3. What difference in expected losses under G remains when the score of G is subtracted from that of F?
import numpy as np
def crps_samples(samples, y):
passA probabilistic forecast is judged by calibration, sharpness and decision usefulness, using appropriate scores and data not involved in its construction.
The last cell lets you check the numerical exercise calculation after attempting it.
print("CRPS de N(0,1) en y=1:",float(crps_normal(0,1,1)))