_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q266400
_get_permutations
test
def _get_permutations(num_results, dims, seed=None): """Uniform iid sample from the space of permutations. Draws a sample of size `num_results` from the group of permutations of degrees specified by the `dims` tensor. These are packed together into one tensor such that each row is one sample from each of the d...
python
{ "resource": "" }
q266401
_get_indices
test
def _get_indices(num_results, sequence_indices, dtype, name=None): """Generates starting points for the Halton sequence procedure. The k'th element of the sequence is generated starting from a positive integer which must be distinct for each `k`. It is conventional to choose the starting point as `k` itself (o...
python
{ "resource": "" }
q266402
_base_expansion_size
test
def _base_expansion_size(num, bases): """Computes the number of terms in the place value expansion. Let num = a0 + a1 b + a2 b^2 + ... ak b^k be the place value expansion of `num` in base b (ak <> 0). This function computes and returns `k+1` for each base `b` specified in `bases`. This can be inferred from ...
python
{ "resource": "" }
q266403
_primes_less_than
test
def _primes_less_than(n): # Based on # https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 """Returns sorted array of primes such that `2 <= prime < n`.""" small_primes = np.array((2, 3, 5)) if n <= 6: return small_primes[small_primes < n] sieve =...
python
{ "resource": "" }
q266404
_machine_eps
test
def _machine_eps(dtype): """Returns the machine epsilon for the supplied dtype.""" if isinstance(dtype, tf.DType): dtype = dtype.as_numpy_dtype() return np.finfo(dtype).eps
python
{ "resource": "" }
q266405
hager_zhang
test
def hager_zhang(value_and_gradients_function, initial_step_size=None, value_at_initial_step=None, value_at_zero=None, converged=None, threshold_use_approximate_wolfe_condition=1e-6, shrinkage_param=0.66, expa...
python
{ "resource": "" }
q266406
_fix_step_size
test
def _fix_step_size(value_and_gradients_function, val_c_input, active, step_size_shrink_param): """Shrinks the input step size until the value and grad become finite.""" # The maximum iterations permitted are determined as the number of halvings # it takes t...
python
{ "resource": "" }
q266407
_bracket_and_search
test
def _bracket_and_search( value_and_gradients_function, init_interval, f_lim, max_iterations, shrinkage_param, expansion_param, sufficient_decrease_param, curvature_param): """Brackets the minimum and performs a line search. Args: value_and_gradients_function: A Python callable t...
python
{ "resource": "" }
q266408
_line_search_after_bracketing
test
def _line_search_after_bracketing( value_and_gradients_function, search_interval, val_0, f_lim, max_iterations, sufficient_decrease_param, curvature_param, shrinkage_param): """The main loop of line search after the minimum has been bracketed. Args: value_and_gradients_function:...
python
{ "resource": "" }
q266409
_line_search_inner_bisection
test
def _line_search_inner_bisection( value_and_gradients_function, search_interval, active, f_lim): """Performs bisection and updates the interval.""" midpoint = (search_interval.left.x + search_interval.right.x) / 2 val_mid = value_and_gradients_function(midpoint) is_valid_mid = hzl.is_finite(val_...
python
{ "resource": "" }
q266410
_prepare_args
test
def _prepare_args(value_and_gradients_function, initial_step_size, val_initial, val_0, approximate_wolfe_threshold): """Prepares the arguments for the line search initialization. Args: value_and_gradients_function: A Python callable that a...
python
{ "resource": "" }
q266411
_print
test
def _print(pass_through_tensor, values): """Wrapper for tf.Print which supports lists and namedtuples for printing.""" flat_values = [] for value in values: # Checks if it is a namedtuple. if hasattr(value, '_fields'): for field in value._fields: flat_values.extend([field, _to_str(getattr(va...
python
{ "resource": "" }
q266412
quadrature_scheme_softmaxnormal_gauss_hermite
test
def quadrature_scheme_softmaxnormal_gauss_hermite( normal_loc, normal_scale, quadrature_size, validate_args=False, name=None): """Use Gauss-Hermite quadrature to form quadrature on `K - 1` simplex. A `SoftmaxNormal` random variable `Y` may be generated via ``` Y = SoftmaxCentered(X), X = Normal(norm...
python
{ "resource": "" }
q266413
quadrature_scheme_softmaxnormal_quantiles
test
def quadrature_scheme_softmaxnormal_quantiles( normal_loc, normal_scale, quadrature_size, validate_args=False, name=None): """Use SoftmaxNormal quantiles to form quadrature on `K - 1` simplex. A `SoftmaxNormal` random variable `Y` may be generated via ``` Y = SoftmaxCentered(X), X = Normal(normal_lo...
python
{ "resource": "" }
q266414
maybe_check_quadrature_param
test
def maybe_check_quadrature_param(param, name, validate_args): """Helper which checks validity of `loc` and `scale` init args.""" with tf.name_scope("check_" + name): assertions = [] if tensorshape_util.rank(param.shape) is not None: if tensorshape_util.rank(param.shape) == 0: raise ValueError(...
python
{ "resource": "" }
q266415
determine_batch_event_shapes
test
def determine_batch_event_shapes(grid, endpoint_affine): """Helper to infer batch_shape and event_shape.""" with tf.name_scope("determine_batch_event_shapes"): # grid # shape: [B, k, q] # endpoint_affine # len=k, shape: [B, d, d] batch_shape = grid.shape[:-2] batch_shape_tensor = tf.shape(input...
python
{ "resource": "" }
q266416
interpolate_loc
test
def interpolate_loc(grid, loc): """Helper which interpolates between two locs.""" if len(loc) != 2: raise NotImplementedError("Currently only bimixtures are supported; " "len(scale)={} is not 2.".format(len(loc))) deg = tf.compat.dimension_value( tensorshape_util.with_rank_...
python
{ "resource": "" }
q266417
interpolate_scale
test
def interpolate_scale(grid, scale): """Helper which interpolates between two scales.""" if len(scale) != 2: raise NotImplementedError("Currently only bimixtures are supported; " "len(scale)={} is not 2.".format(len(scale))) deg = tf.compat.dimension_value( tensorshape_util....
python
{ "resource": "" }
q266418
linop_scale
test
def linop_scale(w, op): """Creates weighted `LinOp` from existing `LinOp`.""" # We assume w > 0. (This assumption only relates to the is_* attributes.) with tf.name_scope("linop_scale"): # TODO(b/35301104): LinearOperatorComposition doesn't combine operators, so # special case combinations here. Once it d...
python
{ "resource": "" }
q266419
concat_vectors
test
def concat_vectors(*args): """Concatenates input vectors, statically if possible.""" args_ = [tf.get_static_value(x) for x in args] if any(vec is None for vec in args_): return tf.concat(args, axis=0) return [val for vec in args_ for val in vec]
python
{ "resource": "" }
q266420
_log_vector_matrix
test
def _log_vector_matrix(vs, ms): """Multiply tensor of vectors by matrices assuming values stored are logs.""" return tf.reduce_logsumexp(input_tensor=vs[..., tf.newaxis] + ms, axis=-2)
python
{ "resource": "" }
q266421
_log_matrix_vector
test
def _log_matrix_vector(ms, vs): """Multiply tensor of matrices by vectors assuming values stored are logs.""" return tf.reduce_logsumexp(input_tensor=ms + vs[..., tf.newaxis, :], axis=-1)
python
{ "resource": "" }
q266422
_vector_matrix
test
def _vector_matrix(vs, ms): """Multiply tensor of vectors by matrices.""" return tf.reduce_sum(input_tensor=vs[..., tf.newaxis] * ms, axis=-2)
python
{ "resource": "" }
q266423
_extract_log_probs
test
def _extract_log_probs(num_states, dist): """Tabulate log probabilities from a batch of distributions.""" states = tf.reshape(tf.range(num_states), tf.concat([[num_states], tf.ones_like(dist.batch_shape_tensor())], axis=0)) re...
python
{ "resource": "" }
q266424
HiddenMarkovModel._marginal_hidden_probs
test
def _marginal_hidden_probs(self): """Compute marginal pdf for each individual observable.""" initial_log_probs = tf.broadcast_to(self._log_init, tf.concat([self.batch_shape_tensor(), [self._num_states]], ...
python
{ "resource": "" }
q266425
HiddenMarkovModel.posterior_marginals
test
def posterior_marginals(self, observations, name=None): """Compute marginal posterior distribution for each state. This function computes, for each time step, the marginal conditional probability that the hidden Markov model was in each possible state given the observations that were made at each t...
python
{ "resource": "" }
q266426
HiddenMarkovModel.posterior_mode
test
def posterior_mode(self, observations, name=None): """Compute maximum likelihood sequence of hidden states. When this function is provided with a sequence of observations `x[0], ..., x[num_steps - 1]`, it returns the sequence of hidden states `z[0], ..., z[num_steps - 1]`, drawn from the underlying ...
python
{ "resource": "" }
q266427
_choose_random_direction
test
def _choose_random_direction(current_state_parts, batch_rank, seed=None): """Chooses a random direction in the event space.""" seed_gen = distributions.SeedStream(seed, salt='_choose_random_direction') # Chooses the random directions across each of the input components. rnd_direction_parts = [ tf.random.n...
python
{ "resource": "" }
q266428
_sample_next
test
def _sample_next(target_log_prob_fn, current_state_parts, step_sizes, max_doublings, current_target_log_prob, batch_rank, seed=None, name=None): """Applies a single iteration of slice sampling update...
python
{ "resource": "" }
q266429
_maybe_call_fn
test
def _maybe_call_fn(fn, fn_arg_list, fn_result=None, description='target_log_prob'): """Helper which computes `fn_result` if needed.""" fn_arg_list = (list(fn_arg_list) if mcmc_util.is_list_like(fn_arg_list) else [fn_arg_list]) if fn_result ...
python
{ "resource": "" }
q266430
_right_pad
test
def _right_pad(x, final_rank): """Pads the shape of x to the right to be of rank final_rank. Expands the dims of `x` to the right such that its rank is equal to final_rank. For example, if `x` is of shape [1, 5, 7, 2] and `final_rank` is 7, we return padded_x, which is of shape [1, 5, 7, 2, 1, 1, 1]. Args: ...
python
{ "resource": "" }
q266431
SliceSampler.one_step
test
def one_step(self, current_state, previous_kernel_results): """Runs one iteration of Slice Sampler. Args: current_state: `Tensor` or Python `list` of `Tensor`s representing the current state(s) of the Markov chain(s). The first `r` dimensions index independent chains, `r = tf.rank...
python
{ "resource": "" }
q266432
_build_trainable_posterior
test
def _build_trainable_posterior(param, initial_loc_fn): """Built a transformed-normal variational dist over a parameter's support.""" loc = tf.compat.v1.get_variable( param.name + '_loc', initializer=lambda: initial_loc_fn(param), dtype=param.prior.dtype, use_resource=True) scale = tf.nn.so...
python
{ "resource": "" }
q266433
build_factored_variational_loss
test
def build_factored_variational_loss(model, observed_time_series, init_batch_shape=(), seed=None, name=None): """Build a loss function for variational inference in STS models....
python
{ "resource": "" }
q266434
_minimize_in_graph
test
def _minimize_in_graph(build_loss_fn, num_steps=200, optimizer=None): """Run an optimizer within the graph to minimize a loss function.""" optimizer = tf.compat.v1.train.AdamOptimizer( 0.1) if optimizer is None else optimizer def train_loop_body(step): train_op = optimizer.minimize( build_loss_...
python
{ "resource": "" }
q266435
moments_of_masked_time_series
test
def moments_of_masked_time_series(time_series_tensor, broadcast_mask): """Compute mean and variance, accounting for a mask. Args: time_series_tensor: float `Tensor` time series of shape `concat([batch_shape, [num_timesteps]])`. broadcast_mask: bool `Tensor` of the same shape as `time_series`. Retur...
python
{ "resource": "" }
q266436
initial_value_of_masked_time_series
test
def initial_value_of_masked_time_series(time_series_tensor, broadcast_mask): """Get the first unmasked entry of each time series in the batch. Args: time_series_tensor: float `Tensor` of shape [..., num_timesteps]. broadcast_mask: bool `Tensor` of same shape as `time_series`. """ num_timesteps = tf.sh...
python
{ "resource": "" }
q266437
broadcast_batch_shape
test
def broadcast_batch_shape(distributions): """Get broadcast batch shape from distributions, statically if possible.""" # Static case batch_shape = distributions[0].batch_shape for distribution in distributions: batch_shape = tf.broadcast_static_shape(batch_shape, ...
python
{ "resource": "" }
q266438
factored_joint_mvn
test
def factored_joint_mvn(distributions): """Combine MultivariateNormals into a factored joint distribution. Given a list of multivariate normal distributions `dist[i] = Normal(loc[i], scale[i])`, construct the joint distribution given by concatenating independent samples from these distributions. This is m...
python
{ "resource": "" }
q266439
sum_mvns
test
def sum_mvns(distributions): """Attempt to sum MultivariateNormal distributions. The sum of (multivariate) normal random variables is itself (multivariate) normal, with mean given by the sum of means and (co)variance given by the sum of (co)variances. This method exploits this fact to compute the sum of a li...
python
{ "resource": "" }
q266440
empirical_statistics
test
def empirical_statistics(observed_time_series): """Compute statistics of a provided time series, as heuristic initialization. Args: observed_time_series: `Tensor` representing a time series, or batch of time series, of shape either `batch_shape + [num_timesteps, 1]` or `batch_shape + [num_timeste...
python
{ "resource": "" }
q266441
_maybe_expand_trailing_dim
test
def _maybe_expand_trailing_dim(observed_time_series_tensor): """Ensures `observed_time_series_tensor` has a trailing dimension of size 1. The `tfd.LinearGaussianStateSpaceModel` Distribution has event shape of `[num_timesteps, observation_size]`, but canonical BSTS models are univariate, so their observation_s...
python
{ "resource": "" }
q266442
canonicalize_observed_time_series_with_mask
test
def canonicalize_observed_time_series_with_mask( maybe_masked_observed_time_series): """Extract a Tensor with canonical shape and optional mask. Args: maybe_masked_observed_time_series: a `Tensor`-like object with shape `[..., num_timesteps]` or `[..., num_timesteps, 1]`, or a `tfp.sts.MaskedTi...
python
{ "resource": "" }
q266443
mix_over_posterior_draws
test
def mix_over_posterior_draws(means, variances): """Construct a predictive normal distribution that mixes over posterior draws. Args: means: float `Tensor` of shape `[num_posterior_draws, ..., num_timesteps]`. variances: float `Tensor` of shape `[num_posterior_draws, ..., num_timesteps]`. Ret...
python
{ "resource": "" }
q266444
Uniform.range
test
def range(self, name="range"): """`high - low`.""" with self._name_scope(name): return self.high - self.low
python
{ "resource": "" }
q266445
_make_summary_statistic
test
def _make_summary_statistic(attr): """Factory for making summary statistics, eg, mean, mode, stddev.""" def _fn(self): if any(self._dist_fn_args): # pylint: disable=protected-access raise ValueError( 'Can only compute ' + attr + ' when all distributions are ' 'independent; {}'.format(...
python
{ "resource": "" }
q266446
_unify_call_signature
test
def _unify_call_signature(i, dist_fn): """Creates `dist_fn_wrapped` which calls `dist_fn` with all prev nodes. Args: i: Python `int` corresponding to position in topologically sorted DAG. dist_fn: Python `callable` which takes a subset of previously constructed distributions (in reverse order) and pr...
python
{ "resource": "" }
q266447
_resolve_distribution_names
test
def _resolve_distribution_names(dist_fn_args, dist_names, leaf_name): """Uses arg names to resolve distribution names.""" if dist_names is None: dist_names = [] else: dist_names = dist_names.copy() n = len(dist_fn_args) dist_names.extend([None]*(n - len(dist_names))) for i_, args in enumerate(revers...
python
{ "resource": "" }
q266448
_get_required_args
test
def _get_required_args(fn): """Returns the distribution's required args.""" argspec = tf_inspect.getfullargspec(fn) args = argspec.args if tf_inspect.isclass(fn): args = args[1:] # Remove the `self` arg. if argspec.defaults: # Remove the args which have defaults. By convention we only feed # *req...
python
{ "resource": "" }
q266449
_kl_joint_joint
test
def _kl_joint_joint(d0, d1, name=None): """Calculate the KL divergence between two `JointDistributionSequential`s. Args: d0: instance of a `JointDistributionSequential` object. d1: instance of a `JointDistributionSequential` object. name: (optional) Name to use for created operations. Default val...
python
{ "resource": "" }
q266450
JointDistributionSequential._build
test
def _build(self, model): """Creates `dist_fn`, `dist_fn_wrapped`, `dist_fn_args`.""" if not isinstance(model, collections.Sequence): raise TypeError('`model` must be `list`-like (saw: {}).'.format( type(model).__name__)) self._dist_fn = model self._dist_fn_wrapped, self._dist_fn_args = z...
python
{ "resource": "" }
q266451
JointDistributionSequential._resolve_graph
test
def _resolve_graph(self, distribution_names=None, leaf_name='x'): """Creates a `tuple` of `tuple`s of dependencies. This function is **experimental**. That said, we encourage its use and ask that you report problems to `tfprobability@tensorflow.org`. Args: distribution_names: `list` of `str` or ...
python
{ "resource": "" }
q266452
JointDistributionSequential._entropy
test
def _entropy(self): """Shannon entropy in nats.""" if any(self._dist_fn_args): raise ValueError( 'Can only compute entropy when all distributions are independent.') return sum(joint_distribution_lib.maybe_check_wont_broadcast( (d().entropy() for d in self._dist_fn_wrapped), s...
python
{ "resource": "" }
q266453
check_arg_in_support
test
def check_arg_in_support(f): """Decorator function for argument bounds checking. This decorator is meant to be used with methods that require the first argument to be in the support of the distribution. If `validate_args` is `True`, the method is wrapped with an assertion that the first argument is greater t...
python
{ "resource": "" }
q266454
image_summary
test
def image_summary(seqs, name, num=None): """Visualizes sequences as TensorBoard summaries. Args: seqs: A tensor of shape [n, t, h, w, c]. name: String name of this summary. num: Integer for the number of examples to visualize. Defaults to all examples. """ seqs = tf.clip_by_value(seqs, 0., 1....
python
{ "resource": "" }
q266455
visualize_reconstruction
test
def visualize_reconstruction(inputs, reconstruct, num=3, name="reconstruction"): """Visualizes the reconstruction of inputs in TensorBoard. Args: inputs: A tensor of the original inputs, of shape [batch, timesteps, h, w, c]. reconstruct: A tensor of a reconstruction of inputs, of shape [batch, ...
python
{ "resource": "" }
q266456
visualize_qualitative_analysis
test
def visualize_qualitative_analysis(inputs, model, samples=1, batch_size=3, length=8): """Visualizes a qualitative analysis of a given model. Args: inputs: A tensor of the original inputs, of shape [batch, timesteps, h, w, c]. model: A DisentangledSequentialVAE model...
python
{ "resource": "" }
q266457
summarize_dist_params
test
def summarize_dist_params(dist, name, name_scope="dist_params"): """Summarize the parameters of a distribution. Args: dist: A Distribution object with mean and standard deviation parameters. name: The name of the distribution. name_scope: The name scope of this summary. """ with tf.compat.v1....
python
{ "resource": "" }
q266458
summarize_mean_in_nats_and_bits
test
def summarize_mean_in_nats_and_bits(inputs, units, name, nats_name_scope="nats", bits_name_scope="bits_per_dim"): """Summarize the mean of a tensor in nats and bits per unit. Args: inputs: A tensor of values measured in nats. units: Th...
python
{ "resource": "" }
q266459
LearnableMultivariateNormalDiag.call
test
def call(self, inputs): """Runs the model to generate multivariate normal distribution. Args: inputs: Unused. Returns: A MultivariateNormalDiag distribution with event shape [dimensions], batch shape [], and sample shape [sample_shape, dimensions]. """ del inputs # unused ...
python
{ "resource": "" }
q266460
LearnableMultivariateNormalDiagCell.zero_state
test
def zero_state(self, sample_batch_shape=()): """Returns an initial state for the LSTM cell. Args: sample_batch_shape: A 0D or 1D tensor of the combined sample and batch shape. Returns: A tuple of the initial previous output at timestep 0 of shape [sample_batch_shape, dimensions],...
python
{ "resource": "" }
q266461
LearnableMultivariateNormalDiagCell.call
test
def call(self, inputs, state): """Runs the model to generate a distribution for a single timestep. This generates a batched MultivariateNormalDiag distribution using the output of the recurrent model at the current timestep to parameterize the distribution. Args: inputs: The sampled value of...
python
{ "resource": "" }
q266462
Compressor.call
test
def call(self, inputs): """Runs the model to generate an intermediate representation of x_t. Args: inputs: A batch of image sequences `x_{1:T}` of shape `[sample_shape, batch_size, timesteps, height, width, channels]`. Returns: A batch of intermediate representations of shape [...
python
{ "resource": "" }
q266463
DisentangledSequentialVAE.generate
test
def generate(self, batch_size, length, samples=1, fix_static=False, fix_dynamic=False): """Generate new sequences. Args: batch_size: Number of sequences to generate. length: Number of timesteps to generate for each sequence. samples: Number of samples to draw from the latent di...
python
{ "resource": "" }
q266464
DisentangledSequentialVAE.reconstruct
test
def reconstruct(self, inputs, samples=1, sample_static=False, sample_dynamic=False, swap_static=False, swap_dynamic=False, fix_static=False, fix_dynamic=False): """Reconstruct the given input sequences. Args: inputs: A batch of image sequences `x_{1:T}` of shape ...
python
{ "resource": "" }
q266465
DisentangledSequentialVAE.sample_static_prior
test
def sample_static_prior(self, samples, batch_size, fixed=False): """Sample the static latent prior. Args: samples: Number of samples to draw from the latent distribution. batch_size: Number of sequences to sample. fixed: Boolean for whether or not to share the same random sample acros...
python
{ "resource": "" }
q266466
DisentangledSequentialVAE.sample_dynamic_prior
test
def sample_dynamic_prior(self, samples, batch_size, length, fixed=False): """Sample the dynamic latent prior. Args: samples: Number of samples to draw from the latent distribution. batch_size: Number of sequences to sample. length: Number of timesteps to sample for each sequence. fixed:...
python
{ "resource": "" }
q266467
StructuralTimeSeries.batch_shape
test
def batch_shape(self): """Static batch shape of models represented by this component. Returns: batch_shape: A `tf.TensorShape` giving the broadcast batch shape of all model parameters. This should match the batch shape of derived state space models, i.e., `self.make_state_space_mo...
python
{ "resource": "" }
q266468
StructuralTimeSeries.batch_shape_tensor
test
def batch_shape_tensor(self): """Runtime batch shape of models represented by this component. Returns: batch_shape: `int` `Tensor` giving the broadcast batch shape of all model parameters. This should match the batch shape of derived state space models, i.e., `self.make_state_spac...
python
{ "resource": "" }
q266469
StructuralTimeSeries.make_state_space_model
test
def make_state_space_model(self, num_timesteps, param_vals=None, initial_state_prior=None, initial_step=0): """Instantiate this model as a Distribution over specified `num_timesteps`. Args: ...
python
{ "resource": "" }
q266470
StructuralTimeSeries.prior_sample
test
def prior_sample(self, num_timesteps, initial_step=0, params_sample_shape=(), trajectories_sample_shape=(), seed=None): """Sample from the joint prior over model parameters and trajectories. Args: num_timesteps...
python
{ "resource": "" }
q266471
_compute_min_event_ndims
test
def _compute_min_event_ndims(bijector_list, compute_forward=True): """Computes the min_event_ndims associated with the give list of bijectors. Given a list `bijector_list` of bijectors, compute the min_event_ndims that is associated with the composition of bijectors in that list. min_event_ndims is the # of r...
python
{ "resource": "" }
q266472
vector_size_to_square_matrix_size
test
def vector_size_to_square_matrix_size(d, validate_args, name=None): """Convert a vector size to a matrix size.""" if isinstance(d, (float, int, np.generic, np.ndarray)): n = (-1 + np.sqrt(1 + 8 * d)) / 2. if float(int(n)) != n: raise ValueError("Vector length is not a triangular number.") return i...
python
{ "resource": "" }
q266473
_argsort
test
def _argsort(values, axis=-1, direction='ASCENDING', stable=False, name=None): # pylint: disable=unused-argument """Numpy implementation of `tf.argsort`.""" if direction == 'ASCENDING': pass elif direction == 'DESCENDING': values = np.negative(values) else: raise ValueError('Unrecognized direction:...
python
{ "resource": "" }
q266474
_sort
test
def _sort(values, axis=-1, direction='ASCENDING', stable=False, name=None): # pylint: disable=unused-argument """Numpy implementation of `tf.sort`.""" if direction == 'ASCENDING': pass elif direction == 'DESCENDING': values = np.negative(values) else: raise ValueError('Unrecognized direction: {}.'....
python
{ "resource": "" }
q266475
ndtr
test
def ndtr(x, name="ndtr"): """Normal distribution function. Returns the area under the Gaussian probability density function, integrated from minus infinity to x: ``` 1 / x ndtr(x) = ---------- | exp(-0.5 t**2) dt sqrt(2 pi) /-inf = 0.5 (1 + e...
python
{ "resource": "" }
q266476
_ndtr
test
def _ndtr(x): """Implements ndtr core logic.""" half_sqrt_2 = tf.constant( 0.5 * np.sqrt(2.), dtype=x.dtype, name="half_sqrt_2") w = x * half_sqrt_2 z = tf.abs(w) y = tf.where( tf.less(z, half_sqrt_2), 1. + tf.math.erf(w), tf.where(tf.greater(w, 0.), 2. - tf.math.erfc(z), tf.math.erfc(z))) ...
python
{ "resource": "" }
q266477
ndtri
test
def ndtri(p, name="ndtri"): """The inverse of the CDF of the Normal distribution function. Returns x such that the area under the pdf from minus infinity to x is equal to p. A piece-wise rational approximation is done for the function. This is a port of the implementation in netlib. Args: p: `Tensor`...
python
{ "resource": "" }
q266478
log_ndtr
test
def log_ndtr(x, series_order=3, name="log_ndtr"): """Log Normal distribution function. For details of the Normal distribution function see `ndtr`. This function calculates `(log o ndtr)(x)` by either calling `log(ndtr(x))` or using an asymptotic series. Specifically: - For `x > upper_segment`, use the appro...
python
{ "resource": "" }
q266479
_log_ndtr_asymptotic_series
test
def _log_ndtr_asymptotic_series(x, series_order): """Calculates the asymptotic series used in log_ndtr.""" npdt = dtype_util.as_numpy_dtype(x.dtype) if series_order <= 0: return npdt(1) x_2 = tf.square(x) even_sum = tf.zeros_like(x) odd_sum = tf.zeros_like(x) x_2n = x_2 # Start with x^{2*1} = x^{2*n}...
python
{ "resource": "" }
q266480
erfinv
test
def erfinv(x, name="erfinv"): """The inverse function for erf, the error function. Args: x: `Tensor` of type `float32`, `float64`. name: Python string. A name for the operation (default="erfinv"). Returns: x: `Tensor` with `dtype=x.dtype`. Raises: TypeError: if `x` is not floating-type. """...
python
{ "resource": "" }
q266481
log_cdf_laplace
test
def log_cdf_laplace(x, name="log_cdf_laplace"): """Log Laplace distribution function. This function calculates `Log[L(x)]`, where `L(x)` is the cumulative distribution function of the Laplace distribution, i.e. ```L(x) := 0.5 * int_{-infty}^x e^{-|t|} dt``` For numerical accuracy, `L(x)` is computed in dif...
python
{ "resource": "" }
q266482
text_messages_joint_log_prob
test
def text_messages_joint_log_prob(count_data, lambda_1, lambda_2, tau): """Joint log probability function.""" alpha = (1. / tf.reduce_mean(input_tensor=count_data)) rv_lambda = tfd.Exponential(rate=alpha) rv_tau = tfd.Uniform() lambda_ = tf.gather( [lambda_1, lambda_2], indices=tf.cast( ...
python
{ "resource": "" }
q266483
benchmark_text_messages_hmc
test
def benchmark_text_messages_hmc( num_results=int(3e3), num_burnin_steps=int(3e3), num_leapfrog_steps=3): """Runs HMC on the text-messages unnormalized posterior.""" if not tf.executing_eagerly(): tf.compat.v1.reset_default_graph() # Build a static, pretend dataset. count_data = tf.cast( ...
python
{ "resource": "" }
q266484
GaussianProcess._is_univariate_marginal
test
def _is_univariate_marginal(self, index_points): """True if the given index_points would yield a univariate marginal. Args: index_points: the set of index set locations at which to compute the marginal Gaussian distribution. If this set is of size 1, the marginal is univariate. Returns: ...
python
{ "resource": "" }
q266485
GaussianProcess.get_marginal_distribution
test
def get_marginal_distribution(self, index_points=None): """Compute the marginal of this GP over function values at `index_points`. Args: index_points: `float` `Tensor` representing finite (batch of) vector(s) of points in the index set over which the GP is defined. Shape has the form `[b1...
python
{ "resource": "" }
q266486
GaussianProcess._get_index_points
test
def _get_index_points(self, index_points=None): """Return `index_points` if not None, else `self._index_points`. Args: index_points: if given, this is what is returned; else, `self._index_points` Returns: index_points: the given arg, if not None, else the class member `self._index_...
python
{ "resource": "" }
q266487
make_iaf_stack
test
def make_iaf_stack(total_event_size, num_hidden_layers=2, seed=None, dtype=tf.float32): """Creates an stacked IAF bijector. This bijector operates on vector-valued events. Args: total_event_size: Number of dimensions to operate over. num_hidden_la...
python
{ "resource": "" }
q266488
NeuTra.one_step
test
def one_step(self, current_state, previous_kernel_results): """Runs one iteration of NeuTra. Args: current_state: `Tensor` or Python `list` of `Tensor`s representing the current state(s) of the Markov chain(s). The first `r` dimensions index independent chains, `r = tf.rank(target_log_pro...
python
{ "resource": "" }
q266489
NeuTra.bootstrap_results
test
def bootstrap_results(self, state): """Trains the bijector and creates initial `previous_kernel_results`. The supplied `state` is only used to determine the number of chains to run in parallel_iterations Args: state: `Tensor` or Python `list` of `Tensor`s representing the initial state(s...
python
{ "resource": "" }
q266490
_outer_squared_difference
test
def _outer_squared_difference(x, y): """Convenience function analogous to tf.squared_difference.""" z = x - y return z[..., tf.newaxis, :] * z[..., tf.newaxis]
python
{ "resource": "" }
q266491
_value_and_batch_jacobian
test
def _value_and_batch_jacobian(f, x): """Enables uniform interface to value and batch jacobian calculation. Works in both eager and graph modes. Arguments: f: The scalar function to evaluate. x: The value at which to compute the value and the batch jacobian. Returns: A tuple (f(x), J(x)), where J(...
python
{ "resource": "" }
q266492
_prevent_2nd_derivative
test
def _prevent_2nd_derivative(x): """Disables computation of the second derivatives for a tensor. NB: you need to apply a non-identity function to the output tensor for the exception to be raised. Arguments: x: A tensor. Returns: A tensor with the same value and the same derivative as x, but that rai...
python
{ "resource": "" }
q266493
MixtureSameFamily._distributional_transform
test
def _distributional_transform(self, x): """Performs distributional transform of the mixture samples. Distributional transform removes the parameters from samples of a multivariate distribution by applying conditional CDFs: (F(x_1), F(x_2 | x1_), ..., F(x_d | x_1, ..., x_d-1)) (the indexing is ove...
python
{ "resource": "" }
q266494
_split_covariance_into_marginals
test
def _split_covariance_into_marginals(covariance, block_sizes): """Split a covariance matrix into block-diagonal marginals of given sizes.""" start_dim = 0 marginals = [] for size in block_sizes: end_dim = start_dim + size marginals.append(covariance[..., start_dim:end_dim, start_dim:end_dim]) start_...
python
{ "resource": "" }
q266495
_decompose_from_posterior_marginals
test
def _decompose_from_posterior_marginals( model, posterior_means, posterior_covs, parameter_samples): """Utility method to decompose a joint posterior into components. Args: model: `tfp.sts.Sum` instance defining an additive STS model. posterior_means: float `Tensor` of shape `concat( [[num_poster...
python
{ "resource": "" }
q266496
decompose_by_component
test
def decompose_by_component(model, observed_time_series, parameter_samples): """Decompose an observed time series into contributions from each component. This method decomposes a time series according to the posterior represention of a structural time series model. In particular, it: - Computes the posterior ...
python
{ "resource": "" }
q266497
decompose_forecast_by_component
test
def decompose_forecast_by_component(model, forecast_dist, parameter_samples): """Decompose a forecast distribution into contributions from each component. Args: model: An instance of `tfp.sts.Sum` representing a structural time series model. forecast_dist: A `Distribution` instance returned by `tfp.s...
python
{ "resource": "" }
q266498
dense_to_sparse
test
def dense_to_sparse(x, ignore_value=None, name=None): """Converts dense `Tensor` to `SparseTensor`, dropping `ignore_value` cells. Args: x: A `Tensor`. ignore_value: Entries in `x` equal to this value will be absent from the return `SparseTensor`. If `None`, default value of `x` dtype will be u...
python
{ "resource": "" }
q266499
_operator
test
def _operator(attr): """Defers an operator overload to `attr`. Args: attr: Operator attribute to use. Returns: Function calling operator attribute. """ @functools.wraps(attr) def func(a, *args): return attr(a.value, *args) return func
python
{ "resource": "" }