INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Generates starting points for the Halton sequence procedure. | def _get_indices(num_results, sequence_indices, dtype, name=None):
"""Generates starting points for the Halton sequence procedure.
The k'th element of the sequence is generated starting from a positive integer
which must be distinct for each `k`. It is conventional to choose the starting
point as `k` itself (o... |
Computes the number of terms in the place value expansion. | def _base_expansion_size(num, bases):
"""Computes the number of terms in the place value expansion.
Let num = a0 + a1 b + a2 b^2 + ... ak b^k be the place value expansion of
`num` in base b (ak <> 0). This function computes and returns `k+1` for each
base `b` specified in `bases`.
This can be inferred from ... |
Returns sorted array of primes such that 2 < = prime < n. | def _primes_less_than(n):
# Based on
# https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
"""Returns sorted array of primes such that `2 <= prime < n`."""
small_primes = np.array((2, 3, 5))
if n <= 6:
return small_primes[small_primes < n]
sieve =... |
Returns the machine epsilon for the supplied dtype. | def _machine_eps(dtype):
"""Returns the machine epsilon for the supplied dtype."""
if isinstance(dtype, tf.DType):
dtype = dtype.as_numpy_dtype()
return np.finfo(dtype).eps |
The Hager Zhang line search algorithm. | def hager_zhang(value_and_gradients_function,
initial_step_size=None,
value_at_initial_step=None,
value_at_zero=None,
converged=None,
threshold_use_approximate_wolfe_condition=1e-6,
shrinkage_param=0.66,
expa... |
Shrinks the input step size until the value and grad become finite. | def _fix_step_size(value_and_gradients_function,
val_c_input,
active,
step_size_shrink_param):
"""Shrinks the input step size until the value and grad become finite."""
# The maximum iterations permitted are determined as the number of halvings
# it takes t... |
Brackets the minimum and performs a line search. | def _bracket_and_search(
value_and_gradients_function,
init_interval,
f_lim,
max_iterations,
shrinkage_param,
expansion_param,
sufficient_decrease_param,
curvature_param):
"""Brackets the minimum and performs a line search.
Args:
value_and_gradients_function: A Python callable t... |
The main loop of line search after the minimum has been bracketed. | def _line_search_after_bracketing(
value_and_gradients_function,
search_interval,
val_0,
f_lim,
max_iterations,
sufficient_decrease_param,
curvature_param,
shrinkage_param):
"""The main loop of line search after the minimum has been bracketed.
Args:
value_and_gradients_function:... |
Performs bisection and updates the interval. | def _line_search_inner_bisection(
value_and_gradients_function,
search_interval,
active,
f_lim):
"""Performs bisection and updates the interval."""
midpoint = (search_interval.left.x + search_interval.right.x) / 2
val_mid = value_and_gradients_function(midpoint)
is_valid_mid = hzl.is_finite(val_... |
Prepares the arguments for the line search initialization. | def _prepare_args(value_and_gradients_function,
initial_step_size,
val_initial,
val_0,
approximate_wolfe_threshold):
"""Prepares the arguments for the line search initialization.
Args:
value_and_gradients_function: A Python callable that a... |
Converts a bool tensor to a string with True/ False values. | def _to_str(x):
"""Converts a bool tensor to a string with True/False values."""
x = tf.convert_to_tensor(value=x)
if x.dtype == tf.bool:
return tf.where(x, tf.fill(x.shape, 'True'), tf.fill(x.shape, 'False'))
return x |
Wrapper for tf. Print which supports lists and namedtuples for printing. | def _print(pass_through_tensor, values):
"""Wrapper for tf.Print which supports lists and namedtuples for printing."""
flat_values = []
for value in values:
# Checks if it is a namedtuple.
if hasattr(value, '_fields'):
for field in value._fields:
flat_values.extend([field, _to_str(getattr(va... |
Batched KL divergence KL ( a || b ) for multivariate Normals. | def _kl_brute_force(a, b, name=None):
"""Batched KL divergence `KL(a || b)` for multivariate Normals.
With `X`, `Y` both multivariate Normals in `R^k` with means `mu_a`, `mu_b` and
covariance `C_a`, `C_b` respectively,
```
KL(a || b) = 0.5 * ( L - k + T + Q ),
L := Log[Det(C_b)] - Log[Det(C_a)]
T := tra... |
Use Gauss - Hermite quadrature to form quadrature on K - 1 simplex. | def quadrature_scheme_softmaxnormal_gauss_hermite(
normal_loc, normal_scale, quadrature_size,
validate_args=False, name=None):
"""Use Gauss-Hermite quadrature to form quadrature on `K - 1` simplex.
A `SoftmaxNormal` random variable `Y` may be generated via
```
Y = SoftmaxCentered(X),
X = Normal(norm... |
Use SoftmaxNormal quantiles to form quadrature on K - 1 simplex. | def quadrature_scheme_softmaxnormal_quantiles(
normal_loc, normal_scale, quadrature_size,
validate_args=False, name=None):
"""Use SoftmaxNormal quantiles to form quadrature on `K - 1` simplex.
A `SoftmaxNormal` random variable `Y` may be generated via
```
Y = SoftmaxCentered(X),
X = Normal(normal_lo... |
Helper which checks validity of loc and scale init args. | def maybe_check_quadrature_param(param, name, validate_args):
"""Helper which checks validity of `loc` and `scale` init args."""
with tf.name_scope("check_" + name):
assertions = []
if tensorshape_util.rank(param.shape) is not None:
if tensorshape_util.rank(param.shape) == 0:
raise ValueError(... |
Helper to infer batch_shape and event_shape. | def determine_batch_event_shapes(grid, endpoint_affine):
"""Helper to infer batch_shape and event_shape."""
with tf.name_scope("determine_batch_event_shapes"):
# grid # shape: [B, k, q]
# endpoint_affine # len=k, shape: [B, d, d]
batch_shape = grid.shape[:-2]
batch_shape_tensor = tf.shape(input... |
Helper which interpolates between two locs. | def interpolate_loc(grid, loc):
"""Helper which interpolates between two locs."""
if len(loc) != 2:
raise NotImplementedError("Currently only bimixtures are supported; "
"len(scale)={} is not 2.".format(len(loc)))
deg = tf.compat.dimension_value(
tensorshape_util.with_rank_... |
Helper which interpolates between two scales. | def interpolate_scale(grid, scale):
"""Helper which interpolates between two scales."""
if len(scale) != 2:
raise NotImplementedError("Currently only bimixtures are supported; "
"len(scale)={} is not 2.".format(len(scale)))
deg = tf.compat.dimension_value(
tensorshape_util.... |
Creates weighted LinOp from existing LinOp. | def linop_scale(w, op):
"""Creates weighted `LinOp` from existing `LinOp`."""
# We assume w > 0. (This assumption only relates to the is_* attributes.)
with tf.name_scope("linop_scale"):
# TODO(b/35301104): LinearOperatorComposition doesn't combine operators, so
# special case combinations here. Once it d... |
Concatenates input vectors statically if possible. | def concat_vectors(*args):
"""Concatenates input vectors, statically if possible."""
args_ = [tf.get_static_value(x) for x in args]
if any(vec is None for vec in args_):
return tf.concat(args, axis=0)
return [val for vec in args_ for val in vec] |
Equivalent to tf. nn. softmax but works around b/ 70297725. | def softmax(x, axis, name=None):
"""Equivalent to tf.nn.softmax but works around b/70297725."""
with tf.name_scope(name or "softmax"):
x = tf.convert_to_tensor(value=x, name="x")
ndims = (
tensorshape_util.rank(x.shape)
if tensorshape_util.rank(x.shape) is not None else tf.rank(
... |
Ensures self. distribution. mean () has [ batch event ] shape. | def _expand_base_distribution_mean(self):
"""Ensures `self.distribution.mean()` has `[batch, event]` shape."""
single_draw_shape = concat_vectors(self.batch_shape_tensor(),
self.event_shape_tensor())
m = tf.reshape(
self.distribution.mean(), # A scalar.
... |
Multiply tensor of vectors by matrices assuming values stored are logs. | def _log_vector_matrix(vs, ms):
"""Multiply tensor of vectors by matrices assuming values stored are logs."""
return tf.reduce_logsumexp(input_tensor=vs[..., tf.newaxis] + ms, axis=-2) |
Multiply tensor of matrices by vectors assuming values stored are logs. | def _log_matrix_vector(ms, vs):
"""Multiply tensor of matrices by vectors assuming values stored are logs."""
return tf.reduce_logsumexp(input_tensor=ms + vs[..., tf.newaxis, :], axis=-1) |
Multiply tensor of vectors by matrices. | def _vector_matrix(vs, ms):
"""Multiply tensor of vectors by matrices."""
return tf.reduce_sum(input_tensor=vs[..., tf.newaxis] * ms, axis=-2) |
Tabulate log probabilities from a batch of distributions. | def _extract_log_probs(num_states, dist):
"""Tabulate log probabilities from a batch of distributions."""
states = tf.reshape(tf.range(num_states),
tf.concat([[num_states],
tf.ones_like(dist.batch_shape_tensor())],
axis=0))
re... |
Compute marginal pdf for each individual observable. | def _marginal_hidden_probs(self):
"""Compute marginal pdf for each individual observable."""
initial_log_probs = tf.broadcast_to(self._log_init,
tf.concat([self.batch_shape_tensor(),
[self._num_states]],
... |
Compute marginal posterior distribution for each state. | def posterior_marginals(self, observations, name=None):
"""Compute marginal posterior distribution for each state.
This function computes, for each time step, the marginal
conditional probability that the hidden Markov model was in
each possible state given the observations that were made
at each t... |
Compute maximum likelihood sequence of hidden states. | def posterior_mode(self, observations, name=None):
"""Compute maximum likelihood sequence of hidden states.
When this function is provided with a sequence of observations
`x[0], ..., x[num_steps - 1]`, it returns the sequence of hidden
states `z[0], ..., z[num_steps - 1]`, drawn from the underlying
... |
Chooses a random direction in the event space. | def _choose_random_direction(current_state_parts, batch_rank, seed=None):
"""Chooses a random direction in the event space."""
seed_gen = distributions.SeedStream(seed, salt='_choose_random_direction')
# Chooses the random directions across each of the input components.
rnd_direction_parts = [
tf.random.n... |
Applies a single iteration of slice sampling update. | def _sample_next(target_log_prob_fn,
current_state_parts,
step_sizes,
max_doublings,
current_target_log_prob,
batch_rank,
seed=None,
name=None):
"""Applies a single iteration of slice sampling update... |
Helper which computes fn_result if needed. | def _maybe_call_fn(fn,
fn_arg_list,
fn_result=None,
description='target_log_prob'):
"""Helper which computes `fn_result` if needed."""
fn_arg_list = (list(fn_arg_list) if mcmc_util.is_list_like(fn_arg_list)
else [fn_arg_list])
if fn_result ... |
Pads the shape of x to the right to be of rank final_rank. | def _right_pad(x, final_rank):
"""Pads the shape of x to the right to be of rank final_rank.
Expands the dims of `x` to the right such that its rank is equal to
final_rank. For example, if `x` is of shape [1, 5, 7, 2] and `final_rank` is
7, we return padded_x, which is of shape [1, 5, 7, 2, 1, 1, 1].
Args:
... |
Processes input args to meet list - like assumptions. | def _prepare_args(target_log_prob_fn, state, step_size,
target_log_prob=None, maybe_expand=False,
description='target_log_prob'):
"""Processes input args to meet list-like assumptions."""
state_parts = list(state) if mcmc_util.is_list_like(state) else [state]
state_parts = [
... |
Runs one iteration of Slice Sampler. | def one_step(self, current_state, previous_kernel_results):
"""Runs one iteration of Slice Sampler.
Args:
current_state: `Tensor` or Python `list` of `Tensor`s representing the
current state(s) of the Markov chain(s). The first `r` dimensions
index independent chains,
`r = tf.rank... |
Initialize from a uniform [ - 2 2 ] distribution in unconstrained space. | def sample_uniform_initial_state(parameter,
return_constrained=True,
init_sample_shape=(),
seed=None):
"""Initialize from a uniform [-2, 2] distribution in unconstrained space.
Args:
parameter: `sts.Parameter` na... |
Built a transformed - normal variational dist over a parameter s support. | def _build_trainable_posterior(param, initial_loc_fn):
"""Built a transformed-normal variational dist over a parameter's support."""
loc = tf.compat.v1.get_variable(
param.name + '_loc',
initializer=lambda: initial_loc_fn(param),
dtype=param.prior.dtype,
use_resource=True)
scale = tf.nn.so... |
Build a loss function for variational inference in STS models. | def build_factored_variational_loss(model,
observed_time_series,
init_batch_shape=(),
seed=None,
name=None):
"""Build a loss function for variational inference in STS models.... |
Run an optimizer within the graph to minimize a loss function. | def _minimize_in_graph(build_loss_fn, num_steps=200, optimizer=None):
"""Run an optimizer within the graph to minimize a loss function."""
optimizer = tf.compat.v1.train.AdamOptimizer(
0.1) if optimizer is None else optimizer
def train_loop_body(step):
train_op = optimizer.minimize(
build_loss_... |
Draw posterior samples using Hamiltonian Monte Carlo ( HMC ). | def fit_with_hmc(model,
observed_time_series,
num_results=100,
num_warmup_steps=50,
num_leapfrog_steps=15,
initial_state=None,
initial_step_size=None,
chain_batch_shape=(),
num_variati... |
Compute mean and variance accounting for a mask. | def moments_of_masked_time_series(time_series_tensor, broadcast_mask):
"""Compute mean and variance, accounting for a mask.
Args:
time_series_tensor: float `Tensor` time series of shape
`concat([batch_shape, [num_timesteps]])`.
broadcast_mask: bool `Tensor` of the same shape as `time_series`.
Retur... |
Get the first unmasked entry of each time series in the batch. | def initial_value_of_masked_time_series(time_series_tensor, broadcast_mask):
"""Get the first unmasked entry of each time series in the batch.
Args:
time_series_tensor: float `Tensor` of shape [..., num_timesteps].
broadcast_mask: bool `Tensor` of same shape as `time_series`.
"""
num_timesteps = tf.sh... |
Get broadcast batch shape from distributions statically if possible. | def broadcast_batch_shape(distributions):
"""Get broadcast batch shape from distributions, statically if possible."""
# Static case
batch_shape = distributions[0].batch_shape
for distribution in distributions:
batch_shape = tf.broadcast_static_shape(batch_shape,
... |
Expand the observed time series with extra batch dimension ( s ). | def pad_batch_dimension_for_multiple_chains(
observed_time_series, model, chain_batch_shape):
""""Expand the observed time series with extra batch dimension(s)."""
# Running with multiple chains introduces an extra batch dimension. In
# general we also need to pad the observed time series with a matching batc... |
Combine MultivariateNormals into a factored joint distribution. | def factored_joint_mvn(distributions):
"""Combine MultivariateNormals into a factored joint distribution.
Given a list of multivariate normal distributions
`dist[i] = Normal(loc[i], scale[i])`, construct the joint
distribution given by concatenating independent samples from these
distributions. This is m... |
Attempt to sum MultivariateNormal distributions. | def sum_mvns(distributions):
"""Attempt to sum MultivariateNormal distributions.
The sum of (multivariate) normal random variables is itself (multivariate)
normal, with mean given by the sum of means and (co)variance given by the
sum of (co)variances. This method exploits this fact to compute the
sum of a li... |
Compute statistics of a provided time series as heuristic initialization. | def empirical_statistics(observed_time_series):
"""Compute statistics of a provided time series, as heuristic initialization.
Args:
observed_time_series: `Tensor` representing a time series, or batch of time
series, of shape either `batch_shape + [num_timesteps, 1]` or
`batch_shape + [num_timeste... |
Ensures observed_time_series_tensor has a trailing dimension of size 1. | def _maybe_expand_trailing_dim(observed_time_series_tensor):
"""Ensures `observed_time_series_tensor` has a trailing dimension of size 1.
The `tfd.LinearGaussianStateSpaceModel` Distribution has event shape of
`[num_timesteps, observation_size]`, but canonical BSTS models
are univariate, so their observation_s... |
Extract a Tensor with canonical shape and optional mask. | def canonicalize_observed_time_series_with_mask(
maybe_masked_observed_time_series):
"""Extract a Tensor with canonical shape and optional mask.
Args:
maybe_masked_observed_time_series: a `Tensor`-like object with shape
`[..., num_timesteps]` or `[..., num_timesteps, 1]`, or a
`tfp.sts.MaskedTi... |
Construct a predictive normal distribution that mixes over posterior draws. | def mix_over_posterior_draws(means, variances):
"""Construct a predictive normal distribution that mixes over posterior draws.
Args:
means: float `Tensor` of shape
`[num_posterior_draws, ..., num_timesteps]`.
variances: float `Tensor` of shape
`[num_posterior_draws, ..., num_timesteps]`.
Ret... |
Calculate the batched KL divergence KL ( a || b ) with a and b Uniform. | def _kl_uniform_uniform(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a and b Uniform.
Note that the KL divergence is infinite if the support of `a` is not a subset
of the support of `b`.
Args:
a: instance of a Uniform distribution object.
b: instance of a Uniform distributi... |
high - low. | def range(self, name="range"):
"""`high - low`."""
with self._name_scope(name):
return self.high - self.low |
Factory for making summary statistics eg mean mode stddev. | def _make_summary_statistic(attr):
"""Factory for making summary statistics, eg, mean, mode, stddev."""
def _fn(self):
if any(self._dist_fn_args): # pylint: disable=protected-access
raise ValueError(
'Can only compute ' + attr + ' when all distributions are '
'independent; {}'.format(... |
Creates dist_fn_wrapped which calls dist_fn with all prev nodes. | def _unify_call_signature(i, dist_fn):
"""Creates `dist_fn_wrapped` which calls `dist_fn` with all prev nodes.
Args:
i: Python `int` corresponding to position in topologically sorted DAG.
dist_fn: Python `callable` which takes a subset of previously constructed
distributions (in reverse order) and pr... |
Uses arg names to resolve distribution names. | def _resolve_distribution_names(dist_fn_args, dist_names, leaf_name):
"""Uses arg names to resolve distribution names."""
if dist_names is None:
dist_names = []
else:
dist_names = dist_names.copy()
n = len(dist_fn_args)
dist_names.extend([None]*(n - len(dist_names)))
for i_, args in enumerate(revers... |
Returns the distribution s required args. | def _get_required_args(fn):
"""Returns the distribution's required args."""
argspec = tf_inspect.getfullargspec(fn)
args = argspec.args
if tf_inspect.isclass(fn):
args = args[1:] # Remove the `self` arg.
if argspec.defaults:
# Remove the args which have defaults. By convention we only feed
# *req... |
Calculate the KL divergence between two JointDistributionSequential s. | def _kl_joint_joint(d0, d1, name=None):
"""Calculate the KL divergence between two `JointDistributionSequential`s.
Args:
d0: instance of a `JointDistributionSequential` object.
d1: instance of a `JointDistributionSequential` object.
name: (optional) Name to use for created operations.
Default val... |
Creates dist_fn dist_fn_wrapped dist_fn_args. | def _build(self, model):
"""Creates `dist_fn`, `dist_fn_wrapped`, `dist_fn_args`."""
if not isinstance(model, collections.Sequence):
raise TypeError('`model` must be `list`-like (saw: {}).'.format(
type(model).__name__))
self._dist_fn = model
self._dist_fn_wrapped, self._dist_fn_args = z... |
Creates a tuple of tuple s of dependencies. | def _resolve_graph(self, distribution_names=None, leaf_name='x'):
"""Creates a `tuple` of `tuple`s of dependencies.
This function is **experimental**. That said, we encourage its use
and ask that you report problems to `tfprobability@tensorflow.org`.
Args:
distribution_names: `list` of `str` or ... |
Shannon entropy in nats. | def _entropy(self):
"""Shannon entropy in nats."""
if any(self._dist_fn_args):
raise ValueError(
'Can only compute entropy when all distributions are independent.')
return sum(joint_distribution_lib.maybe_check_wont_broadcast(
(d().entropy() for d in self._dist_fn_wrapped),
s... |
Decorator function for argument bounds checking. | def check_arg_in_support(f):
"""Decorator function for argument bounds checking.
This decorator is meant to be used with methods that require the first
argument to be in the support of the distribution. If `validate_args` is
`True`, the method is wrapped with an assertion that the first argument is
greater t... |
Returns f ( x ) if x is in the support and default_value otherwise. | def _extend_support_with_default_value(self, x, f, default_value):
"""Returns `f(x)` if x is in the support, and `default_value` otherwise.
Given `f` which is defined on the support of this distribution
(`x >= loc`), extend the function definition to the real line
by defining `f(x) = default_value` for... |
Processes input args to meet list - like assumptions. | def _prepare_args(log_likelihood_fn, state,
log_likelihood=None, description='log_likelihood'):
"""Processes input args to meet list-like assumptions."""
state_parts = list(state) if mcmc_util.is_list_like(state) else [state]
state_parts = [tf.convert_to_tensor(s, name='current_state')
... |
Runs one iteration of the Elliptical Slice Sampler. | def one_step(self, current_state, previous_kernel_results):
"""Runs one iteration of the Elliptical Slice Sampler.
Args:
current_state: `Tensor` or Python `list` of `Tensor`s representing the
current state(s) of the Markov chain(s). The first `r` dimensions
index independent chains,
... |
Visualizes sequences as TensorBoard summaries. | def image_summary(seqs, name, num=None):
"""Visualizes sequences as TensorBoard summaries.
Args:
seqs: A tensor of shape [n, t, h, w, c].
name: String name of this summary.
num: Integer for the number of examples to visualize. Defaults to
all examples.
"""
seqs = tf.clip_by_value(seqs, 0., 1.... |
Visualizes the reconstruction of inputs in TensorBoard. | def visualize_reconstruction(inputs, reconstruct, num=3, name="reconstruction"):
"""Visualizes the reconstruction of inputs in TensorBoard.
Args:
inputs: A tensor of the original inputs, of shape [batch, timesteps,
h, w, c].
reconstruct: A tensor of a reconstruction of inputs, of shape
[batch, ... |
Visualizes a qualitative analysis of a given model. | def visualize_qualitative_analysis(inputs, model, samples=1, batch_size=3,
length=8):
"""Visualizes a qualitative analysis of a given model.
Args:
inputs: A tensor of the original inputs, of shape [batch, timesteps,
h, w, c].
model: A DisentangledSequentialVAE model... |
Summarize the parameters of a distribution. | def summarize_dist_params(dist, name, name_scope="dist_params"):
"""Summarize the parameters of a distribution.
Args:
dist: A Distribution object with mean and standard deviation
parameters.
name: The name of the distribution.
name_scope: The name scope of this summary.
"""
with tf.compat.v1.... |
Summarize the mean of a tensor in nats and bits per unit. | def summarize_mean_in_nats_and_bits(inputs, units, name,
nats_name_scope="nats",
bits_name_scope="bits_per_dim"):
"""Summarize the mean of a tensor in nats and bits per unit.
Args:
inputs: A tensor of values measured in nats.
units: Th... |
Runs the model to generate multivariate normal distribution. | def call(self, inputs):
"""Runs the model to generate multivariate normal distribution.
Args:
inputs: Unused.
Returns:
A MultivariateNormalDiag distribution with event shape
[dimensions], batch shape [], and sample shape [sample_shape,
dimensions].
"""
del inputs # unused
... |
Returns an initial state for the LSTM cell. | def zero_state(self, sample_batch_shape=()):
"""Returns an initial state for the LSTM cell.
Args:
sample_batch_shape: A 0D or 1D tensor of the combined sample and
batch shape.
Returns:
A tuple of the initial previous output at timestep 0 of shape
[sample_batch_shape, dimensions],... |
Runs the model to generate a distribution for a single timestep. | def call(self, inputs, state):
"""Runs the model to generate a distribution for a single timestep.
This generates a batched MultivariateNormalDiag distribution using
the output of the recurrent model at the current timestep to
parameterize the distribution.
Args:
inputs: The sampled value of... |
Runs the model to generate a distribution p ( x_t | z_t f ). | def call(self, inputs):
"""Runs the model to generate a distribution p(x_t | z_t, f).
Args:
inputs: A tuple of (z_{1:T}, f), where `z_{1:T}` is a tensor of
shape [..., batch_size, timesteps, latent_size_dynamic], and `f`
is of shape [..., batch_size, latent_size_static].
Returns:
... |
Runs the model to generate an intermediate representation of x_t. | def call(self, inputs):
"""Runs the model to generate an intermediate representation of x_t.
Args:
inputs: A batch of image sequences `x_{1:T}` of shape
`[sample_shape, batch_size, timesteps, height, width,
channels]`.
Returns:
A batch of intermediate representations of shape [... |
Runs the model to generate a distribution q ( f | x_ { 1: T } ). | def call(self, inputs):
"""Runs the model to generate a distribution `q(f | x_{1:T})`.
This generates a list of batched MultivariateNormalDiag
distributions using the output of the recurrent model at each
timestep to parameterize each distribution.
Args:
inputs: A batch of intermediate repre... |
Runs the model to generate a distribution q ( z_ { 1: T } | x_ { 1: T } ). | def call(self, inputs):
"""Runs the model to generate a distribution `q(z_{1:T} | x_{1:T})`.
Args:
inputs: A batch of intermediate representations of image frames
across all timesteps, of shape [..., batch_size, timesteps,
hidden_size].
Returns:
A batch of MultivariateNormalDia... |
Runs the model to generate a distribution q ( z_ { 1: T } | x_ { 1: T } f ). | def call(self, inputs):
"""Runs the model to generate a distribution `q(z_{1:T} | x_{1:T}, f)`.
This generates a list of batched MultivariateNormalDiag
distributions using the output of the recurrent model at each
timestep to parameterize each distribution.
Args:
inputs: A tuple of a batch o... |
Generate new sequences. | def generate(self, batch_size, length, samples=1, fix_static=False,
fix_dynamic=False):
"""Generate new sequences.
Args:
batch_size: Number of sequences to generate.
length: Number of timesteps to generate for each sequence.
samples: Number of samples to draw from the latent di... |
Reconstruct the given input sequences. | def reconstruct(self, inputs, samples=1, sample_static=False,
sample_dynamic=False, swap_static=False, swap_dynamic=False,
fix_static=False, fix_dynamic=False):
"""Reconstruct the given input sequences.
Args:
inputs: A batch of image sequences `x_{1:T}` of shape
... |
Sample the static latent prior. | def sample_static_prior(self, samples, batch_size, fixed=False):
"""Sample the static latent prior.
Args:
samples: Number of samples to draw from the latent distribution.
batch_size: Number of sequences to sample.
fixed: Boolean for whether or not to share the same random
sample acros... |
Sample the static latent posterior. | def sample_static_posterior(self, inputs, samples):
"""Sample the static latent posterior.
Args:
inputs: A batch of intermediate representations of image frames
across all timesteps, of shape [..., batch_size, timesteps,
hidden_size].
samples: Number of samples to draw from the late... |
Sample the dynamic latent prior. | def sample_dynamic_prior(self, samples, batch_size, length, fixed=False):
"""Sample the dynamic latent prior.
Args:
samples: Number of samples to draw from the latent distribution.
batch_size: Number of sequences to sample.
length: Number of timesteps to sample for each sequence.
fixed:... |
Sample the static latent posterior. | def sample_dynamic_posterior(self, inputs, samples, static_sample=None):
"""Sample the static latent posterior.
Args:
inputs: A batch of intermediate representations of image frames
across all timesteps, of shape [..., batch_size, timesteps,
hidden_size].
samples: Number of samples ... |
Static batch shape of models represented by this component. | def batch_shape(self):
"""Static batch shape of models represented by this component.
Returns:
batch_shape: A `tf.TensorShape` 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_mo... |
Runtime batch shape of models represented by this component. | def batch_shape_tensor(self):
"""Runtime batch shape of models represented by this component.
Returns:
batch_shape: `int` `Tensor` 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_spac... |
If given an ordered list of parameter values build a name: value map. | def _canonicalize_param_vals_as_map(self, param_vals):
"""If given an ordered list of parameter values, build a name:value map.
This is a utility method that allows parameter values to be specified as
either lists or dicts, by transforming lists to a canonical dict
representation.
Args:
para... |
Instantiate this model as a Distribution over specified num_timesteps. | def make_state_space_model(self,
num_timesteps,
param_vals=None,
initial_state_prior=None,
initial_step=0):
"""Instantiate this model as a Distribution over specified `num_timesteps`.
Args:
... |
Sample from the joint prior over model parameters and trajectories. | def prior_sample(self,
num_timesteps,
initial_step=0,
params_sample_shape=(),
trajectories_sample_shape=(),
seed=None):
"""Sample from the joint prior over model parameters and trajectories.
Args:
num_timesteps... |
Build the joint density log p ( params ) + log p ( y|params ) as a callable. | def joint_log_prob(self, observed_time_series):
"""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... |
Computes the min_event_ndims associated with the give list of bijectors. | def _compute_min_event_ndims(bijector_list, compute_forward=True):
"""Computes the min_event_ndims associated with the give list of bijectors.
Given a list `bijector_list` of bijectors, compute the min_event_ndims that is
associated with the composition of bijectors in that list.
min_event_ndims is the # of r... |
Convert a vector size to a matrix size. | def vector_size_to_square_matrix_size(d, validate_args, name=None):
"""Convert a vector size to a matrix size."""
if isinstance(d, (float, int, np.generic, np.ndarray)):
n = (-1 + np.sqrt(1 + 8 * d)) / 2.
if float(int(n)) != n:
raise ValueError("Vector length is not a triangular number.")
return i... |
Numpy implementation of tf. argsort. | def _argsort(values, axis=-1, direction='ASCENDING', stable=False, name=None): # pylint: disable=unused-argument
"""Numpy implementation of `tf.argsort`."""
if direction == 'ASCENDING':
pass
elif direction == 'DESCENDING':
values = np.negative(values)
else:
raise ValueError('Unrecognized direction:... |
Numpy implementation of tf. sort. | def _sort(values, axis=-1, direction='ASCENDING', stable=False, name=None): # pylint: disable=unused-argument
"""Numpy implementation of `tf.sort`."""
if direction == 'ASCENDING':
pass
elif direction == 'DESCENDING':
values = np.negative(values)
else:
raise ValueError('Unrecognized direction: {}.'.... |
Calculate the batched KL divergence KL ( a || b ) with a and b Gumbel. | def _kl_gumbel_gumbel(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a and b Gumbel.
Args:
a: instance of a Gumbel distribution object.
b: instance of a Gumbel distribution object.
name: (optional) Name to use for created operations.
default is "kl_gumbel_gumbel".
Ret... |
Normal distribution function. | def ndtr(x, name="ndtr"):
"""Normal distribution function.
Returns the area under the Gaussian probability density function, integrated
from minus infinity to x:
```
1 / x
ndtr(x) = ---------- | exp(-0.5 t**2) dt
sqrt(2 pi) /-inf
= 0.5 (1 + e... |
Implements ndtr core logic. | def _ndtr(x):
"""Implements ndtr core logic."""
half_sqrt_2 = tf.constant(
0.5 * np.sqrt(2.), dtype=x.dtype, name="half_sqrt_2")
w = x * half_sqrt_2
z = tf.abs(w)
y = tf.where(
tf.less(z, half_sqrt_2), 1. + tf.math.erf(w),
tf.where(tf.greater(w, 0.), 2. - tf.math.erfc(z), tf.math.erfc(z)))
... |
The inverse of the CDF of the Normal distribution function. | def ndtri(p, name="ndtri"):
"""The inverse of the CDF of the Normal distribution function.
Returns x such that the area under the pdf from minus infinity to x is equal
to p.
A piece-wise rational approximation is done for the function.
This is a port of the implementation in netlib.
Args:
p: `Tensor`... |
Implements ndtri core logic. | def _ndtri(p):
"""Implements ndtri core logic."""
# Constants used in piece-wise rational approximations. Taken from the cephes
# library:
# https://root.cern.ch/doc/v608/SpecFuncCephesInv_8cxx_source.html
p0 = list(reversed([-5.99633501014107895267E1,
9.80010754185999661536E1,
... |
Log Normal distribution function. | def log_ndtr(x, series_order=3, name="log_ndtr"):
"""Log Normal distribution function.
For details of the Normal distribution function see `ndtr`.
This function calculates `(log o ndtr)(x)` by either calling `log(ndtr(x))` or
using an asymptotic series. Specifically:
- For `x > upper_segment`, use the appro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.