A StructuralTimeSeries object represents a declarative specification of a
structural time series model, including priors on model parameters.
It implements a joint probability model
p(params, y) = p(params) p(y | params),
where params denotes a list of real-valued parameters specified by the child
class, and p(y | params) is a linear Gaussian state space model with
structure determined by the child class.
Args
parameters
list of Parameter namedtuples, each specifying the name
and prior distribution of a model parameter along with a
bijective transformation from an unconstrained space to the support
of that parameter. The order of this list determines the canonical
parameter ordering used by fitting and inference algorithms.
latent_size
Python int specifying the dimensionality of the latent
state space for this model.
init_parameters
Python dict of parameters used to instantiate this
model component.
name
Python str name for this model component.
Attributes
batch_shape
Static batch shape of models represented by this component.
init_parameters
Parameters used to instantiate this StructuralTimeSeries.
latent_size
Python int dimensionality of the latent space in this model.
name
Name of this model component.
parameters
List of Parameter(name, prior, bijector) namedtuples for this model.
Runtime batch shape of models represented by this component.
Returns
batch_shape
intTensor giving the broadcast batch shape of
all model parameters. This should match the batch shape of
derived state space models, i.e.,
self.make_state_space_model(...).batch_shape_tensor().
String/value dictionary of initialization
arguments to override with new values.
Returns
copy
A new instance of type(self) initialized from the union
of self.init_parameters and override_parameters_kwargs, i.e.,
dict(self.init_parameters, **override_parameters_kwargs).
Constructs the joint distribution over parameters and observed values.
Args
observed_time_series
Optional observed time series to model, as a
Tensor or tfp.sts.MaskedTimeSeries instance having shape
concat([batch_shape, trajectories_shape, num_timesteps, 1]). If
an observed time series is provided, the num_timesteps,
trajectories_shape, and mask arguments are ignored, and
an unnormalized (pinned) distribution over parameter values is returned.
Default value: None.
num_timesteps
scalar intTensor number of timesteps to model. This
must be specified either directly or by passing an
observed_time_series.
Default value: 0.
trajectories_shape
intTensor shape of sampled trajectories
for each set of parameter values. Ignored if an observed_time_series
is passed.
Default value: ().
initial_step
Optional scalar intTensor specifying the starting
timestep.
Default value: 0.
mask
Optional boolTensor having shape
concat([batch_shape, trajectories_shape, num_timesteps]), in which
True entries indicate that the series value at the corresponding step
is missing and should be ignored. This argument should be passed only
if observed_time_series is not specified or does not already contain
a missingness mask; it is an error to pass both this
argument and an observed_time_series value containing a missingness
mask.
Default value: None.
experimental_parallelize
If True, use parallel message passing
algorithms from tfp.experimental.parallel_filter to perform time
series operations in O(log num_timesteps) sequential steps. The
overall FLOP and memory cost may be larger than for the sequential
implementations by a constant factor.
Default value: False.
Returns
joint_distribution
joint distribution of model parameters and
observed trajectories. If no observed_time_series was specified, this
is an instance of tfd.JointDistributionNamedAutoBatched with a
random variable for each model parameter (with names and order matching
self.parameters), plus a final random variable observed_time_series
representing a trajectory(ies) conditioned on the parameters. If
observed_time_series was specified, the return value is given by
joint_distribution.experimental_pin(
observed_time_series=observed_time_series) where joint_distribution
is as just described, so it defines an unnormalized posterior
distribution over the parameters.
Example:
The joint distribution can generate prior samples of parameters and
trajectories:
from matplotlib import pylab as plt
import tensorflow_probability as tfp; tfp = tfp.substrates.numpy
# Sample and plot 100 trajectories from the prior.
model = tfp.sts.LocalLinearTrendModel()
prior_samples = model.joint_distribution().sample([100])
plt.plot(
tf.linalg.matrix_transpose(prior_samples['observed_time_series'][..., 0]))
It also integrates with TFP inference APIs, providing a more flexible
alternative to the STS-specific fitting utilities.
Build the joint density log p(params) + log p(y|params) as a callable.
Args
observed_time_series
Observed Tensor trajectories of shape
sample_shape + batch_shape + [num_timesteps, 1] (the trailing
1 dimension is optional if num_timesteps > 1), where
batch_shape should match self.batch_shape (the broadcast batch
shape of all priors on parameters for this structural time series
model). Any NaNs are interpreted as missing observations; missingness
may be also be explicitly specified by passing a
tfp.sts.MaskedTimeSeries instance.
Returns
log_joint_fn
A function taking a Tensor argument for each model
parameter, in canonical order, and returning a Tensor log probability
of shape batch_shape. Note that, unliketfp.Distributionslog_prob methods, the log_joint sums over the sample_shape from y,
so that sample_shape does not appear in the output log_prob. This
corresponds to viewing multiple samples in y as iid observations from a
single model, which is typically the desired behavior for parameter
inference.
Instantiate this model as a Distribution over specified num_timesteps.
Args
num_timesteps
Python int number of timesteps to model.
param_vals
a list of Tensor parameter values in order corresponding to
self.parameters, or a dict mapping from parameter names to values.
initial_state_prior
an optional Distribution instance overriding the
default prior on the model's initial state. This is used in forecasting
("today's prior is yesterday's posterior").
initial_step
optional int specifying the initial timestep to model.
This is relevant when the model contains time-varying components,
e.g., holidays or seasonality.
**linear_gaussian_ssm_kwargs
Optional additional keyword arguments to
to the base tfd.LinearGaussianStateSpaceModel constructor.
Returns
dist
a LinearGaussianStateSpaceModel Distribution object.
Sample from the joint prior over model parameters and trajectories.
Args
num_timesteps
Scalar intTensor number of timesteps to model.
initial_step
Optional scalar intTensor specifying the starting
timestep.
Default value: 0.
params_sample_shape
Number of possible worlds to sample iid from the
parameter prior, or more generally, Tensorint shape to fill with
iid samples.
Default value: [] (i.e., draw a single sample and don't expand the
shape).
trajectories_sample_shape
For each sampled set of parameters, number
of trajectories to sample, or more generally, Tensorint shape to
fill with iid samples.
Default value: [] (i.e., draw a single sample and don't expand the
shape).
floatTensor of shape
trajectories_sample_shape + params_sample_shape + [num_timesteps, 1]
containing all sampled trajectories.
param_samples
list of sampled parameter value Tensors, in order
corresponding to self.parameters, each of shape
params_sample_shape + prior.batch_shape + prior.event_shape.