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: object

Per-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); 0 for 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 requested num_samples with forecaster_cls; with forecast_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; nan with forecast_fn, whose fit is timed in test_walltime.

  • test_walltime (float) – Wall-clock seconds for the forecast call: forecaster.forecast, or the whole forecast_fn call, fit included.

  • metrics (dict) – Metric name → value (float) on the test window.

  • train_metrics (dict, optional) – Metric name → in-sample value (float); empty unless eval_train=True. Defaults to an empty dict.

  • prediction (xarray.DataArray, optional) – Forecast samples for the window, after transform if one was given (None unless keep_predictions=True). With a transform its dims are the ones transform returns.

pymc_forecast.evaluate.WindowType#

Allowed window_type values of backtest(), "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, default Forecaster) 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 (data as a Dataset), and targets other than the observed series.

Forecaster protocol. backtest uses forecaster_cls through 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_data is rows t0:t1 of data, window_covariates the covariate rows t0:t2 (training plus test span; zero-width covariates when covariates is None) and fit_seed an int.

  • .forecast(window_covariates, num_samples=num_samples, random_seed=forecast_seed), where forecast_seed is an int. backtest scores result["predictions"][var_name].

  • .predict_in_sample(num_samples=num_samples, random_seed=forecast_seed), only with eval_train=True. backtest scores result["posterior_predictive"]["obs"] against train_data.

When batch_size is not None, both methods also get batch_size=batch_size. A class whose forecast (or, with eval_train, predict_in_sample) has neither a batch_size parameter nor **kwargs, such as StatespaceForecaster, is then rejected before the first fit. The check reads the methods of the class; a factory function or a functools.partial is not checked.

Closure protocol. forecast_fn and in_sample_fn get positional arguments and a keyword batch_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)

rng is a numpy.random.Generator, a separate stream per window and per closure. model_fn is passed through as given. train_covariates are the covariate rows t0:t1 and full_covariates the rows t0:t2. forecast_fn returns the forecast draws of the test rows and in_sample_fn the draws of the training rows, each an xarray.DataArray with the sample dims chain and draw, or a sample dim stacked as by arviz.extract: any of the sample dims the metrics accept. Without a transform the other dims must align with the truth (time_future or time, and the data dims); with one, any dims are allowed. The closure may return another number of draws than num_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. With eval_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 training time coords. A forecast_fn on 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.DataFrame or array_like) – The full series, normalized with as_dataarray() ("time" first; 2-D input gets a "series" dim). An xarray.Dataset holds several observed tables, cut at each window like an array, with the dims and dtype of each table kept. It requires forecast_fn and transform, and every data variable must have a "time" dim so that no table reaches the closure past the forecast origin. A Dataset without "time" coords gets an integer range.

  • covariates (xarray.DataArray, pandas.Series, pandas.DataFrame or array_like or None) – Covariates over the same span as data (normalized with as_dataarray; 2-D input gets a "covariate" dim), sliced by position alongside data. None for models without covariates. With forecast_fn, the covariate "time" coords must start with the ones of data, as the forecasters require.

  • model_fn (callable, pymc_forecast.model.ForecastingModel or None) – The model body or ForecastingModel, passed to forecaster_cls or to the closures. May be None with forecast_fn.

  • forecaster_cls (type, optional) – Forecaster class constructed per window (see the forecaster protocol above). None means Forecaster when forecast_fn is not given. Cannot be combined with forecast_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 requires forecast_fn and eval_train=True, and eval_train with forecast_fn requires it.

  • var_name (str, default "forecast") – Variable of the predictions group of forecaster_cls.forecast that is scored and kept, e.g. "mu_future". The built-in forecasters record "forecast", every free *_future variable, "mu_future" and, when the model supplies it, "expected_observation_future"; a pm.Deterministic is not recorded. Another name than "forecast" cannot be combined with forecast_fn, which returns its target directly, or with eval_train, whose in-sample score is of "obs".

  • metrics (mapping, optional) – Metric name → function; defaults to DEFAULT_METRICS. Bind metric parameters with functools.partial.

  • per_window_metrics (callable, optional) – Optional (t0, t1, t2) -> Mapping producing extra metrics per window (e.g. a MASE scaled by that window’s training slice via make_mase()); entries override same-named metrics.

  • transform (callable, optional) – Optional (pred, truth) -> (pred, truth) applied before metrics (both labeled: pred has chain/draw sample dims, truth is the test rows of data renamed to time_future so names align). With eval_train, it is also applied to the in-sample samples and the training slice, which both use the "time" dim. Required for Dataset data: truth is then a Dataset, and transform returns the truth of the target as a DataArray.

  • window_type ({"expanding", "rolling"}, optional) – "expanding" trains from the start of the series; "rolling" uses a fixed train_window. None infers "rolling" when train_window is 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, default 1) – Minimum training length; the first split for expanding windows.

  • test_window (int, optional) – Maximum test length; None tests to the end of the series.

  • min_test_window (int, default 1) – Minimum test length; splits stop once fewer than this many test steps would remain, so every window has at least min_test_window test steps.

  • stride (int, default 1) – Step between successive splits.

  • num_samples (int, default 100) – 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 the forecast and predict_in_sample methods of forecaster_cls when not None.

  • forecaster_options (mapping or callable, optional) – Extra constructor kwargs for forecaster_cls — a mapping, or a callable (t0, t1, t2) -> mapping for per-window options. Cannot be combined with forecast_fn.

  • eval_train (bool, default False) – Also score the in-sample posterior predictive of each window.

  • keep_predictions (bool, default False) – Keep each window’s (transformed) forecast samples on the result.

  • random_seed (int, sequence of int, SeedSequence, Generator or None, optional) – Base seed. Each window gets a child numpy.random.SeedSequence, spawned from SeedSequence(random_seed), or by the spawn method of a SeedSequence or Generator. forecaster_cls gets two int seeds per window (fit and forecast) from the child. The closures get one Generator each, from two children of the window’s SeedSequence, so eval_train does not change the forecasts. spawn advances the spawn counter of the object: two calls with the same Generator or SeedSequence give different results. Numbers drawn from a Generator do not change its children, so only its seed and its spawn counter matter: for the same integer seed, a fresh default_rng(seed) or SeedSequence(seed) gives the same results as seed.

Returns:

list of BacktestResult – One result per window, in time order.

Raises:
  • pymc_forecast.exceptions.BacktestWindowError – If window_type is unknown or conflicts with train_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 data or covariates cannot be normalized, or a Dataset data variable has no "time" dim. With forecast_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 of data, or a shared non-time dim with another size or other labels. Errors raised by forecaster_cls or the closures (fitting/forecasting) and by the metrics propagate.

  • ValueError – Before any fit, if forecast_fn is combined with forecaster_cls, forecaster_options or a var_name other than "forecast"; in_sample_fn is given without forecast_fn or without eval_train; eval_train is set with forecast_fn and no in_sample_fn, or with a var_name other than "forecast"; or data is a Dataset and transform is not given. After a closure call, if its draws have no sample dim.

  • TypeError – Before any fit, if data is a Dataset and forecast_fn is not given, or batch_size is set and a method of forecaster_cls does not accept it. After a closure call, if it returned something other than an xarray.DataArray.

  • KeyError – After the first forecast, if the result of forecaster_cls.forecast has no predictions group or no var_name variable 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 (list of BacktestResult) – Results of backtest().

Returns:

pandas.DataFrame – Columns t0, t1, t2, num_samples, train_walltime, test_walltime, then one per metric and one train_<name> per in-sample metric; prediction is not included.