INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Runs multiple Fisher scoring steps. | def fit(
model_matrix,
response,
model,
model_coefficients_start=None,
predicted_linear_response_start=None,
l2_regularizer=None,
dispersion=None,
offset=None,
convergence_criteria_fn=None,
learning_rate=None,
fast_unsafe_numerics=True,
maximum_iterations=None,
name=N... |
Runs one step of Fisher scoring. | def fit_one_step(
model_matrix,
response,
model,
model_coefficients_start=None,
predicted_linear_response_start=None,
l2_regularizer=None,
dispersion=None,
offset=None,
learning_rate=None,
fast_unsafe_numerics=True,
name=None):
"""Runs one step of Fisher scoring.
Args:
... |
Returns Python callable which indicates fitting procedure has converged. | def convergence_criteria_small_relative_norm_weights_change(
tolerance=1e-5,
norm_order=2):
"""Returns Python `callable` which indicates fitting procedure has converged.
Writing old, new `model_coefficients` as `w0`, `w1`, this function
defines convergence as,
```python
relative_euclidean_norm = (tf... |
Helper to fit which sanitizes input args. | def prepare_args(model_matrix,
response,
model_coefficients,
predicted_linear_response,
offset,
name=None):
"""Helper to `fit` which sanitizes input args.
Args:
model_matrix: (Batch of) `float`-like, matrix-shaped `Tensor` whe... |
Computes model_matrix | def calculate_linear_predictor(model_matrix, model_coefficients, offset=None,
name=None):
"""Computes `model_matrix @ model_coefficients + offset`."""
with tf.compat.v1.name_scope(name, 'calculate_linear_predictor',
[model_matrix, model_coefficients, off... |
Returns number of cols in a given Tensor. | def num_cols(x):
"""Returns number of cols in a given `Tensor`."""
if tf.compat.dimension_value(x.shape[-1]) is not None:
return tf.compat.dimension_value(x.shape[-1])
return tf.shape(input=x)[-1] |
Wraps original_fn preferring to call static_fn when inputs are static. | def _prefer_static(original_fn, static_fn):
"""Wraps original_fn, preferring to call static_fn when inputs are static."""
original_spec = tf_inspect.getfullargspec(original_fn)
static_spec = tf_inspect.getfullargspec(static_fn)
if original_spec != static_spec:
raise ValueError(
'Arg specs do not mat... |
Wraps new_fn with the doc of original_fn. | def _copy_docstring(original_fn, new_fn):
"""Wraps new_fn with the doc of original_fn."""
original_spec = tf_inspect.getfullargspec(original_fn)
new_spec = tf_inspect.getfullargspec(new_fn)
if original_spec != new_spec:
raise ValueError(
'Arg specs do not match: original={}, new={}, fn={}'.format(
... |
Helper function for statically evaluating predicates in cond. | def _get_static_predicate(pred):
"""Helper function for statically evaluating predicates in `cond`."""
if pred in {0, 1}: # Accept 1/0 as valid boolean values
pred_value = bool(pred)
elif isinstance(pred, bool):
pred_value = pred
elif isinstance(pred, tf.Tensor):
pred_value = tf.get_static_value(pr... |
Computes rank given a Tensor s shape. | def rank_from_shape(shape_tensor_fn, tensorshape=None):
"""Computes `rank` given a `Tensor`'s `shape`."""
if tensorshape is None:
shape_tensor = (shape_tensor_fn() if callable(shape_tensor_fn)
else shape_tensor_fn)
if (hasattr(shape_tensor, 'shape') and
hasattr(shape_tensor.shap... |
Return either true_fn () if predicate pred is true else false_fn (). | def cond(pred, true_fn=None, false_fn=None, name=None):
"""Return either `true_fn()` if predicate `pred` is true else `false_fn()`.
If `pred` is a bool or has a constant value, we return either `true_fn()`
or `false_fn()`, otherwise we use `tf.cond` to dynamically route to both.
Arguments:
pred: A scalar ... |
Like tf. case except attempts to statically evaluate predicates. | def case(pred_fn_pairs, default=None, exclusive=False, name='smart_case'):
"""Like tf.case, except attempts to statically evaluate predicates.
If any predicate in `pred_fn_pairs` is a bool or has a constant value, the
associated callable will be called or omitted depending on its value.
Otherwise this function... |
Computes D ( param = mean ( r )). log_prob ( response ) for linear response r. | def log_prob(self, response, predicted_linear_response, name=None):
"""Computes `D(param=mean(r)).log_prob(response)` for linear response, `r`.
Args:
response: `float`-like `Tensor` representing observed ("actual")
responses.
predicted_linear_response: `float`-like `Tensor` corresponding to... |
Helper function to standardize op scope. | def _name_scope(self, name=None, default_name=None, values=None):
"""Helper function to standardize op scope."""
with tf.compat.v1.name_scope(self.name):
with tf.compat.v1.name_scope(
name, default_name, values=values or []) as scope:
yield scope |
Computes the standard deviation of a mixture distribution. | def mixture_stddev(mixture_weight_vector, mean_vector, stddev_vector):
"""Computes the standard deviation of a mixture distribution.
This function works regardless of the component distribution, so long as
each component's mean and standard deviation can be provided.
Args:
mixture_weight_vector: A 2D tens... |
Creates a LinearOperator representing a lower triangular matrix. | def make_tril_scale(loc=None,
scale_tril=None,
scale_diag=None,
scale_identity_multiplier=None,
shape_hint=None,
validate_args=False,
assert_positive=False,
name=None):
"""Create... |
Creates a LinearOperator representing a diagonal matrix. | def make_diag_scale(loc=None,
scale_diag=None,
scale_identity_multiplier=None,
shape_hint=None,
validate_args=False,
assert_positive=False,
name=None,
dtype=None):
"""Creates a L... |
Infer distribution batch and event shapes from a location and scale. | def shapes_from_loc_and_scale(loc, scale, name="shapes_from_loc_and_scale"):
"""Infer distribution batch and event shapes from a location and scale.
Location and scale family distributions determine their batch/event shape by
broadcasting the `loc` and `scale` args. This helper does that broadcast,
statically... |
Get broadcast shape as a Python list of integers ( preferred ) or Tensor. | def get_broadcast_shape(*tensors):
"""Get broadcast shape as a Python list of integers (preferred) or `Tensor`.
Args:
*tensors: One or more `Tensor` objects (already converted!).
Returns:
broadcast shape: Python list (if shapes determined statically), otherwise
an `int32` `Tensor`.
"""
# Try... |
Returns True if scale is a LinearOperator that is known to be diag. | def is_diagonal_scale(scale):
"""Returns `True` if `scale` is a `LinearOperator` that is known to be diag.
Args:
scale: `LinearOperator` instance.
Returns:
Python `bool`.
Raises:
TypeError: If `scale` is not a `LinearOperator`.
"""
if not isinstance(scale, tf.linalg.LinearOperator):
rai... |
Helper which checks validity of a scalar distribution init arg. | def maybe_check_scalar_distribution(distribution, expected_base_dtype,
validate_args):
"""Helper which checks validity of a scalar `distribution` init arg.
Valid here means:
* `distribution` has scalar batch and event shapes.
* `distribution` is `FULLY_REPARAMETERIZED`
* ... |
Pad dimensions of event tensors for mixture distributions. | def pad_mixture_dimensions(x, mixture_distribution, categorical_distribution,
event_ndims):
"""Pad dimensions of event tensors for mixture distributions.
See `Mixture._sample_n` and `MixtureSameFamily._sample_n` for usage examples.
Args:
x: event tensor to pad.
mixture_distrib... |
Convenience function that chooses one of two values based on the predicate. | def pick_scalar_condition(pred, true_value, false_value, name=None):
"""Convenience function that chooses one of two values based on the predicate.
This utility is equivalent to a version of `tf.where` that accepts only a
scalar predicate and computes its result statically when possible. It may also
be used in... |
Make ( possibly negatively indexed ) axis argument non - negative. | def make_non_negative_axis(axis, rank):
"""Make (possibly negatively indexed) `axis` argument non-negative."""
axis = tf.convert_to_tensor(value=axis, name="axis")
rank = tf.convert_to_tensor(value=rank, name="rank")
axis_ = tf.get_static_value(axis)
rank_ = tf.get_static_value(rank)
# Static case.
if ax... |
Move a single tensor dimension within its shape. | def move_dimension(x, source_idx, dest_idx):
"""Move a single tensor dimension within its shape.
This is a special case of `tf.transpose()`, which applies
arbitrary permutations to tensor dimensions.
Args:
x: Tensor of rank `ndims`.
source_idx: Integer index into `x.shape` (negative indexing is suppor... |
Assert that x has integer components ( or floats equal to integers ). | def assert_integer_form(x,
data=None,
summarize=None,
message=None,
int_dtype=None,
name="assert_integer_form"):
"""Assert that x has integer components (or floats equal to integers).
Args:
x... |
Assert x is a non - negative tensor and optionally of integers. | def embed_check_nonnegative_integer_form(
x, name="embed_check_nonnegative_integer_form"):
"""Assert x is a non-negative tensor, and optionally of integers."""
with tf.name_scope(name):
x = tf.convert_to_tensor(value=x, name="x")
assertions = [
assert_util.assert_non_negative(
x, mes... |
Returns whether a and b have the same dynamic shape. | def same_dynamic_shape(a, b):
"""Returns whether a and b have the same dynamic shape.
Args:
a: `Tensor`
b: `Tensor`
Returns:
`bool` `Tensor` representing if both tensors have the same shape.
"""
a = tf.convert_to_tensor(value=a, name="a")
b = tf.convert_to_tensor(value=b, name="b")
# Here w... |
Helper which tries to return a static value. | def maybe_get_static_value(x, dtype=None):
"""Helper which tries to return a static value.
Given `x`, extract it's value statically, optionally casting to a specific
dtype. If this is not possible, None is returned.
Args:
x: `Tensor` for which to extract a value statically.
dtype: Optional dtype to ca... |
Converts logit to probabilities ( or vice - versa ) and returns both. | def get_logits_and_probs(logits=None,
probs=None,
multidimensional=False,
validate_args=False,
name="get_logits_and_probs",
dtype=None):
"""Converts logit to probabilities (or vice-versa), and ... |
Helper returning True if dtype is known to be unsigned. | def _is_known_unsigned_by_dtype(dt):
"""Helper returning True if dtype is known to be unsigned."""
return {
tf.bool: True,
tf.uint8: True,
tf.uint16: True,
}.get(dt.base_dtype, False) |
Helper returning True if dtype is known to be signed. | def _is_known_signed_by_dtype(dt):
"""Helper returning True if dtype is known to be signed."""
return {
tf.float16: True,
tf.float32: True,
tf.float64: True,
tf.int8: True,
tf.int16: True,
tf.int32: True,
tf.int64: True,
}.get(dt.base_dtype, False) |
Helper returning the largest integer exactly representable by dtype. | def _largest_integer_by_dtype(dt):
"""Helper returning the largest integer exactly representable by dtype."""
if not _is_known_dtype(dt):
raise TypeError("Unrecognized dtype: {}".format(dt.name))
if dt.is_floating:
return int(2**(np.finfo(dt.as_numpy_dtype).nmant + 1))
if dt.is_integer:
return np.ii... |
Helper returning the smallest integer exactly representable by dtype. | def _smallest_integer_by_dtype(dt):
"""Helper returning the smallest integer exactly representable by dtype."""
if not _is_known_dtype(dt):
raise TypeError("Unrecognized dtype: {}".format(dt.name))
if _is_known_unsigned_by_dtype(dt):
return 0
return -1 * _largest_integer_by_dtype(dt) |
Helper returning True if dtype. is_integer or is bool. | def _is_integer_like_by_dtype(dt):
"""Helper returning True if dtype.is_integer or is `bool`."""
if not _is_known_dtype(dt):
raise TypeError("Unrecognized dtype: {}".format(dt.name))
return dt.is_integer or dt.base_dtype == tf.bool |
Embeds checks that categorical distributions don t have too many classes. | def embed_check_categorical_event_shape(
categorical_param, name="embed_check_categorical_event_shape"):
"""Embeds checks that categorical distributions don't have too many classes.
A categorical-type distribution is one which, e.g., returns the class label
rather than a one-hot encoding. E.g., `Categorical... |
Ensures integers remain unaffected despite casting to/ from int/ float types. | def embed_check_integer_casting_closed(x,
target_dtype,
assert_nonnegative=True,
assert_positive=False,
name="embed_check_casting_closed"):
"""Ensures integers re... |
Multinomial coefficient. | def log_combinations(n, counts, name="log_combinations"):
"""Multinomial coefficient.
Given `n` and `counts`, where `counts` has last dimension `k`, we compute
the multinomial coefficient as:
```n! / sum_i n_i!```
where `i` runs over all `k` classes.
Args:
n: Floating-point `Tensor` broadcastable wi... |
Transform diagonal of [ batch - ] matrix leave rest of matrix unchanged. | def matrix_diag_transform(matrix, transform=None, name=None):
"""Transform diagonal of [batch-]matrix, leave rest of matrix unchanged.
Create a trainable covariance defined by a Cholesky factor:
```python
# Transform network layer into 2 x 2 array.
matrix_values = tf.contrib.layers.fully_connected(activatio... |
Circularly moves dims left or right. | def rotate_transpose(x, shift, name="rotate_transpose"):
"""Circularly moves dims left or right.
Effectively identical to:
```python
numpy.transpose(x, numpy.roll(numpy.arange(len(x.shape)), shift))
```
When `validate_args=False` additional graph-runtime checks are
performed. These checks entail moving... |
Picks possibly different length row Tensor s based on condition. | def pick_vector(cond, true_vector, false_vector, name="pick_vector"):
"""Picks possibly different length row `Tensor`s based on condition.
Value `Tensor`s should have exactly one dimension.
If `cond` is a python Boolean or `tf.constant` then either `true_vector` or
`false_vector` is immediately returned. I.e.... |
Convenience function which statically broadcasts shape when possible. | def prefer_static_broadcast_shape(shape1,
shape2,
name="prefer_static_broadcast_shape"):
"""Convenience function which statically broadcasts shape when possible.
Args:
shape1: `1-D` integer `Tensor`. Already converted to tensor!
shape2: ... |
Generate a new seed from the given seed and salt. | def gen_new_seed(seed, salt):
"""Generate a new seed, from the given seed and salt."""
if seed is None:
return None
string = (str(seed) + salt).encode("utf-8")
return int(hashlib.md5(string).hexdigest()[:8], 16) & 0x7FFFFFFF |
r Creates a ( batch of ) triangular matrix from a vector of inputs. | def fill_triangular(x, upper=False, name=None):
r"""Creates a (batch of) triangular matrix from a vector of inputs.
Created matrix can be lower- or upper-triangular. (It is more efficient to
create the matrix as upper or lower, rather than transpose.)
Triangular matrix elements are filled in a clockwise spira... |
Creates a vector from a ( batch of ) triangular matrix. | def fill_triangular_inverse(x, upper=False, name=None):
"""Creates a vector from a (batch of) triangular matrix.
The vector is created from the lower-triangular or upper-triangular portion
depending on the value of the parameter `upper`.
If `x.shape` is `[b1, b2, ..., bB, n, n]` then the output shape is
`[b... |
Creates a matrix with values set above below and on the diagonal. | def tridiag(below=None, diag=None, above=None, name=None):
"""Creates a matrix with values set above, below, and on the diagonal.
Example:
```python
tridiag(below=[1., 2., 3.],
diag=[4., 5., 6., 7.],
above=[8., 9., 10.])
# ==> array([[ 4., 8., 0., 0.],
# [ 1., 5., ... |
Computes log ( abs ( sum ( weight * exp ( elements across tensor dimensions )))). | def reduce_weighted_logsumexp(logx,
w=None,
axis=None,
keep_dims=False,
return_sign=False,
name=None):
"""Computes `log(abs(sum(weight * exp(elements across tensor dime... |
Computes the inverse softplus i. e. x = softplus_inverse ( softplus ( x )). | def softplus_inverse(x, name=None):
"""Computes the inverse softplus, i.e., x = softplus_inverse(softplus(x)).
Mathematically this op is equivalent to:
```none
softplus_inverse = log(exp(x) - 1.)
```
Args:
x: `Tensor`. Non-negative (not enforced), floating-point.
name: A name for the operation (o... |
Returns the size of a specific dimension. | def dimension_size(x, axis):
"""Returns the size of a specific dimension."""
# Since tf.gather isn't "constant-in, constant-out", we must first check the
# static shape or fallback to dynamic shape.
s = tf.compat.dimension_value(
tensorshape_util.with_rank_at_least(x.shape, np.abs(axis))[axis])
if s is ... |
Validates quadrature grid probs or computes them as necessary. | def process_quadrature_grid_and_probs(quadrature_grid_and_probs,
dtype,
validate_args,
name=None):
"""Validates quadrature grid, probs or computes them as necessary.
Args:
quadrature_grid_and_probs... |
Pads value to the front and/ or back of a Tensor dim count times. | def pad(x, axis, front=False, back=False, value=0, count=1, name=None):
"""Pads `value` to the front and/or back of a `Tensor` dim, `count` times.
Args:
x: `Tensor` input.
axis: Scalar `int`-like `Tensor` representing the single dimension to pad.
(Negative indexing is supported.)
front: Python `b... |
Returns parent frame arguments. | def parent_frame_arguments():
"""Returns parent frame arguments.
When called inside a function, returns a dictionary with the caller's function
arguments. These are positional arguments and keyword arguments (**kwargs),
while variable arguments (*varargs) are excluded.
When called at global scope, this will... |
Transform a 0 - D or 1 - D Tensor to be 1 - D. | def expand_to_vector(x, tensor_name=None, op_name=None, validate_args=False):
"""Transform a 0-D or 1-D `Tensor` to be 1-D.
For user convenience, many parts of the TensorFlow Probability API accept
inputs of rank 0 or 1 -- i.e., allowing an `event_shape` of `[5]` to be passed
to the API as either `5` or `[5]`.... |
Produces the content of output_tensor only after dependencies. | def with_dependencies(dependencies, output_tensor, name=None):
"""Produces the content of `output_tensor` only after `dependencies`.
In some cases, a user may want the output of an operation to be consumed
externally only after some other dependencies have run first. This function
returns `output_tensor`, but ... |
Checks that rightmost_transposed_ndims is valid. | def _maybe_validate_rightmost_transposed_ndims(
rightmost_transposed_ndims, validate_args, name=None):
"""Checks that `rightmost_transposed_ndims` is valid."""
with tf.name_scope(name or 'maybe_validate_rightmost_transposed_ndims'):
assertions = []
if not dtype_util.is_integer(rightmost_transposed_ndims... |
Checks that perm is valid. | def _maybe_validate_perm(perm, validate_args, name=None):
"""Checks that `perm` is valid."""
with tf.name_scope(name or 'maybe_validate_perm'):
assertions = []
if not dtype_util.is_integer(perm.dtype):
raise TypeError('`perm` must be integer type')
msg = '`perm` must be a vector.'
if tensorsh... |
Helper for _forward and _inverse_event_shape. | def _event_shape(self, shape, static_perm_to_shape):
"""Helper for _forward and _inverse_event_shape."""
rightmost_ = tf.get_static_value(self.rightmost_transposed_ndims)
if tensorshape_util.rank(shape) is None or rightmost_ is None:
return tf.TensorShape(None)
if tensorshape_util.rank(shape) < ri... |
Returns the concatenation of the dimension in x and other. | def concatenate(x, other):
"""Returns the concatenation of the dimension in `x` and `other`.
*Note:* If either `x` or `other` is completely unknown, concatenation will
discard information about the other shape. In future, we might support
concatenation that preserves this information for use with slicing.
F... |
A version of constant_value () that returns a TensorShape. | def constant_value_as_shape(tensor): # pylint: disable=invalid-name
"""A version of `constant_value()` that returns a `TensorShape`.
This version should be used when a constant tensor value is
interpreted as a (possibly partial) shape, e.g. in the shape
function for `tf.reshape()`. By explicitly requesting a
... |
Returns a list of dimension sizes or None if rank is unknown. | def dims(x):
"""Returns a list of dimension sizes, or `None` if `rank` is unknown.
For more details, see `help(tf.TensorShape.dims)`.
Args:
x: object representing a shape; convertible to `tf.TensorShape`.
Returns:
shape_as_list: list of sizes or `None` values representing each
dimensions size i... |
Returns a shape combining the information in x and other. | def merge_with(x, other):
"""Returns a shape combining the information in `x` and `other`.
The dimensions in `x` and `other` are merged elementwise, according to the
rules defined for `tf.Dimension.merge_with()`.
For more details, see `help(tf.TensorShape.merge_with)`.
Args:
x: object representing a sh... |
Returns a shape based on x with at least the given rank. | def with_rank_at_least(x, rank): # pylint: disable=redefined-outer-name
"""Returns a shape based on `x` with at least the given `rank`.
For more details, see `help(tf.TensorShape.with_rank_at_least)`.
Args:
x: object representing a shape; convertible to `tf.TensorShape`.
rank: An `int` representing the... |
Check that source and target shape match statically if possible. | def _check_equal_shape(name,
static_shape,
dynamic_shape,
static_target_shape,
dynamic_target_shape=None):
"""Check that source and target shape match, statically if possible."""
static_target_shape = tf.TensorShape(static_... |
Augment a sample shape to broadcast batch dimensions. | def _augment_sample_shape(partial_batch_dist,
full_sample_and_batch_shape,
validate_args=False):
"""Augment a sample shape to broadcast batch dimensions.
Computes an augmented sample shape, so that any batch dimensions not
part of the distribution `partial_batc... |
Build a callable that perform one step for backward smoothing. | def build_backward_pass_step(get_transition_matrix_for_timestep):
"""Build a callable that perform one step for backward smoothing.
Args:
get_transition_matrix_for_timestep: callable taking a timestep
as an integer `Tensor` argument, and returning a `LinearOperator`
of shape `[latent_size, latent_s... |
Backward update for a Kalman smoother. | def backward_smoothing_update(filtered_mean,
filtered_cov,
predicted_mean,
predicted_cov,
next_posterior_mean,
next_posterior_cov,
transitio... |
Build a callable that performs one step of Kalman filtering. | def build_kalman_filter_step(get_transition_matrix_for_timestep,
get_transition_noise_for_timestep,
get_observation_matrix_for_timestep,
get_observation_noise_for_timestep):
"""Build a callable that performs one step of Kalman filt... |
Conjugate update for a linear Gaussian model. | def linear_gaussian_update(
prior_mean, prior_cov, observation_matrix, observation_noise, x_observed):
"""Conjugate update for a linear Gaussian model.
Given a normal prior on a latent variable `z`,
`p(z) = N(prior_mean, prior_cov) = N(u, P)`,
for which we observe a linear Gaussian transformation `x`,
... |
Propagate a filtered distribution through a transition model. | def kalman_transition(filtered_mean, filtered_cov,
transition_matrix, transition_noise):
"""Propagate a filtered distribution through a transition model."""
predicted_mean = _propagate_mean(filtered_mean,
transition_matrix,
... |
Build a callable that performs one step of Kalman mean recursion. | def build_kalman_mean_step(get_transition_matrix_for_timestep,
get_transition_noise_for_timestep,
get_observation_matrix_for_timestep,
get_observation_noise_for_timestep):
"""Build a callable that performs one step of Kalman mean recursi... |
Build a callable for one step of Kalman covariance recursion. | def build_kalman_cov_step(get_transition_matrix_for_timestep,
get_transition_noise_for_timestep,
get_observation_matrix_for_timestep,
get_observation_noise_for_timestep):
"""Build a callable for one step of Kalman covariance recursion.
A... |
Build a callable for one step of Kalman sampling recursion. | def build_kalman_sample_step(get_transition_matrix_for_timestep,
get_transition_noise_for_timestep,
get_observation_matrix_for_timestep,
get_observation_noise_for_timestep,
full_sample_and_batch_shape,
... |
Build a callable to push latent means/ covs to observed means/ covs. | def build_pushforward_latents_step(get_observation_matrix_for_timestep,
get_observation_noise_for_timestep):
"""Build a callable to push latent means/covs to observed means/covs.
Args:
get_observation_matrix_for_timestep: callable taking a timestep
as an integer `Tensor... |
Propagate a mean through linear Gaussian transformation. | def _propagate_mean(mean, linop, dist):
"""Propagate a mean through linear Gaussian transformation."""
return linop.matmul(mean) + dist.mean()[..., tf.newaxis] |
Propagate covariance through linear Gaussian transformation. | def _propagate_cov(cov, linop, dist):
"""Propagate covariance through linear Gaussian transformation."""
# For linop A and input cov P, returns `A P A' + dist.cov()`
return linop.matmul(linop.matmul(cov), adjoint_arg=True) + dist.covariance() |
Run the backward pass in Kalman smoother. | def backward_smoothing_pass(self,
filtered_means,
filtered_covs,
predicted_means,
predicted_covs):
"""Run the backward pass in Kalman smoother.
The backward smoothing is using Rauch, Tung and... |
Draw a joint sample from the prior over latents and observations. | def _joint_sample_n(self, n, seed=None):
"""Draw a joint sample from the prior over latents and observations."""
with tf.name_scope("sample_n_joint"):
stream = seed_stream.SeedStream(
seed, salt="LinearGaussianStateSpaceModel_sample_n_joint")
sample_and_batch_shape = distribution_util.pr... |
Run a Kalman filter over a provided sequence of outputs. | def forward_filter(self, x, mask=None):
"""Run a Kalman filter over a provided sequence of outputs.
Note that the returned values `filtered_means`, `predicted_means`, and
`observation_means` depend on the observed time series `x`, while the
corresponding covariances are independent of the observed seri... |
Run a Kalman smoother to return posterior mean and cov. | def posterior_marginals(self, x, mask=None):
"""Run a Kalman smoother to return posterior mean and cov.
Note that the returned values `smoothed_means` depend on the observed
time series `x`, while the `smoothed_covs` are independent
of the observed series; i.e., they depend only on the model itself.
... |
Compute prior means for all variables via dynamic programming. | def _joint_mean(self):
"""Compute prior means for all variables via dynamic programming.
Returns:
latent_means: Prior means of latent states `z_t`, as a `Tensor`
of shape `batch_shape + [num_timesteps, latent_size]`
observation_means: Prior covariance matrices of observations
`x_t`,... |
Compute prior covariances for all variables via dynamic programming. | def _joint_covariances(self):
"""Compute prior covariances for all variables via dynamic programming.
Returns:
latent_covs: Prior covariance matrices of latent states `z_t`, as
a `Tensor` of shape `batch_shape + [num_timesteps,
latent_size, latent_size]`
observation_covs: Prior cova... |
Push latent means and covariances forward through the observation model. | def latents_to_observations(self, latent_means, latent_covs):
"""Push latent means and covariances forward through the observation model.
Args:
latent_means: float `Tensor` of shape `[..., num_timesteps, latent_size]`
latent_covs: float `Tensor` of shape
`[..., num_timesteps, latent_size, l... |
Computes I_v ( z ) * exp ( - abs ( z )) using a recurrence relation where z > 0. | def _bessel_ive(v, z, cache=None):
"""Computes I_v(z)*exp(-abs(z)) using a recurrence relation, where z > 0."""
# TODO(b/67497980): Switch to a more numerically faithful implementation.
z = tf.convert_to_tensor(value=z)
wrap = lambda result: tf.debugging.check_numerics(result, 'besseli{}'.format(v
... |
Computes the log - normalizer of the distribution. | def _log_normalization(self):
"""Computes the log-normalizer of the distribution."""
event_dim = tf.compat.dimension_value(self.event_shape[0])
if event_dim is None:
raise ValueError('vMF _log_normalizer currently only supports '
'statically known event shape')
safe_conc = t... |
Check counts for proper shape values then return tensor version. | def _maybe_assert_valid_sample(self, samples):
"""Check counts for proper shape, values, then return tensor version."""
if not self.validate_args:
return samples
with tf.control_dependencies([
assert_util.assert_near(
1.,
tf.linalg.norm(tensor=samples, axis=-1),
... |
The mode of the von Mises - Fisher distribution is the mean direction. | def _mode(self):
"""The mode of the von Mises-Fisher distribution is the mean direction."""
return (self.mean_direction +
tf.zeros_like(self.concentration)[..., tf.newaxis]) |
Applies a Householder rotation to samples. | def _rotate(self, samples):
"""Applies a Householder rotation to `samples`."""
event_dim = (
tf.compat.dimension_value(self.event_shape[0]) or
self._event_shape_tensor()[0])
basis = tf.concat([[1.], tf.zeros([event_dim - 1], dtype=self.dtype)],
axis=0),
u = tf.nn.l2... |
Specialized inversion sampler for 3D. | def _sample_3d(self, n, seed=None):
"""Specialized inversion sampler for 3D."""
seed = seed_stream.SeedStream(seed, salt='von_mises_fisher_3d')
u_shape = tf.concat([[n], self._batch_shape_tensor()], axis=0)
z = tf.random.uniform(u_shape, seed=seed(), dtype=self.dtype)
# TODO(bjp): Higher-order odd d... |
Create a deep copy of fn. | def _copy_fn(fn):
"""Create a deep copy of fn.
Args:
fn: a callable
Returns:
A `FunctionType`: a deep copy of fn.
Raises:
TypeError: if `fn` is not a callable.
"""
if not callable(fn):
raise TypeError("fn is not callable: {}".format(fn))
# The blessed way to copy a function. copy.deepco... |
Update old_str by inserting append_str just before the Args: section. | def _update_docstring(old_str, append_str):
"""Update old_str by inserting append_str just before the "Args:" section."""
old_str = old_str or ""
old_str_lines = old_str.split("\n")
# Step 0: Prepend spaces to all lines of append_str. This is
# necessary for correct markdown generation.
append_str = "\n".j... |
Converts the given value to a ( structure of ) Tensor. | def _convert_to_tensor(value, dtype=None, dtype_hint=None, name=None):
"""Converts the given `value` to a (structure of) `Tensor`.
This function converts Python objects of various types to a (structure of)
`Tensor` objects. It accepts `Tensor` objects, numpy arrays, Python lists, and
Python scalars. For exampl... |
Removes dict keys which have have self as value. | def _remove_dict_keys_with_value(dict_, val):
"""Removes `dict` keys which have have `self` as value."""
return {k: v for k, v in dict_.items() if v is not val} |
Recursively replace dict s with _PrettyDict. | def _recursively_replace_dict_for_pretty_dict(x):
"""Recursively replace `dict`s with `_PrettyDict`."""
# We use "PrettyDict" because collections.OrderedDict repr/str has the word
# "OrderedDict" in it. We only want to print "OrderedDict" if in fact the
# input really is an OrderedDict.
if isinstance(x, dict)... |
Computes the Monte - Carlo approximation of E_p [ f ( X ) ]. | def expectation(f, samples, log_prob=None, use_reparametrization=True,
axis=0, keep_dims=False, name=None):
"""Computes the Monte-Carlo approximation of `E_p[f(X)]`.
This function computes the Monte-Carlo approximation of an expectation, i.e.,
```none
E_p[f(X)] approx= m**-1 sum_i^m f(x_j), x... |
Check args and return samples. | def _get_samples(dist, z, n, seed):
"""Check args and return samples."""
with tf.compat.v1.name_scope('get_samples', values=[z, n]):
if (n is None) == (z is None):
raise ValueError(
'Must specify exactly one of arguments "n" and "z". Found: '
'n = %s, z = %s' % (n, z))
if n is not... |
Helper which returns True if input is collections. namedtuple - like. | def is_namedtuple_like(x):
"""Helper which returns `True` if input is `collections.namedtuple`-like."""
try:
for fn in x._fields:
_ = getattr(x, fn)
return True
except AttributeError:
return False |
Helper which makes a str name ; useful for tf. compat. v1. name_scope. | def make_name(super_name, default_super_name, sub_name):
"""Helper which makes a `str` name; useful for tf.compat.v1.name_scope."""
name = super_name if super_name is not None else default_super_name
if sub_name is not None:
name += '_' + sub_name
return name |
Helper to choose which expand_dims is_accepted and applies tf. where. | def _choose_base_case(is_accepted,
accepted,
rejected,
name=None):
"""Helper to `choose` which expand_dims `is_accepted` and applies tf.where."""
def _expand_is_accepted_like(x):
"""Helper to expand `is_accepted` like the shape of some input arg.... |
Helper which expand_dims is_accepted then applies tf. where. | def choose(is_accepted, accepted, rejected, name=None):
"""Helper which expand_dims `is_accepted` then applies tf.where."""
if not is_namedtuple_like(accepted):
return _choose_base_case(is_accepted, accepted, rejected, name=name)
if not isinstance(accepted, type(rejected)):
raise TypeError('Type of `accep... |
Elementwise adds list members replacing non - finite results with alt_value. | def safe_sum(x, alt_value=-np.inf, name=None):
"""Elementwise adds list members, replacing non-finite results with alt_value.
Typically the `alt_value` is chosen so the `MetropolisHastings`
`TransitionKernel` always rejects the proposal.
Args:
x: Python `list` of `Tensors` to elementwise add.
alt_valu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.