_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
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 objective values at the simplex. Args: objective_function: A Python callable that accepts a point as a real `Tensor` and returns a `Tensor` of real dtype containing the value of the function at that point. The function to be evaluated at the simplex. If `batch_evaluate_objective` is `True`, the callable may be evaluated on a `Tensor` of shape `[n+1] + s ` where `n` is the dimension of the problem and `s` is the shape of a single point in the domain (so `n` is the size of a `Tensor` representing a single point). In this case, the expected return value is a `Tensor` of shape `[n+1]`. initial_simplex: None or `Tensor` of real dtype. The initial simplex to start the search. If supplied, should be a `Tensor` of shape `[n+1] + s` where `n` is the dimension of the problem and `s` is the shape of a single point in the domain. Each row (i.e. the `Tensor` with a given value of the first index) is interpreted as a vertex of a simplex and hence the rows must be affinely independent. If not supplied, an axes aligned simplex is constructed using the `initial_vertex` and `step_sizes`. Only one and at least one of `initial_simplex` and `initial_vertex` must be supplied. initial_vertex: None or `Tensor` of real dtype and any shape that can be consumed by the `objective_function`. A single point in the domain that will be used to construct an axes aligned initial simplex. step_sizes: None or `Tensor` of real dtype and shape broadcasting compatible with `initial_vertex`. Supplies the simplex scale along each axes. Only used if `initial_simplex` is not supplied. See the docstring of `minimize` for more details. objective_at_initial_simplex: None or rank `1` `Tensor` of real dtype. The value of the objective function at the initial simplex. May be supplied only if `initial_simplex` is supplied. If not supplied, it will be computed. objective_at_initial_vertex: None or scalar `Tensor` of real dtype. The value of the objective function at the initial vertex. May be supplied only if the `initial_vertex` is also supplied. batch_evaluate_objective: Python `bool`. If True, the objective function will be evaluated on all the vertices of the simplex packed into a single tensor. If False, the objective will be mapped across each vertex separately. Returns: prepared_args: A tuple containing the following elements: dimension: Scalar `Tensor` of `int32` dtype. The dimension of the problem as inferred from the supplied arguments. num_vertices: Scalar `Tensor` of `int32` dtype. The number of vertices in the simplex. simplex: A `Tensor` of same dtype as `initial_simplex` (or `initial_vertex`). The first component of the shape of the `Tensor` is `num_vertices` and each element represents a vertex of the simplex. objective_at_simplex: A `Tensor` of same dtype as the dtype of the return value of objective_function. The shape
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.""" initial_simplex = tf.convert_to_tensor(value=initial_simplex) # If d is the dimension of the problem, the number of vertices in the #
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 axes aligned simplex.""" dim = tf.size(input=initial_vertex) num_vertices = dim + 1 unit_vectors_along_axes = tf.reshape( tf.eye(dim, dim, dtype=initial_vertex.dtype.base_dtype), tf.concat([[dim], tf.shape(input=initial_vertex)], axis=0)) # If step_sizes does not broadcast to initial_vertex, the multiplication # in the second term will fail. simplex_face = initial_vertex + step_sizes * unit_vectors_along_axes simplex = tf.concat([tf.expand_dims(initial_vertex, axis=0), simplex_face], axis=0) num_evaluations = 0 # Evaluate the objective function at the simplex vertices. if objective_at_initial_vertex
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 `arg_batch`. Args: objective_function: A Python callable that accepts a single `Tensor` of rank 'R > 1' and any shape 's' and returns a scalar `Tensor` of real dtype containing the value of the function at that point. If `batch a `Tensor` of shape `[batch_size] + s ` where `batch_size` is the size of the batch of args. In this case, the expected return value is a `Tensor` of shape `[batch_size]`. arg_batch: A `Tensor` of real dtype. The batch of arguments at which to evaluate the `objective_function`. If `batch_evaluate_objective` is False, `arg_batch` will be unpacked along the zeroth axis and the `objective_function` will be applied to
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 posterior means of weight varibles. qs_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 `float`-like Numpy array of shape `[num_monte_carlo, num_heldout, num_classes]` containing Monte Carlo samples of class probabilities for each heldout sample. fname: Python `str` filename to save the plot to. n: Python `int` number of datapoints to vizualize. title: Python `str` title for the plot. """ fig = figure.Figure(figsize=(9, 3*n)) canvas = backend_agg.FigureCanvasAgg(fig) for i in range(n): ax = fig.add_subplot(n, 3, 3*i + 1) ax.imshow(input_vals[i, :].reshape(IMAGE_SHAPE[:-1]), interpolation="None") ax = fig.add_subplot(n, 3, 3*i + 2) for
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.int32(np.random.permutation( np.arange(num_examples))) mnist_data.train.num_examples = num_examples mnist_data.validation
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(
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)
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('Numpy backend
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) ], -1)) df = _broadcast_to_shape(df, tf.shape(input=statistic)) # We need to put the tf.where inside the outer tf.where to ensure we never # hit a NaN in the gradient. denom = tf.where(df > 2., df - 2., tf.ones_like(df)) statistic = statistic * df_factor_fn(df / denom) # When 1 < df <= 2, stddev/variance are infinite. inf = dtype_util.as_numpy_dtype(self.dtype)(np.inf) result_where_defined = tf.where( df > 2., statistic, tf.fill(tf.shape(input=statistic), inf, name="inf")) if self.allow_nan_stats: nan = dtype_util.as_numpy_dtype(self.dtype)(np.nan)
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 precisely, a `tf.Variable`, `log_mean_exp_var`, is updated by `log_value` using the following identity: ```none log_mean_exp_var = = log(decay exp(log_mean_exp_var) + (1 - decay) exp(log_value)) = log(exp(log_mean_exp_var + log(decay)) + exp(log_value + log1p(-decay))) = log_mean_exp_var + log( exp(log_mean_exp_var - log_mean_exp_var + log(decay)) + exp(log_value - log_mean_exp_var + log1p(-decay))) = log_mean_exp_var + log_sum_exp([log(decay), log_value - log_mean_exp_var + log1p(-decay)]). ``` In addition to numerical stability, this formulation is advantageous because `log_mean_exp_var` can be updated in a lock-free manner, i.e., using `assign_add`. (Note: the updates are not thread-safe; it's just that the update to the tf.Variable is presumed efficient due to being lock-free.) Args: log_mean_exp_var: `float`-like `Variable` representing the log of the exponentially weighted moving mean of the exp. Same shape as `log_value`. log_value: `float`-like `Tensor` representing a new (streaming) observation. Same shape as `log_mean_exp_var`. decay: A `float`-like `Tensor`. The moving mean decay. Typically close to `1.`, e.g., `0.999`. name: Optional name of the returned operation. Returns: log_mean_exp_var: A reference to the input 'Variable' tensor with the `log_value`-updated log of the exponentially weighted moving mean of exp. Raises: TypeError: if `log_mean_exp_var` does not have float type `dtype`. TypeError: if `log_mean_exp_var`, `log_value`, `decay` have different `base_dtype`. """ with tf.compat.v1.name_scope(name, "assign_log_moving_mean_exp",
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`. Returns:
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` representing shape of output. dtype: (Optional) TF `dtype` representing `dtype` of output. seed: (Optional) Python integer to seed the random number generator. name: Python `str` name prefixed to Ops created by this function. Default value: `None` (i.e., 'random_rademacher'). Returns: rademacher: `Tensor` with specified `shape` and `dtype` consisting of `-1` or `+1` chosen uniformly-at-random. """ with tf.compat.v1.name_scope(name, 'random_rademacher', [shape, seed]): # Choose the dtype to cause `2 * random_bernoulli - 1` to run in the same
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) ``` For more details, see [Rayleigh distribution]( https://en.wikipedia.org/wiki/Rayleigh_distribution) Args: shape: Vector-shaped, `int` `Tensor` representing shape of output. scale: (Optional) Positive `float` `Tensor` representing `Rayleigh` scale. Default value: `None` (i.e., `scale = 1.`). dtype: (Optional) TF `dtype` representing `dtype` of output. Default value: `tf.float32`. seed: (Optional) Python integer to seed the random number generator. Default value: `None` (i.e., no seed). name: Python `str` name prefixed to Ops created by this function. Default value: `None` (i.e., 'random_rayleigh'). Returns: rayleigh:
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
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_kwargs) if self._is_maybe_event_override: log_prob = tf.reduce_sum( input_tensor=log_prob, axis=self._reduce_event_indices) log_prob += tf.cast(ildj, log_prob.dtype)
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)
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
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. Args: x: Input `Tensor` of arbitrary dimensionality. mean: A mean `Tensor`. variance: A variance `Tensor`. offset: An offset `Tensor`, often denoted `beta` in equations, or None. If present, will be added to the normalized tensor. scale: A scale `Tensor`, often denoted `gamma` in equations, or `None`. If present, the scale is applied to the normalized tensor. variance_epsilon: A small `float` added to the minibatch `variance` to prevent dividing by zero. name: A name for this operation (optional). Returns: batch_unnormalized: The de-normalized, de-scaled,
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 `batchnorm_layer.virtual_batch_size` is specified. """ if (not isinstance(layer, tf.keras.layers.BatchNormalization) and not isinstance(layer, tf.compat.v1.layers.BatchNormalization)): raise ValueError(
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. dist_batch_shape: The distribution's batch shape `Tensor`. Returns: new_param: A `Tensor`, batch-sliced according to slices. """ # Extend param shape with ones on the left to match dist_batch_shape. param_shape = tf.shape(input=param) insert_ones = tf.ones( [tf.size(input=dist_batch_shape) + param_event_ndims - tf.rank(param)], dtype=param_shape.dtype) new_param_shape = tf.concat([insert_ones, param_shape], axis=0) full_batch_param = tf.reshape(param, new_param_shape) param_slices = [] # We separately track the batch axis from the parameter axis because we want # them to align for positive indexing, and be offset by param_event_ndims for # negative indexing. param_dim_idx = 0 batch_dim_idx = 0 for slc in slices: if slc is tf.newaxis: param_slices.append(slc) continue if slc is Ellipsis: if batch_dim_idx < 0: raise ValueError('Found multiple `...` in slices {}'.format(slices)) param_slices.append(slc) # Switch over to negative indexing for the broadcast check. num_remaining_non_newaxis_slices = sum( [s is not tf.newaxis for s in slices[slices.index(Ellipsis) + 1:]]) batch_dim_idx = -num_remaining_non_newaxis_slices param_dim_idx = batch_dim_idx - param_event_ndims
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: overrides: `str->Tensor` `dict` of batch-sliced parameter overrides. """ override_dict = {} for param_name, param_event_ndims in six.iteritems(params_event_ndims): # Verify that either None or a legit value is in the parameters dict. if param_name not in dist.parameters: raise ValueError('Distribution {} is missing advertised '
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:
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
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 parameterize a single event. params_overrides: A `dict` of parameter overrides. (e.g. from `Distribution.copy`). slices: A `slice` or `int` or `int` `Tensor` or `tf.newaxis` or `tuple` thereof. (e.g. the argument of a
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=None): """Runs multiple Fisher scoring steps. Args: model_matrix: (Batch of) `float`-like, matrix-shaped `Tensor` where each row represents a sample's features. response: (Batch of) vector-shaped `Tensor` where each element represents a sample's observed response (to the corresponding row of features). Must have same `dtype` as `model_matrix`. model: `tfp.glm.ExponentialFamily`-like instance which implicitly characterizes a negative log-likelihood loss by specifying the distribuion's `mean`, `gradient_mean`, and `variance`. model_coefficients_start: Optional (batch of) vector-shaped `Tensor` representing the initial model coefficients, one for each column in `model_matrix`. Must have same `dtype` as `model_matrix`. Default value: Zeros. predicted_linear_response_start: Optional `Tensor` with `shape`, `dtype` matching `response`; represents `offset` shifted initial linear predictions based on `model_coefficients_start`. Default value: `offset` if `model_coefficients is None`, and `tf.linalg.matvec(model_matrix, model_coefficients_start) + offset` otherwise. l2_regularizer: Optional scalar `Tensor` representing L2 regularization penalty, i.e., `loss(w) = sum{-log p(y[i]|x[i],w) : i=1..n} + l2_regularizer ||w||_2^2`. Default value: `None` (i.e., no L2 regularization). dispersion: Optional (batch of) `Tensor` representing `response` dispersion, i.e., as in, `p(y|theta) := exp((y theta - A(theta)) / dispersion)`. Must broadcast with rows of `model_matrix`. Default value: `None` (i.e., "no dispersion"). offset: Optional `Tensor` representing constant shift applied to `predicted_linear_response`. Must broadcast to `response`. Default value: `None` (i.e., `tf.zeros_like(response)`). convergence_criteria_fn: Python `callable` taking: `is_converged_previous`, `iter_`, `model_coefficients_previous`, `predicted_linear_response_previous`, `model_coefficients_next`, `predicted_linear_response_next`, `response`, `model`, `dispersion` and returning a `bool` `Tensor` indicating that Fisher scoring has converged. See `convergence_criteria_small_relative_norm_weights_change` as an example function. Default value: `None` (i.e., `convergence_criteria_small_relative_norm_weights_change`). learning_rate: Optional (batch of) scalar `Tensor` used to dampen iterative progress. Typically only needed if optimization diverges, should be no larger than `1` and typically very close to `1`. Default value: `None` (i.e., `1`). fast_unsafe_numerics: Optional Python `bool` indicating if faster, less numerically accurate methods can be employed for computing the weighted least-squares solution. Default value: `True` (i.e., "fast but possibly diminished accuracy"). maximum_iterations: Optional maximum number of iterations of Fisher scoring to run; "and-ed" with result of `convergence_criteria_fn`. Default value: `None` (i.e., `infinity`). name: Python `str` used as name prefix to ops created by this function. Default value: `"fit"`. Returns: model_coefficients: (Batch of) vector-shaped `Tensor`; represents the fitted model coefficients, one for each column in `model_matrix`. predicted_linear_response: `response`-shaped `Tensor`
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.norm(w0 - w1, ord=2, axis=-1) / (1. + tf.norm(w0, ord=2, axis=-1))) reduce_all(relative_euclidean_norm < tolerance) ``` where `tf.norm(x, ord=2)` denotes the [Euclidean norm]( https://en.wikipedia.org/wiki/Norm_(mathematics)#Euclidean_norm) of `x`. Args: tolerance: `float`-like `Tensor` indicating convergence, i.e., when max relative Euclidean norm weights difference < tolerance`. Default value: `1e-5`. norm_order: Order of the norm. Default value: `2` (i.e., "Euclidean norm".) Returns: convergence_criteria_fn: Python `callable` which returns `bool` `Tensor` indicated fitting procedure has converged. (See inner function specification for argument signature.) Default value: `1e-5`. """ def convergence_criteria_fn( is_converged_previous, # pylint: disable=unused-argument iter_, model_coefficients_previous, predicted_linear_response_previous, # pylint: disable=unused-argument model_coefficients_next, predicted_linear_response_next, # pylint: disable=unused-argument response, # pylint: disable=unused-argument model, # pylint: disable=unused-argument dispersion): # pylint: disable=unused-argument """Returns `bool` `Tensor` indicating if fitting procedure has converged. Args: is_converged_previous: "old" convergence results. iter_: Iteration number. model_coefficients_previous: "old" `model_coefficients`. predicted_linear_response_previous: "old" `predicted_linear_response`. model_coefficients_next: "new" `model_coefficients`. predicted_linear_response_next: "new: `predicted_linear_response`. response: (Batch of) vector-shaped `Tensor` where each element represents
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` where each row represents a sample's features. response: (Batch of) vector-shaped `Tensor` where each element represents a sample's observed response (to the corresponding row of features). Must have same `dtype` as `model_matrix`. model_coefficients: Optional (batch of) vector-shaped `Tensor` representing the model coefficients, one for each column in `model_matrix`. Must have same `dtype` as `model_matrix`. Default value: `tf.zeros(tf.shape(model_matrix)[-1], model_matrix.dtype)`. predicted_linear_response: Optional `Tensor` with `shape`, `dtype` matching `response`; represents `offset` shifted initial linear predictions based on current `model_coefficients`. Default value: `offset` if `model_coefficients is None`, and `tf.linalg.matvec(model_matrix, model_coefficients_start) + offset` otherwise. offset: Optional `Tensor` with `shape`, `dtype` matching `response`; represents constant shift applied to `predicted_linear_response`. Default value: `None` (i.e., `tf.zeros_like(response)`). name: Python `str` used as name prefix to ops created by this function. Default value: `"prepare_args"`. Returns: model_matrix: A `Tensor` with `shape`, `dtype` and values of the `model_matrix` argument. response: A `Tensor` with `shape`, `dtype` and values of the `response` argument. model_coefficients_start: A `Tensor` with `shape`, `dtype` and values of the `model_coefficients_start` argument if specified. A (batch of) vector-shaped `Tensors` with `dtype` matching `model_matrix`
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])
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 match: original={}, static={}, fn={}'.format( original_spec, static_spec, original_fn)) @decorator.decorator
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(pred)
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.shape, 'num_elements')): ndims_ = tensorshape_util.num_elements(shape_tensor.shape) else: ndims_ = len(shape_tensor) ndims_fn = lambda: tf.size(input=shape_tensor) else:
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 functions like tf.case. Args: pred_fn_pairs: Dict or list of pairs of a boolean scalar tensor and a callable which returns a list of tensors. default: Optional callable that returns a list of tensors. exclusive: True iff at most one predicate is allowed to evaluate to `True`. name: A name for this operation (optional). Returns: The tensors returned by the first pair whose predicate evaluated to True, or those returned by `default` if none does. Raises:
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):
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 tensor with shape [batch_size, num_components] mean_vector: A 2D tensor of mixture component means. Has shape `[batch_size, num_components]`. stddev_vector: A 2D tensor of mixture component standard deviations. Has shape `[batch_size, num_components]`. Returns: A 1D tensor of shape `[batch_size]` representing the standard deviation of the mixture distribution with given weights and component means and standard deviations. Raises: ValueError: If the shapes of the input tensors are not as expected. """ tensorshape_util.assert_has_rank(mixture_weight_vector.shape, 2) if not tensorshape_util.is_compatible_with(mean_vector.shape, mixture_weight_vector.shape): raise ValueError("Expecting means to have same shape as mixture weights.") if not tensorshape_util.is_compatible_with(stddev_vector.shape, mixture_weight_vector.shape): raise ValueError("Expecting stddevs to have same shape as mixture weights.") # Reshape the distribution parameters for batched vectorized dot products.
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): """Creates a LinearOperator representing a lower triangular matrix. Args: loc: Floating-point `Tensor`. This is used for inferring shape in the case where only `scale_identity_multiplier` is set. scale_tril: Floating-point `Tensor` representing the diagonal matrix. `scale_diag` has shape [N1, N2, ... k, k], which represents a k x k lower triangular matrix. When `None` no `scale_tril` term is added to the LinearOperator. The upper triangular elements above the diagonal are ignored. scale_diag: Floating-point `Tensor` representing the diagonal matrix. `scale_diag` has shape [N1, N2, ... k], which represents a k x k diagonal matrix. When `None` no diagonal term is added to the LinearOperator. scale_identity_multiplier: floating point rank 0 `Tensor` representing a scaling done to the identity matrix. When `scale_identity_multiplier = scale_diag = scale_tril = None` then `scale += IdentityMatrix`. Otherwise no scaled-identity-matrix is added to `scale`. shape_hint: scalar integer `Tensor` representing a hint at the dimension of the identity matrix when only `scale_identity_multiplier` is set. validate_args: Python `bool` indicating whether arguments should be checked for correctness.
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 LinearOperator representing a diagonal matrix. Args: loc: Floating-point `Tensor`. This is used for inferring shape in the case where only `scale_identity_multiplier` is set. scale_diag: Floating-point `Tensor` representing the diagonal matrix. `scale_diag` has shape [N1, N2, ... k], which represents a k x k diagonal matrix. When `None` no diagonal term is added to the LinearOperator. scale_identity_multiplier: floating point rank 0 `Tensor` representing a scaling done to the identity matrix. When `scale_identity_multiplier = scale_diag = scale_tril = None` then `scale += IdentityMatrix`. Otherwise no scaled-identity-matrix is added to `scale`. shape_hint: scalar integer `Tensor` representing a hint at the dimension of the identity matrix when only `scale_identity_multiplier` is set. validate_args: Python `bool` indicating whether arguments should be checked for correctness. assert_positive: Python `bool` indicating whether LinearOperator should be checked for being positive definite. name: Python `str` name given to ops managed by this object. dtype: TF `DType` to prefer when converting args to `Tensor`s. Else, we fall back to a compatible dtype across all of `loc`, `scale_diag`, and `scale_identity_multiplier`. Returns:
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 if possible. Batch shape broadcasts as per the normal rules. We allow the `loc` event shape to broadcast up to that of `scale`. We do not allow `scale`'s event shape to change. Therefore, the last dimension of `loc` must either be size `1`, or the same as `scale.range_dimension`. See `MultivariateNormalLinearOperator` for a usage example. Args: loc: `Tensor` (already converted to tensor) or `None`. If `None`, or `rank(loc)==0`, both batch and event shape are determined by `scale`. scale: A `LinearOperator` instance. name: A string name to prepend to created ops. Returns: batch_shape: `TensorShape` (if broadcast is done statically), or `Tensor`. event_shape: `TensorShape` (if broadcast is done statically), or `Tensor`. Raises: ValueError: If the last dimension of `loc` is determined statically to be different than the range of `scale`. """ if loc is not None and tensorshape_util.rank(loc.shape) == 0: loc = None # scalar loc is irrelevant to determining batch/event shape. with tf.name_scope(name): # Get event shape. event_size = scale.range_dimension_tensor() event_size_ = tf.get_static_value(event_size) loc_event_size_ = (None if loc is None else tf.compat.dimension_value(loc.shape[-1])) if event_size_ is not None and loc_event_size_ is not None: # Static check that event shapes match. if loc_event_size_ != 1 and loc_event_size_ != event_size_: raise ValueError(
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): raise TypeError("Expected argument 'scale' to be instance of LinearOperator"
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` * `distribution` has expected dtype. Args: distribution: `Distribution`-like object. expected_base_dtype: `TensorFlow` `dtype`. validate_args: Python `bool`. Whether to do additional checks: (i) check that reparameterization_type is `FULLY_REPARAMETERIZED`. (ii) add `tf.Assert` ops to the graph to enforce that distribution is scalar in the event that this cannot be determined statically. Returns: List of `tf.Assert` ops to run to enforce validity checks that could not be statically determined. Empty if `not validate_args`. Raises: ValueError: If validate_args and distribution is not FULLY_REPARAMETERIZED ValueError: If distribution is statically determined to not have both scalar batch and scalar event shapes. """ if distribution.dtype != expected_base_dtype: raise TypeError("dtype mismatch; " "distribution.dtype=\"{}\" is not \"{}\"".format( dtype_util.name(distribution.dtype), dtype_util.name(expected_base_dtype))) # Although `reparameterization_type` is a static property, we guard it by # `validate_args`. This allows users to use a `distribution` which is not # reparameterized itself. However, we tacitly assume that although the # distribution is not reparameterized, it only depends on non-trainable # variables. if validate_args and (distribution.reparameterization_type !=
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_distribution: Base distribution of the mixture. categorical_distribution: `Categorical` distribution that mixes the base distribution. event_ndims: Integer specifying the number of event dimensions in the event tensor. Returns: A padded version of `x`
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 place of `tf.cond` when both branches yield a `Tensor` of the same shape; the operational difference is that `tf.cond` uses control flow to evaluate only the branch that's needed, while `tf.where` (and thus this method) may evaluate both branches before the predicate's truth is known. This means that `tf.cond` is preferred when one of the branches is expensive to evaluate (like performing a large matmul), while this method is preferred when both branches are cheap, e.g., constants. In the latter case, we expect
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 supported). dest_idx: Integer index into `x.shape` (negative indexing is supported). Returns: x_perm: Tensor of rank `ndims`, in which the dimension at original index `source_idx` has been moved to new index `dest_idx`, with all other dimensions retained in their original order. Example: ```python x = tf.placeholder(shape=[200, 30, 4, 1, 6]) x_perm = _move_dimension(x, 1, 1) # no-op x_perm = _move_dimension(x, 0, 3) # result shape [30, 4, 1, 200, 6] x_perm = _move_dimension(x, 0, -2) # equivalent to previous x_perm = _move_dimension(x, 4, 2) # result shape [200, 30, 6, 4, 1] ``` """ ndims = prefer_static_rank(x) dtype = dtype_util.common_dtype([source_idx, dest_idx], preferred_dtype=tf.int32) source_idx = tf.convert_to_tensor(value=source_idx, dtype=dtype) dest_idx = tf.convert_to_tensor(value=dest_idx, dtype=dtype) # Handle negative indexing. source_idx = pick_scalar_condition(source_idx < 0, ndims + source_idx, source_idx) dest_idx = pick_scalar_condition(dest_idx < 0, ndims + dest_idx, dest_idx) # Construct the appropriate permutation of dimensions, depending # whether the source is before or after the destination. def move_left_permutation(): return prefer_static_value( tf.concat([
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, message="'{}' must be non-negative.".format(x)), ]
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 we can't just do tf.equal(a.shape, b.shape), since # static
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 cast to. Returns: Statically inferred value if possible, otherwise None. """
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,
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,
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.iinfo(dt.as_numpy_dtype).max
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))
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):
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(probs)`. Since distributions output samples in the same dtype as the parameters, we must ensure that casting doesn't lose precision. That is, the `parameter.dtype` implies a maximum number of classes. However, since shape is `int32` and categorical variables are presumed to be indexes into a `Tensor`, we must also ensure that the number of classes is no larger than the largest possible `int32` index, i.e., `2**31-1`. In other words the number of classes, `K`, must satisfy the following condition: ```python K <= min( int(2**31 - 1), # Largest float as an index. { tf.float16: int(2**11), # Largest int as a float16. tf.float32: int(2**24), tf.float64: int(2**53), }.get(dtype_util.base_dtype(categorical_param.dtype), 0)) ``` Args: categorical_param: Floating-point `Tensor` representing parameters of distribution over categories. The rightmost shape is presumed to be the number of categories. name: A name for this operation (optional). Returns: categorical_param: Input `Tensor` with appropriate assertions embedded. Raises: TypeError: if `categorical_param` has an unknown `dtype`. ValueError: if we can statically identify `categorical_param` as being too large (for being closed under int32/float casting). """ with tf.name_scope(name): x = tf.convert_to_tensor(value=categorical_param, name="categorical_param") # The size must not exceed
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 with `counts`. This represents `n` outcomes. counts: Floating-point `Tensor` broadcastable with `n`. This represents counts in `k` classes, where `k` is the last dimension of the tensor. name: A name for this operation (optional). Returns: `Tensor` representing the multinomial coefficient between `n` and `counts`. """ # First a bit about the number of ways counts could have come in: # E.g. if counts = [1, 2], then this is 3 choose 2. # In general, this is (sum counts)! / sum(counts!) # The sum should be along the last
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 data from to GPU to CPU. Example: ```python x = tf.random_normal([1, 2, 3, 4]) # Tensor of shape [1, 2, 3, 4]. rotate_transpose(x, -1).shape == [2, 3, 4, 1] rotate_transpose(x, -2).shape == [3, 4, 1, 2] rotate_transpose(x, 1).shape == [4, 1, 2, 3] rotate_transpose(x, 2).shape == [3, 4, 1, 2] rotate_transpose(x, 7).shape == rotate_transpose(x, 3).shape # [2, 3, 4, 1] rotate_transpose(x, -7).shape == rotate_transpose(x, -3).shape # [4, 1, 2, 3] ``` Args: x: `Tensor`. shift: `Tensor`. Number of dimensions to transpose left (shift<0) or transpose right (shift>0). name: Python `str`. The name to give this op. Returns: rotated_x: Input `Tensor` with dimensions circularly rotated by shift. Raises: TypeError: if shift is not integer type. """ with tf.name_scope(name): x = tf.convert_to_tensor(value=x, name="x") shift = tf.convert_to_tensor(value=shift, name="shift") # We do not assign back to preserve constant-ness. assert_util.assert_integer(shift) shift_value_static = tf.get_static_value(shift) ndims = tensorshape_util.rank(x.shape) if ndims is not None and shift_value_static is not None: if ndims < 2: return x shift_value_static = np.sign(shift_value_static) * ( abs(shift_value_static) % ndims) if shift_value_static == 0: return x perm = np.roll(np.arange(ndims), shift_value_static)
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., no graph nodes are created and no validation happens. Args: cond: `Tensor`. Must have `dtype=tf.bool` and be scalar. true_vector: `Tensor` of one dimension. Returned when cond is `True`. false_vector: `Tensor` of one dimension. Returned when cond is `False`. name: Python `str`. The name to give this op. Example: ```python pick_vector(tf.less(0, 5), tf.range(10, 12), tf.range(15, 18)) # [10, 11] pick_vector(tf.less(5, 0), tf.range(10, 12), tf.range(15, 18))
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: `1-D` integer `Tensor`. Already converted to tensor! name: A string name to prepend to created ops. Returns: The broadcast shape, either as `TensorShape` (if broadcast can be done statically), or as a `Tensor`. """ with tf.name_scope(name): def make_shape_tensor(x): return tf.convert_to_tensor(value=x, name="shape", dtype=tf.int32) def get_tensor_shape(s): if isinstance(s, tf.TensorShape): return s s_ = tf.get_static_value(make_shape_tensor(s)) if s_ is not None: return tf.TensorShape(s_) return None
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
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., 9., 0.], # [ 0., 2., 6., 10.], # [ 0., 0., 3., 7.]], dtype=float32) ``` Warning: This Op is intended for convenience, not efficiency. Args: below: `Tensor` of shape `[B1, ..., Bb, d-1]` corresponding to the below diagonal part. `None` is logically equivalent to `below = 0`. diag: `Tensor` of shape `[B1, ..., Bb, d]` corresponding to the diagonal part. `None` is logically equivalent to `diag = 0`. above: `Tensor` of shape `[B1, ..., Bb, d-1]` corresponding to the above diagonal part. `None` is logically equivalent to `above = 0`. name: Python `str`. The name to give this op. Returns: tridiag: `Tensor` with values set above, below and on the diagonal. Raises: ValueError: if all inputs are `None`. """ def _pad(x): """Prepends and appends a zero to every vector in a batch of vectors.""" shape = tf.concat([tf.shape(input=x)[:-1], [1]], axis=0) z = tf.zeros(shape, dtype=x.dtype) return tf.concat([z, x, z], axis=-1) def _add(*x): """Adds list of Tensors, ignoring `None`.""" s = None for y in x: if y is None:
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(
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 pair of `float`-like `Tensor`s representing the sample points and the corresponding (possibly normalized) weight. When `None`, defaults to: `np.polynomial.hermite.hermgauss(deg=8)`. dtype: The expected `dtype` of `grid` and `probs`. validate_args: Python `bool`, default `False`. When `True` distribution parameters are checked for validity despite possibly degrading runtime performance. When `False` invalid inputs may silently render incorrect outputs. name: Python `str` name prefixed to Ops created by this class. Returns: quadrature_grid_and_probs: Python pair of `float`-like `Tensor`s representing the sample points and the corresponding (possibly normalized) weight. Raises: ValueError: if `quadrature_grid_and_probs is not None` and `len(quadrature_grid_and_probs[0]) != len(quadrature_grid_and_probs[1])` """ with tf.name_scope(name or "process_quadrature_grid_and_probs"): if quadrature_grid_and_probs is None: grid, probs = np.polynomial.hermite.hermgauss(deg=8) grid = grid.astype(dtype_util.as_numpy_dtype(dtype)) probs = probs.astype(dtype_util.as_numpy_dtype(dtype)) probs /= np.linalg.norm(probs, ord=1, keepdims=True) grid = tf.convert_to_tensor(value=grid, name="grid", dtype=dtype) probs = tf.convert_to_tensor(value=probs, name="probs", dtype=dtype) return grid, probs grid, probs = tuple(quadrature_grid_and_probs) grid = tf.convert_to_tensor(value=grid, name="grid", dtype=dtype) probs = tf.convert_to_tensor( value=probs, name="unnormalized_probs", dtype=dtype) probs /= tf.norm(tensor=probs, ord=1, axis=-1, keepdims=True, name="probs") def _static_event_size(x):
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 return an empty dictionary, since there are no arguments. WARNING: If caller function argument names are overloaded before invoking this method, then values will reflect the overloaded value. For this reason, we recommend calling `parent_frame_arguments` at the beginning of the function. """ # All arguments and the names used for *varargs, and **kwargs arg_names, variable_arg_name, keyword_arg_name, local_vars = ( tf_inspect._inspect.getargvalues( # pylint: disable=protected-access # Get the first frame of the caller of this method. tf_inspect._inspect.stack()[1][0]))
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]`. This function can be used to transform such an argument to always be 1-D. NOTE: Python or NumPy values will be converted to `Tensor`s with standard type inference/conversion. In particular, an empty list or tuple will become an empty `Tensor` with dtype `float32`. Callers should convert values to `Tensor`s before calling this function if different behavior is desired (e.g. converting empty lists / other values to `Tensor`s with dtype `int32`). Args: x: A 0-D or 1-D `Tensor`. tensor_name: Python `str` name for `Tensor`s created by this function. op_name: Python `str` name for `Op`s created by this function. validate_args: Python `bool, default `False`. When `True`, arguments may be checked for validity at execution time, possibly degrading runtime performance. When `False`, invalid inputs may silently render incorrect outputs. Returns: vector: a 1-D `Tensor`. """ with tf.name_scope(op_name or "expand_to_vector"): x = tf.convert_to_tensor(value=x, name="x") ndims = tensorshape_util.rank(x.shape) if ndims is None: # Maybe expand ndims from 0 to 1. if validate_args: x = with_dependencies([
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 only after all operations in `dependencies` have run. Note that this means that there is no guarantee that `output_tensor` will be evaluated after any `dependencies` have run. See also `tf.tuple` and `tf.group`. Args: dependencies: Iterable of operations to run before this op finishes. output_tensor: A `Tensor` or `IndexedSlices` that will be returned. name: (Optional) A name for this operation. Returns: output_with_deps: Same as `output_tensor` but with embedded dependencies. Raises: TypeError: if `output_tensor` is not a `Tensor` or `IndexedSlices`. """ if tf.executing_eagerly():
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.dtype): raise TypeError('`rightmost_transposed_ndims` must be integer type.') if tensorshape_util.rank(rightmost_transposed_ndims.shape) is not None: if tensorshape_util.rank(rightmost_transposed_ndims.shape) != 0: raise ValueError('`rightmost_transposed_ndims` must be a scalar, '
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 tensorshape_util.rank(perm.shape) is not None: if tensorshape_util.rank(perm.shape) != 1: raise ValueError( msg[:-1] + ', saw rank: {}.'.format(tensorshape_util.rank(perm.shape))) elif validate_args: assertions += [assert_util.assert_rank(perm, 1, message=msg)] perm_ = tf.get_static_value(perm) msg = '`perm` must be a valid permutation vector.' if
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) < rightmost_: raise ValueError('Invalid shape: min event ndims={} but got {}'.format( rightmost_, shape)) perm_ = tf.get_static_value(self.perm, partial=True) if perm_ is None: return shape[:tensorshape_util.rank(shape) - rightmost_].concatenate( [None] * int(rightmost_)) # We can use elimination to reidentify a single None dimension. if sum(p is None for p in perm_) == 1: present = np.argsort([-1 if p is
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. For more details, see `help(tf.TensorShape.concatenate)`. Args: x: object representing a shape; convertible to `tf.TensorShape`. other: object representing a
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 if known. A size is `tf.Dimension` if input is a `tf.TensorShape`
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 shape; convertible to `tf.TensorShape`. other: object representing a shape; convertible to `tf.TensorShape`. Returns:
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 minimum rank of `x` or else an assertion is raised. Returns: shape: a shape
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_target_shape) if tensorshape_util.is_fully_defined( static_shape) and tensorshape_util.is_fully_defined(static_target_shape): if static_shape != static_target_shape: raise ValueError("{}: required shape {} but found {}". format(name, static_target_shape, static_shape)) return None else: if dynamic_target_shape is None: if tensorshape_util.is_fully_defined(static_target_shape):
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_batch_dist` are treated as identical distributions. # partial_batch_dist.batch_shape = [ 7] # full_sample_and_batch_shape = [3, 4, 7] # => return an augmented sample shape of [3, 4] so that # partial_batch_dist.sample(augmented_sample_shape) has combined # sample and batch shape of [3, 4, 7]. Args: partial_batch_dist: `tfd.Distribution` instance with batch shape a prefix of `full_sample_and_batch_shape`. full_sample_and_batch_shape: a Tensor or Tensor-like shape. validate_args: if True, check for shape errors at runtime. Returns: augmented_sample_shape: sample shape such that `partial_batch_dist.sample(augmented_sample_shape)` has combined sample and batch shape of `full_sample_and_batch_shape`. Raises: ValueError: if `partial_batch_dist.batch_shape` has more dimensions than `full_sample_and_batch_shape`. NotImplementedError: if broadcasting would be required to make `partial_batch_dist.batch_shape` into a prefix of `full_sample_and_batch_shape` . """ full_ndims = distribution_util.prefer_static_shape( full_sample_and_batch_shape)[0] partial_batch_ndims = ( tensorshape_util.rank(partial_batch_dist.batch_shape) # pylint: disable=g-long-ternary if tensorshape_util.rank(partial_batch_dist.batch_shape) is not None else distribution_util.prefer_static_shape( partial_batch_dist.batch_shape_tensor())[0]) num_broadcast_dims = full_ndims - partial_batch_ndims expected_partial_batch_shape = ( full_sample_and_batch_shape[num_broadcast_dims:]) expected_partial_batch_shape_static = tf.get_static_value( full_sample_and_batch_shape[num_broadcast_dims:]) # Raise errors statically if possible. num_broadcast_dims_static = tf.get_static_value(num_broadcast_dims) if num_broadcast_dims_static is not None: if num_broadcast_dims_static < 0: raise ValueError("Cannot broadcast distribution {} batch shape to " "target batch shape with fewer dimensions"
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_size]`. Returns: backward_pass_step: a callable that updates a BackwardPassState from timestep `t` to `t-1`. """ def backward_pass_step(state, filtered_parameters): """Run a single step of backward smoothing.""" (filtered_mean, filtered_cov, predicted_mean, predicted_cov) = filtered_parameters transition_matrix = get_transition_matrix_for_timestep(state.timestep)
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, transition_matrix): """Backward update for a Kalman smoother. Give the `filtered_mean` mu(t | t), `filtered_cov` sigma(t | t), `predicted_mean` mu(t+1 | t) and `predicted_cov` sigma(t+1 | t), as returns from the `forward_filter` function, as well as `next_posterior_mean` mu(t+1 | 1:T) and `next_posterior_cov` sigma(t+1 | 1:T), if the `transition_matrix` of states from time t to time t+1 is given as A(t+1), the 1 step backward smoothed distribution parameter could be calculated as: p(z(t) | Obs(1:T)) = N( mu(t | 1:T), sigma(t | 1:T)), mu(t | 1:T) = mu(t | t) + J(t) * (mu(t+1 | 1:T) - mu(t+1 | t)), sigma(t | 1:T) = sigma(t | t) + J(t) * (sigma(t+1 | 1:T) - sigma(t+1 | t) * J(t)', J(t) = sigma(t | t) * A(t+1)' / sigma(t+1 | t), where all the multiplications are matrix multiplication, and `/` is the matrix inverse. J(t) is the backward Kalman gain matrix. The algorithm can be intialized from mu(T | 1:T) and sigma(T | 1:T), which are the last step parameters returned by forward_filter. Args: filtered_mean: `Tensor` with event shape `[latent_size, 1]` and batch shape `B`, containing mu(t | t). filtered_cov: `Tensor` with event shape `[latent_size, latent_size]` and batch shape `B`, containing sigma(t | t). predicted_mean: `Tensor` with event shape `[latent_size, 1]` and batch shape `B`, containing mu(t+1 | t). predicted_cov: `Tensor` with event shape `[latent_size, latent_size]` and batch shape `B`, containing sigma(t+1 | t). next_posterior_mean: `Tensor` with event shape `[latent_size, 1]` and batch shape `B`, containing mu(t+1 | 1:T). next_posterior_cov: `Tensor` with event shape `[latent_size, latent_size]` and batch shape `B`, containing sigma(t+1 | 1:T).
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 filtering. Args: get_transition_matrix_for_timestep: callable taking a timestep as an integer `Tensor` argument, and returning a `LinearOperator` of shape `[latent_size, latent_size]`. get_transition_noise_for_timestep: callable taking a timestep as an integer `Tensor` argument, and returning a `MultivariateNormalLinearOperator` of event shape `[latent_size]`. get_observation_matrix_for_timestep: callable taking a timestep as an integer `Tensor` argument, and returning a `LinearOperator` of shape `[observation_size, observation_size]`. get_observation_noise_for_timestep: callable taking a timestep as an integer `Tensor` argument, and returning a `MultivariateNormalLinearOperator` of event shape `[observation_size]`. Returns: kalman_filter_step: a callable that updates a KalmanFilterState from timestep `t-1` to `t`. """ def kalman_filter_step(state, elems_t): """Run a single step of Kalman filtering. Args: state: A `KalmanFilterState` object representing the previous filter state at time `t-1`. elems_t: A tuple of Tensors `(x_t, mask_t)`, or a `Tensor` `x_t`. `x_t` is a `Tensor` with rightmost shape dimensions `[observation_size, 1]` representing the vector observed at time `t`, and `mask_t` is a `Tensor` with rightmost dimensions`[1, 1]` representing the observation mask at time `t`. Both `x_t` and `mask_t` may have batch dimensions, which must be compatible with the batch dimensions of `state.predicted_mean` and `state.predictived_cov` respectively. If `mask_t` is not provided, it is assumed to be `None`. Returns: new_state: A `KalmanFilterState` object representing the new filter state at time `t`. """ if isinstance(elems_t, tuple): x_t, mask_t = elems_t else: x_t = elems_t mask_t = None observation_matrix = get_observation_matrix_for_timestep(state.timestep) observation_noise = get_observation_noise_for_timestep(state.timestep) if mask_t is not None: # Before running the update, fill in masked observations using the prior # expectation. The precise filled value shouldn't matter since updates # from masked elements will not be selected below, but we need to ensure # that any results we incidently compute on masked values are at least # finite (not inf or NaN) so that they don't screw up gradient propagation # through `tf.where`, as described in # https://github.com/tensorflow/tensorflow/issues/2540. # We fill with the prior expectation because any fixed value such as zero # might be arbitrarily unlikely under the prior, leading to overflow in # the updates, but the prior expectation should always be a # 'reasonable' observation. x_expected = _propagate_mean(state.predicted_mean,
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`, `p(x|z) = N(H * z + c, R)`, the posterior is also normal: `p(z|x) = N(u*, P*)`. We can write this update as x_expected = H * u + c # pushforward prior mean S = R + H * P * H' # pushforward prior cov K = P * H' * S^{-1} # optimal Kalman gain u* = u + K * (x_observed - x_expected) # posterior mean P* = (I - K * H) * P (I - K * H)' + K * R * K' # posterior cov (see, e.g., https://en.wikipedia.org/wiki/Kalman_filter#Update) Args: prior_mean: `Tensor` with event shape `[latent_size, 1]` and potential batch shape `B = [b1, ..., b_n]`. prior_cov: `Tensor` with event shape `[latent_size, latent_size]` and batch shape `B` (matching `prior_mean`). observation_matrix: `LinearOperator` with shape `[observation_size, latent_size]` and batch shape broadcastable to `B`. observation_noise: potentially-batched `MultivariateNormalLinearOperator` instance with event shape `[observation_size]` and batch shape broadcastable to `B`. x_observed: potentially batched `Tensor` with event shape `[observation_size, 1]` and batch shape `B`. Returns: posterior_mean: `Tensor` with event shape `[latent_size, 1]` and batch shape `B`. posterior_cov: `Tensor` with event shape `[latent_size, latent_size]` and batch shape `B`. predictive_dist: the prior predictive distribution `p(x|z)`, as a `Distribution` instance with event shape `[observation_size]` and batch shape `B`. This will typically be `tfd.MultivariateNormalTriL`, but when `observation_size=1` we return a `tfd.Independent(tfd.Normal)` instance as an optimization. """ # If observations are scalar, we can avoid some matrix ops. observation_size_is_static_and_scalar = ( tf.compat.dimension_value(observation_matrix.shape[-2]) == 1) # Push the predicted mean for the latent state through the # observation model x_expected = _propagate_mean(prior_mean, observation_matrix, observation_noise) # Push the predictive covariance of the latent state through the # observation model: # S = R + H * P * H'. # We use a temporary variable for H * P, # reused below to compute Kalman gain. tmp_obs_cov = observation_matrix.matmul(prior_cov) predicted_obs_cov = ( observation_matrix.matmul(tmp_obs_cov, adjoint_arg=True) + observation_noise.covariance()) # Compute optimal Kalman gain: # K = P * H' * S^{-1} # Since both S and P are cov matrices, thus symmetric, # we can take the transpose and reuse our previous # computation: # = (S^{-1} * H * P)' # = (S^{-1} * tmp_obs_cov) ' # = (S \ tmp_obs_cov)' if observation_size_is_static_and_scalar: gain_transpose = tmp_obs_cov/predicted_obs_cov else: predicted_obs_cov_chol = tf.linalg.cholesky(predicted_obs_cov) gain_transpose =
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, transition_noise)
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 recursion. Args: get_transition_matrix_for_timestep: callable taking a timestep as an integer `Tensor` argument, and returning a `LinearOperator` of shape `[latent_size, latent_size]`. get_transition_noise_for_timestep: callable taking a timestep as an integer `Tensor` argument, and returning a `MultivariateNormalLinearOperator` of event shape `[latent_size]`. get_observation_matrix_for_timestep: callable taking a timestep as an integer `Tensor` argument, and returning a `LinearOperator` of shape `[observation_size, observation_size]`. get_observation_noise_for_timestep: callable taking a timestep as an integer `Tensor` argument, and returning a `MultivariateNormalLinearOperator` of event shape `[observation_size]`. Returns:
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. Args: get_transition_matrix_for_timestep: callable taking a timestep as an integer `Tensor` argument, and returning a `LinearOperator` of shape `[latent_size, latent_size]`. get_transition_noise_for_timestep: callable taking a timestep as an integer `Tensor` argument, and returning a `MultivariateNormalLinearOperator` of event shape `[latent_size]`. get_observation_matrix_for_timestep: callable taking a timestep as an integer `Tensor` argument, and returning a `LinearOperator` of shape `[observation_size, observation_size]`. get_observation_noise_for_timestep: callable taking a timestep as an integer `Tensor` argument, and returning a `MultivariateNormalLinearOperator` of event shape `[observation_size]`.
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, stream, validate_args=False): """Build a callable for one step of Kalman sampling recursion. Args: get_transition_matrix_for_timestep: callable taking a timestep as an integer `Tensor` argument, and returning a `LinearOperator` of shape `[latent_size, latent_size]`. get_transition_noise_for_timestep: callable taking a timestep as an integer `Tensor` argument, and returning a `MultivariateNormalLinearOperator` of event shape `[latent_size]`. get_observation_matrix_for_timestep: callable taking a timestep as an integer `Tensor` argument, and returning a `LinearOperator` of shape `[observation_size, observation_size]`. get_observation_noise_for_timestep: callable taking a timestep as an integer `Tensor` argument, and returning a `MultivariateNormalLinearOperator` of event shape `[observation_size]`. full_sample_and_batch_shape: Desired sample and batch shape of the returned samples, concatenated in a single `Tensor`. stream: `tfd.SeedStream` instance used to generate a sequence of random seeds. validate_args: if True, perform error checking at runtime. Returns: sample_step: a callable that samples the latent state and observation at time `t`, given latent state at time `t-1`. """ def sample_step(sampled_prev, t): """Sample values for a single timestep."""
python
{ "resource": "" }
q266682
_propagate_mean
test
def _propagate_mean(mean, linop, dist): """Propagate a mean through linear Gaussian transformation."""
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()`
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 Striebel smoother as as discussed in section 18.3.2 of Kevin P. Murphy, 2012, Machine Learning: A Probabilistic Perspective, The MIT Press. The inputs are returned by `forward_filter` function. Args: filtered_means: Means of the per-timestep filtered marginal distributions p(z_t | x_{:t}), as a Tensor of shape `sample_shape(x) + batch_shape + [num_timesteps, latent_size]`. filtered_covs: Covariances of the per-timestep filtered marginal distributions p(z_t | x_{:t}), as a Tensor of shape `batch_shape + [num_timesteps, latent_size, latent_size]`. predicted_means: Means of the per-timestep predictive distributions over latent states, p(z_{t+1} | x_{:t}), as a Tensor of shape `sample_shape(x) + batch_shape + [num_timesteps, latent_size]`. predicted_covs: Covariances of the per-timestep predictive distributions over latent states, p(z_{t+1} | x_{:t}), as a Tensor of shape `batch_shape + [num_timesteps, latent_size, latent_size]`. Returns: posterior_means: Means of the smoothed marginal distributions p(z_t | x_{1:T}), as a Tensor of shape `sample_shape(x) + batch_shape + [num_timesteps, latent_size]`, which is of the same shape as filtered_means. posterior_covs: Covariances of the smoothed marginal distributions p(z_t | x_{1:T}), as a Tensor of
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.prefer_static_value( tf.concat([[n], self.batch_shape_tensor()], axis=0)) # Sample the initial timestep from the prior. Since we want # this sample to have full batch shape (not just the batch shape # of the self.initial_state_prior object which might in general be # smaller), we augment the sample shape to include whatever # extra batch dimensions are required. with tf.control_dependencies(self.runtime_assertions): initial_latent = self.initial_state_prior.sample( sample_shape=_augment_sample_shape( self.initial_state_prior, sample_and_batch_shape, self.validate_args), seed=stream()) # Add a dummy dimension so that matmul() does matrix-vector # multiplication. initial_latent = initial_latent[..., tf.newaxis] initial_observation_matrix = ( self.get_observation_matrix_for_timestep(self.initial_step)) initial_observation_noise = ( self.get_observation_noise_for_timestep(self.initial_step)) initial_observation_pred = initial_observation_matrix.matmul( initial_latent) initial_observation = (initial_observation_pred + initial_observation_noise.sample( sample_shape=_augment_sample_shape( initial_observation_noise, sample_and_batch_shape, self.validate_args), seed=stream())[..., tf.newaxis]) sample_step = build_kalman_sample_step( self.get_transition_matrix_for_timestep, self.get_transition_noise_for_timestep, self.get_observation_matrix_for_timestep, self.get_observation_noise_for_timestep,
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. This means that the mean values have shape `concat([sample_shape(x), batch_shape, [num_timesteps, {latent/observation}_size]])`, while the covariances have shape `concat[(batch_shape, [num_timesteps, {latent/observation}_size, {latent/observation}_size]])`, which does not depend on the sample shape. This function only performs smoothing. If the user wants the intermediate values, which are returned by filtering pass `forward_filter`, one could get it by: ``` (log_likelihoods, filtered_means, filtered_covs, predicted_means, predicted_covs, observation_means, observation_covs) = model.forward_filter(x) smoothed_means, smoothed_covs = model.backward_smoothing_pass(x) ``` where `x` is an observation sequence. Args: x: a float-type `Tensor` with rightmost dimensions `[num_timesteps, observation_size]` matching `self.event_shape`. Additional dimensions must match or be broadcastable to `self.batch_shape`; any further dimensions are interpreted as a sample shape. mask: optional bool-type `Tensor` with rightmost dimension `[num_timesteps]`; `True` values specify that the value of `x` at that timestep is masked, i.e., not conditioned on. Additional dimensions must match or be broadcastable to `self.batch_shape`; any further dimensions must match or be broadcastable to the sample
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`, as a `Tensor` of shape `batch_shape + [num_timesteps, observation_size]` """ with tf.name_scope("mean_joint"): # The initial timestep is a special case, since we sample the # latent state from the prior rather than the transition model. with tf.control_dependencies(self.runtime_assertions): # Broadcast to ensure we represent the full batch shape. initial_latent_mean = _broadcast_to_shape( self.initial_state_prior.mean()[..., tf.newaxis], tf.concat([self.batch_shape_tensor(), [self.latent_size, 1]], axis=0)) initial_observation_mean = _propagate_mean( initial_latent_mean, self.get_observation_matrix_for_timestep(self.initial_step), self.get_observation_noise_for_timestep(self.initial_step)) mean_step = build_kalman_mean_step( self.get_transition_matrix_for_timestep, self.get_transition_noise_for_timestep, self.get_observation_matrix_for_timestep, self.get_observation_noise_for_timestep) # Scan over all timesteps following the initial step. (latent_means, observation_means) = tf.scan( mean_step, elems=tf.range(self.initial_step+1, self.final_step), initializer=(initial_latent_mean, initial_observation_mean)) # Squish the initial step back on top of the other (scanned) timesteps
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 covariance matrices of observations `x_t`, as a `Tensor` of shape `batch_shape + [num_timesteps, observation_size, observation_size]` """ with tf.name_scope("covariance_joint"): with tf.control_dependencies(self.runtime_assertions): initial_latent_cov = _broadcast_to_shape( self.initial_state_prior.covariance(), tf.concat([self.batch_shape_tensor(), [self.latent_size, self.latent_size]], axis=0)) initial_observation_cov = _propagate_cov( initial_latent_cov, self.get_observation_matrix_for_timestep(self.initial_step), self.get_observation_noise_for_timestep(self.initial_step)) cov_step = build_kalman_cov_step( self.get_transition_matrix_for_timestep, self.get_transition_noise_for_timestep, self.get_observation_matrix_for_timestep, self.get_observation_noise_for_timestep) # Scan over all timesteps following the initial step. (latent_covs, observation_covs) = tf.scan( cov_step, elems=tf.range(self.initial_step+1, self.final_step), initializer=(initial_latent_cov, initial_observation_cov)) # Squish the initial step back on top of the other (scanned) timesteps
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, latent_size]`. Returns: observation_means: float `Tensor` of shape `[..., num_timesteps, observation_size]` observation_covs: float `Tensor` of shape `[..., num_timesteps, observation_size, observation_size]` """ with tf.name_scope("latents_to_observations"): pushforward_latents_step = build_pushforward_latents_step( self.get_observation_matrix_for_timestep, self.get_observation_noise_for_timestep) latent_means = distribution_util.move_dimension( latent_means, source_idx=-2, dest_idx=0) latent_means = latent_means[..., tf.newaxis] # Make matmul happy. latent_covs = distribution_util.move_dimension( latent_covs, source_idx=-3, dest_idx=0) (initial_observation_mean, initial_observation_cov) = pushforward_latents_step( _=None, # Loop body ignores previous observations. latent_t_mean_cov=(self.initial_step, latent_means[self.initial_step],
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 = tf.where(self.concentration > 0, self.concentration, tf.ones_like(self.concentration)) safe_lognorm = ((event_dim / 2 - 1) * tf.math.log(safe_conc) - (event_dim / 2) * np.log(2 * np.pi) -
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 +
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),
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 dim analytic CDFs are available in [1], could # be bisected for bounded sampling runtime (i.e. not rejection sampling). # [1]: Inversion sampler via: https://ieeexplore.ieee.org/document/7347705/ # The inversion is: u = 1 + log(z + (1-z)*exp(-2*kappa)) / kappa # We
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.deepcopy fails to create a # non-reference copy. Since: # types.FunctionType == type(lambda: None), # and the docstring for the function type states: # # function(code, globals[, name[, argdefs[, closure]]])
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."""
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): return _PrettyDict({ k: _recursively_replace_dict_for_pretty_dict(v)
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: '
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: _
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.""" with tf.compat.v1.name_scope('expand_is_accepted_like'): expand_shape = tf.concat([ tf.shape(input=is_accepted), tf.ones([tf.rank(x) - tf.rank(is_accepted)], dtype=tf.int32), ], axis=0) multiples = tf.concat([ tf.ones([tf.rank(is_accepted)], dtype=tf.int32),
python
{ "resource": "" }