State Space Model

The base-class for time-series modeling with state-space models. Generates forecasts in the form of torchcast.state_space.Predictions, which can be used for training (log_prob()), evaluation (to_dataframe()) or visualization (plot()).

This class is abstract; see torchcast.kalman_filter.KalmanFilter for the go-to forecasting model.

class torchcast.state_space.StateSpaceModel(processes: Sequence[Process], measures: Sequence[str], measure_covariance: Covariance | None = None, measure_funs: dict[str, str] | None = None, adaptive_scaling: bool | AdaptiveScaler = False, mixture: MixtureModel | Sequence[MixtureComponent] | None = None)

Bases:

Base-class for any torch.nn.Module which generates predictions/forecasts using a state-space model.

Parameters:
  • processes – A list of Process modules.

  • measures – A list of strings specifying the names of the dimensions of the time-series being measured.

  • measure_covariance – A module created with Covariance.from_measures(measures).

  • measure_funs – A dictionary mapping measure-names to measurement-functions. Currently only supports ‘sigmoid’.

  • adaptive_scaling – Experimental feature to adaptively scale the covariance as a function of residuals. This is useful if different groups have very different magnitudes.

  • mixture – Experimental. A MixtureModel of alternative regimes for one or more measures – e.g. for outliers, which are then explained by a mixture component rather than updating the state. Can also pass a list of MixtureComponent objects, as shorthand for MixtureModel(components).

forward(y: Tensor | None = None, n_step: int | float = 1, start_offsets: Sequence | None = None, out_timesteps: int | float | None = None, initial_state: tuple[Tensor, Tensor] | Tensor | None = None, every_step: bool = True, include_updates_in_output: bool = False, simulate: int | None = None, prediction_kwargs: dict | None = None, generator: Generator | None = None, **kwargs) → Predictions

Generate n-step-ahead predictions from the model.

Parameters:
  • y – A (group X time X measures) tensor. Optional if initial_state is specified.

  • n_step – What is the horizon for the predictions output for each timepoint? Defaults to one-step-ahead predictions (i.e. n_step=1).

  • start_offsets – If your model includes seasonal processes, then these needs to know the start-time for each group in y. If you passed dt_unit when constructing those processes, then you should pass an array of datetimes here. Otherwise you can pass an array of integers. Or leave None if there are no seasonal processes.

  • out_timesteps – The number of timesteps to produce in the output. This is useful when passing a tensor of predictors that goes later in time than the input tensor – you can specify out_timesteps=X.shape[1] to get forecasts into this later time horizon.

  • initial_state – The initial prediction for the state of the system. This is a tuple of mean, cov tensors you might extract from a previous call to forward (see include_updates_in_output below); you would have a Predictions object, which you can call get_state_at_times() on. If left unset, will learn the initial state from the data. You can also pass a mean but not a cov, in situations where you want to predict the initial state mean but use the default cov. For models with mixture components, pass the StateTuple returned by get_state_at_times() to also carry over the combo-probabilities (with a plain (mean, cov) tuple, the combo-probabilities start from the transition’s initial()).

  • every_step – By default, n_step ahead predictions will be generated at every timestep. If every_step=False, then these predictions will only be generated every n_step timesteps. For example, with hourly data, n_step=24 and every_step=True, each timepoint would be a forecast generated with data 24-hours in the past. But with every_step=False the first timestep would be 1-step-ahead, the 2nd would be 2-step-ahead, … the 23rd would be 24-step-ahead, the 24th would be 1-step-ahead, etc. The advantage to every_step=False is speed: training data for long-range forecasts can be generated without requiring the model to produce and discard intermediate predictions every timestep.

  • include_updates_in_output – If False, only the n_step ahead predictions are included in the output. This means that we cannot use this output to generate the initial_state for subsequent forward-passes. Set to True to allow this – False by default to reduce memory.

  • simulate – If specified, will generate simulate state-trajectories from the model (see simulate()): the output’s states are the simulated ones (rather than predictions). Requires n_step=1.

  • generator – With simulate, an optional torch.Generator for the simulation’s draws, for reproducibility.

  • prediction_kwargs – A dictionary of kwargs to pass to initialize Predictions().

  • kwargs – Further arguments passed to the processes. For example, the LinearModel expects an X argument for predictors.

