_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q266600
_prepare_args
test
def _prepare_args(objective_function, initial_simplex, initial_vertex, step_sizes, objective_at_initial_simplex, objective_at_initial_vertex, batch_evaluate_objective): """Computes the initial simplex and the o...
python
{ "resource": "" }
q266601
_prepare_args_with_initial_simplex
test
def _prepare_args_with_initial_simplex(objective_function, initial_simplex, objective_at_initial_simplex, batch_evaluate_objective): """Evaluates the objective function at the specified initial simplex...
python
{ "resource": "" }
q266602
_prepare_args_with_initial_vertex
test
def _prepare_args_with_initial_vertex(objective_function, initial_vertex, step_sizes, objective_at_initial_vertex, batch_evaluate_objective): """Constructs a standard...
python
{ "resource": "" }
q266603
_evaluate_objective_multiple
test
def _evaluate_objective_multiple(objective_function, arg_batch, batch_evaluate_objective): """Evaluates the objective function on a batch of points. If `batch_evaluate_objective` is True, returns `objective function(arg_batch)` else it maps the `objective_function` across the `...
python
{ "resource": "" }
q266604
plot_weight_posteriors
test
def plot_weight_posteriors(names, qm_vals, qs_vals, fname): """Save a PNG plot with histograms of weight means and stddevs. Args: names: A Python `iterable` of `str` variable names. qm_vals: A Python `iterable`, the same length as `names`, whose elements are Numpy `array`s, of any shape, containing ...
python
{ "resource": "" }
q266605
plot_heldout_prediction
test
def plot_heldout_prediction(input_vals, probs, fname, n=10, title=""): """Save a PNG plot visualizing posterior uncertainty on heldout data. Args: input_vals: A `float`-like Numpy `array` of shape `[num_heldout] + IMAGE_SHAPE`, containing heldout input images. probs: A `fl...
python
{ "resource": "" }
q266606
build_fake_data
test
def build_fake_data(num_examples=10): """Build fake MNIST-style data for unit testing.""" class Dummy(object): pass num_examples = 10 mnist_data = Dummy() mnist_data.train = Dummy() mnist_data.train.images = np.float32(np.random.randn( num_examples, *IMAGE_SHAPE)) mnist_data.train.labels = np....
python
{ "resource": "" }
q266607
BlockwiseInitializer.get_config
test
def get_config(self): """Returns initializer configuration as a JSON-serializable dict.""" return { 'initializers': [ tf.compat.v2.initializers.serialize( tf.keras.initializers.get(init)) for init in self.initializers ], 'sizes': self.sizes, ...
python
{ "resource": "" }
q266608
BlockwiseInitializer.from_config
test
def from_config(cls, config): """Instantiates an initializer from a configuration dictionary.""" return cls(**{ 'initializers': [tf.compat.v2.initializers.deserialize(init) for init in config.get('initializers', [])], 'sizes': config.get('sizes', []), 'validate_a...
python
{ "resource": "" }
q266609
_matmul
test
def _matmul(a, b, transpose_a=False, transpose_b=False, adjoint_a=False, adjoint_b=False, a_is_sparse=False, b_is_sparse=False, name=None): # pylint: disable=unused-argument """Numpy matmul wrapper.""" if a_is_sparse or b_is_sparse: raise NotImplementedError('Num...
python
{ "resource": "" }
q266610
MultivariateStudentTLinearOperator._std_var_helper
test
def _std_var_helper(self, statistic, statistic_name, statistic_ndims, df_factor_fn): """Helper to compute stddev, covariance and variance.""" df = tf.reshape( self.df, tf.concat([ tf.shape(input=self.df), tf.ones([statistic_ndims], dtype=tf.int32) ...
python
{ "resource": "" }
q266611
assign_log_moving_mean_exp
test
def assign_log_moving_mean_exp( log_mean_exp_var, log_value, decay, name=None): """Compute the log of the exponentially weighted moving mean of the exp. If `log_value` is a draw from a stationary random variable, this function approximates `log(E[exp(log_value)])`, i.e., a weighted log-sum-exp. More precis...
python
{ "resource": "" }
q266612
CholeskyOuterProduct._make_columnar
test
def _make_columnar(self, x): """Ensures non-scalar input has at least one column. Example: If `x = [1, 2, 3]` then the output is `[[1], [2], [3]]`. If `x = [[1, 2, 3], [4, 5, 6]]` then the output is unchanged. If `x = 1` then the output is unchanged. Args: x: `Tensor`. Retur...
python
{ "resource": "" }
q266613
random_rademacher
test
def random_rademacher(shape, dtype=tf.float32, seed=None, name=None): """Generates `Tensor` consisting of `-1` or `+1`, chosen uniformly at random. For more details, see [Rademacher distribution]( https://en.wikipedia.org/wiki/Rademacher_distribution). Args: shape: Vector-shaped, `int` `Tensor` representi...
python
{ "resource": "" }
q266614
random_rayleigh
test
def random_rayleigh(shape, scale=None, dtype=tf.float32, seed=None, name=None): """Generates `Tensor` of positive reals drawn from a Rayleigh distributions. The probability density function of a Rayleigh distribution with `scale` parameter is given by: ```none f(x) = x scale**-2 exp(-x**2 0.5 scale**-2) `...
python
{ "resource": "" }
q266615
_pick_scalar_condition
test
def _pick_scalar_condition(pred, cond_true, cond_false): """Convenience function which chooses the condition based on the predicate.""" # Note: This function is only valid if all of pred, cond_true, and cond_false # are scalars. This means its semantics are arguably more like tf.cond than # tf.where even though...
python
{ "resource": "" }
q266616
TransformedDistribution._finish_log_prob_for_one_fiber
test
def _finish_log_prob_for_one_fiber(self, y, x, ildj, event_ndims, **distribution_kwargs): """Finish computation of log_prob on one element of the inverse image.""" x = self._maybe_rotate_dims(x, rotate_right=True) log_prob = self.distribution.log_prob(x, **distribution_k...
python
{ "resource": "" }
q266617
TransformedDistribution._finish_prob_for_one_fiber
test
def _finish_prob_for_one_fiber(self, y, x, ildj, event_ndims, **distribution_kwargs): """Finish computation of prob on one element of the inverse image.""" x = self._maybe_rotate_dims(x, rotate_right=True) prob = self.distribution.prob(x, **distribution_kwargs) if self._...
python
{ "resource": "" }
q266618
TransformedDistribution._maybe_rotate_dims
test
def _maybe_rotate_dims(self, x, rotate_right=False): """Helper which rolls left event_dims left or right event_dims right.""" needs_rotation_const = tf.get_static_value(self._needs_rotation) if needs_rotation_const is not None and not needs_rotation_const: return x ndims = prefer_static.rank(x) ...
python
{ "resource": "" }
q266619
_undo_batch_normalization
test
def _undo_batch_normalization(x, mean, variance, offset, scale, variance_epsilon, name=None): r"""Inverse of tf.nn.batch_normalization. ...
python
{ "resource": "" }
q266620
BatchNormalization._validate_bn_layer
test
def _validate_bn_layer(self, layer): """Check for valid BatchNormalization layer. Args: layer: Instance of `tf.layers.BatchNormalization`. Raises: ValueError: If batchnorm_layer argument is not an instance of `tf.layers.BatchNormalization`, or if `batchnorm_layer.renorm=True` or if ...
python
{ "resource": "" }
q266621
_slice_single_param
test
def _slice_single_param(param, param_event_ndims, slices, dist_batch_shape): """Slices a single parameter of a distribution. Args: param: A `Tensor`, the original parameter to slice. param_event_ndims: `int` event parameterization rank for this parameter. slices: A `tuple` of normalized slices. dis...
python
{ "resource": "" }
q266622
_slice_params_to_dict
test
def _slice_params_to_dict(dist, params_event_ndims, slices): """Computes the override dictionary of sliced parameters. Args: dist: The tfd.Distribution being batch-sliced. params_event_ndims: Per-event parameter ranks, a `str->int` `dict`. slices: Slices as received by __getitem__. Returns: over...
python
{ "resource": "" }
q266623
_apply_single_step
test
def _apply_single_step(dist, params_event_ndims, slices, params_overrides): """Applies a single slicing step to `dist`, returning a new instance.""" if len(slices) == 1 and slices[0] == Ellipsis: # The path used by Distribution.copy: batch_slice(...args..., Ellipsis) override_dict = {} else: override_...
python
{ "resource": "" }
q266624
_apply_slice_sequence
test
def _apply_slice_sequence(dist, params_event_ndims, slice_overrides_seq): """Applies a sequence of slice or copy-with-overrides operations to `dist`.""" for slices, overrides in slice_overrides_seq: dist = _apply_single_step(dist, params_event_ndims, slices, overrides) return dist
python
{ "resource": "" }
q266625
batch_slice
test
def batch_slice(dist, params_event_ndims, params_overrides, slices): """Slices `dist` along its batch dimensions. Helper for tfd.Distribution. Args: dist: A `tfd.Distribution` instance. params_event_ndims: A `dict` of `str->int` indicating the number of dimensions of a given parameter required to par...
python
{ "resource": "" }
q266626
fit
test
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...
python
{ "resource": "" }
q266627
convergence_criteria_small_relative_norm_weights_change
test
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...
python
{ "resource": "" }
q266628
prepare_args
test
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...
python
{ "resource": "" }
q266629
num_cols
test
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]
python
{ "resource": "" }
q266630
_prefer_static
test
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...
python
{ "resource": "" }
q266631
_copy_docstring
test
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( ...
python
{ "resource": "" }
q266632
_get_static_predicate
test
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...
python
{ "resource": "" }
q266633
rank_from_shape
test
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...
python
{ "resource": "" }
q266634
case
test
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...
python
{ "resource": "" }
q266635
ExponentialFamily._name_scope
test
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
python
{ "resource": "" }
q266636
mixture_stddev
test
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...
python
{ "resource": "" }
q266637
make_tril_scale
test
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...
python
{ "resource": "" }
q266638
make_diag_scale
test
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...
python
{ "resource": "" }
q266639
shapes_from_loc_and_scale
test
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...
python
{ "resource": "" }
q266640
is_diagonal_scale
test
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...
python
{ "resource": "" }
q266641
maybe_check_scalar_distribution
test
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` * ...
python
{ "resource": "" }
q266642
pad_mixture_dimensions
test
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...
python
{ "resource": "" }
q266643
pick_scalar_condition
test
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...
python
{ "resource": "" }
q266644
move_dimension
test
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...
python
{ "resource": "" }
q266645
embed_check_nonnegative_integer_form
test
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...
python
{ "resource": "" }
q266646
same_dynamic_shape
test
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...
python
{ "resource": "" }
q266647
maybe_get_static_value
test
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...
python
{ "resource": "" }
q266648
_is_known_unsigned_by_dtype
test
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)
python
{ "resource": "" }
q266649
_is_known_signed_by_dtype
test
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)
python
{ "resource": "" }
q266650
_largest_integer_by_dtype
test
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...
python
{ "resource": "" }
q266651
_smallest_integer_by_dtype
test
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)
python
{ "resource": "" }
q266652
_is_integer_like_by_dtype
test
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
python
{ "resource": "" }
q266653
embed_check_categorical_event_shape
test
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...
python
{ "resource": "" }
q266654
log_combinations
test
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...
python
{ "resource": "" }
q266655
rotate_transpose
test
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...
python
{ "resource": "" }
q266656
pick_vector
test
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....
python
{ "resource": "" }
q266657
prefer_static_broadcast_shape
test
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: ...
python
{ "resource": "" }
q266658
gen_new_seed
test
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
python
{ "resource": "" }
q266659
tridiag
test
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., ...
python
{ "resource": "" }
q266660
dimension_size
test
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 ...
python
{ "resource": "" }
q266661
process_quadrature_grid_and_probs
test
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...
python
{ "resource": "" }
q266662
parent_frame_arguments
test
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...
python
{ "resource": "" }
q266663
expand_to_vector
test
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]`....
python
{ "resource": "" }
q266664
with_dependencies
test
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 ...
python
{ "resource": "" }
q266665
_maybe_validate_rightmost_transposed_ndims
test
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...
python
{ "resource": "" }
q266666
_maybe_validate_perm
test
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...
python
{ "resource": "" }
q266667
Transpose._event_shape
test
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...
python
{ "resource": "" }
q266668
concatenate
test
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...
python
{ "resource": "" }
q266669
dims
test
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...
python
{ "resource": "" }
q266670
merge_with
test
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...
python
{ "resource": "" }
q266671
with_rank_at_least
test
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...
python
{ "resource": "" }
q266672
_check_equal_shape
test
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_...
python
{ "resource": "" }
q266673
_augment_sample_shape
test
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...
python
{ "resource": "" }
q266674
build_backward_pass_step
test
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...
python
{ "resource": "" }
q266675
backward_smoothing_update
test
def backward_smoothing_update(filtered_mean, filtered_cov, predicted_mean, predicted_cov, next_posterior_mean, next_posterior_cov, transitio...
python
{ "resource": "" }
q266676
build_kalman_filter_step
test
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...
python
{ "resource": "" }
q266677
linear_gaussian_update
test
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`, ...
python
{ "resource": "" }
q266678
kalman_transition
test
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, ...
python
{ "resource": "" }
q266679
build_kalman_mean_step
test
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...
python
{ "resource": "" }
q266680
build_kalman_cov_step
test
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...
python
{ "resource": "" }
q266681
build_kalman_sample_step
test
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, ...
python
{ "resource": "" }
q266682
_propagate_mean
test
def _propagate_mean(mean, linop, dist): """Propagate a mean through linear Gaussian transformation.""" return linop.matmul(mean) + dist.mean()[..., tf.newaxis]
python
{ "resource": "" }
q266683
_propagate_cov
test
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()
python
{ "resource": "" }
q266684
LinearGaussianStateSpaceModel.backward_smoothing_pass
test
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...
python
{ "resource": "" }
q266685
LinearGaussianStateSpaceModel._joint_sample_n
test
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...
python
{ "resource": "" }
q266686
LinearGaussianStateSpaceModel.posterior_marginals
test
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. ...
python
{ "resource": "" }
q266687
LinearGaussianStateSpaceModel._joint_mean
test
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`,...
python
{ "resource": "" }
q266688
LinearGaussianStateSpaceModel._joint_covariances
test
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...
python
{ "resource": "" }
q266689
LinearGaussianStateSpaceModel.latents_to_observations
test
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...
python
{ "resource": "" }
q266690
VonMisesFisher._log_normalization
test
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...
python
{ "resource": "" }
q266691
VonMisesFisher._mode
test
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])
python
{ "resource": "" }
q266692
VonMisesFisher._rotate
test
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...
python
{ "resource": "" }
q266693
VonMisesFisher._sample_3d
test
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...
python
{ "resource": "" }
q266694
_copy_fn
test
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...
python
{ "resource": "" }
q266695
_remove_dict_keys_with_value
test
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}
python
{ "resource": "" }
q266696
_recursively_replace_dict_for_pretty_dict
test
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)...
python
{ "resource": "" }
q266697
_get_samples
test
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...
python
{ "resource": "" }
q266698
is_namedtuple_like
test
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
python
{ "resource": "" }
q266699
_choose_base_case
test
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....
python
{ "resource": "" }