pymc_forecast.evaluate#
Backtesting: score a forecasting model over moving train/test windows.
Each window is a pure refit: the forecaster is constructed on the window’s
training slice and asked to forecast the test slice, and metrics are computed
on the sampled predictions. 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) – Requested number of forecast samples (thebacktestargument).train_walltime (
float) – Wall-clock seconds to construct (build and fit) the forecaster.test_walltime (
float) – Wall-clock seconds for the forecast call.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).
- 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=<class 'pymc_forecast.forecaster.Forecaster'>, 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, forecaster_options=None, eval_train=False, keep_predictions=False, random_seed=None)[source]#
Backtest a forecasting model on moving
(train, test)windows.- Parameters:
data (
xarray.DataArray,pandas.Series,pandas.DataFrameorarray_like) – The full series, normalized withas_dataarray()("time"first; 2-D input gets a"series"dim).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.model_fn (
callableorpymc_forecast.model.ForecastingModel) – The model body orForecastingModel.forecaster_cls (
type, defaultpymc_forecast.forecaster.Forecaster) – Forecaster class constructed per window asforecaster_cls(model_fn, train_data, window_covariates, random_seed=..., **options), wherewindow_covariatesare the covariate rowst0:t2(training plus test span; zero-width covariates whencovariatesisNone).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 renamed totime_futureso names align). Witheval_train, it is also applied to the in-sampleobssamples and the training slice, which both use the"time"dim.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 per window (also used for in-sample predictions).forecaster_options (
mappingorcallable, optional) – Extra constructor kwargs forforecaster_cls— a mapping, or a callable(t0, t1, t2) -> mappingfor per-window options.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 (
intorsequenceofint, optional) – Base seed (numpy.random.SeedSequenceentropy); per-window fit/forecast seeds are derived deterministically.
- 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; errors raised byforecaster_cls(fitting/forecasting) and by the metrics propagate.
- 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.