Returns:

A Predictions object with Predictions.log_prob() and Predictions.to_dataframe() methods.

fit(y: Tensor, optimizer: Optimizer | Callable[[Sequence[Tensor]], Optimizer] = None, stopping: Stopping | dict = None, verbose: int = 2, callbacks: Sequence[Callable] = (), get_loss: Callable | None = None, callable_kwargs: dict[str, Callable] | None = None, set_initial_values: bool = True, **kwargs)

A high-level interface for fitting a state-space model when all the training data fits in memory. If your data does not fit in memory, consider torchcast.utils.training.StateSpaceTrainer or tools like pytorch lightning.

Parameters:
  • y – A tensor containing the batch of time-series(es), see StateSpaceModel.forward().

  • optimizer – The optimizer to use. Can also pass a function which takes the parameters and returns an optimizer instance. Default is torch.optim.LBFGS with (line_search_fn='strong_wolfe', max_iter=1, max_eval=25).

  • stopping – Controls stopping/convergence rules; should be a torchcast.utils.Stopping instance, or a dict of keyword-args to one. Example: stopping={'abstol' : .001, 'monitor_params' : True}

  • verbose – If True (default) will print the loss and epoch.

  • callbacks – A list of functions that will be called at the end of each epoch, which take the current epoch’s loss value.

  • get_loss – A function that takes the Predictions` object and the input data and returns the loss. The default is to use the mean negative log-prob (from ``Predictions.log_prob()). You can use your own function, or for small modifications (e.g. including weights) pass an instance of LossFun.

  • set_initial_values – If True, will set the initial mean to sensible value given y, which helps speed up training if the data are not centered. Set to False if you are resuming fit on a partially fitted model.

  • kwargs – Further keyword-arguments passed to StateSpaceModel.forward(); but see also callable_kwargs.

  • callable_kwargs – The kwargs passed to the forward pass are static, but sometimes you want to recompute them each iteration – indeed, this is required in some cases by how pytorch’s autograd works. The values in this dictionary are no-argument functions that will be called each iteration to recompute the corresponding arguments.

Returns:

This StateSpaceModel instance.

get_laplace_mvnorm(y: Tensor, get_loss: Callable | None = None, **kwargs) → tuple[MultivariateNormal, List[str]]
Parameters:
  • y – observed data

  • get_loss – A function that takes the Predictions object and the input data and returns the loss; note that unlike in fit(), this function should return the summed loss (not mean). Default is just -pred.log_prob(y).sum(), but you can override (e.g. for weights). The most convenient way to override is with LossFun

  • kwargs – Keyword-arguments to the forward pass.

Returns:

The multivariate normal distribution for the Laplace approximation, and the corresponding names of the parameters.

simulate(out_timesteps: int, initial_state: tuple[Tensor, Tensor] | None = None, start_offsets: Sequence | None = None, num_sims: int = 1, num_groups: int | None = None, generator: Generator | None = None, **kwargs)

Generate simulated state-trajectories from your model.

For models with mixture components, the regimes are simulated too: at each timestep, a regime-combo is drawn from the combo-prior given the trajectory so far (so stickiness and latent classes carry over), and the output’s combo_probs are these (one-hot) draws. So e.g. sample() on the output uses the simulated regimes.

Parameters:
  • out_timesteps – The number of timesteps to generate in the output.

  • initial_state – The initial state of the system: a tuple of mean, cov. Can be obtained from previous model-predictions by calling get_state_at_times() on the output predictions.

  • start_offsets – If your model includes seasonal processes, then these needs to know the start-time for each group in initial_state. If you passed dt_unit when constructing those processes, then you should pass an array of datetimes here, otherwise an array of ints. If there are no seasonal processes you can omit.

  • num_sims – The number of state-trajectories to simulate per group. The output will be laid out in blocks (e.g. if there are 10 groups, the first ten elements of the output are sim 1, the next 10 elements are sim 2, etc.). Tensors associated with this output can be reshaped with tensor.reshape(num_sims, num_groups, ...).

  • num_groups – The number of groups; if None will be inferred from the shape of initial_state and/or start_offsets.

  • generator – An optional torch.Generator for the simulation’s draws, for reproducibility.

  • kwargs – Further arguments passed to the processes.

Returns:

A Predictions object whose states are the simulated ones (with zero covariance, up to a small jitter), so e.g. its means are the measured-means of the trajectories, and Predictions.sample() draws observations around them. (With include_updates_in_output=True, the update_* attributes are the same states.) For models with mixture components, the regimes are simulated too: each timestep’s combo_probs are one-hot, for the simulated regime-combo (drawn from the prior given the previous one), so Predictions.sample() draws observations in that regime.

class torchcast.state_space.LossFun(weights: Tensor | None = None, reduce: str | None = 'mean')

Bases:

Useful for customizing the loss in your model’s fit() calls. For example, my_model.fit(get_loss=LossFun(weights=my_weights)).

Parameters:
  • weights – A num_groups X num_times tensor of weights.

  • reduce – Can be ‘mean’, ‘sum’, or None.

class torchcast.state_space.StateTuple(mean: Tensor, cov: Tensor, combo_probs: Tensor | None = None, scaling: Mapping[str, Tensor] | None = None)

Bases:

The state of a StateSpaceModel at a single timestep: a (num_groups, state_dim) mean and a (num_groups, state_dim, state_dim) covariance. If the model has mixture components, also holds the (num_groups, num_combos) combo-probabilities (combo_probs). If the model has adaptive_scaling, also holds the adaptive-scaler’s state (scaling: a dict of (num_groups, ...) tensors, incl. the pending 'multiplier' for the next step), so that a forecast continued from this state matches one made in a single pass.

Behaves like the tuple (mean, cov) – e.g. mean, cov = state – so it can be passed anywhere a (mean, cov) tuple is accepted, such as the initial_state argument of StateSpaceModel.forward().

class torchcast.state_space.Predictions(measurement_model: MeasurementModel, states: Sequence[StateTuple] | StateTuple | tuple, measure_covs: Sequence[Tensor] | Tensor, updates: Sequence[StateTuple] | StateTuple | tuple | None = None, mc_white_noise: FixedWhiteNoise | None = None, mixture: MixtureModel | None = None)

Bases:

The output of the StateSpaceModel forward pass, containing the underlying state means and covariances, as well as methods such as log_prob(), to_dataframe(), and plot().

The states (state_means, state_covs) are those that each timestep’s observations are predicted from: for filtering/forecasting, the predicted (prior) states, before that timestep’s update; for simulate(), the simulated states. (update_means and update_covs, if included, are the states after each update.)

property means: Tensor

Returns the observed means of the predictions, i.e. the measured means of the state.

For models with mixture components, means and covs are the exact mean and covariance of the mixture over regimes – but the predictive distribution is not gaussian, so e.g. don’t use them to construct intervals, or to back-transform a transformed measure. Use get_mixture() (or _get_regime_combos()) instead.

get_means(transform: Transform | dict[str, Transform] | None = None, use_map: bool | None = None, num_samples: int = 1000, generator: Generator | None = None) → Tensor

The predicted means, as in the mean column of to_dataframe() with the same transform, use_map, num_samples and generator – without computing any intervals.

Parameters:
Returns:

A (num_groups, num_timesteps, num_measures) tensor.

log_prob(obs: Tensor, weights: Tensor | None = None, nan_groups_flat: Sequence[tuple[Tensor, Tensor | None]] | None = None) → Tensor

Compute the log-probability of data (e.g. data that was originally fed into the StateSpaceModel).

Parameters:
  • obs – A Tensor that could be used in the StateSpaceModel forward pass.

  • weights – If specified, will be used to weight the log-probability of each group X timestep.

  • nan_groups_flat – used by StateSpaceModel.fit() for speeding up computations, pre-computing nan-masks at the start of fitting rather than doing so on each call to log_prob().

Returns:

A tensor with one element for each group X timestep indicating the log-probability.

to_dataframe(dataset: TimeSeriesDataset | None = None, type: str = 'predictions', group_colname: str | None = None, time_colname: str | None = None, conf: float | None | bool = 0.95, use_map: bool | None = None, transform: Transform | dict[str, Transform] | None = None, derived: dict[str, Callable[[dict[str, Tensor]], Tensor]] | None = None, num_samples: int = 1000, generator: Generator | None = None) → DataFrame
Parameters:
  • dataset – If not provided, will use the metadata set by set_metadata().

  • type – What type of dataframe to return, either ‘predictions’, ‘states’, or ‘observed_states’.

  • group_colname – The name of the column to use for groups, defaults to the metadata’s group_colname.

  • time_colname – The name of the column to use for time, defaults to the metadata’s time_colname.

  • conf – The confidence level for the confidence intervals, defaults to 0.95. None returns a std column instead of the intervals; False returns only the means, skipping all of the work of computing intervals (for predictions; see also get_means()).

  • use_map – For measures with a nonlinear measured-mean (e.g. a measure-function, or nonlinear processes): whether the mean averages over the state’s uncertainty by monte-carlo (use_map=False), or plugs in the state’s mean (use_map=True; the MAP), treating the measure like a linear one, with the moments of the linearized measurement-model. (The intervals are monte-carlo either way.) Reasons to use the MAP: for a monotone measure-function (e.g. a sigmoid), it’s the predictive median of the measured-mean rather than its mean (better for e.g. absolute error); it doesn’t depend on the state’s variance, so it’s robust to that being miscalibrated (an overestimated variance pulls the monte-carlo mean of a sigmoid towards .5); and it’s cheap. With a transform, the back-transformed mean then works as for linear measures: its bias_adjust sets how much of the (linearized) variance is used – e.g. bias_adjust=0 gives the plug-in inverse(MAP), a median-like forecast throughout. (bias_adjust works the same way for the monte-carlo mean, where it scales the state’s variance too.) Ignored for models without nonlinear measures, whose means are exact.

  • transform – For measures that were transformed before modeling (e.g. log), a Transform to map the predictions (and actuals) back to the original scale: either a single Transform for all measures, or a dictionary of {measure: Transform}. The mean is back-transformed exactly (not just the mean on the modeled scale, back-transformed), as are the intervals. Only for type='predictions'.

  • derived – Quantities computed from multiple measures, e.g. {'total': lambda s: s['a'] + s['b']}. Each function receives a dictionary of {measure: (num_samples, num_groups, num_timesteps)} samples from the (joint) predictive distribution, including observation noise and on the scale given by transform, and should return a (num_samples, num_groups, num_timesteps) tensor, computing each group and timestep from its own values (e.g. not a total across groups: for memory, it’s applied to chunks of groups at a time). Each is added to the output with its key as the ‘measure’; the mean and intervals are computed across samples (see sample()). The mean uses the measures whose means are exact (those with a linear measured-mean) as control variates, which reduces its monte-carlo error – e.g. a sum of these measures is exact. If there are actuals, the function is applied to them too (so it should handle missing values, which are nan; measures that aren’t in dataset are all-nan). Only for type='predictions'.

  • num_samples – The number of monte-carlo samples, for the outputs that need them: the means (with use_map=False or a transform) and intervals of measures with a nonlinear measured-mean, derived, and type='states'/'observed_states' for nonlinear models. (Separate from the model’s mc_sampling, which is only for the log-prob, in training.)

  • generator – An optional torch.Generator for those samples. By default, their seed comes from torch.initial_seed() – the seed last set by torch.manual_seed(), which makes them reproducible, or else a random one fixed for the process – so repeated calls agree. With a generator, this call draws its seed from the generator instead (leaving the predictions’ own seed as it was).

samples_to_dataframe(samples: dict[str, Tensor], dataset: TimeSeriesDataset | None = None, conf: float = 0.95, actuals: dict[str, Tensor] | None = None, group_colname: str | None = None, time_colname: str | None = None) → DataFrame

Summarize samples (e.g. of some quantity computed from sample()) into a dataframe with the same format as to_dataframe(): the mean and the conf interval across samples, for each group and timestep.

Parameters:
  • samples – A dictionary with (num_samples, num_groups, num_timesteps) tensors. The keys become the ‘measure’ column of the output.

  • dataset – If not provided, will use the metadata set by set_metadata().

  • conf – The confidence level for the intervals.

  • actuals – Optionally, a dictionary with (num_groups, num_timesteps) tensors of actual values for some keys of samples.

  • group_colname – The name of the column to use for groups, defaults to the metadata’s group_colname.

  • time_colname – The name of the column to use for time, defaults to the metadata’s time_colname.

plot(df: DataFrame | TimeSeriesDataset | None = None, group_colname: str = None, time_colname: str = None, max_num_groups: int = 1, split_dt: datetime64 | None = None, **kwargs)
Parameters:
  • df – A dataset, or the output of Predictions.to_dataframe().

  • group_colname – The name of the group-column.

  • time_colname – The name of the time-column.

  • max_num_groups – Max. number of groups to plot; if the number of groups in the dataframe is greater than this, a random subset will be taken.

  • split_dt – If supplied, will draw a vertical line at this date (useful for showing pre/post validation).

  • kwargs – Further keyword arguments to pass to plotnine.theme (e.g. figure_size=(x,y))

Returns:

A plot of the predicted and actual values.

sample(num_samples: int, shared_noise: bool, observation_noise: bool = True, generator: Generator | None = None, regime_noise_scale: Mapping[str, float] | None = None) → PredictionSamples

Draw samples from the predictive distribution: jointly across measures, for each group and timestep. These are not trajectories – the model’s timesteps are correlated (via the state), while samples for different timesteps are not – so quantities that combine timesteps shouldn’t be computed from them; see StateSpaceModel.simulate() for that.

Each sample is a draw of the state (and, for models with mixture components, of the regime), giving a conditional distribution for the measures: means and covs. These capture uncertainty about the state, but not the observation noise around it. With observation_noise=True, each sample also includes a draw of the observations from that conditional distribution (for binary measures: binomial draws).

Parameters:
  • num_samples – The number of samples.

  • shared_noise – If True, the underlying random draws (the standard-normal noise for the state and for the gaussian observation-noise, and the uniforms for the regime) are the same for every group and timestep (binomial draws are still independent). Each row’s distribution is still correct, so this is fine for per-row summaries (means, quantiles, functions of several measures), and it uses less memory. But samples are then correlated across rows. If False, samples are independent across rows, so they can be aggregated across groups (e.g. summed), since groups are independent in the model – but still not across timesteps (see above).

  • observation_noise – If True (the default), also sample the observations.

  • generator – An optional torch.Generator, for reproducibility.

  • regime_noise_scale – For models with mixture components: scales the randomness of draws in a component’s regime, {component_id: scale} (or '{measure}.{component_id}'; others get 1). A draw’s value for that measure is its regime’s center – the measured-mean of the state’s mean (the MAP), plus the component’s offset – plus scale times its deviation from that center (from the state, the observation noise, and the component’s extra variance). E.g. {'low': 0.} pins draws in a ‘low’ regime at its center (on the modeled scale), while the standard regime is sampled as usual: e.g. to check how much a component’s variance contributes to back-transformed outputs (a sample-based analogue of a transform’s per-regime bias_adjust=0). The regimes are drawn as usual. The state is shared across measures, so this also weakens the draws’ correlation with other measures. The scales are in PredictionSamples.noise_scales (and reflected in covs).

Returns:

A PredictionSamples.

property latent_class_probs: Tensor

For a model with latent classes (MixtureModel(..., classes=)), each group’s posterior probability of each class. Since a group’s class is fixed, these accumulate evidence over time: like combo_probs, they’re the prior at each timestep, so [:, t] uses the data up to t - 1. At the first timestep, before any data, they’re the learned prior (the share of groups in each class).

Returns:

A (num_groups, num_timesteps, num_classes) tensor, in the order of MixtureModel.classes.

get_mixture(measure: str) → MixtureOfNormals

For a measure with mixture components, the predictive distribution as a (univariate) mixture of normals: the standard regime, then each of the measure’s components.

For a measure with a nonlinear measurement (a measure-function or nonlinear processes), the standard regime isn’t actually normal: its mean and variance are from the linearized (EKF) measurement-model, so are approximate (with a warning). The regime-probabilities are still exact. (to_dataframe() and means use monte-carlo for these measures instead.)

Parameters:

measure – The name of the measure.

Returns:

A MixtureOfNormals whose tensors have shape (num_groups, num_timesteps, num_components).

get_state_at_times(times: ndarray | datetime64, type_: str = 'update') → StateTuple

For each group, get the state (tuple of (mean, cov)) for a timepoint. This is often useful since predictions are right-aligned and padded, so that the final prediction for each group is arbitrarily padded and does not correspond to a timepoint of interest – e.g. for simulation (i.e., calling StateSpaceModel.simulate(initial_state=get_state_at_times(...))).

Parameters:
  • times – An array/sequence containing the time for each group; or a single datetime to apply to all groups. If the model/predictions are dateless (no dt_unit) then simply an array of indices

  • type – What type of state? Since this method is typically used for getting an initial_state for another call to StateSpaceModel.forward(), this should generally be ‘update’ (the default); other option is ‘prediction’.

Returns:

A StateTuple, appropriate for forecasting by passing as initial_state for StateSpaceModel.forward(). This behaves like a tuple of (state_means, state_covs); if the model has mixture components, it also carries the combo_probs at those times.

with_new_start_times(start_times: ndarray | datetime64, n_timesteps: int) → Predictions
Parameters:
  • start_times – An array/sequence containing the start time for each group; or a single datetime to apply to all groups. If the model/predictions are dateless (no dt_unit) then simply an array of indices.

  • n_timesteps – Each group will be sliced to this many timesteps, so times is start and times + n_timesteps is end.

Returns:

A new Predictions object, with the state and measurement tensors sliced to the given times.

class torchcast.state_space.PredictionSamples(measures: list, means: Tensor, measure_covs: Tensor, extra_vars: Tensor | None = None, observations: Tensor | None = None, combos: Tensor | None = None, noise_scales: Tensor | None = None)

Bases:

Samples from the predictive distribution, from Predictions.sample().

Parameters:
  • measures – The names of the measures (the last dimension of the tensors).

  • means – A (num_samples, num_groups, num_timesteps, num_measures) tensor: for each sample (of the state, and regime if applicable), the mean of the measures.

  • measure_covs – A (num_groups, num_timesteps, num_measures, num_measures) tensor: the observation-noise covariance that’s the same for every sample.

  • extra_vars – Optionally, a (num_samples, num_groups, num_timesteps, num_measures) tensor of per-sample variances added to the diagonal of measure_covs (e.g. a binary measure’s binomial variance, or a regime’s extra variance). See covs.

  • observations – If observation_noise=True, a (num_samples, num_groups, num_timesteps, num_measures) tensor of sampled observations.

  • combos – For models with mixture components, a (num_samples, num_groups, num_timesteps) tensor with the index of each sample’s regime-combo (as in MixtureModel.labels).

  • noise_scales – With sample(regime_noise_scale=...), a (num_samples, num_groups, num_timesteps, num_measures) tensor of the scales applied to each draw’s deviation from its regime’s center.

property covs: Tensor

A (num_samples, num_groups, num_timesteps, num_measures, num_measures) tensor: for each sample, the covariance of the observations around means (i.e. the observation-noise). Computed on access (a view, if there are no extra_vars; otherwise a new, potentially large, tensor).