def _parameter_properties(cls, dtype, num_classes=None): # pylint: disable=g-long-lambda return dict(df=parameter_properties.ParameterProperties( default_constraining_bijector_fn=( lambda: softplus_bijector.Softplus(low=dtype_util.eps(dtype)) )))
def _forward(self, x): dtype = dtype_util.base_dtype(x.dtype) return tf.math.abs(x) + dtype_util.eps(dtype)
def _parameter_properties(cls, dtype): return dict(temperature=parameter_properties.ParameterProperties( default_constraining_bijector_fn=( lambda: softplus_bijector.Softplus(low=dtype_util.eps(dtype)) )))
def testEps(self, dtype): self.assertEqual( dtype_util.eps(dtype).dtype, dtype_util.as_numpy_dtype(dtype))
def _parameter_properties(cls, dtype): return dict(hinge_softness=parameter_properties.ParameterProperties( default_constraining_bijector_fn=( lambda: Softplus(low=dtype_util.eps(dtype)))), low=parameter_properties.ParameterProperties())
def _parameter_properties(cls, dtype): from tensorflow_probability.python.bijectors import softplus # pylint:disable=g-import-not-at-top return dict(constant=parameter_properties.ParameterProperties( default_constraining_bijector_fn=( lambda: softplus.Softplus(low=dtype_util.eps(dtype)))))
def __init__(self, order, coefficients_prior=None, level_scale_prior=None, initial_state_prior=None, coefficient_constraining_bijector=None, observed_time_series=None, name=None): """Specify an autoregressive model. Args: order: scalar Python positive `int` specifying the number of past timesteps to regress on. coefficients_prior: optional `tfd.Distribution` instance specifying a prior on the `coefficients` parameter. If `None`, a default standard normal (`tfd.MultivariateNormalDiag(scale_diag=tf.ones([order]))`) prior is used. Default value: `None`. level_scale_prior: optional `tfd.Distribution` instance specifying a prior on the `level_scale` parameter. If `None`, a heuristic default prior is constructed based on the provided `observed_time_series`. Default value: `None`. initial_state_prior: optional `tfd.Distribution` instance specifying a prior on the initial state, corresponding to the values of the process at a set of size `order` of imagined timesteps before the initial step. If `None`, a heuristic default prior is constructed based on the provided `observed_time_series`. Default value: `None`. coefficient_constraining_bijector: optional `tfb.Bijector` instance representing a constraining mapping for the autoregressive coefficients. For example, `tfb.Tanh()` constrains the coefficients to lie in `(-1, 1)`, while `tfb.Softplus()` constrains them to be positive, and `tfb.Identity()` implies no constraint. If `None`, the default behavior constrains the coefficients to lie in `(-1, 1)` using a `Tanh` bijector. Default value: `None`. observed_time_series: optional `float` `Tensor` of shape `batch_shape + [T, 1]` (omitting the trailing unit dimension is also supported when `T > 1`), specifying an observed time series. Any `NaN`s are interpreted as missing observations; missingness may be also be explicitly specified by passing a `tfp.sts.MaskedTimeSeries` instance. Any priors not explicitly set will be given default values according to the scale of the observed time series (or batch of time series). Default value: `None`. name: the name of this model component. Default value: 'Autoregressive'. """ init_parameters = dict(locals()) with tf.name_scope(name or 'Autoregressive') as name: masked_time_series = None if observed_time_series is not None: masked_time_series = ( sts_util.canonicalize_observed_time_series_with_mask( observed_time_series)) dtype = dtype_util.common_dtype( [(masked_time_series.time_series if masked_time_series is not None else None), coefficients_prior, level_scale_prior, initial_state_prior], dtype_hint=tf.float32) if observed_time_series is not None: _, observed_stddev, observed_initial = sts_util.empirical_statistics( masked_time_series) else: observed_stddev, observed_initial = (tf.convert_to_tensor( value=1., dtype=dtype), tf.convert_to_tensor(value=0., dtype=dtype)) batch_ones = tf.ones( tf.concat( [ tf.shape(observed_initial), # Batch shape [order] ], axis=0), dtype=dtype) # Heuristic default priors. Overriding these may dramatically # change inference performance and results. if coefficients_prior is None: coefficients_prior = tfd.MultivariateNormalDiag( scale_diag=batch_ones) if level_scale_prior is None: level_scale_prior = tfd.LogNormal(loc=tf.math.log( 0.05 * observed_stddev), scale=3.) if (coefficients_prior.event_shape.is_fully_defined() and order != coefficients_prior.event_shape[0]): raise ValueError( "Prior dimension {} doesn't match order {}.".format( coefficients_prior.event_shape[0], order)) if initial_state_prior is None: initial_state_prior = tfd.MultivariateNormalDiag( loc=observed_initial[..., tf.newaxis] * batch_ones, scale_diag=(tf.abs(observed_initial) + observed_stddev)[..., tf.newaxis] * batch_ones) self._order = order self._coefficients_prior = coefficients_prior self._level_scale_prior = level_scale_prior self._initial_state_prior = initial_state_prior if coefficient_constraining_bijector is None: coefficient_constraining_bijector = tfb.Tanh() super(Autoregressive, self).__init__(parameters=[ Parameter('coefficients', coefficients_prior, coefficient_constraining_bijector), Parameter( 'level_scale', level_scale_prior, tfb.Chain([ tfb.Scale(scale=observed_stddev), tfb.Softplus(low=dtype_util.eps(dtype)) ])) ], latent_size=order, init_parameters=init_parameters, name=name)
def __init__(self, level_scale_prior=None, slope_scale_prior=None, initial_level_prior=None, initial_slope_prior=None, observed_time_series=None, name=None): """Specify a local linear trend model. Args: level_scale_prior: optional `tfd.Distribution` instance specifying a prior on the `level_scale` parameter. If `None`, a heuristic default prior is constructed based on the provided `observed_time_series`. Default value: `None`. slope_scale_prior: optional `tfd.Distribution` instance specifying a prior on the `slope_scale` parameter. If `None`, a heuristic default prior is constructed based on the provided `observed_time_series`. Default value: `None`. initial_level_prior: optional `tfd.Distribution` instance specifying a prior on the initial level. If `None`, a heuristic default prior is constructed based on the provided `observed_time_series`. Default value: `None`. initial_slope_prior: optional `tfd.Distribution` instance specifying a prior on the initial slope. If `None`, a heuristic default prior is constructed based on the provided `observed_time_series`. Default value: `None`. observed_time_series: optional `float` `Tensor` of shape `batch_shape + [T, 1]` (omitting the trailing unit dimension is also supported when `T > 1`), specifying an observed time series. Any `NaN`s are interpreted as missing observations; missingness may be also be explicitly specified by passing a `tfp.sts.MaskedTimeSeries` instance. Any priors not explicitly set will be given default values according to the scale of the observed time series (or batch of time series). Default value: `None`. name: the name of this model component. Default value: 'LocalLinearTrend'. """ init_parameters = dict(locals()) with tf.name_scope(name or 'LocalLinearTrend') as name: _, observed_stddev, observed_initial = ( sts_util.empirical_statistics(observed_time_series) if observed_time_series is not None else (0., 1., 0.)) # Heuristic default priors. Overriding these may dramatically # change inference performance and results. if level_scale_prior is None: level_scale_prior = tfd.LogNormal(loc=tf.math.log( .05 * observed_stddev), scale=3., name='level_scale_prior') if slope_scale_prior is None: slope_scale_prior = tfd.LogNormal(loc=tf.math.log( .05 * observed_stddev), scale=3., name='slope_scale_prior') if initial_level_prior is None: initial_level_prior = tfd.Normal( loc=observed_initial, scale=tf.abs(observed_initial) + observed_stddev, name='initial_level_prior') if initial_slope_prior is None: initial_slope_prior = tfd.Normal(loc=0., scale=observed_stddev, name='initial_slope_prior') dtype = dtype_util.common_dtype([ level_scale_prior, slope_scale_prior, initial_level_prior, initial_slope_prior ]) self._initial_state_prior = tfd.MultivariateNormalDiag( loc=tf.stack( [initial_level_prior.mean(), initial_slope_prior.mean()], axis=-1), scale_diag=tf.stack([ initial_level_prior.stddev(), initial_slope_prior.stddev() ], axis=-1)) scaled_softplus = tfb.Chain([ tfb.Scale(scale=observed_stddev), tfb.Softplus(low=dtype_util.eps(dtype)) ]) super(LocalLinearTrend, self).__init__(parameters=[ Parameter('level_scale', level_scale_prior, scaled_softplus), Parameter('slope_scale', slope_scale_prior, scaled_softplus) ], latent_size=2, init_parameters=init_parameters, name=name)
def __init__(self, design_matrix, weights_prior_scale=0.1, weights_batch_shape=None, name=None): """Specify a sparse linear regression model. Args: design_matrix: float `Tensor` of shape `concat([batch_shape, [num_timesteps, num_features]])`. This may also optionally be an instance of `tf.linalg.LinearOperator`. weights_prior_scale: float `Tensor` defining the scale of the Horseshoe prior on regression weights. Small values encourage the weights to be sparse. The shape must broadcast with `weights_batch_shape`. Default value: `0.1`. weights_batch_shape: if `None`, defaults to `design_matrix.batch_shape_tensor()`. Must broadcast with the batch shape of `design_matrix`. Default value: `None`. name: the name of this model component. Default value: 'SparseLinearRegression'. """ init_parameters = dict(locals()) with tf.name_scope(name or 'SparseLinearRegression') as name: if not isinstance(design_matrix, tfl.LinearOperator): design_matrix = tfl.LinearOperatorFullMatrix( tf.convert_to_tensor(value=design_matrix, name='design_matrix'), name='design_matrix_linop') if tf.compat.dimension_value(design_matrix.shape[-1]) is not None: num_features = design_matrix.shape[-1] else: num_features = design_matrix.shape_tensor()[-1] if weights_batch_shape is None: weights_batch_shape = design_matrix.batch_shape_tensor() else: weights_batch_shape = tf.convert_to_tensor( value=weights_batch_shape, dtype=tf.int32) weights_shape = tf.concat([weights_batch_shape, [num_features]], axis=0) dtype = design_matrix.dtype self._design_matrix = design_matrix self._weights_prior_scale = weights_prior_scale ones_like_weights_batch = tf.ones(weights_batch_shape, dtype=dtype) ones_like_weights = tf.ones(weights_shape, dtype=dtype) super(SparseLinearRegression, self).__init__( parameters=[ Parameter( 'global_scale_variance', prior=tfd.InverseGamma(0.5 * ones_like_weights_batch, 0.5 * ones_like_weights_batch), bijector=tfb.Softplus(low=dtype_util.eps(dtype))), Parameter( 'global_scale_noncentered', prior=tfd.HalfNormal(scale=ones_like_weights_batch), bijector=tfb.Softplus(low=dtype_util.eps(dtype))), Parameter( 'local_scale_variances', prior=tfd.Independent(tfd.InverseGamma( 0.5 * ones_like_weights, 0.5 * ones_like_weights), reinterpreted_batch_ndims=1), bijector=tfb.Softplus(low=dtype_util.eps(dtype))), Parameter( 'local_scales_noncentered', prior=tfd.Independent( tfd.HalfNormal(scale=ones_like_weights), reinterpreted_batch_ndims=1), bijector=tfb.Softplus(low=dtype_util.eps(dtype))), Parameter('weights_noncentered', prior=tfd.Independent( tfd.Normal( loc=tf.zeros_like(ones_like_weights), scale=ones_like_weights), reinterpreted_batch_ndims=1), bijector=tfb.Identity()) ], latent_size=0, init_parameters=init_parameters, name=name)
def _parameter_properties(cls, dtype): return dict(tailweight=parameter_properties.ParameterProperties( default_constraining_bijector_fn=( lambda: tfb_softplus.Softplus(low=dtype_util.eps(dtype)))))
def __init__(self, num_seasons, num_steps_per_season=1, allow_drift=True, drift_scale_prior=None, initial_effect_prior=None, constrain_mean_effect_to_zero=True, observed_time_series=None, name=None): """Specify a seasonal effects model. Args: num_seasons: Scalar Python `int` number of seasons. num_steps_per_season: Python `int` number of steps in each season. This may be either a scalar (shape `[]`), in which case all seasons have the same length, or a NumPy array of shape `[num_seasons]`, in which seasons have different length, but remain constant around different cycles, or a NumPy array of shape `[num_cycles, num_seasons]`, in which num_steps_per_season for each season also varies in different cycle (e.g., a 4 years cycle with leap day). Default value: 1. allow_drift: optional Python `bool` specifying whether the seasonal effects can drift over time. Setting this to `False` removes the `drift_scale` parameter from the model. This is mathematically equivalent to `drift_scale_prior = tfd.Deterministic(0.)`, but removing drift directly is preferred because it avoids the use of a degenerate prior. Default value: `True`. drift_scale_prior: optional `tfd.Distribution` instance specifying a prior on the `drift_scale` parameter. If `None`, a heuristic default prior is constructed based on the provided `observed_time_series`. Default value: `None`. initial_effect_prior: optional `tfd.Distribution` instance specifying a normal prior on the initial effect of each season. This may be either a scalar `tfd.Normal` prior, in which case it applies independently to every season, or it may be multivariate normal (e.g., `tfd.MultivariateNormalDiag`) with event shape `[num_seasons]`, in which case it specifies a joint prior across all seasons. If `None`, a heuristic default prior is constructed based on the provided `observed_time_series`. Default value: `None`. constrain_mean_effect_to_zero: if `True`, use a model parameterization that constrains the mean effect across all seasons to be zero. This constraint is generally helpful in identifying the contributions of different model components and can lead to more interpretable posterior decompositions. It may be undesirable if you plan to directly examine the latent space of the underlying state space model. Default value: `True`. observed_time_series: optional `float` `Tensor` of shape `batch_shape + [T, 1]` (omitting the trailing unit dimension is also supported when `T > 1`), specifying an observed time series. Any `NaN`s are interpreted as missing observations; missingness may be also be explicitly specified by passing a `tfp.sts.MaskedTimeSeries` instance. Any priors not explicitly set will be given default values according to the scale of the observed time series (or batch of time series). Default value: `None`. name: the name of this model component. Default value: 'Seasonal'. """ init_parameters = dict(locals()) with tf.name_scope(name or 'Seasonal') as name: _, observed_stddev, observed_initial = ( sts_util.empirical_statistics(observed_time_series) if observed_time_series is not None else (0., 1., 0.)) # Heuristic default priors. Overriding these may dramatically # change inference performance and results. if initial_effect_prior is None: initial_effect_prior = tfd.Normal( loc=observed_initial, scale=tf.abs(observed_initial) + observed_stddev) dtype = initial_effect_prior.dtype if drift_scale_prior is None: scale_factor = tf.convert_to_tensor(.01, dtype=dtype) drift_scale_prior = tfd.LogNormal( loc=tf.math.log(scale_factor * observed_stddev), scale=3.) if isinstance(initial_effect_prior, tfd.Normal): initial_state_prior = tfd.MultivariateNormalDiag( loc=tf.stack([initial_effect_prior.mean()] * num_seasons, axis=-1), scale_diag=tf.stack([initial_effect_prior.stddev()] * num_seasons, axis=-1)) else: initial_state_prior = initial_effect_prior if constrain_mean_effect_to_zero: # Transform the prior to the residual parameterization used by # `ConstrainedSeasonalStateSpaceModel`, imposing a zero-sum constraint. # This doesn't change the marginal prior on individual effects, but # does introduce dependence between the effects. (effects_to_residuals, _) = build_effects_to_residuals_matrix( num_seasons, dtype=dtype) effects_to_residuals_linop = tf.linalg.LinearOperatorFullMatrix( effects_to_residuals) # Use linop so that matmul broadcasts. initial_state_prior_loc = effects_to_residuals_linop.matvec( initial_state_prior.mean()) initial_state_prior_scale_linop = effects_to_residuals_linop.matmul( initial_state_prior.scale) # returns LinearOperator initial_state_prior = tfd.MultivariateNormalFullCovariance( loc=initial_state_prior_loc, covariance_matrix=initial_state_prior_scale_linop.matmul( initial_state_prior_scale_linop.to_dense(), adjoint_arg=True)) self._constrain_mean_effect_to_zero = constrain_mean_effect_to_zero self._initial_state_prior = initial_state_prior self._num_seasons = num_seasons self._num_steps_per_season = num_steps_per_season parameters = [] if allow_drift: parameters.append(Parameter( 'drift_scale', drift_scale_prior, tfb.Chain([tfb.Scale(scale=observed_stddev), tfb.Softplus(low=dtype_util.eps(dtype))]))) self._allow_drift = allow_drift super(Seasonal, self).__init__( parameters, latent_size=(num_seasons - 1 if self.constrain_mean_effect_to_zero else num_seasons), init_parameters=init_parameters, name=name)
def __init__(self, design_matrix, drift_scale_prior=None, initial_weights_prior=None, observed_time_series=None, name=None): """Specify a dynamic linear regression. Args: design_matrix: float `Tensor` of shape `concat([batch_shape, [num_timesteps, num_features]])`. drift_scale_prior: instance of `tfd.Distribution` specifying a prior on the `drift_scale` parameter. If `None`, a heuristic default prior is constructed based on the provided `observed_time_series`. Default value: `None`. initial_weights_prior: instance of `tfd.MultivariateNormal` representing the prior distribution on the latent states (the regression weights). Must have event shape `[num_features]`. If `None`, a weakly-informative Normal(0., 10.) prior is used. Default value: `None`. observed_time_series: optional `float` `Tensor` of shape `batch_shape + [T, 1]` (omitting the trailing unit dimension is also supported when `T > 1`), specifying an observed time series. Any `NaN`s are interpreted as missing observations; missingness may be also be explicitly specified by passing a `tfp.sts.MaskedTimeSeries` instance. Any priors not explicitly set will be given default values according to the scale of the observed time series (or batch of time series). Default value: `None`. name: Python `str` for the name of this component. Default value: 'DynamicLinearRegression'. """ init_parameters = dict(locals()) with tf.name_scope(name or 'DynamicLinearRegression') as name: dtype = dtype_util.common_dtype( [design_matrix, drift_scale_prior, initial_weights_prior]) num_features = prefer_static.shape(design_matrix)[-1] # Default to a weakly-informative Normal(0., 10.) for the initital state if initial_weights_prior is None: initial_weights_prior = tfd.MultivariateNormalDiag( scale_diag=10. * tf.ones([num_features], dtype=dtype)) # Heuristic default priors. Overriding these may dramatically # change inference performance and results. if drift_scale_prior is None: if observed_time_series is None: observed_stddev = tf.constant(1.0, dtype=dtype) else: _, observed_stddev, _ = sts_util.empirical_statistics( observed_time_series) drift_scale_prior = tfd.LogNormal( loc=tf.math.log(.05 * observed_stddev), scale=3., name='drift_scale_prior') self._initial_state_prior = initial_weights_prior self._design_matrix = design_matrix super(DynamicLinearRegression, self).__init__( parameters=[ Parameter('drift_scale', drift_scale_prior, tfb.Chain([tfb.Scale(scale=observed_stddev), tfb.Softplus(low=dtype_util.eps(dtype))])) ], latent_size=num_features, init_parameters=init_parameters, name=name)
def __init__(self, level_scale_prior=None, slope_mean_prior=None, slope_scale_prior=None, autoregressive_coef_prior=None, initial_level_prior=None, initial_slope_prior=None, observed_time_series=None, constrain_ar_coef_stationary=True, constrain_ar_coef_positive=False, name=None): """Specify a semi-local linear trend model. Args: level_scale_prior: optional `tfd.Distribution` instance specifying a prior on the `level_scale` parameter. If `None`, a heuristic default prior is constructed based on the provided `observed_time_series`. Default value: `None`. slope_mean_prior: optional `tfd.Distribution` instance specifying a prior on the `slope_mean` parameter. If `None`, a heuristic default prior is constructed based on the provided `observed_time_series`. Default value: `None`. slope_scale_prior: optional `tfd.Distribution` instance specifying a prior on the `slope_scale` parameter. If `None`, a heuristic default prior is constructed based on the provided `observed_time_series`. Default value: `None`. autoregressive_coef_prior: optional `tfd.Distribution` instance specifying a prior on the `autoregressive_coef` parameter. If `None`, the default prior is a standard `Normal(0., 1.)`. Note that the prior may be implicitly truncated by `constrain_ar_coef_stationary` and/or `constrain_ar_coef_positive`. Default value: `None`. initial_level_prior: optional `tfd.Distribution` instance specifying a prior on the initial level. If `None`, a heuristic default prior is constructed based on the provided `observed_time_series`. Default value: `None`. initial_slope_prior: optional `tfd.Distribution` instance specifying a prior on the initial slope. If `None`, a heuristic default prior is constructed based on the provided `observed_time_series`. Default value: `None`. observed_time_series: optional `float` `Tensor` of shape `batch_shape + [T, 1]` (omitting the trailing unit dimension is also supported when `T > 1`), specifying an observed time series. Any `NaN`s are interpreted as missing observations; missingness may be also be explicitly specified by passing a `tfp.sts.MaskedTimeSeries` instance. Any priors not explicitly set will be given default values according to the scale of the observed time series (or batch of time series). Default value: `None`. constrain_ar_coef_stationary: if `True`, perform inference using a parameterization that restricts `autoregressive_coef` to the interval `(-1, 1)`, or `(0, 1)` if `force_positive_ar_coef` is also `True`, corresponding to stationary processes. This will implicitly truncates the support of `autoregressive_coef_prior`. Default value: `True`. constrain_ar_coef_positive: if `True`, perform inference using a parameterization that restricts `autoregressive_coef` to be positive, or in `(0, 1)` if `constrain_ar_coef_stationary` is also `True`. This will implicitly truncate the support of `autoregressive_coef_prior`. Default value: `False`. name: the name of this model component. Default value: 'SemiLocalLinearTrend'. """ init_parameters = dict(locals()) with tf.name_scope(name or 'SemiLocalLinearTrend') as name: if observed_time_series is not None: _, observed_stddev, observed_initial = sts_util.empirical_statistics( observed_time_series) else: observed_stddev, observed_initial = 1., 0. # Heuristic default priors. Overriding these may dramatically # change inference performance and results. if level_scale_prior is None: level_scale_prior = tfd.LogNormal(loc=tf.math.log( .01 * observed_stddev), scale=2.) if slope_mean_prior is None: slope_mean_prior = tfd.Normal(loc=0., scale=observed_stddev) if slope_scale_prior is None: slope_scale_prior = tfd.LogNormal(loc=tf.math.log( .01 * observed_stddev), scale=2.) if autoregressive_coef_prior is None: autoregressive_coef_prior = tfd.Normal( loc=0., scale=tf.ones_like(observed_initial)) if initial_level_prior is None: initial_level_prior = tfd.Normal( loc=observed_initial, scale=tf.abs(observed_initial) + observed_stddev) if initial_slope_prior is None: initial_slope_prior = tfd.Normal(loc=0., scale=observed_stddev) dtype = dtype_util.common_dtype([ level_scale_prior, slope_scale_prior, autoregressive_coef_prior, initial_level_prior, initial_slope_prior ]) self._initial_state_prior = tfd.MultivariateNormalDiag( loc=tf.stack( [initial_level_prior.mean(), initial_slope_prior.mean()], axis=-1), scale_diag=tf.stack([ initial_level_prior.stddev(), initial_slope_prior.stddev() ], axis=-1)) # Constrain the support of the autoregressive coefficient. if constrain_ar_coef_stationary and constrain_ar_coef_positive: autoregressive_coef_bijector = tfb.Sigmoid( ) # support in (0, 1) elif constrain_ar_coef_positive: autoregressive_coef_bijector = tfb.Softplus( ) # support in (0, infty) elif constrain_ar_coef_stationary: autoregressive_coef_bijector = tfb.Tanh() # support in (-1, 1) else: autoregressive_coef_bijector = tfb.Identity() # unconstrained stddev_preconditioner = tfb.Scale(scale=observed_stddev) scaled_softplus = tfb.Chain([ stddev_preconditioner, tfb.Softplus(low=dtype_util.eps(dtype)) ]) super(SemiLocalLinearTrend, self).__init__(parameters=[ Parameter('level_scale', level_scale_prior, scaled_softplus), Parameter('slope_mean', slope_mean_prior, stddev_preconditioner), Parameter('slope_scale', slope_scale_prior, scaled_softplus), Parameter('autoregressive_coef', autoregressive_coef_prior, autoregressive_coef_bijector), ], latent_size=2, init_parameters=init_parameters, name=name)
def mcmc(data_file, output_file, config, use_autograph=False, use_xla=True): """Constructs and runs the MCMC""" if tf.test.gpu_device_name(): print("Using GPU") else: print("Using CPU") data = xarray.open_dataset(data_file, group="constant_data") cases = xarray.open_dataset(data_file, group="observations")[ "cases" ].astype(DTYPE) dates = cases.coords["time"] # Impute censored events, return cases # Take the last week of data, and repeat a further 3 times # to get a better occult initialisation. extra_cases = tf.tile(cases[:, -7:], [1, 3]) cases = tf.concat([cases, extra_cases], axis=-1) events = model_spec.impute_censored_events(cases).numpy() # Initial conditions are calculated by calculating the state # at the beginning of the inference period # # Imputed censored events that pre-date the first I-R events # in the cases dataset are discarded. They are only used to # to set up a sensible initial state. state = compute_state( initial_state=tf.concat( [ tf.constant(data["N"], DTYPE)[:, tf.newaxis], tf.zeros_like(events[:, 0, :]), ], axis=-1, ), events=events, stoichiometry=model_spec.STOICHIOMETRY, ) start_time = state.shape[1] - cases.shape[1] initial_state = state[:, start_time, :] events = events[:, start_time:-21, :] # Clip off the "extra" events ######################################################## # Construct the MCMC kernels # ######################################################## model = model_spec.CovidUK( covariates=data, initial_state=initial_state, initial_step=0, num_steps=events.shape[1], ) param_bij = tfb.Invert( # Forward transform unconstrains params tfb.Blockwise( [ tfb.Softplus(low=dtype_util.eps(DTYPE)), tfb.Identity(), tfb.Identity(), ], block_sizes=[1, 3, events.shape[1]], ) ) def joint_log_prob(unconstrained_params, events): params = param_bij.inverse(unconstrained_params) return model.log_prob( dict( psi=params[0], beta_area=params[1], gamma0=params[2], gamma1=params[3], alpha_0=params[4], alpha_t=params[5:], seir=events, ) ) + param_bij.inverse_log_det_jacobian( unconstrained_params, event_ndims=1 ) # MCMC tracing functions ############################### # Construct bursted MCMC loop # ############################### current_chain_state = [ tf.concat( [ np.array([0.1, 0.0, 0.0, 0.0], dtype=DTYPE), np.full(events.shape[1], -1.75, dtype=DTYPE,), ], axis=0, ), events, ] print("Num time steps:", events.shape[1], flush=True) print("alpha_t shape", model.event_shape["alpha_t"], flush=True) print("Initial chain state:", current_chain_state[0], flush=True) print("Initial logpi:", joint_log_prob(*current_chain_state), flush=True) # Output file posterior = run_mcmc( joint_log_prob_fn=joint_log_prob, current_state=current_chain_state, param_bijector=param_bij, initial_conditions=initial_state, config=config, output_file=output_file, ) posterior._file.create_dataset("initial_state", data=initial_state) posterior._file.create_dataset( "time", data=np.array(dates).astype(str).astype(h5py.string_dtype()), ) print(f"Acceptance theta: {posterior['results/hmc/is_accepted'][:].mean()}") print( f"Acceptance move S->E: {posterior['results/move/S->E/is_accepted'][:].mean()}" ) print( f"Acceptance move E->I: {posterior['results/move/E->I/is_accepted'][:].mean()}" ) print( f"Acceptance occult S->E: {posterior['results/occult/S->E/is_accepted'][:].mean()}" ) print( f"Acceptance occult E->I: {posterior['results/occult/E->I/is_accepted'][:].mean()}" ) del posterior
def __init__(self, ar_order, ma_order, integration_degree=0, ar_coefficients_prior=None, ma_coefficients_prior=None, level_drift_prior=None, level_scale_prior=None, initial_state_prior=None, ar_coefficient_constraining_bijector=None, ma_coefficient_constraining_bijector=None, observed_time_series=None, name=None): """Specifies an ARIMA(p=ar_order, d=integration_degree, q=ma_order) model. Args: ar_order: scalar Python positive `int` specifying the order of the autoregressive process (`p` in `ARIMA(p, d, q)`). ma_order: scalar Python positive `int` specifying the order of the moving-average process (`q` in `ARIMA(p, d, q)`). integration_degree: scalar Python positive `int` specifying the number of times to integrate an ARMA process. (`d` in `ARIMA(p, d, q)`). Default value: `0`. ar_coefficients_prior: optional `tfd.Distribution` instance specifying a prior on the `ar_coefficients` parameter. If `None`, a default standard normal (`tfd.MultivariateNormalDiag(scale_diag=tf.ones([ar_order]))`) prior is used. Default value: `None`. ma_coefficients_prior: optional `tfd.Distribution` instance specifying a prior on the `ma_coefficients` parameter. If `None`, a default standard normal (`tfd.MultivariateNormalDiag(scale_diag=tf.ones([ma_order]))`) prior is used. Default value: `None`. level_drift_prior: optional `tfd.Distribution` instance specifying a prior on the `level_drift` parameter. If `None`, the parameter is not inferred and is instead fixed to zero. Default value: `None`. level_scale_prior: optional `tfd.Distribution` instance specifying a prior on the `level_scale` parameter. If `None`, a heuristic default prior is constructed based on the provided `observed_time_series`. Default value: `None`. initial_state_prior: optional `tfd.Distribution` instance specifying a prior on the initial state, corresponding to the values of the process at a set of size `order` of imagined timesteps before the initial step. If `None`, a heuristic default prior is constructed based on the provided `observed_time_series`. Default value: `None`. ar_coefficient_constraining_bijector: optional `tfb.Bijector` instance representing a constraining mapping for the autoregressive coefficients. For example, `tfb.Tanh()` constrains the coefficients to lie in `(-1, 1)`, while `tfb.Softplus()` constrains them to be positive, and `tfb.Identity()` implies no constraint. If `None`, the default behavior constrains the coefficients to lie in `(-1, 1)` using a `Tanh` bijector. Default value: `None`. ma_coefficient_constraining_bijector: optional `tfb.Bijector` instance representing a constraining mapping for the moving average coefficients. For example, `tfb.Tanh()` constrains the coefficients to lie in `(-1, 1)`, while `tfb.Softplus()` constrains them to be positive, and `tfb.Identity()` implies no constraint. If `None`, the default behavior is to apply no constraint. Default value: `None`. observed_time_series: optional `float` `Tensor` of shape `batch_shape + [T, 1]` (omitting the trailing unit dimension is also supported when `T > 1`), specifying an observed time series. Any `NaN`s are interpreted as missing observations; missingness may be also be explicitly specified by passing a `tfp.sts.MaskedTimeSeries` instance. Any priors not explicitly set will be given default values according to the scale of the observed time series (or batch of time series). Default value: `None`. name: the name of this model component. Default value: 'ARIMA'. """ init_parameters = dict(locals()) with tf.name_scope(name or 'ARIMA') as name: masked_time_series = None if observed_time_series is not None: masked_time_series = ( sts_util.canonicalize_observed_time_series_with_mask( observed_time_series)) dtype = dtype_util.common_dtype( [(masked_time_series.time_series if masked_time_series is not None else None), ar_coefficients_prior, ma_coefficients_prior, level_scale_prior, initial_state_prior], dtype_hint=tf.float32) if observed_time_series is not None: for _ in range(integration_degree): # Compute statistics using `integration_order`-order differences. masked_time_series = ( missing_values_util.differentiate_masked_time_series( masked_time_series)) _, observed_stddev, observed_initial = sts_util.empirical_statistics( masked_time_series) else: observed_stddev, observed_initial = ( tf.convert_to_tensor(value=1., dtype=dtype), tf.convert_to_tensor(value=0., dtype=dtype)) batch_ones = ps.ones(ps.concat([ ps.shape(observed_initial), # Batch shape [1]], axis=0), dtype=dtype) # Heuristic default priors. Overriding these may dramatically # change inference performance and results. if ar_coefficients_prior is None: ar_coefficients_prior = tfd.MultivariateNormalDiag( scale_diag=batch_ones * ps.ones([ar_order])) if ma_coefficients_prior is None: ma_coefficients_prior = tfd.MultivariateNormalDiag( scale_diag=batch_ones * ps.ones([ma_order])) if level_scale_prior is None: level_scale_prior = tfd.LogNormal( loc=tf.math.log(0.05 * observed_stddev), scale=3.) if (ar_coefficients_prior.event_shape.is_fully_defined() and ar_order != ar_coefficients_prior.event_shape[0]): raise ValueError( "Autoregressive prior dimension {} doesn't match order {}.".format( ar_coefficients_prior.event_shape[0], ar_order)) if (ma_coefficients_prior.event_shape.is_fully_defined() and ma_order != ma_coefficients_prior.event_shape[0]): raise ValueError( "Moving average prior dimension {} doesn't match order {}.".format( ma_coefficients_prior.event_shape[0], ma_order)) latent_size = ps.maximum(ar_order, ma_order + 1) + integration_degree if initial_state_prior is None: initial_state_prior = tfd.MultivariateNormalDiag( loc=sts_util.pad_tensor_with_trailing_zeros( observed_initial[..., tf.newaxis] * batch_ones, num_zeros=latent_size - 1), scale_diag=sts_util.pad_tensor_with_trailing_zeros( (tf.abs(observed_initial) + observed_stddev)[..., tf.newaxis] * batch_ones, num_zeros=latent_size - 1)) self._ar_order = ar_order self._ma_order = ma_order self._integration_degree = integration_degree self._ar_coefficients_prior = ar_coefficients_prior self._ma_coefficients_prior = ma_coefficients_prior self._level_scale_prior = level_scale_prior self._initial_state_prior = initial_state_prior parameters = [] if ar_order > 0: parameters.append( Parameter('ar_coefficients', ar_coefficients_prior, (ar_coefficient_constraining_bijector if ar_coefficient_constraining_bijector else tfb.Tanh()))) if ma_order > 0: parameters.append( Parameter('ma_coefficients', ma_coefficients_prior, (ma_coefficient_constraining_bijector if ma_coefficient_constraining_bijector else tfb.Identity()))) if level_drift_prior is not None: parameters.append( Parameter( 'level_drift', level_drift_prior, tfb.Chain([ tfb.Scale(scale=observed_stddev), (level_drift_prior. experimental_default_event_space_bijector())]))) super(AutoregressiveIntegratedMovingAverage, self).__init__( parameters=parameters + [ Parameter('level_scale', level_scale_prior, tfb.Chain([tfb.Scale(scale=observed_stddev), tfb.Softplus(low=dtype_util.eps(dtype))])) ], latent_size=latent_size, init_parameters=init_parameters, name=name)
def __init__(self, period, frequency_multipliers, allow_drift=True, drift_scale_prior=None, initial_state_prior=None, observed_time_series=None, name=None): """Specify a smooth seasonal effects model. Args: period: positive scalar `float` `Tensor` giving the number of timesteps required for the longest cyclic effect to repeat. frequency_multipliers: One-dimensional `float` `Tensor` listing the frequencies (cyclic components) included in the model, as multipliers of the base/fundamental frequency `2. * pi / period`. Each component is specified by the number of times it repeats per period, and adds two latent dimensions to the model. A smooth seasonal model that can represent any periodic function is given by `frequency_multipliers = [1, 2, ..., floor(period / 2)]`. However, it is often desirable to enforce a smoothness assumption (and reduce the computational burden) by dropping some of the higher frequencies. allow_drift: optional Python `bool` specifying whether the seasonal effects can drift over time. Setting this to `False` removes the `drift_scale` parameter from the model. This is mathematically equivalent to `drift_scale_prior = tfd.Deterministic(0.)`, but removing drift directly is preferred because it avoids the use of a degenerate prior. Default value: `True`. drift_scale_prior: optional `tfd.Distribution` instance specifying a prior on the `drift_scale` parameter. If `None`, a heuristic default prior is constructed based on the provided `observed_time_series`. Default value: `None`. initial_state_prior: instance of `tfd.MultivariateNormal` representing the prior distribution on the latent states. Must have event shape `[2 * len(frequency_multipliers)]`. If `None`, a heuristic default prior is constructed based on the provided `observed_time_series`. observed_time_series: optional `float` `Tensor` of shape `batch_shape + [T, 1]` (omitting the trailing unit dimension is also supported when `T > 1`), specifying an observed time series. Any `NaN`s are interpreted as missing observations; missingness may be also be explicitly specified by passing a `tfp.sts.MaskedTimeSeries` instance. Any priors not explicitly set will be given default values according to the scale of the observed time series (or batch of time series). Default value: `None`. name: the name of this model component. Default value: 'SmoothSeasonal'. """ init_parameters = dict(locals()) with tf.name_scope(name or 'SmoothSeasonal') as name: _, observed_stddev, observed_initial = ( sts_util.empirical_statistics(observed_time_series) if observed_time_series is not None else (0., 1., 0.)) latent_size = 2 * static_num_frequencies(frequency_multipliers) # Heuristic default priors. Overriding these may dramatically # change inference performance and results. if drift_scale_prior is None: drift_scale_prior = tfd.LogNormal(loc=tf.math.log( .01 * observed_stddev), scale=3.) if initial_state_prior is None: initial_state_scale = (tf.abs(observed_initial) + observed_stddev)[..., tf.newaxis] ones = tf.ones([latent_size], dtype=drift_scale_prior.dtype) initial_state_prior = tfd.MultivariateNormalDiag( scale_diag=initial_state_scale * ones) dtype = dtype_util.common_dtype( [drift_scale_prior, initial_state_prior]) self._initial_state_prior = initial_state_prior self._period = period self._frequency_multipliers = frequency_multipliers parameters = [] if allow_drift: parameters.append( Parameter( 'drift_scale', drift_scale_prior, tfb.Chain([ tfb.Scale(scale=observed_stddev), tfb.Softplus(low=dtype_util.eps(dtype)) ]))) self._allow_drift = allow_drift super(SmoothSeasonal, self).__init__(parameters=parameters, latent_size=latent_size, init_parameters=init_parameters, name=name)