_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q266500
_numpy_text
test
def _numpy_text(tensor, is_repr=False): """Human-readable representation of a tensor's numpy value.""" if tensor.dtype.is_numpy_compatible: text = repr(tensor.numpy()) if is_repr
python
{ "resource": "" }
q266501
RandomVariable.sample_shape
test
def sample_shape(self): """Sample shape of random variable as a `TensorShape`.""" if isinstance(self._sample_shape,
python
{ "resource": "" }
q266502
RandomVariable.sample_shape_tensor
test
def sample_shape_tensor(self, name="sample_shape_tensor"): """Sample shape of random variable as a 1-D `Tensor`. Args: name: name to give to the op Returns: sample_shape: `Tensor`. """ with
python
{ "resource": "" }
q266503
RandomVariable.value
test
def value(self): """Get tensor that the random variable corresponds to.""" if self._value is None: try: self._value = self.distribution.sample(self.sample_shape_tensor()) except NotImplementedError: raise NotImplementedError( "sample is not implemented for {0}.
python
{ "resource": "" }
q266504
RandomVariable.eval
test
def eval(self, session=None, feed_dict=None): """In a session, computes and returns the value of this random variable. This is not a graph construction method, it does not add ops to the graph. This convenience method requires a session where the graph containing this variable has been launched. If no session is passed, the default session is used. Args: session: tf.BaseSession. The `tf.Session` to use to evaluate this random variable. If none, the default session is used. feed_dict: dict. A dictionary that maps `tf.Tensor` objects to feed values. See `tf.Session.run()` for a description of the valid feed values. Returns:
python
{ "resource": "" }
q266505
RandomVariable.numpy
test
def numpy(self): """Value as NumPy array, only available for TF Eager.""" if not isinstance(self.value,
python
{ "resource": "" }
q266506
normal_conjugates_known_scale_posterior
test
def normal_conjugates_known_scale_posterior(prior, scale, s, n): """Posterior Normal distribution with conjugate prior on the mean. This model assumes that `n` observations (with sum `s`) come from a Normal with unknown mean `loc` (described by the Normal `prior`) and known variance `scale**2`. The "known scale posterior" is the distribution of the unknown `loc`. Accepts a prior Normal distribution object, having parameters `loc0` and `scale0`, as well as known `scale` values of the predictive distribution(s) (also assumed Normal), and statistical estimates `s` (the sum(s) of the observations) and `n` (the number(s) of observations). Returns a posterior (also Normal) distribution object, with parameters `(loc', scale'**2)`, where: ``` mu ~ N(mu', sigma'**2) sigma'**2 = 1/(1/sigma0**2 + n/sigma**2), mu' = (mu0/sigma0**2 + s/sigma**2) * sigma'**2.
python
{ "resource": "" }
q266507
real_nvp_default_template
test
def real_nvp_default_template(hidden_layers, shift_only=False, activation=tf.nn.relu, name=None, *args, # pylint: disable=keyword-arg-before-vararg **kwargs): """Build a scale-and-shift function using a multi-layer neural network. This will be wrapped in a make_template to ensure the variables are only created once. It takes the `d`-dimensional input x[0:d] and returns the `D-d` dimensional outputs `loc` ("mu") and `log_scale` ("alpha"). The default template does not support conditioning and will raise an exception if `condition_kwargs` are passed to it. To use conditioning in real nvp bijector, implement a conditioned shift/scale template that handles the `condition_kwargs`. Arguments: hidden_layers: Python `list`-like of non-negative integer, scalars indicating the number of units in each hidden layer. Default: `[512, 512]. shift_only: Python `bool` indicating if only the `shift` term shall be computed (i.e. NICE bijector). Default: `False`. activation: Activation function (callable). Explicitly setting to `None` implies a linear activation. name: A name for ops managed by this function. Default: "real_nvp_default_template". *args: `tf.layers.dense` arguments. **kwargs: `tf.layers.dense` keyword arguments. Returns: shift: `Float`-like `Tensor` of shift terms ("mu" in [Papamakarios et al. (2016)][1]). log_scale: `Float`-like `Tensor` of log(scale) terms ("alpha" in [Papamakarios et al. (2016)][1]). Raises: NotImplementedError: if rightmost dimension of `inputs` is unknown prior to graph execution, or if `condition_kwargs` is not empty. #### References [1]: George Papamakarios, Theo Pavlakou, and Iain Murray. Masked Autoregressive Flow for Density Estimation. In _Neural Information Processing Systems_,
python
{ "resource": "" }
q266508
_uniform_unit_norm
test
def _uniform_unit_norm(dimension, shape, dtype, seed): """Returns a batch of points chosen uniformly from the unit hypersphere.""" # This works because the Gaussian distribution is spherically symmetric. # raw shape: shape + [dimension] raw = normal.Normal( loc=dtype_util.as_numpy_dtype(dtype)(0),
python
{ "resource": "" }
q266509
LKJ._log_unnorm_prob
test
def _log_unnorm_prob(self, x, name=None): """Returns the unnormalized log density of an LKJ distribution. Args: x: `float` or `double` `Tensor` of correlation matrices. The shape of `x` must be `B + [D, D]`, where `B` broadcasts with the shape of `concentration`. name: Python `str` name prefixed to Ops created by this function. Returns: log_p: A Tensor of the unnormalized log density of each matrix element of `x`, with respect to an LKJ distribution with parameter the corresponding element of `concentration`. """ with tf.name_scope(name or 'log_unnorm_prob_lkj'): x = tf.convert_to_tensor(value=x, name='x') # The density is det(matrix) ** (concentration - 1). # Computing the determinant with `logdet` is usually fine, since # correlation matrices are Hermitian and PSD. But in some cases, for a # PSD matrix whose eigenvalues are close to zero, `logdet` raises an error # complaining that it is not PSD. The root cause is the computation of the # cholesky decomposition in `logdet`. Hence, we use the less efficient but # more robust `slogdet` which does not use `cholesky`. # # An alternative would have been to check allow_nan_stats and use # eigenvalues = tf.linalg.self_adjoint_eigvals(x) # psd_mask = tf.cast(
python
{ "resource": "" }
q266510
LKJ._log_normalization
test
def _log_normalization(self, name='log_normalization'): """Returns the log normalization of an LKJ distribution. Args: name: Python `str` name prefixed to Ops created by this function. Returns: log_z: A Tensor of the same shape and dtype as `concentration`, containing the corresponding log normalizers. """ # The formula is from D. Lewandowski et al [1], p. 1999, from the # proof that eqs 16 and 17 are equivalent. with tf.name_scope(name or 'log_normalization_lkj'):
python
{ "resource": "" }
q266511
common_dtype
test
def common_dtype(args_list, preferred_dtype=None): """Returns explict dtype from `args_list` if exists, else preferred_dtype.""" dtype = None preferred_dtype = (None if preferred_dtype is None else tf.as_dtype(preferred_dtype)) for a in tf.nest.flatten(args_list): if hasattr(a, 'dtype'): dt = tf.as_dtype(a.dtype) else: continue if dtype
python
{ "resource": "" }
q266512
_make_summary_statistic
test
def _make_summary_statistic(attr): """Factory for implementing summary statistics, eg, mean, stddev, mode.""" def _fn(self, **kwargs): """Implements summary statistic, eg, mean, stddev, mode.""" x = getattr(self.distribution, attr)(**kwargs) shape = prefer_static.concat([ self.distribution.batch_shape_tensor(), prefer_static.ones(prefer_static.rank_from_shape(self.sample_shape),
python
{ "resource": "" }
q266513
_broadcast_to
test
def _broadcast_to(tensor_to_broadcast, target_tensors): """Helper to broadcast a tensor using a list of target tensors.""" output =
python
{ "resource": "" }
q266514
Triangular._pdf_at_peak
test
def _pdf_at_peak(self): """Pdf evaluated at
python
{ "resource": "" }
q266515
effective_sample_size
test
def effective_sample_size(states, filter_threshold=0., filter_beyond_lag=None, name=None): """Estimate a lower bound on effective sample size for each independent chain. Roughly speaking, "effective sample size" (ESS) is the size of an iid sample with the same variance as `state`. More precisely, given a stationary sequence of possibly correlated random variables `X_1, X_2,...,X_N`, each identically distributed ESS is the number such that ```Variance{ N**-1 * Sum{X_i} } = ESS**-1 * Variance{ X_1 }.``` If the sequence is uncorrelated, `ESS = N`. In general, one should expect `ESS <= N`, with more highly correlated sequences having smaller `ESS`. Args: states: `Tensor` or list of `Tensor` objects. Dimension zero should index identically distributed states. filter_threshold: `Tensor` or list of `Tensor` objects. Must broadcast with `state`. The auto-correlation sequence is truncated after the first appearance of a term less than `filter_threshold`. Setting to `None` means we use no threshold filter. Since `|R_k| <= 1`, setting to any number less than `-1` has the same effect. filter_beyond_lag: `Tensor` or list of `Tensor` objects. Must be `int`-like and scalar valued. The auto-correlation sequence is truncated to this length. Setting to `None` means we do not filter based on number of lags. name: `String` name to prepend to created ops. Returns: ess: `Tensor` or list of `Tensor` objects. The effective sample size of each component of `states`. Shape will be `states.shape[1:]`. Raises: ValueError: If `states` and `filter_threshold` or `states` and
python
{ "resource": "" }
q266516
_effective_sample_size_single_state
test
def _effective_sample_size_single_state(states, filter_beyond_lag, filter_threshold): """ESS computation for one single Tensor argument.""" with tf.compat.v1.name_scope( 'effective_sample_size_single_state', values=[states, filter_beyond_lag, filter_threshold]): states = tf.convert_to_tensor(value=states, name='states') dt = states.dtype # filter_beyond_lag == None ==> auto_corr is the full sequence. auto_corr = stats.auto_correlation( states, axis=0, max_lags=filter_beyond_lag) if filter_threshold is not None: filter_threshold = tf.convert_to_tensor( value=filter_threshold, dtype=dt, name='filter_threshold') # Get a binary mask to zero out values of auto_corr below the threshold. # mask[i, ...] = 1 if auto_corr[j, ...] > threshold for all j <= i, # mask[i, ...] = 0, otherwise. # So, along dimension zero, the mask will look like [1, 1, ..., 0, 0,...] # Building step by step, # Assume auto_corr = [1, 0.5, 0.0, 0.3], and filter_threshold = 0.2. # Step 1: mask = [False, False, True, False] mask = auto_corr < filter_threshold # Step 2: mask = [0, 0, 1, 1] mask = tf.cast(mask, dtype=dt) # Step 3: mask = [0, 0, 1, 2] mask = tf.cumsum(mask, axis=0) # Step 4: mask = [1, 1, 0, 0] mask = tf.maximum(1. -
python
{ "resource": "" }
q266517
_potential_scale_reduction_single_state
test
def _potential_scale_reduction_single_state(state, independent_chain_ndims): """potential_scale_reduction for one single state `Tensor`.""" with tf.compat.v1.name_scope( 'potential_scale_reduction_single_state', values=[state, independent_chain_ndims]): # We assume exactly one leading dimension indexes e.g. correlated samples # from each Markov chain. state = tf.convert_to_tensor(value=state, name='state') sample_ndims = 1 sample_axis = tf.range(0, sample_ndims) chain_axis = tf.range(sample_ndims, sample_ndims + independent_chain_ndims) sample_and_chain_axis = tf.range( 0, sample_ndims + independent_chain_ndims) n = _axis_size(state, sample_axis) m = _axis_size(state, chain_axis) # In the language of Brooks and Gelman (1998), # B / n is the between chain variance, the variance of the chain means. # W is the within
python
{ "resource": "" }
q266518
_axis_size
test
def _axis_size(x, axis=None): """Get number of elements of `x` in `axis`, as type `x.dtype`.""" if axis is
python
{ "resource": "" }
q266519
_broadcast_maybelist_arg
test
def _broadcast_maybelist_arg(states, secondary_arg, name): """Broadcast a listable secondary_arg to that of states.""" if _is_list_like(secondary_arg): if len(secondary_arg) != len(states): raise ValueError('Argument `%s` was a list of different length ({}) than '
python
{ "resource": "" }
q266520
quadrature_scheme_lognormal_gauss_hermite
test
def quadrature_scheme_lognormal_gauss_hermite( loc, scale, quadrature_size, validate_args=False, name=None): # pylint: disable=unused-argument """Use Gauss-Hermite quadrature to form quadrature on positive-reals. Note: for a given `quadrature_size`, this method is generally less accurate than `quadrature_scheme_lognormal_quantiles`. Args: loc: `float`-like (batch of) scalar `Tensor`; the location parameter of the LogNormal prior. scale: `float`-like (batch of) scalar `Tensor`; the scale parameter of the LogNormal prior. quadrature_size: Python `int` scalar representing the number of quadrature points. 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: grid: (Batch of) length-`quadrature_size` vectors representing the `log_rate` parameters of a `Poisson`. probs: (Batch of) length-`quadrature_size`
python
{ "resource": "" }
q266521
quadrature_scheme_lognormal_quantiles
test
def quadrature_scheme_lognormal_quantiles( loc, scale, quadrature_size, validate_args=False, name=None): """Use LogNormal quantiles to form quadrature on positive-reals. Args: loc: `float`-like (batch of) scalar `Tensor`; the location parameter of the LogNormal prior. scale: `float`-like (batch of) scalar `Tensor`; the scale parameter of the LogNormal prior. quadrature_size: Python `int` scalar representing the number of quadrature points. 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: grid: (Batch of) length-`quadrature_size` vectors representing the `log_rate` parameters of a `Poisson`. probs: (Batch of) length-`quadrature_size` vectors representing the weight associate with each `grid` value. """ with tf.name_scope(name or "quadrature_scheme_lognormal_quantiles"): # Create a LogNormal distribution. dist = transformed_distribution.TransformedDistribution( distribution=normal.Normal(loc=loc, scale=scale), bijector=exp_bijector.Exp(), validate_args=validate_args) batch_ndims = tensorshape_util.rank(dist.batch_shape) if batch_ndims is None: batch_ndims = tf.shape(input=dist.batch_shape_tensor())[0] def _compute_quantiles(): """Helper to build quantiles.""" # Omit {0, 1} since they might lead to Inf/NaN. zero = tf.zeros([], dtype=dist.dtype) edges = tf.linspace(zero, 1., quadrature_size + 3)[1:-1] # Expand edges so its broadcast across batch dims. edges
python
{ "resource": "" }
q266522
_Mapping.merge
test
def merge(self, x=None, y=None, ildj=None, kwargs=None, mapping=None): """Returns new _Mapping with args merged with self. Args: x: `Tensor` or None. Input to forward; output of inverse. y: `Tensor` or None. Input to inverse; output of forward. ildj: `Tensor`. This is the (un-reduce_sum'ed) inverse log det jacobian. kwargs: Python dictionary. Extra args supplied to forward/inverse/etc functions. mapping: Instance of _Mapping to merge. Can only be specified if no other arg is specified. Returns: mapping: New instance of `_Mapping` which has inputs merged with self. Raises: ValueError: if mapping and any other arg is not `None`. """ if
python
{ "resource": "" }
q266523
_Mapping.remove
test
def remove(self, field): """To support weak referencing, removes cache key from the cache value.""" return _Mapping( x=None if field == "x" else
python
{ "resource": "" }
q266524
_Mapping._merge
test
def _merge(self, old, new, use_equals=False): """Helper to merge which handles merging one value.""" if old is None:
python
{ "resource": "" }
q266525
_Mapping._deep_tuple
test
def _deep_tuple(self, x): """Converts nested `tuple`, `list`, or `dict` to nested `tuple`.""" if isinstance(x, dict): return self._deep_tuple(tuple(sorted(x.items())))
python
{ "resource": "" }
q266526
_left_doubling_increments
test
def _left_doubling_increments(batch_shape, max_doublings, step_size, seed=None, name=None): """Computes the doubling increments for the left end point. The doubling procedure expands an initial interval to find a superset of the true slice. At each doubling iteration, the interval width is doubled to either the left or the right hand side with equal probability. If, initially, the left end point is at `L(0)` and the width of the interval is `w(0)`, then the left end point and the width at the k-th iteration (denoted L(k) and w(k) respectively) are given by the following recursions: ```none w(k) = 2 * w(k-1) L(k) = L(k-1) - w(k-1) * X_k, X_k ~ Bernoulli(0.5) or, L(0) - L(k) = w(0) Sum(2^i * X(i+1), 0 <= i < k) ``` This function computes the sequence of `L(0)-L(k)` and `w(k)` for k between 0 and `max_doublings` independently for each chain. Args: batch_shape: Positive int32 `tf.Tensor`. The batch shape. max_doublings: Scalar positive int32 `tf.Tensor`. The maximum number of doublings to consider. step_size: A real `tf.Tensor` with shape compatible with [num_chains]. The size of the initial interval. seed: (Optional) positive int. The random seed. If None, no seed is set. name: Python `str` name prefixed to Ops created by this function. Default value: `None` (i.e., 'find_slice_bounds'). Returns: left_increments: A tensor of shape (max_doublings+1, batch_shape). The relative position of the left end point after the doublings. widths: A tensor of shape (max_doublings+1, ones_like(batch_shape)). The widths of the intervals at each stage of the doubling. """ with tf.compat.v1.name_scope(name, 'left_doubling_increments', [batch_shape, max_doublings, step_size]):
python
{ "resource": "" }
q266527
_find_best_interval_idx
test
def _find_best_interval_idx(x, name=None): """Finds the index of the optimal set of bounds for each chain. For each chain, finds the smallest set of bounds for which both edges lie outside the slice. This is equivalent to the point at which a for loop implementation (P715 of Neal (2003)) of the algorithm would terminate. Performs the following calculation, where i is the number of doublings that have been performed and k is the max number of doublings: (2 * k - i) * flag + i The argmax of the above returns the earliest index where the bounds were outside the slice and if there is no such point, the widest bounds. Args: x: A tensor of shape (max_doublings+1, batch_shape). Type int32, with value 0 or 1. Indicates if this set of bounds is outside the slice. name: Python `str` name prefixed to Ops created by this function. Default value: `None` (i.e., 'find_slice_bounds'). Returns: indices: A tensor of shape batch_shape. Type int32, with the index of the
python
{ "resource": "" }
q266528
slice_bounds_by_doubling
test
def slice_bounds_by_doubling(x_initial, target_log_prob, log_slice_heights, max_doublings, step_size, seed=None, name=None): """Returns the bounds of the slice at each stage of doubling procedure. Precomputes the x coordinates of the left (L) and right (R) endpoints of the interval `I` produced in the "doubling" algorithm [Neal 2003][1] P713. Note that we simultaneously compute all possible doubling values for each chain, for the reason that at small-medium densities, the gains from parallel evaluation might cause a speed-up, but this will be benchmarked against the while loop implementation. Args: x_initial: `tf.Tensor` of any shape and any real dtype consumable by `target_log_prob`. The initial points. target_log_prob: A callable taking a `tf.Tensor` of shape and dtype as `x_initial` and returning a tensor of the same shape. The log density of the target distribution. log_slice_heights: `tf.Tensor` with the same shape as `x_initial` and the same dtype as returned by `target_log_prob`. The log of the height of the slice for each chain. The values must be bounded above by `target_log_prob(x_initial)`. max_doublings: Scalar positive int32 `tf.Tensor`. The maximum number of doublings to consider. step_size: `tf.Tensor` with same dtype as and shape compatible with `x_initial`. The size of the initial interval. seed: (Optional) positive int. The random seed. If None, no seed is set. name: Python `str` name prefixed to Ops created by this function. Default value: `None` (i.e., 'find_slice_bounds'). Returns: upper_bounds: A tensor of same shape and dtype as `x_initial`. Slice upper bounds for each chain.
python
{ "resource": "" }
q266529
_sample_with_shrinkage
test
def _sample_with_shrinkage(x_initial, target_log_prob, log_slice_heights, step_size, lower_bounds, upper_bounds, seed=None, name=None): """Samples from the slice by applying shrinkage for rejected points. Implements the one dimensional slice sampling algorithm of Neal (2003), with a doubling algorithm (Neal 2003 P715 Fig. 4), which doubles the size of the interval at each iteration and shrinkage (Neal 2003 P716 Fig. 5), which reduces the width of the slice when a selected point is rejected, by setting the relevant bound that that value. Randomly sampled points are checked for two criteria: that they lie within the slice and that they pass the acceptability check (Neal 2003 P717 Fig. 6), which tests that the new state could have generated the previous one. Args: x_initial: A tensor of any shape. The initial positions of the chains. This function assumes that all the dimensions of `x_initial` are batch dimensions (i.e. the event shape is `[]`). target_log_prob: Callable accepting a tensor like `x_initial` and returning a tensor containing the log density at that point of the same shape. log_slice_heights: Tensor of the same shape and dtype as the return value of `target_log_prob` when applied to `x_initial`. The log of the height of the chosen slice. step_size: A tensor of shape and dtype compatible with `x_initial`. The min interval size in the doubling algorithm. lower_bounds: Tensor of same shape and dtype as `x_initial`. Slice lower bounds for each chain. upper_bounds: Tensor of same shape and dtype as `x_initial`. Slice upper bounds for each chain. seed: (Optional) positive int. The random seed. If None, no seed is set. name: Python `str` name prefixed to Ops created by this function. Default value: `None` (i.e., 'find_slice_bounds'). Returns: x_proposed: A tensor of the same shape and dtype as `x_initial`. The next proposed state of the chain. """ with tf.compat.v1.name_scope( name, 'sample_with_shrinkage', [x_initial, log_slice_heights, step_size, lower_bounds, upper_bounds]): seed_gen = distributions.SeedStream(seed, salt='_sample_with_shrinkage') # Keeps track of whether an acceptable sample has been found for the chain.
python
{ "resource": "" }
q266530
slice_sampler_one_dim
test
def slice_sampler_one_dim(target_log_prob, x_initial, step_size=0.01, max_doublings=30, seed=None, name=None): """For a given x position in each Markov chain, returns the next x. Applies the one dimensional slice sampling algorithm as defined in Neal (2003) to an input tensor x of shape (num_chains,) where num_chains is the number of simulataneous Markov chains, and returns the next tensor x of shape (num_chains,) when these chains are evolved by the slice sampling algorithm. Args: target_log_prob: Callable accepting a tensor like `x_initial` and returning a tensor containing the log density at that point of the same shape. x_initial: A tensor of any shape. The initial positions of the chains. This function assumes that all the dimensions of `x_initial` are batch dimensions (i.e. the event shape is `[]`). step_size: A tensor of shape and dtype compatible with `x_initial`. The min interval size in the doubling algorithm. max_doublings: Scalar tensor of dtype `tf.int32`. The maximum number of doublings to try to find the slice bounds. seed: (Optional) positive int. The random seed. If None, no seed is set. name: Python `str` name prefixed to Ops created by this function. Default value: `None` (i.e., 'find_slice_bounds'). Returns: retval: A tensor of the same shape and dtype as `x_initial`. The next state of the Markov chain. next_target_log_prob: The target log density evaluated at `retval`. bounds_satisfied: A tensor of bool dtype and shape batch dimensions. upper_bounds: Tensor of the same shape and dtype as `x_initial`. The upper bounds for the slice found. lower_bounds: Tensor of the same shape and dtype as `x_initial`. The lower bounds for the slice found. """ with tf.compat.v1.name_scope(name, 'slice_sampler_one_dim',
python
{ "resource": "" }
q266531
make_value_setter
test
def make_value_setter(**model_kwargs): """Creates a value-setting interceptor. This function creates an interceptor that sets values of Edward2 random variable objects. This is useful for a range of tasks, including conditioning on observed data, sampling from posterior predictive distributions, and as a building block of inference primitives such as computing log joint probabilities (see examples below). Args: **model_kwargs: dict of str to Tensor. Keys are the names of random variables in the model to which this interceptor is being applied. Values are Tensors to set their value to. Variables not included in this dict will not be set and will maintain their existing value semantics (by default, a sample from the parent-conditional distribution). Returns: set_values: function that sets the value of intercepted ops. #### Examples Consider for illustration a model with latent `z` and observed `x`, and a corresponding trainable posterior model: ```python num_observations = 10 def model(): z = ed.Normal(loc=0, scale=1., name='z') # log rate x = ed.Poisson(rate=tf.exp(z) * tf.ones(num_observations), name='x') return x def variational_model(): return ed.Normal(loc=tf.Variable(0.), scale=tf.nn.softplus(tf.Variable(-4.)), name='z') # for simplicity, match name of the model RV. ``` We can use a value-setting interceptor to condition the model on observed data. This approach is slightly more cumbersome than that of partially evaluating the complete log-joint function, but has the potential advantage that it returns a new model callable, which may be used to sample downstream variables, passed into additional transformations, etc. ```python x_observed = np.array([6, 3, 1, 8, 7, 0, 6, 4, 7, 5]) def observed_model(): with ed.interception(make_value_setter(x=x_observed)): model() observed_log_joint_fn = ed.make_log_joint_fn(observed_model) # After fixing 'x', the observed log joint is now only a function of 'z'. # This enables us to define a variational lower bound, # `E_q[ log p(x, z) - log q(z)]`, simply by evaluating the observed and # variational log joints at variational samples. variational_log_joint_fn = ed.make_log_joint_fn(variational_model) with ed.tape() as variational_sample: # Sample trace from variational model.
python
{ "resource": "" }
q266532
make_log_joint_fn
test
def make_log_joint_fn(model): """Takes Edward probabilistic program and returns its log joint function. Args: model: Python callable which executes the generative process of a computable probability distribution using `ed.RandomVariable`s. Returns: A log-joint probability function. Its inputs are `model`'s original inputs and random variables which appear during the program execution. Its output is a scalar tf.Tensor. #### Examples Below we define Bayesian logistic regression as an Edward program, representing the model's generative process. We apply `make_log_joint_fn` in order to represent the model in terms of its joint probability function. ```python from tensorflow_probability import edward2 as ed def logistic_regression(features): coeffs = ed.Normal(loc=0., scale=1., sample_shape=features.shape[1], name="coeffs") outcomes = ed.Bernoulli(logits=tf.tensordot(features, coeffs, [[1], [0]]), name="outcomes") return outcomes log_joint = ed.make_log_joint_fn(logistic_regression) features = tf.random_normal([3, 2]) coeffs_value = tf.random_normal([2]) outcomes_value = tf.round(tf.random_uniform([3])) output = log_joint(features, coeffs=coeffs_value, outcomes=outcomes_value) ``` """ def log_joint_fn(*args, **kwargs): """Log-probability of inputs according to a joint probability distribution. Args: *args: Positional arguments. They are the model's original inputs and can alternatively be specified as part of `kwargs`. **kwargs: Keyword arguments, where for each key-value pair `k` and `v`, `v` is passed as a `value` to the random variable(s) whose keyword argument `name` during construction is equal to `k`. Returns: Scalar tf.Tensor, which represents the model's log-probability summed over all Edward random variables and their dimensions. Raises:
python
{ "resource": "" }
q266533
_get_function_inputs
test
def _get_function_inputs(f, src_kwargs): """Filters inputs to be compatible with function `f`'s signature. Args: f: Function according to whose input signature we filter arguments. src_kwargs: Keyword arguments to filter according to `f`. Returns: kwargs: Dict of key-value pairs in `src_kwargs` which exist in `f`'s signature. """ if hasattr(f, "_func"): # functions returned by tf.make_template f = f._func
python
{ "resource": "" }
q266534
_vggconv_block
test
def _vggconv_block(x, filters, kernel, stride, kernel_posterior_fn): """Network block for VGG.""" out = tfp.layers.Convolution2DFlipout( filters, kernel, padding='same', kernel_posterior_fn=kernel_posterior_fn)(x) out = tf.keras.layers.BatchNormalization()(out) out = tf.keras.layers.Activation('relu')(out) out = tfp.layers.Convolution2DFlipout( filters, kernel, padding='same',
python
{ "resource": "" }
q266535
_build_tree
test
def _build_tree(value_and_gradients_fn, current_state, current_target_log_prob, current_grads_target_log_prob, current_momentum, direction, depth, step_size, log_slice_sample, max_simulation_error=1000., seed=None): """Builds a tree at a given tree depth and at a given state. The `current` state is immediately adjacent to, but outside of, the subtrajectory spanned by the returned `forward` and `reverse` states. Args: value_and_gradients_fn: Python callable which takes an argument like `*current_state` and returns a tuple of its (possibly unnormalized) log-density under the target distribution and its gradient with respect to each state. current_state: List of `Tensor`s representing the current states of the NUTS trajectory. current_target_log_prob: Scalar `Tensor` representing the value of `target_log_prob_fn` at the `current_state`. current_grads_target_log_prob: List of `Tensor`s representing gradient of `current_target_log_prob` with respect to `current_state`. Must have same shape as `current_state`. current_momentum: List of `Tensor`s representing the momentums of `current_state`. Must have same shape as `current_state`. direction: int that is either -1 or 1. It determines whether to perform leapfrog integration backwards (reverse) or forward in time respectively. depth: non-negative int that indicates how deep of a tree to build. Each call to `_build_tree` takes `2**depth` leapfrog steps. step_size: List of `Tensor`s representing the step sizes for the leapfrog integrator. Must have same shape as `current_state`. log_slice_sample: The log of an auxiliary slice variable. It is used together with `max_simulation_error` to avoid simulating trajectories with too much numerical error. max_simulation_error: Maximum simulation error to tolerate before terminating the trajectory. Simulation error is the `log_slice_sample` minus the log-joint probability at the simulated state. seed: Integer to seed the random number generator. Returns: reverse_state: List of `Tensor`s representing the "reverse" states of the NUTS trajectory. Has same shape as `current_state`. reverse_target_log_prob: Scalar `Tensor` representing the value of `target_log_prob_fn` at the `reverse_state`. reverse_grads_target_log_prob: List of `Tensor`s representing gradient of `reverse_target_log_prob` with respect to `reverse_state`. Has same shape as `reverse_state`. reverse_momentum: List of `Tensor`s representing the momentums of `reverse_state`. Has same shape as `reverse_state`. forward_state: List of `Tensor`s representing the "forward" states of the NUTS trajectory. Has same shape as `current_state`. forward_target_log_prob: Scalar `Tensor` representing the value of `target_log_prob_fn` at the `forward_state`. forward_grads_target_log_prob: List of `Tensor`s representing gradient of `forward_target_log_prob` with respect to `forward_state`. Has same shape as `forward_state`. forward_momentum: List of `Tensor`s representing the momentums of `forward_state`. Has same shape as `forward_state`. next_state: List of `Tensor`s representing the next states of the NUTS trajectory. Has same shape as `current_state`. next_target_log_prob: Scalar `Tensor` representing the value of `target_log_prob_fn` at `next_state`. next_grads_target_log_prob: List of `Tensor`s representing the gradient of `next_target_log_prob` with respect to `next_state`. num_states: Number of acceptable candidate states in the subtree. A state is acceptable if it is "in the slice", that is, if its log-joint probability with its momentum is greater than `log_slice_sample`. continue_trajectory: bool determining whether to continue the simulation trajectory. The trajectory is continued if no U-turns are encountered within the built subtree, and if the log-probability accumulation due to integration error does not exceed `max_simulation_error`. """ if depth == 0: # base case # Take a leapfrog step. Terminate the tree-building if the simulation # error from the leapfrog integrator is too large. States discovered by # continuing the simulation are likely to have very low probability. [ next_state, next_target_log_prob, next_grads_target_log_prob, next_momentum, ] = _leapfrog( value_and_gradients_fn=value_and_gradients_fn, current_state=current_state, current_grads_target_log_prob=current_grads_target_log_prob, current_momentum=current_momentum, step_size=direction * step_size) next_log_joint = _log_joint(next_target_log_prob, next_momentum) num_states = tf.cast(next_log_joint > log_slice_sample, dtype=tf.int32) continue_trajectory = (next_log_joint > log_slice_sample - max_simulation_error) return [ next_state, next_target_log_prob, next_grads_target_log_prob, next_momentum, next_state, next_target_log_prob, next_grads_target_log_prob, next_momentum, next_state, next_target_log_prob, next_grads_target_log_prob, num_states, continue_trajectory, ] # Build a tree at the current state. seed_stream = tfd.SeedStream(seed, "build_tree") [ reverse_state, reverse_target_log_prob, reverse_grads_target_log_prob, reverse_momentum, forward_state, forward_target_log_prob, forward_grads_target_log_prob, forward_momentum, next_state, next_target_log_prob, next_grads_target_log_prob, num_states, continue_trajectory, ] = _build_tree(value_and_gradients_fn=value_and_gradients_fn, current_state=current_state, current_target_log_prob=current_target_log_prob,
python
{ "resource": "" }
q266536
_embed_no_none_gradient_check
test
def _embed_no_none_gradient_check(value_and_gradients_fn): """Wraps value and gradients function to assist with None gradients.""" @functools.wraps(value_and_gradients_fn) def func_wrapped(*args, **kwargs): """Wrapped function which checks for None gradients.""" value, grads
python
{ "resource": "" }
q266537
_has_no_u_turn
test
def _has_no_u_turn(state_one, state_two, momentum): """If two given states and momentum do not exhibit a U-turn pattern.""" dot_product = sum([ tf.reduce_sum(input_tensor=(s1 - s2) * m)
python
{ "resource": "" }
q266538
_leapfrog
test
def _leapfrog(value_and_gradients_fn, current_state, current_grads_target_log_prob, current_momentum, step_size): """Runs one step of leapfrog integration.""" mid_momentum = [ m + 0.5 * step * g for m, step, g in zip(current_momentum, step_size, current_grads_target_log_prob)] next_state = [ s + step * m for s, step, m in zip(current_state, step_size, mid_momentum)] next_target_log_prob, next_grads_target_log_prob =
python
{ "resource": "" }
q266539
_log_joint
test
def _log_joint(current_target_log_prob, current_momentum): """Log-joint probability given a state's log-probability and
python
{ "resource": "" }
q266540
_random_bernoulli
test
def _random_bernoulli(shape, probs, dtype=tf.int32, seed=None, name=None): """Returns samples from a Bernoulli distribution.""" with tf.compat.v1.name_scope(name, "random_bernoulli",
python
{ "resource": "" }
q266541
default_loc_scale_fn
test
def default_loc_scale_fn( is_singular=False, loc_initializer=tf.compat.v1.initializers.random_normal(stddev=0.1), untransformed_scale_initializer=tf.compat.v1.initializers.random_normal( mean=-3., stddev=0.1), loc_regularizer=None, untransformed_scale_regularizer=None, loc_constraint=None, untransformed_scale_constraint=None): """Makes closure which creates `loc`, `scale` params from `tf.get_variable`. This function produces a closure which produces `loc`, `scale` using `tf.get_variable`. The closure accepts the following arguments: dtype: Type of parameter's event. shape: Python `list`-like representing the parameter's event shape. name: Python `str` name prepended to any created (or existing) `tf.Variable`s. trainable: Python `bool` indicating all created `tf.Variable`s should be added to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. add_variable_fn: `tf.get_variable`-like `callable` used to create (or access existing) `tf.Variable`s. Args: is_singular: Python `bool` indicating if `scale is None`. Default: `False`. loc_initializer: Initializer function for the `loc` parameters. The default is `tf.random_normal_initializer(mean=0., stddev=0.1)`. untransformed_scale_initializer: Initializer function for the `scale` parameters. Default value: `tf.random_normal_initializer(mean=-3., stddev=0.1)`. This implies the softplus transformed result is initialized near `0`. It allows a `Normal` distribution with `scale` parameter set to this value to approximately act like a point mass. loc_regularizer: Regularizer function for the `loc` parameters. The default (`None`) is to use the `tf.get_variable` default. untransformed_scale_regularizer: Regularizer function for the `scale` parameters. The default (`None`) is to use the `tf.get_variable` default. loc_constraint: An optional projection function to be applied to the loc after being updated by an `Optimizer`. The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing
python
{ "resource": "" }
q266542
default_mean_field_normal_fn
test
def default_mean_field_normal_fn( is_singular=False, loc_initializer=tf.compat.v1.initializers.random_normal(stddev=0.1), untransformed_scale_initializer=tf.compat.v1.initializers.random_normal( mean=-3., stddev=0.1), loc_regularizer=None, untransformed_scale_regularizer=None, loc_constraint=None, untransformed_scale_constraint=None): """Creates a function to build Normal distributions with trainable params. This function produces a closure which produces `tfd.Normal` parameterized by a loc` and `scale` each created using `tf.get_variable`. Args: is_singular: Python `bool` if `True`, forces the special case limit of `scale->0`, i.e., a `Deterministic` distribution. loc_initializer: Initializer function for the `loc` parameters. The default is `tf.random_normal_initializer(mean=0., stddev=0.1)`. untransformed_scale_initializer: Initializer function for the `scale` parameters. Default value: `tf.random_normal_initializer(mean=-3., stddev=0.1)`. This implies the softplus transformed result is initialized near `0`. It allows a `Normal` distribution with `scale` parameter set to this value to approximately act like a point mass. loc_regularizer: Regularizer function for the `loc` parameters. untransformed_scale_regularizer: Regularizer function for the `scale` parameters. loc_constraint: An optional projection function to be applied to the loc after being updated by an `Optimizer`. The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. untransformed_scale_constraint: An optional projection function to be applied to the `scale` parameters after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints). The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training.
python
{ "resource": "" }
q266543
default_multivariate_normal_fn
test
def default_multivariate_normal_fn(dtype, shape, name, trainable, add_variable_fn): """Creates multivariate standard `Normal` distribution. Args: dtype: Type of parameter's event. shape: Python `list`-like representing the parameter's event shape. name: Python `str` name prepended to any created (or existing) `tf.Variable`s. trainable: Python `bool` indicating all created `tf.Variable`s should be added to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. add_variable_fn: `tf.get_variable`-like `callable` used to create (or
python
{ "resource": "" }
q266544
deserialize_function
test
def deserialize_function(serial, function_type): """Deserializes the Keras-serialized function. (De)serializing Python functions from/to bytecode is unsafe. Therefore we also use the function's type as an anonymous function ('lambda') or named function in the Python environment ('function'). In the latter case, this lets us use the Python scope to obtain the function rather than reload it from bytecode. (Note that both cases are brittle!) Keras-deserialized functions do not perform lexical scoping. Any modules that the function requires must be imported within the function itself. This serialization mimicks the implementation in `tf.keras.layers.Lambda`. Args: serial: Serialized Keras object: typically a dict, string, or bytecode. function_type: Python string denoting 'function' or 'lambda'. Returns: function: Function the serialized Keras object represents. #### Examples ```python serial, function_type = serialize_function(lambda x: x)
python
{ "resource": "" }
q266545
serialize_function
test
def serialize_function(func): """Serializes function for Keras. (De)serializing Python functions from/to bytecode is unsafe. Therefore we return the function's type as an anonymous function ('lambda') or named function in the Python environment ('function'). In the latter case, this lets us use the Python scope to obtain the function rather than reload it from bytecode. (Note that both cases are brittle!) This serialization mimicks the implementation in `tf.keras.layers.Lambda`. Args: func: Python function to
python
{ "resource": "" }
q266546
broadcast_structure
test
def broadcast_structure(to_structure, from_structure): """Broadcasts `from_structure` to `to_structure`. This is useful for downstream usage of `zip` or `tf.nest.map_structure`. If `from_structure` is a singleton, it is tiled to match the structure of `to_structure`. Note that the elements in `from_structure` are not copied if this tiling occurs. Args: to_structure: A structure. from_structure: A structure. Returns: new_from_structure: Same structure as `to_structure`. #### Example: ```python a_structure = ['a', 'b', 'c']
python
{ "resource": "" }
q266547
_nested_convert_to_tensor
test
def _nested_convert_to_tensor(struct, dtype=None, name=None): """Eagerly converts struct to Tensor, recursing upon failure.""" if dtype is not None or not tf.nest.is_nested(struct): return tf.convert_to_tensor(struct, dtype=dtype) if _maybe_convertible_to_tensor(struct): try: # Try converting the structure wholesale. return tf.convert_to_tensor(value=struct, name=name) except (ValueError, TypeError): # Unfortunately
python
{ "resource": "" }
q266548
convert_args_to_tensor
test
def convert_args_to_tensor(args, dtype=None, name=None): """Converts `args` to `Tensor`s. Use this when it is necessary to convert user-provided arguments that will then be passed to user-provided callables. When `dtype` is `None` this function behaves as follows: 1A. If the top-level structure is a `list`/`tuple` but not a `namedtuple`, then it is left as is and only its elements are converted to `Tensor`s. 2A. The sub-structures are converted to `Tensor`s eagerly. E.g. if `args` is `{'arg': [[1], [2]]}` it is converted to `{'arg': tf.constant([[1], [2]])}`. If the conversion fails, it will attempt to recurse into its children. When `dtype` is specified, it acts as both a structural and numeric type constraint. `dtype` can be a single `DType`, `None` or a nested collection thereof. The conversion rule becomes as follows: 1B. The return value of this function will have the same structure as `dtype`. 2B. If the leaf of `dtype` is a concrete `DType`, then the corresponding sub-structure in `args` is converted to a `Tensor`. 3B. If the leaf of `dtype` is `None`, then the corresponding sub-structure is converted eagerly as described in the rule 2A above. Args: args: Arguments to convert to `Tensor`s. dtype: Optional structure/numeric type constraint. name: Optional name-scope to use. Returns: args: Converted `args`. #### Examples. This table shows some useful conversion cases. `T` means `Tensor`, `NT` means `namedtuple` and `CNT` means a `namedtuple` with a `Tensor`-conversion function registered. | args | dtype | output |
python
{ "resource": "" }
q266549
call_fn
test
def call_fn(fn, args): """Calls `fn` with `args`, possibly expanding `args`. Use this function when calling a user-provided callable using user-provided arguments. The expansion rules are as follows: `fn(*args)` if `args` is a `list` or a `tuple`, but not a `namedtuple`. `fn(**args)` if `args` is a `dict`. `fn(args)` otherwise. Args: fn: A callable that takes either `args` as an argument(s).
python
{ "resource": "" }
q266550
_get_tensor_like_attributes
test
def _get_tensor_like_attributes(): """Returns `Tensor` attributes related to shape and Python builtins.""" # Enable "Tensor semantics" for distributions. # See tensorflow/python/framework/ops.py `class Tensor` for details. attrs = dict() # Setup overloadable operators and white-listed members / properties. attrs.update((attr, _wrap_method(tf.Tensor, attr))
python
{ "resource": "" }
q266551
make_mixture_prior
test
def make_mixture_prior(latent_size, mixture_components): """Creates the mixture of Gaussians prior distribution. Args: latent_size: The dimensionality of the latent representation. mixture_components: Number of elements of the mixture. Returns: random_prior: A `tfd.Distribution` instance representing the distribution over encodings in the absence of any evidence. """ if mixture_components == 1: # See the module docstring for why we don't learn the parameters here. return tfd.MultivariateNormalDiag( loc=tf.zeros([latent_size]), scale_identity_multiplier=1.0) loc = tf.compat.v1.get_variable(
python
{ "resource": "" }
q266552
pack_images
test
def pack_images(images, rows, cols): """Helper utility to make a field of images.""" shape = tf.shape(input=images) width = shape[-3] height = shape[-2] depth = shape[-1] images = tf.reshape(images, (-1, width, height, depth))
python
{ "resource": "" }
q266553
download
test
def download(directory, filename): """Downloads a file.""" filepath = os.path.join(directory, filename) if tf.io.gfile.exists(filepath): return filepath
python
{ "resource": "" }
q266554
build_fake_input_fns
test
def build_fake_input_fns(batch_size): """Builds fake MNIST-style data for unit testing.""" random_sample = np.random.rand(batch_size, *IMAGE_SHAPE).astype("float32") def train_input_fn(): dataset = tf.data.Dataset.from_tensor_slices( random_sample).map(lambda row: (row, 0)).batch(batch_size).repeat() return tf.compat.v1.data.make_one_shot_iterator(dataset).get_next() def eval_input_fn():
python
{ "resource": "" }
q266555
_validate_block_sizes
test
def _validate_block_sizes(block_sizes, bijectors, validate_args): """Helper to validate block sizes.""" block_sizes_shape = block_sizes.shape if tensorshape_util.is_fully_defined(block_sizes_shape): if (tensorshape_util.rank(block_sizes_shape) != 1 or (tensorshape_util.num_elements(block_sizes_shape) != len(bijectors))): raise ValueError( '`block_sizes` must be `None`, or a vector of the same length as ' '`bijectors`. Got a `Tensor` with shape {} and `bijectors` of ' 'length {}'.format(block_sizes_shape, len(bijectors))) return block_sizes elif validate_args: message = ('`block_sizes` must be `None`, or a vector of the same length '
python
{ "resource": "" }
q266556
maybe_check_wont_broadcast
test
def maybe_check_wont_broadcast(flat_xs, validate_args): """Verifies that `parts` don't broadcast.""" flat_xs = tuple(flat_xs) # So we can receive generators. if not validate_args: # Note: we don't try static validation because it is theoretically # possible that a user wants to take advantage of broadcasting. # Only when `validate_args` is `True` do we enforce the validation. return flat_xs msg = 'Broadcasting probably indicates an error in model specification.' s = tuple(x.shape for x in flat_xs)
python
{ "resource": "" }
q266557
multivariate_normal_tril
test
def multivariate_normal_tril(x, dims, layer_fn=tf.compat.v1.layers.dense, loc_fn=lambda x: x, scale_fn=tril_with_diag_softplus_and_shift, name=None): """Constructs a trainable `tfd.MultivariateNormalTriL` distribution. This function creates a MultivariateNormal (MVN) with lower-triangular scale matrix. By default the MVN is parameterized via affine transformation of input tensor `x`. Using default args, this function is mathematically equivalent to: ```none Y = MVN(loc=matmul(W, x) + b, scale_tril=f(reshape_tril(matmul(M, x) + c))) where, W in R^[d, n] M in R^[d*(d+1)/2, n] b in R^d c in R^d f(S) = set_diag(S, softplus(matrix_diag_part(S)) + 1e-5) ``` Observe that `f` makes the diagonal of the triangular-lower scale matrix be positive and no smaller than `1e-5`. #### Examples ```python # This example fits a multilinear regression loss. import tensorflow as tf import tensorflow_probability as tfp # Create fictitious training data. dtype = np.float32 n = 3000 # number of samples x_size = 4 # size of single x y_size = 2 # size of single y def make_training_data(): np.random.seed(142) x = np.random.randn(n, x_size).astype(dtype) w = np.random.randn(x_size, y_size).astype(dtype) b = np.random.randn(1, y_size).astype(dtype) true_mean = np.tensordot(x, w, axes=[[-1], [0]]) + b noise = np.random.randn(n, y_size).astype(dtype) y = true_mean + noise return y, x y, x = make_training_data() # Build TF graph for fitting MVNTriL maximum likelihood estimator. mvn = tfp.trainable_distributions.multivariate_normal_tril(x, dims=y_size) loss = -tf.reduce_mean(mvn.log_prob(y)) train_op = tf.train.AdamOptimizer(learning_rate=2.**-3).minimize(loss) mse = tf.reduce_mean(tf.squared_difference(y, mvn.mean())) init_op = tf.global_variables_initializer() # Run graph 1000 times. num_steps = 1000 loss_ = np.zeros(num_steps) # Style: `_` to indicate sess.run result. mse_ = np.zeros(num_steps) with tf.Session() as sess: sess.run(init_op) for it in xrange(loss_.size): _, loss_[it], mse_[it] = sess.run([train_op, loss, mse]) if it % 200 == 0 or it == loss_.size - 1: print("iteration:{} loss:{} mse:{}".format(it, loss_[it], mse_[it])) # ==> iteration:0 loss:38.2020797729 mse:4.17175960541 # iteration:200 loss:2.90179634094 mse:0.990987896919 #
python
{ "resource": "" }
q266558
bernoulli
test
def bernoulli(x, layer_fn=tf.compat.v1.layers.dense, name=None): """Constructs a trainable `tfd.Bernoulli` distribution. This function creates a Bernoulli distribution parameterized by logits. Using default args, this function is mathematically equivalent to: ```none Y = Bernoulli(logits=matmul(W, x) + b) where, W in R^[d, n] b in R^d ``` #### Examples This function can be used as a [logistic regression]( https://en.wikipedia.org/wiki/Logistic_regression) loss. ```python # This example fits a logistic regression loss. import tensorflow as tf import tensorflow_probability as tfp # Create fictitious training data. dtype = np.float32 n = 3000 # number of samples x_size = 4 # size of single x def make_training_data(): np.random.seed(142) x = np.random.randn(n, x_size).astype(dtype) w = np.random.randn(x_size).astype(dtype) b = np.random.randn(1).astype(dtype) true_logits = np.tensordot(x, w, axes=[[-1], [-1]]) + b noise = np.random.logistic(size=n).astype(dtype) y = dtype(true_logits + noise > 0.) return y, x y, x = make_training_data() # Build TF graph for fitting Bernoulli maximum likelihood estimator. bernoulli = tfp.trainable_distributions.bernoulli(x) loss = -tf.reduce_mean(bernoulli.log_prob(y)) train_op = tf.train.AdamOptimizer(learning_rate=2.**-5).minimize(loss) mse = tf.reduce_mean(tf.squared_difference(y, bernoulli.mean())) init_op = tf.global_variables_initializer() # Run graph 1000 times. num_steps = 1000 loss_ = np.zeros(num_steps) # Style: `_` to indicate sess.run result. mse_ = np.zeros(num_steps) with tf.Session() as sess: sess.run(init_op) for it in xrange(loss_.size): _, loss_[it], mse_[it] = sess.run([train_op, loss, mse]) if it % 200 == 0 or it == loss_.size - 1: print("iteration:{} loss:{} mse:{}".format(it, loss_[it], mse_[it])) # ==> iteration:0 loss:0.635675370693 mse:0.222526371479 # iteration:200 loss:0.440077394247 mse:0.143687799573
python
{ "resource": "" }
q266559
normal
test
def normal(x, layer_fn=tf.compat.v1.layers.dense, loc_fn=lambda x: x, scale_fn=1., name=None): """Constructs a trainable `tfd.Normal` distribution. This function creates a Normal distribution parameterized by loc and scale. Using default args, this function is mathematically equivalent to: ```none Y = Normal(loc=matmul(W, x) + b, scale=1) where, W in R^[d, n] b in R^d ``` #### Examples This function can be used as a [linear regression]( https://en.wikipedia.org/wiki/Linear_regression) loss. ```python # This example fits a linear regression loss. import tensorflow as tf import tensorflow_probability as tfp # Create fictitious training data. dtype = np.float32 n = 3000 # number of samples x_size = 4 # size of single x def make_training_data(): np.random.seed(142) x = np.random.randn(n, x_size).astype(dtype) w = np.random.randn(x_size).astype(dtype) b = np.random.randn(1).astype(dtype) true_mean = np.tensordot(x, w, axes=[[-1], [-1]]) + b noise = np.random.randn(n).astype(dtype) y = true_mean + noise return y, x y, x = make_training_data() # Build TF graph for fitting Normal maximum likelihood estimator. normal = tfp.trainable_distributions.normal(x) loss = -tf.reduce_mean(normal.log_prob(y)) train_op = tf.train.AdamOptimizer(learning_rate=2.**-5).minimize(loss) mse = tf.reduce_mean(tf.squared_difference(y, normal.mean())) init_op = tf.global_variables_initializer() # Run graph 1000 times. num_steps = 1000 loss_ = np.zeros(num_steps) # Style: `_` to indicate sess.run result. mse_ = np.zeros(num_steps) with tf.Session() as sess: sess.run(init_op) for it in xrange(loss_.size): _, loss_[it], mse_[it] = sess.run([train_op, loss, mse]) if it % 200 == 0 or it == loss_.size - 1: print("iteration:{} loss:{} mse:{}".format(it, loss_[it], mse_[it])) # ==> iteration:0 loss:6.34114170074 mse:10.8444051743 # iteration:200 loss:1.40146839619 mse:0.965059816837 # iteration:400 loss:1.40052902699 mse:0.963181257248 # iteration:600 loss:1.40052902699 mse:0.963181257248
python
{ "resource": "" }
q266560
poisson
test
def poisson(x, layer_fn=tf.compat.v1.layers.dense, log_rate_fn=lambda x: x, name=None): """Constructs a trainable `tfd.Poisson` distribution. This function creates a Poisson distribution parameterized by log rate. Using default args, this function is mathematically equivalent to: ```none Y = Poisson(log_rate=matmul(W, x) + b) where, W in R^[d, n] b in R^d ``` #### Examples This can be used as a [Poisson regression]( https://en.wikipedia.org/wiki/Poisson_regression) loss. ```python # This example fits a poisson regression loss. import numpy as np import tensorflow as tf import tensorflow_probability as tfp # Create fictitious training data. dtype = np.float32 n = 3000 # number of samples x_size = 4 # size of single x def make_training_data(): np.random.seed(142) x = np.random.randn(n, x_size).astype(dtype) w = np.random.randn(x_size).astype(dtype) b = np.random.randn(1).astype(dtype) true_log_rate = np.tensordot(x, w, axes=[[-1], [-1]]) + b y = np.random.poisson(lam=np.exp(true_log_rate)).astype(dtype) return y, x y, x = make_training_data() # Build TF graph for fitting Poisson maximum likelihood estimator. poisson = tfp.trainable_distributions.poisson(x) loss = -tf.reduce_mean(poisson.log_prob(y)) train_op = tf.train.AdamOptimizer(learning_rate=2.**-5).minimize(loss) mse = tf.reduce_mean(tf.squared_difference(y, poisson.mean())) init_op = tf.global_variables_initializer() # Run graph 1000 times. num_steps = 1000 loss_ = np.zeros(num_steps) # Style: `_` to indicate sess.run result. mse_ = np.zeros(num_steps) with tf.Session() as sess: sess.run(init_op) for it in xrange(loss_.size): _, loss_[it], mse_[it] = sess.run([train_op, loss, mse]) if it % 200 == 0 or it == loss_.size - 1: print("iteration:{} loss:{} mse:{}".format(it, loss_[it], mse_[it])) # ==> iteration:0 loss:37.0814208984 mse:6359.41259766 # iteration:200 loss:1.42010736465 mse:40.7654914856 # iteration:400
python
{ "resource": "" }
q266561
_euler_method
test
def _euler_method(random_draw_parts, state_parts, drift_parts, step_size_parts, volatility_parts, name=None): """Applies one step of Euler-Maruyama method. Generates proposal of the form: ```python tfd.Normal(loc=state_parts + _get_drift(state_parts, ...), scale=tf.sqrt(step_size * volatility_fn(current_state))) ``` `_get_drift(state_parts, ..)` is a diffusion drift value at `state_parts`. Args: random_draw_parts: Python `list` of `Tensor`s containing the value(s) of the random perturbation variable(s). Must broadcast with the shape of `state_parts`. state_parts: Python `list` of `Tensor`s representing the current state(s) of the Markov chain(s). drift_parts: Python `list` of `Tensor`s representing value of the drift `_get_drift(*state_parts, ..)`. Must broadcast with the shape of `state_parts`. step_size_parts: Python `list` of `Tensor`s representing the step size for the Euler-Maruyama method. Must broadcast with the shape of `state_parts`. Larger step sizes lead to faster progress, but too-large step sizes make rejection exponentially more likely. When possible, it's often helpful to match per-variable step sizes to the standard deviations of the target distribution in each variable. volatility_parts: Python `list` of `Tensor`s representing the value of `volatility_fn(*state_parts)`. Must broadcast with the shape of `state_parts`. name: Python `str` name prefixed to Ops created by this function. Default value: `None`
python
{ "resource": "" }
q266562
_get_drift
test
def _get_drift(step_size_parts, volatility_parts, grads_volatility, grads_target_log_prob, name=None): """Compute diffusion drift at the current location `current_state`. The drift of the diffusion at is computed as ```none 0.5 * `step_size` * volatility_parts * `target_log_prob_fn(current_state)` + `step_size` * `grads_volatility` ``` where `volatility_parts` = `volatility_fn(current_state)**2` and `grads_volatility` is a gradient of `volatility_parts` at the `current_state`. Args: step_size_parts: Python `list` of `Tensor`s representing the step size for Euler-Maruyama method. Must broadcast with the shape of `volatility_parts`. Larger step sizes lead to faster progress, but too-large step sizes make rejection exponentially more likely. When possible, it's often helpful to match per-variable step sizes to the standard deviations of the target distribution in each variable.
python
{ "resource": "" }
q266563
_compute_log_acceptance_correction
test
def _compute_log_acceptance_correction(current_state_parts, proposed_state_parts, current_volatility_parts, proposed_volatility_parts, current_drift_parts, proposed_drift_parts, step_size_parts, independent_chain_ndims, name=None): r"""Helper to `kernel` which computes the log acceptance-correction. Computes `log_acceptance_correction` as described in `MetropolisHastings` class. The proposal density is normal. More specifically, ```none q(proposed_state | current_state) \sim N(current_state + current_drift, step_size * current_volatility**2) q(current_state | proposed_state) \sim N(proposed_state + proposed_drift, step_size * proposed_volatility**2) ``` The `log_acceptance_correction` is then ```none log_acceptance_correctio = q(current_state | proposed_state) - q(proposed_state | current_state) ``` Args: current_state_parts: Python `list` of `Tensor`s representing the value(s) of the current state of the chain. proposed_state_parts: Python `list` of `Tensor`s representing the value(s) of the proposed state of the chain. Must broadcast with the shape of `current_state_parts`. current_volatility_parts: Python `list` of `Tensor`s representing the value of `volatility_fn(*current_volatility_parts)`. Must broadcast with the shape of `current_state_parts`. proposed_volatility_parts: Python `list` of `Tensor`s representing the value of `volatility_fn(*proposed_volatility_parts)`. Must broadcast with the shape of `current_state_parts` current_drift_parts: Python `list` of `Tensor`s representing value of the drift `_get_drift(*current_state_parts, ..)`. Must broadcast with the shape of `current_state_parts`. proposed_drift_parts: Python `list` of `Tensor`s representing value of the drift `_get_drift(*proposed_drift_parts, ..)`. Must broadcast with the shape of `current_state_parts`. step_size_parts: Python `list` of `Tensor`s representing the step size for Euler-Maruyama method. Must broadcast with the shape of `current_state_parts`. independent_chain_ndims: Scalar `int` `Tensor` representing the number of leftmost `Tensor` dimensions which index independent chains. name: Python `str` name prefixed to Ops created by this function. Default value: `None` (i.e., 'compute_log_acceptance_correction'). Returns: log_acceptance_correction: `Tensor` representing the `log` acceptance-correction. (See docstring for mathematical definition.) """ with tf.compat.v1.name_scope(name, 'compute_log_acceptance_correction', [ current_state_parts, proposed_state_parts, current_volatility_parts, proposed_volatility_parts, current_drift_parts, proposed_drift_parts, step_size_parts, independent_chain_ndims ]): proposed_log_density_parts = [] dual_log_density_parts = [] for [ current_state, proposed_state, current_volatility, proposed_volatility, current_drift, proposed_drift, step_size, ] in zip( current_state_parts,
python
{ "resource": "" }
q266564
_maybe_call_volatility_fn_and_grads
test
def _maybe_call_volatility_fn_and_grads(volatility_fn, state, volatility_fn_results=None, grads_volatility_fn=None, sample_shape=None, parallel_iterations=10): """Helper which computes `volatility_fn` results and grads, if needed.""" state_parts = list(state) if mcmc_util.is_list_like(state) else [state] needs_volatility_fn_gradients = grads_volatility_fn is None # Convert `volatility_fn_results` to a list if volatility_fn_results is None: volatility_fn_results = volatility_fn(*state_parts) volatility_fn_results = (list(volatility_fn_results) if mcmc_util.is_list_like(volatility_fn_results) else [volatility_fn_results]) if len(volatility_fn_results) == 1: volatility_fn_results *= len(state_parts) if len(state_parts) != len(volatility_fn_results): raise ValueError('`volatility_fn` should return a tensor or a list ' 'of the same length as `current_state`.') # The shape of 'volatility_parts' needs to have the number of chains as a # leading dimension. For determinism we broadcast 'volatility_parts' to the # shape of `state_parts` since each dimension of `state_parts` could have a # different volatility value. volatility_fn_results = _maybe_broadcast_volatility(volatility_fn_results,
python
{ "resource": "" }
q266565
_maybe_broadcast_volatility
test
def _maybe_broadcast_volatility(volatility_parts, state_parts): """Helper to broadcast `volatility_parts` to the shape of `state_parts`.""" return
python
{ "resource": "" }
q266566
make_ar_transition_matrix
test
def make_ar_transition_matrix(coefficients): """Build transition matrix for an autoregressive StateSpaceModel. When applied to a vector of previous values, this matrix computes the expected new value (summing the previous states according to the autoregressive coefficients) in the top dimension of the state space, and moves all previous values down by one dimension, 'forgetting' the final (least recent) value. That is, it looks like this: ``` ar_matrix = [ coefs[0], coefs[1], ..., coefs[order] 1., 0 , ..., 0. 0., 1., ..., 0. ... 0., 0., ..., 1., 0. ] ``` Args: coefficients: float `Tensor` of shape `concat([batch_shape, [order]])`. Returns: ar_matrix: float `Tensor` with shape `concat([batch_shape, [order, order]])`.
python
{ "resource": "" }
q266567
BatchReshape._sample_shape
test
def _sample_shape(self, x): """Computes graph and static `sample_shape`.""" x_ndims = ( tf.rank(x) if tensorshape_util.rank(x.shape) is None else tensorshape_util.rank(x.shape)) event_ndims = ( tf.size(input=self.event_shape_tensor()) if tensorshape_util.rank(self.event_shape) is None else tensorshape_util.rank(self.event_shape)) batch_ndims = ( tf.size(input=self._batch_shape_unexpanded) if tensorshape_util.rank(self.batch_shape) is None else tensorshape_util.rank(self.batch_shape))
python
{ "resource": "" }
q266568
BatchReshape._call_reshape_input_output
test
def _call_reshape_input_output(self, fn, x, extra_kwargs=None): """Calls `fn`, appropriately reshaping its input `x` and output.""" # Note: we take `extra_kwargs` as a dict rather than `**extra_kwargs` # because it is possible the user provided extra kwargs would itself # have `fn` and/or `x` as a key. with tf.control_dependencies(self._runtime_assertions + self._validate_sample_arg(x)): sample_shape, static_sample_shape = self._sample_shape(x) old_shape = tf.concat( [ sample_shape, self.distribution.batch_shape_tensor(), self.event_shape_tensor(), ], axis=0) x_reshape = tf.reshape(x, old_shape) result = fn(x_reshape, **extra_kwargs) if extra_kwargs else fn(x_reshape) new_shape = tf.concat( [ sample_shape,
python
{ "resource": "" }
q266569
BatchReshape._call_and_reshape_output
test
def _call_and_reshape_output( self, fn, event_shape_list=None, static_event_shape_list=None, extra_kwargs=None): """Calls `fn` and appropriately reshapes its output.""" # Note: we take `extra_kwargs` as a dict rather than `**extra_kwargs` # because it is possible the user provided extra kwargs would itself # have `fn`, `event_shape_list`, `static_event_shape_list` and/or # `extra_kwargs` as keys. with tf.control_dependencies(self._runtime_assertions): if event_shape_list is None: event_shape_list = [self._event_shape_tensor()] if static_event_shape_list is None: static_event_shape_list = [self.event_shape] new_shape = tf.concat( [self._batch_shape_unexpanded] + event_shape_list, axis=0) result = tf.reshape(fn(**extra_kwargs) if extra_kwargs else fn(),
python
{ "resource": "" }
q266570
_bdtr
test
def _bdtr(k, n, p): """The binomial cumulative distribution function. Args: k: floating point `Tensor`. n: floating point `Tensor`. p: floating point `Tensor`. Returns: `sum_{j=0}^k p^j (1 - p)^(n - j)`. """ # Trick for getting
python
{ "resource": "" }
q266571
JointDistributionCoroutine._flat_sample_distributions
test
def _flat_sample_distributions(self, sample_shape=(), seed=None, value=None): """Executes `model`, creating both samples and distributions.""" ds = [] values_out = [] seed = seed_stream.SeedStream('JointDistributionCoroutine', seed) gen = self._model() index = 0 d = next(gen) try: while True: actual_distribution = d.distribution if isinstance(d, self.Root) else d ds.append(actual_distribution) if (value is not None and len(value) > index and value[index] is not None): seed() next_value = value[index]
python
{ "resource": "" }
q266572
latent_dirichlet_allocation
test
def latent_dirichlet_allocation(concentration, topics_words): """Latent Dirichlet Allocation in terms of its generative process. The model posits a distribution over bags of words and is parameterized by a concentration and the topic-word probabilities. It collapses per-word topic assignments. Args: concentration: A Tensor of shape [1, num_topics], which parameterizes the Dirichlet prior over topics. topics_words: A Tensor of shape [num_topics, num_words],
python
{ "resource": "" }
q266573
make_lda_variational
test
def make_lda_variational(activation, num_topics, layer_sizes): """Creates the variational distribution for LDA. Args: activation: Activation function to use. num_topics: The number of topics. layer_sizes: The number of hidden units per layer in the encoder. Returns: lda_variational: A function that takes a bag-of-words Tensor as input and returns a distribution over topics. """ encoder_net = tf.keras.Sequential() for num_hidden_units in layer_sizes: encoder_net.add( tf.keras.layers.Dense( num_hidden_units, activation=activation, kernel_initializer=tf.compat.v1.glorot_normal_initializer())) encoder_net.add( tf.keras.layers.Dense(
python
{ "resource": "" }
q266574
get_topics_strings
test
def get_topics_strings(topics_words, alpha, vocabulary, topics_to_print=10, words_per_topic=10): """Returns the summary of the learned topics. Arguments: topics_words: KxV tensor with topics as rows and words as columns. alpha: 1xK tensor of prior Dirichlet concentrations for the topics. vocabulary: A mapping of word's integer index to the corresponding string. topics_to_print: The number of topics with highest prior weight to summarize. words_per_topic: Number of wodrs per topic to return. Returns: summary: A np.array with strings. """ alpha = np.squeeze(alpha, axis=0) # Use a stable sorting algorithm so that when alpha is fixed # we always get the same topics.
python
{ "resource": "" }
q266575
newsgroups_dataset
test
def newsgroups_dataset(directory, split_name, num_words, shuffle_and_repeat): """20 newsgroups as a tf.data.Dataset.""" data = np.load(download(directory, FILE_TEMPLATE.format(split=split_name))) # The last row is empty in both train and test. data = data[:-1] # Each row is a list of word ids in the document. We first convert this to # sparse COO matrix (which automatically sums the repeating words). Then, # we convert this COO matrix to CSR format which allows for fast querying of # documents. num_documents = data.shape[0] indices = np.array([(row_idx, column_idx) for row_idx, row in enumerate(data) for column_idx in row]) sparse_matrix = scipy.sparse.coo_matrix( (np.ones(indices.shape[0]), (indices[:, 0], indices[:, 1])), shape=(num_documents, num_words), dtype=np.float32) sparse_matrix = sparse_matrix.tocsr() dataset = tf.data.Dataset.range(num_documents)
python
{ "resource": "" }
q266576
build_fake_input_fns
test
def build_fake_input_fns(batch_size): """Builds fake data for unit testing.""" num_words = 1000 vocabulary = [str(i) for i in range(num_words)] random_sample = np.random.randint( 10, size=(batch_size, num_words)).astype(np.float32) def train_input_fn(): dataset = tf.data.Dataset.from_tensor_slices(random_sample) dataset = dataset.batch(batch_size).repeat() return tf.compat.v1.data.make_one_shot_iterator(dataset).get_next()
python
{ "resource": "" }
q266577
build_input_fns
test
def build_input_fns(data_dir, batch_size): """Builds iterators for train and evaluation data. Each object is represented as a bag-of-words vector. Arguments: data_dir: Folder in which to store the data. batch_size: Batch size for both train and evaluation. Returns: train_input_fn: A function that returns an iterator over the training data. eval_input_fn: A function that returns an iterator over the evaluation data. vocabulary: A mapping of word's integer index to the corresponding string. """ with open(download(data_dir, "vocab.pkl"), "r") as f: words_to_idx = pickle.load(f) num_words = len(words_to_idx) vocabulary = [None] * num_words for word, idx in words_to_idx.items(): vocabulary[idx] = word # Build an iterator over training batches. def train_input_fn(): dataset = newsgroups_dataset( data_dir, "train", num_words, shuffle_and_repeat=True)
python
{ "resource": "" }
q266578
minimize
test
def minimize(grad_and_hessian_loss_fn, x_start, tolerance, l1_regularizer, l2_regularizer=None, maximum_iterations=1, maximum_full_sweeps_per_iteration=1, learning_rate=None, name=None): """Minimize using Hessian-informed proximal gradient descent. This function solves the regularized minimization problem ```none argmin{ Loss(x) + l1_regularizer * ||x||_1 + l2_regularizer * ||x||_2**2 : x in R^n } ``` where `Loss` is a convex C^2 function (typically, `Loss` is the negative log likelihood of a model and `x` is a vector of model coefficients). The `Loss` function does not need to be supplied directly, but this optimizer does need a way to compute the gradient and Hessian of the Loss function at a given value of `x`. The gradient and Hessian are often computationally expensive, and this optimizer calls them relatively few times compared with other algorithms. Args: grad_and_hessian_loss_fn: callable that takes as input a (batch of) `Tensor` of the same shape and dtype as `x_start` and returns the triple `(gradient_unregularized_loss, hessian_unregularized_loss_outer, hessian_unregularized_loss_middle)` as defined in the argument spec of `minimize_one_step`. x_start: (Batch of) vector-shaped, `float` `Tensor` representing the initial value of the argument to the `Loss` function. tolerance: scalar, `float` `Tensor` representing the tolerance for each optimization step; see the `tolerance` argument of `minimize_one_step`. l1_regularizer: scalar, `float` `Tensor` representing the weight of the L1 regularization term (see equation above). l2_regularizer: scalar, `float` `Tensor` representing the weight of the L2 regularization term (see equation above). Default value: `None` (i.e., no L2 regularization). maximum_iterations: Python integer specifying the maximum number of iterations of the outer loop of the optimizer. After this many iterations of the outer loop, the algorithm will terminate even if the return value `optimal_x` has not converged. Default value: `1`. maximum_full_sweeps_per_iteration: Python integer specifying the maximum number of sweeps allowed in each iteration of the outer loop of the optimizer. Passed as the `maximum_full_sweeps` argument to `minimize_one_step`. Default value: `1`. learning_rate: scalar, `float` `Tensor` representing a multiplicative factor used to dampen the proximal gradient descent steps. Default value: `None` (i.e., factor is conceptually `1`). name: Python string representing the name of the TensorFlow operation. The default name is `"minimize"`. Returns: x: `Tensor` of the same shape and dtype as `x_start`, representing the (batches of) computed values of `x` which minimizes `Loss(x)`. is_converged: scalar, `bool` `Tensor` indicating whether the minimization procedure converged within the specified number of iterations across all batches. Here convergence means that an iteration of the inner loop (`minimize_one_step`) returns `True` for its `is_converged` output value. iter: scalar, `int` `Tensor` indicating the actual number of iterations of the outer loop of the optimizer completed (i.e., number of calls to `minimize_one_step` before achieving convergence).
python
{ "resource": "" }
q266579
add_ema_control_dependencies
test
def add_ema_control_dependencies(vector_quantizer, one_hot_assignments, codes, commitment_loss, decay): """Add control dependencies to the commmitment loss to update the codebook. Args: vector_quantizer: An instance of the VectorQuantizer class. one_hot_assignments: The one-hot vectors corresponding to the matched codebook entry for each code in the batch. codes: A `float`-like `Tensor` containing the latent vectors to be compared to the codebook. commitment_loss: The commitment loss from comparing the encoder outputs to their neighboring codebook entries. decay: Decay factor for exponential moving average. Returns: commitment_loss: Commitment loss with control dependencies. """ # Use an exponential moving average to update the codebook. updated_ema_count = moving_averages.assign_moving_average( vector_quantizer.ema_count, tf.reduce_sum(input_tensor=one_hot_assignments, axis=[0, 1]), decay,
python
{ "resource": "" }
q266580
save_imgs
test
def save_imgs(x, fname): """Helper method to save a grid of images to a PNG file. Args: x: A numpy array of shape [n_images, height, width]. fname: The filename to write to (including extension). """ n = x.shape[0] fig = figure.Figure(figsize=(n, 1), frameon=False) canvas = backend_agg.FigureCanvasAgg(fig) for i in range(n):
python
{ "resource": "" }
q266581
visualize_training
test
def visualize_training(images_val, reconstructed_images_val, random_images_val, log_dir, prefix, viz_n=10): """Helper method to save images visualizing model reconstructions. Args: images_val: Numpy array containing a batch of input images. reconstructed_images_val: Numpy array giving the expected output (mean) of the decoder. random_images_val: Optionally, a Numpy array giving the expected output (mean) of decoding samples from the prior, or `None`. log_dir: The directory to write images (Python `str`). prefix: A specific label for the saved visualizations, which determines their filenames (Python `str`). viz_n: The number of images from each batch to visualize (Python `int`). """ save_imgs(images_val[:viz_n],
python
{ "resource": "" }
q266582
load_bernoulli_mnist_dataset
test
def load_bernoulli_mnist_dataset(directory, split_name): """Returns Hugo Larochelle's binary static MNIST tf.data.Dataset.""" amat_file = download(directory, FILE_TEMPLATE.format(split=split_name)) dataset = tf.data.TextLineDataset(amat_file) str_to_arr = lambda string: np.array([c == b"1" for c in string.split()]) def _parser(s):
python
{ "resource": "" }
q266583
as_numpy_dtype
test
def as_numpy_dtype(dtype): """Returns a `np.dtype` based on this `dtype`.""" dtype = tf.as_dtype(dtype) if hasattr(dtype,
python
{ "resource": "" }
q266584
base_dtype
test
def base_dtype(dtype): """Returns a non-reference `dtype` based on this `dtype`.""" dtype = tf.as_dtype(dtype) if hasattr(dtype,
python
{ "resource": "" }
q266585
is_bool
test
def is_bool(dtype): """Returns whether this is a boolean data type.""" dtype = tf.as_dtype(dtype) if hasattr(dtype, 'is_bool'):
python
{ "resource": "" }
q266586
is_complex
test
def is_complex(dtype): """Returns whether this is a complex floating point type.""" dtype = tf.as_dtype(dtype) if hasattr(dtype, 'is_complex'):
python
{ "resource": "" }
q266587
max
test
def max(dtype): # pylint: disable=redefined-builtin """Returns the maximum representable value in this data type.""" dtype =
python
{ "resource": "" }
q266588
name
test
def name(dtype): """Returns the string name for this `dtype`.""" dtype = tf.as_dtype(dtype) if hasattr(dtype, 'name'):
python
{ "resource": "" }
q266589
size
test
def size(dtype): """Returns the number of bytes to represent this `dtype`.""" dtype = tf.as_dtype(dtype) if hasattr(dtype,
python
{ "resource": "" }
q266590
_assert_same_base_type
test
def _assert_same_base_type(items, expected_type=None): r"""Asserts all items are of the same base type. Args: items: List of graph items (e.g., `Variable`, `Tensor`, `SparseTensor`, `Operation`, or `IndexedSlices`). Can include `None` elements, which will be ignored. expected_type: Expected type. If not specified, assert all items are of the same base type. Returns: Validated type, or none if neither expected_type nor items provided. Raises: ValueError: If any types do not match. """ original_expected_type = expected_type mismatch = False for item in items: if item is not None: item_type = base_dtype(item.dtype) if not expected_type: expected_type = item_type elif expected_type != item_type: mismatch = True break if mismatch: # Loop back through and build up an informative error message (this is very # slow, so we don't do it unless we found an error above). expected_type = original_expected_type original_item_str = None get_name = lambda x: x.name if hasattr(x, 'name') else str(x) for item in items: if item is not None: item_type = base_dtype(item.dtype)
python
{ "resource": "" }
q266591
assert_same_float_dtype
test
def assert_same_float_dtype(tensors=None, dtype=None): """Validate and return float type based on `tensors` and `dtype`. For ops such as matrix multiplication, inputs and weights must be of the same float type. This function validates that all `tensors` are the same type, validates that type is `dtype` (if supplied), and returns the type. Type must be a floating point type. If neither `tensors` nor `dtype` is supplied,
python
{ "resource": "" }
q266592
minimize
test
def minimize(objective_function, initial_simplex=None, initial_vertex=None, step_sizes=None, objective_at_initial_simplex=None, objective_at_initial_vertex=None, batch_evaluate_objective=False, func_tolerance=1e-8, position_tolerance=1e-8, parallel_iterations=1, max_iterations=None, reflection=None, expansion=None, contraction=None, shrinkage=None, name=None): """Minimum of the objective function using the Nelder Mead simplex algorithm. Performs an unconstrained minimization of a (possibly non-smooth) function using the Nelder Mead simplex method. Nelder Mead method does not support univariate functions. Hence the dimensions of the domain must be 2 or greater. For details of the algorithm, see [Press, Teukolsky, Vetterling and Flannery(2007)][1]. Points in the domain of the objective function may be represented as a `Tensor` of general shape but with rank at least 1. The algorithm proceeds by modifying a full rank simplex in the domain. The initial simplex may either be specified by the user or can be constructed using a single vertex supplied by the user. In the latter case, if `v0` is the supplied vertex, the simplex is the convex hull of the set: ```None S = {v0} + {v0 + step_i * e_i} ``` Here `e_i` is a vector which is `1` along the `i`-th axis and zero elsewhere and `step_i` is a characteristic length scale along the `i`-th axis. If the step size is not supplied by the user, a unit step size is used in every axis. Alternately, a single step size may be specified which is used for every axis. The most flexible option is to supply a bespoke step size for every axis. ### Usage: The following example demonstrates the usage of the Nelder Mead minimzation on a two dimensional problem with the minimum located at a non-differentiable point. ```python # The objective function def sqrt_quadratic(x): return tf.sqrt(tf.reduce_sum(x ** 2, axis=-1)) start = tf.constant([6.0, -21.0]) # Starting point for the search. optim_results = tfp.optimizer.nelder_mead_minimize( sqrt_quadratic, initial_vertex=start, func_tolerance=1e-8, batch_evaluate_objective=True) with tf.Session() as session: results = session.run(optim_results) # Check that the search converged assert(results.converged) # Check that the argmin is close to the actual value. np.testing.assert_allclose(results.position, np.array([0.0, 0.0]), atol=1e-7) # Print out the total number of function evaluations it took. print ("Function evaluations: %d" % results.num_objective_evaluations) ``` ### References: [1]: William Press, Saul Teukolsky, William Vetterling and Brian Flannery. Numerical Recipes in C++, third edition. pp. 502-507. (2007). http://numerical.recipes/cpppages/chap0sel.pdf [2]: Jeffrey Lagarias, James Reeds, Margaret Wright and Paul Wright. Convergence properties of the Nelder-Mead simplex method in low dimensions, Siam J. Optim., Vol 9, No. 1, pp. 112-147. (1998). http://www.math.kent.edu/~reichel/courses/Opt/reading.material.2/nelder.mead.pdf [3]: Fuchang Gao and Lixing Han. Implementing the Nelder-Mead simplex algorithm with adaptive parameters. Computational Optimization and Applications, Vol 51, Issue 1, pp 259-277. (2012). https://pdfs.semanticscholar.org/15b4/c4aa7437df4d032c6ee6ce98d6030dd627be.pdf 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 minimized. 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]`. Note that this method does not support univariate functions so the problem dimension `n` must be strictly greater than 1. initial_simplex: (Optional) `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: (Optional) `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: (Optional) `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 description above for details on how step sizes and initial vertex are used to construct the initial simplex. objective_at_initial_simplex: (Optional) Rank `1` `Tensor` of real dtype of a rank `1` `Tensor`. 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: (Optional) 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: (Optional) 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. Evaluating the objective function in a batch allows use of vectorization and should be preferred if the objective function allows it. func_tolerance: (Optional) Scalar `Tensor` of real dtype. The algorithm stops if the absolute difference between the largest and the smallest function value on the vertices of the simplex is below this number. position_tolerance: (Optional) Scalar `Tensor` of real dtype. The algorithm stops if the largest absolute difference between the coordinates of the vertices is below this threshold. parallel_iterations: (Optional) Positive integer. The number of iterations allowed to run in parallel. max_iterations: (Optional) Scalar positive `Tensor` of dtype `int32`. The maximum number of iterations allowed. If `None` then no limit is applied. reflection: (Optional) Positive Scalar `Tensor` of same dtype as `initial_vertex`. This parameter controls the scaling of the reflected vertex. See, [Press et al(2007)][1] for details. If not specified, uses the dimension dependent prescription of [Gao and Han(2012)][3]. expansion: (Optional) Positive Scalar `Tensor` of same dtype as `initial_vertex`. Should be greater than `1` and `reflection`. This parameter controls the expanded scaling of a reflected vertex. See, [Press et al(2007)][1] for details. If not specified, uses the dimension dependent prescription of [Gao and Han(2012)][3]. contraction: (Optional) Positive scalar `Tensor` of same dtype as `initial_vertex`. Must be between `0` and `1`. This parameter controls the contraction of the reflected vertex when the objective function at the reflected point fails to show sufficient decrease. See, [Press et al(2007)][1] for more details. If not specified, uses the dimension dependent prescription of [Gao and Han(2012][3]. shrinkage: (Optional) Positive scalar `Tensor` of same dtype as `initial_vertex`.
python
{ "resource": "" }
q266593
nelder_mead_one_step
test
def nelder_mead_one_step(current_simplex, current_objective_values, objective_function=None, dim=None, func_tolerance=None, position_tolerance=None, batch_evaluate_objective=False, reflection=None, expansion=None, contraction=None, shrinkage=None, name=None): """A single iteration of the Nelder Mead algorithm.""" with tf.compat.v1.name_scope(name, 'nelder_mead_one_step'): domain_dtype = current_simplex.dtype.base_dtype order = tf.argsort( current_objective_values, direction='ASCENDING', stable=True) ( best_index, worst_index, second_worst_index ) = order[0], order[-1], order[-2] worst_vertex = current_simplex[worst_index] ( best_objective_value, worst_objective_value, second_worst_objective_value ) = ( current_objective_values[best_index], current_objective_values[worst_index], current_objective_values[second_worst_index] ) # Compute the centroid of the face opposite the worst vertex. face_centroid = tf.reduce_sum( input_tensor=current_simplex, axis=0) - worst_vertex face_centroid /= tf.cast(dim, domain_dtype) # Reflect the worst vertex through the opposite face. reflected = face_centroid + reflection * (face_centroid - worst_vertex) objective_at_reflected = objective_function(reflected) num_evaluations = 1 has_converged = _check_convergence(current_simplex, current_simplex[best_index], best_objective_value, worst_objective_value, func_tolerance, position_tolerance) def _converged_fn(): return (True, current_simplex, current_objective_values, 0) case0 = has_converged, _converged_fn accept_reflected = ( (objective_at_reflected < second_worst_objective_value) & (objective_at_reflected >= best_objective_value)) accept_reflected_fn = _accept_reflected_fn(current_simplex, current_objective_values, worst_index, reflected, objective_at_reflected) case1 = accept_reflected, accept_reflected_fn do_expansion = objective_at_reflected < best_objective_value expansion_fn = _expansion_fn(objective_function, current_simplex, current_objective_values, worst_index, reflected, objective_at_reflected, face_centroid, expansion)
python
{ "resource": "" }
q266594
_accept_reflected_fn
test
def _accept_reflected_fn(simplex, objective_values, worst_index, reflected, objective_at_reflected): """Creates the condition function pair for a reflection to be accepted.""" def _replace_worst_with_reflected(): next_simplex = _replace_at_index(simplex, worst_index, reflected)
python
{ "resource": "" }
q266595
_expansion_fn
test
def _expansion_fn(objective_function, simplex, objective_values, worst_index, reflected, objective_at_reflected, face_centroid, expansion): """Creates the condition function pair for an expansion.""" def _expand_and_maybe_replace(): """Performs the expansion step.""" expanded = face_centroid + expansion * (reflected - face_centroid) expanded_objective_value = objective_function(expanded)
python
{ "resource": "" }
q266596
_outside_contraction_fn
test
def _outside_contraction_fn(objective_function, simplex, objective_values, face_centroid, best_index, worst_index, reflected, objective_at_reflected, contraction, shrinkage, batch_evaluate_objective): """Creates the condition function pair for an outside contraction.""" def _contraction(): """Performs a contraction.""" contracted = face_centroid + contraction * (reflected - face_centroid) objective_at_contracted = objective_function(contracted) is_contracted_acceptable = objective_at_contracted <= objective_at_reflected def _accept_contraction(): next_simplex = _replace_at_index(simplex, worst_index, contracted) objective_at_next_simplex = _replace_at_index( objective_values, worst_index,
python
{ "resource": "" }
q266597
_shrink_towards_best
test
def _shrink_towards_best(objective_function, simplex, best_index, shrinkage, batch_evaluate_objective): """Shrinks the simplex around the best vertex.""" # If the contraction step fails to improve the average
python
{ "resource": "" }
q266598
_replace_at_index
test
def _replace_at_index(x, index, replacement): """Replaces an element at supplied index.""" x_new =
python
{ "resource": "" }
q266599
_check_convergence
test
def _check_convergence(simplex, best_vertex, best_objective, worst_objective, func_tolerance, position_tolerance): """Returns True if the simplex has converged. If the simplex size is smaller than the `position_tolerance` or the variation of the function value over the vertices of the simplex is smaller than the `func_tolerance` return True else False. Args: simplex: `Tensor` of real dtype. The simplex to test for convergence. For more details, see the docstring for `initial_simplex` argument of `minimize`. best_vertex: `Tensor` of real dtype and rank one less than `simplex`. The vertex with the best (i.e. smallest) objective value. best_objective: Scalar `Tensor` of real dtype. The best (i.e. smallest) value of the objective function at a vertex. worst_objective: Scalar `Tensor` of same dtype as `best_objective`. The worst (i.e. largest) value of the objective function at a vertex. func_tolerance: Scalar positive `Tensor`. The tolerance for
python
{ "resource": "" }