pymc_forecast.evaluate#
Backtesting: score a forecasting model over moving train/test windows.
Each window is a pure refit: the model is fitted on the window’s training
slice and forecasts the test slice, and metrics are computed on the sampled
predictions. A forecaster class (forecaster_cls) or a closure
(forecast_fn) does the fit and the forecast. Two windowing strategies are
supported — "expanding" (train from the start of history) and
"rolling" (fixed training length) — with window bookkeeping ported from
numpyro_forecast / Pyro. Windows are positional (integer) slices along
"time": results carry integer split points and the predictions keep their
real time coords.
- class pymc_forecast.evaluate.BacktestResult(t0, t1, t2, num_samples, train_walltime, test_walltime, metrics, train_metrics=<factory>, prediction=None)[source]#
Bases:
objectPer-window result of a
backtest()run.Each parameter is available as an attribute of the same name.
- Parameters:
t0 (
int) – Inclusive start of the training slice (positional index into the data’s"time"dim);0for expanding windows.t1 (
int) – Train/test split: exclusive end of training and inclusive start of the test slice.t2 (
int) – Exclusive end of the test slice.num_samples (
int) – Forecast samples per window: the requestednum_sampleswithforecaster_cls; withforecast_fn, the number of draws it returned (the product of the sizes of its sample dims), which may differ from the request.train_walltime (
float) – Wall-clock seconds to construct (build and fit) the forecaster;nanwithforecast_fn, whose fit is timed intest_walltime.test_walltime (
float) – Wall-clock seconds for the forecast call:forecaster.forecast, or the wholeforecast_fncall, fit included.metrics (
dict) – Metric name → value (float) on the test window.train_metrics (
dict, optional) – Metric name → in-sample value (float); empty unlesseval_train=True. Defaults to an empty dict.prediction (
xarray.DataArray, optional) – Forecast samples for the window, aftertransformif one was given (Noneunlesskeep_predictions=True). With atransformits dims are the onestransformreturns.
- pymc_forecast.evaluate.WindowType#
Allowed
window_typevalues ofbacktest(),"expanding"or"rolling".alias of
Literal[‘expanding’, ‘rolling’]
- pymc_forecast.evaluate.backtest(data, covariates, model_fn, *, forecaster_cls=None, forecast_fn=None, in_sample_fn=None, var_name='forecast', metrics=None, per_window_metrics=None, transform=None, window_type=None, train_window=None, min_train_window=1, test_window=None, min_test_window=1, stride=1, num_samples=100, batch_size=None, forecaster_options=None, eval_train=False, keep_predictions=False, random_seed=None)[source]#
Backtest a forecasting model on moving
(train, test)windows.Each window is fitted and forecast in one of two ways: by a forecaster class (
forecaster_cls, defaultForecaster) or by a closure (forecast_fn) that fits the window and returns the forecast draws itself. The closure suits models outside the forecaster classes, several observed tables (dataas aDataset), and targets other than the observed series.Forecaster protocol.
backtestusesforecaster_clsthrough the calls below and nothing else, so any class that has them works:forecaster_cls(model_fn, train_data, window_covariates, random_seed=fit_seed, **options)fits the window.train_datais rowst0:t1ofdata,window_covariatesthe covariate rowst0:t2(training plus test span; zero-width covariates whencovariatesisNone) andfit_seedanint..forecast(window_covariates, num_samples=num_samples, random_seed=forecast_seed), whereforecast_seedis anint.backtestscoresresult["predictions"][var_name]..predict_in_sample(num_samples=num_samples, random_seed=forecast_seed), only witheval_train=True.backtestscoresresult["posterior_predictive"]["obs"]againsttrain_data.
When
batch_sizeis notNone, both methods also getbatch_size=batch_size. A class whoseforecast(or, witheval_train,predict_in_sample) has neither abatch_sizeparameter nor**kwargs, such asStatespaceForecaster, is then rejected before the first fit. The check reads the methods of the class; a factory function or afunctools.partialis not checked.Closure protocol.
forecast_fnandin_sample_fnget positional arguments and a keywordbatch_size:forecast_fn(rng, model_fn, train_data, train_covariates, full_covariates, num_samples, /, *, batch_size=None) in_sample_fn(rng, model_fn, train_data, train_covariates, num_samples, /, *, batch_size=None)
rngis anumpy.random.Generator, a separate stream per window and per closure.model_fnis passed through as given.train_covariatesare the covariate rowst0:t1andfull_covariatesthe rowst0:t2.forecast_fnreturns the forecast draws of the test rows andin_sample_fnthe draws of the training rows, each anxarray.DataArraywith the sample dimschainanddraw, or asampledim stacked as byarviz.extract: any of the sample dims the metrics accept. Without atransformthe other dims must align with the truth (time_futureortime, and the data dims); with one, any dims are allowed. The closure may return another number of draws thannum_samples; the result records what it returned.Each closure call must fit its own window: the functional
forecast()rejects a posterior fitted on another window. A closure that builds and fits the model also owns any reuse of a compiled model across windows. Witheval_train, each window calls both closures with two generators, so the model is fitted twice per window (as in numpyro_forecast): the test and in-sample scores come from two posteriors, and an MCMC closure pays for two fits. To fit once, the two closures can share a cache of fits keyed on the trainingtimecoords. Aforecast_fnon the functional API:def forecast_fn(rng, model_fn, train_data, train_covariates, full_covariates, num_samples, /, *, batch_size=None): fit = fit_vi(model_fn, train_data, train_covariates, random_seed=int(rng.integers(2**31))) posterior = draw_posterior(fit, num_samples, rng) tree = forecast(model_fn, posterior, train_data, full_covariates, var_names=["forecast"], batch_size=batch_size, random_seed=rng) return tree["predictions"]["forecast"]
- Parameters:
data (
xarray.DataArray,xarray.Dataset,pandas.Series,pandas.DataFrameorarray_like) – The full series, normalized withas_dataarray()("time"first; 2-D input gets a"series"dim). Anxarray.Datasetholds several observed tables, cut at each window like an array, with the dims and dtype of each table kept. It requiresforecast_fnandtransform, and every data variable must have a"time"dim so that no table reaches the closure past the forecast origin. ADatasetwithout"time"coords gets an integer range.covariates (
xarray.DataArray,pandas.Series,pandas.DataFrameorarray_likeorNone) – Covariates over the same span asdata(normalized withas_dataarray; 2-D input gets a"covariate"dim), sliced by position alongsidedata.Nonefor models without covariates. Withforecast_fn, the covariate"time"coords must start with the ones ofdata, as the forecasters require.model_fn (
callable,pymc_forecast.model.ForecastingModelorNone) – The model body orForecastingModel, passed toforecaster_clsor to the closures. May beNonewithforecast_fn.forecaster_cls (
type, optional) – Forecaster class constructed per window (see the forecaster protocol above).NonemeansForecasterwhenforecast_fnis not given. Cannot be combined withforecast_fn.forecast_fn (
callable, optional) – Closure that fits each window and returns its forecast draws (see the closure protocol above).in_sample_fn (
callable, optional) – Closure that fits each window and returns its in-sample draws (see the closure protocol above). It requiresforecast_fnandeval_train=True, andeval_trainwithforecast_fnrequires it.var_name (
str, default"forecast") – Variable of thepredictionsgroup offorecaster_cls.forecastthat is scored and kept, e.g."mu_future". The built-in forecasters record"forecast", every free*_futurevariable,"mu_future"and, when the model supplies it,"expected_observation_future"; apm.Deterministicis not recorded. Another name than"forecast"cannot be combined withforecast_fn, which returns its target directly, or witheval_train, whose in-sample score is of"obs".metrics (
mapping, optional) – Metric name → function; defaults toDEFAULT_METRICS. Bind metric parameters withfunctools.partial.per_window_metrics (
callable, optional) – Optional(t0, t1, t2) -> Mappingproducing extra metrics per window (e.g. a MASE scaled by that window’s training slice viamake_mase()); entries override same-namedmetrics.transform (
callable, optional) – Optional(pred, truth) -> (pred, truth)applied before metrics (both labeled:predhaschain/drawsample dims,truthis the test rows ofdatarenamed totime_futureso names align). Witheval_train, it is also applied to the in-sample samples and the training slice, which both use the"time"dim. Required forDatasetdata:truthis then aDataset, andtransformreturns the truth of the target as aDataArray.window_type (
{"expanding", "rolling"}, optional) –"expanding"trains from the start of the series;"rolling"uses a fixedtrain_window.Noneinfers"rolling"whentrain_windowis set and"expanding"otherwise.train_window (
int, optional) – Fixed training length for rolling windows; required for"rolling"and not allowed with"expanding".min_train_window (
int, default1) – Minimum training length; the first split for expanding windows.test_window (
int, optional) – Maximum test length;Nonetests to the end of the series.min_test_window (
int, default1) – Minimum test length; splits stop once fewer than this many test steps would remain, so every window has at leastmin_test_windowtest steps.stride (
int, default1) – Step between successive splits.num_samples (
int, default100) – Forecast samples requested per window (also used for in-sample predictions).batch_size (
int, optional) – Maximum posterior draws per predictive pass, passed to the closures, and to theforecastandpredict_in_samplemethods offorecaster_clswhen notNone.forecaster_options (
mappingorcallable, optional) – Extra constructor kwargs forforecaster_cls— a mapping, or a callable(t0, t1, t2) -> mappingfor per-window options. Cannot be combined withforecast_fn.eval_train (
bool, defaultFalse) – Also score the in-sample posterior predictive of each window.keep_predictions (
bool, defaultFalse) – Keep each window’s (transformed) forecast samples on the result.random_seed (
int,sequenceofint,SeedSequence,GeneratororNone, optional) – Base seed. Each window gets a childnumpy.random.SeedSequence, spawned fromSeedSequence(random_seed), or by thespawnmethod of aSeedSequenceorGenerator.forecaster_clsgets twointseeds per window (fit and forecast) from the child. The closures get oneGeneratoreach, from two children of the window’sSeedSequence, soeval_traindoes not change the forecasts.spawnadvances the spawn counter of the object: two calls with the sameGeneratororSeedSequencegive different results. Numbers drawn from aGeneratordo not change its children, so only its seed and its spawn counter matter: for the same integer seed, a freshdefault_rng(seed)orSeedSequence(seed)gives the same results asseed.
- Returns:
listofBacktestResult– One result per window, in time order.- Raises:
pymc_forecast.exceptions.BacktestWindowError – If
window_typeis unknown or conflicts withtrain_window, a window parameter is not an integer (or is a bool), a minimum is below 1,test_window < min_test_window,stride < 1,train_window < min_train_window, or the series is too short for any window.pymc_forecast.exceptions.AlignmentError – If
dataorcovariatescannot be normalized, or aDatasetdata variable has no"time"dim. Withforecast_fn, before any fit, if the covariates fail the checks the forecasters run per window (validate_alignment()):"time"coords that do not start with the ones ofdata, or a shared non-time dim with another size or other labels. Errors raised byforecaster_clsor the closures (fitting/forecasting) and by the metrics propagate.ValueError – Before any fit, if
forecast_fnis combined withforecaster_cls,forecaster_optionsor avar_nameother than"forecast";in_sample_fnis given withoutforecast_fnor withouteval_train;eval_trainis set withforecast_fnand noin_sample_fn, or with avar_nameother than"forecast"; ordatais aDatasetandtransformis not given. After a closure call, if its draws have no sample dim.TypeError – Before any fit, if
datais aDatasetandforecast_fnis not given, orbatch_sizeis set and a method offorecaster_clsdoes not accept it. After a closure call, if it returned something other than anxarray.DataArray.KeyError – After the first forecast, if the result of
forecaster_cls.forecasthas nopredictionsgroup or novar_namevariable in it.
- Warns:
UserWarning – From the VI convergence check of the default
forecaster_cls.
- pymc_forecast.evaluate.results_to_dataframe(results)[source]#
Flatten backtest results into a
pandas.DataFrame.One row per window: split points, walltimes, one column per metric, and
train_-prefixed columns for in-sample metrics when present.- Parameters:
results (
listofBacktestResult) – Results ofbacktest().- Returns:
pandas.DataFrame– Columnst0,t1,t2,num_samples,train_walltime,test_walltime, then one per metric and onetrain_<name>per in-sample metric;predictionis not included.