_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
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 else str(tensor.numpy()) else: text = "<unprintable>" if "\n" in text: text = "\n" + text return text
python
{ "resource": "" }
q266501
RandomVariable.sample_shape
test
def sample_shape(self): """Sample shape of random variable as a `TensorShape`.""" if isinstance(self._sample_shape, tf.Tensor): return tf.TensorShape(tf.get_static_value(self._sample_shape)) return tf.TensorShape(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 tf.compat.v1.name_scope(name): if isinstance(self._sample_shape, tf.Tensor): return self._sample_shape return tf.convert_to_tensor( value=self.sample_shape.as_list(), dtype=tf.int32)
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}. You must either pass in the " "value argument or implement sample for {0}." .format(self.distribution.__class__.__name__)) return self._value
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: Value of the random variable. #### Examples ```python x = Normal(0.0, 1.0) with tf.Session() as sess: # Usage passing the session explicitly. print(x.eval(sess)) # Usage with the default session. The 'with' block # above makes 'sess' the default session. print(x.eval()) ``` """ return self.value.eval(session=session, feed_dict=feed_dict)
python
{ "resource": "" }
q266505
RandomVariable.numpy
test
def numpy(self): """Value as NumPy array, only available for TF Eager.""" if not isinstance(self.value, ops.EagerTensor): raise NotImplementedError("value argument must be a EagerTensor.") return self.value.numpy()
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. ``` Distribution parameters from `prior`, as well as `scale`, `s`, and `n`. will broadcast in the case of multidimensional sets of parameters. Args: prior: `Normal` object of type `dtype`: the prior distribution having parameters `(loc0, scale0)`. scale: tensor of type `dtype`, taking values `scale > 0`. The known stddev parameter(s). s: Tensor of type `dtype`. The sum(s) of observations. n: Tensor of type `int`. The number(s) of observations. Returns: A new Normal posterior distribution object for the unknown observation mean `loc`. Raises: TypeError: if dtype of `s` does not match `dtype`, or `prior` is not a Normal object. """ if not isinstance(prior, normal.Normal): raise TypeError("Expected prior to be an instance of type Normal") if s.dtype != prior.dtype: raise TypeError( "Observation sum s.dtype does not match prior dtype: %s vs. %s" % (s.dtype, prior.dtype)) n = tf.cast(n, prior.dtype) scale0_2 = tf.square(prior.scale) scale_2 = tf.square(scale) scalep_2 = 1.0/(1/scale0_2 + n/scale_2) return normal.Normal( loc=(prior.loc / scale0_2 + s / scale_2) * scalep_2, scale=tf.sqrt(scalep_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_, 2017. https://arxiv.org/abs/1705.07057 """ with tf.compat.v2.name_scope(name or "real_nvp_default_template"): def _fn(x, output_units, **condition_kwargs): """Fully connected MLP parameterized via `real_nvp_template`.""" if condition_kwargs: raise NotImplementedError( "Conditioning not implemented in the default template.") if tensorshape_util.rank(x.shape) == 1: x = x[tf.newaxis, ...] reshape_output = lambda x: x[0] else: reshape_output = lambda x: x for units in hidden_layers: x = tf.compat.v1.layers.dense( inputs=x, units=units, activation=activation, *args, # pylint: disable=keyword-arg-before-vararg **kwargs) x = tf.compat.v1.layers.dense( inputs=x, units=(1 if shift_only else 2) * output_units, activation=None, *args, # pylint: disable=keyword-arg-before-vararg **kwargs) if shift_only: return reshape_output(x), None shift, log_scale = tf.split(x, 2, axis=-1) return reshape_output(shift), reshape_output(log_scale) return tf.compat.v1.make_template("real_nvp_default_template", _fn)
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), scale=dtype_util.as_numpy_dtype(dtype)(1)).sample( tf.concat([shape, [dimension]], axis=0), seed=seed()) unit_norm = raw / tf.norm(tensor=raw, ord=2, axis=-1)[..., tf.newaxis] return unit_norm
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( # tf.reduce_min(eigenvalues, axis=-1) >= 0, dtype=x.dtype) # tf.where(psd_mask, answer, float('-inf')) # to emit probability 0 for inputs that are not PSD, without ever raising # an error. More care must be taken, as due to numerical stability issues, # self_adjoint_eigvals can return slightly negative eigenvalues even for # a PSD matrix. if self.input_output_cholesky: logdet = 2.0 * tf.reduce_sum( input_tensor=tf.math.log(tf.linalg.diag_part(x)), axis=[-1]) else: _, logdet = tf.linalg.slogdet(x) answer = (self.concentration - 1.) * logdet return answer
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'): logpi = np.log(np.pi) ans = tf.zeros_like(self.concentration) for k in range(1, self.dimension): ans += logpi * (k / 2.) ans += tf.math.lgamma(self.concentration + (self.dimension - 1 - k) / 2.) ans -= tf.math.lgamma(self.concentration + (self.dimension - 1) / 2.) return ans
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 is None: dtype = dt elif dtype != dt: raise TypeError('Found incompatible dtypes, {} and {}.'.format(dtype, dt)) if dtype is None and preferred_dtype is None: return None return (preferred_dtype if dtype is None else dtype).as_numpy_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), dtype=self.sample_shape.dtype), self.distribution.event_shape_tensor(), ], axis=0) x = tf.reshape(x, shape=shape) shape = prefer_static.concat([ self.distribution.batch_shape_tensor(), self.sample_shape, self.distribution.event_shape_tensor(), ], axis=0) return tf.broadcast_to(x, shape) return _fn
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 = tensor_to_broadcast for tensor in target_tensors: output += tf.zeros_like(tensor) return output
python
{ "resource": "" }
q266514
Triangular._pdf_at_peak
test
def _pdf_at_peak(self): """Pdf evaluated at the peak.""" return (self.peak - self.low) / (self.high - self.low)
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 `filter_beyond_lag` are both lists with different lengths. #### Examples We use ESS to estimate standard error. ``` import tensorflow as tf import tensorflow_probability as tfp tfd = tfp.distributions target = tfd.MultivariateNormalDiag(scale_diag=[1., 2.]) # Get 1000 states from one chain. states = tfp.mcmc.sample_chain( num_burnin_steps=200, num_results=1000, current_state=tf.constant([0., 0.]), kernel=tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=0.05, num_leapfrog_steps=20)) states.shape ==> (1000, 2) ess = effective_sample_size(states) ==> Shape (2,) Tensor mean, variance = tf.nn.moments(states, axis=0) standard_error = tf.sqrt(variance / ess) ``` Some math shows that, with `R_k` the auto-correlation sequence, `R_k := Covariance{X_1, X_{1+k}} / Variance{X_1}`, we have ```ESS(N) = N / [ 1 + 2 * ( (N - 1) / N * R_1 + ... + 1 / N * R_{N-1} ) ]``` This function estimates the above by first estimating the auto-correlation. Since `R_k` must be estimated using only `N - k` samples, it becomes progressively noisier for larger `k`. For this reason, the summation over `R_k` should be truncated at some number `filter_beyond_lag < N`. Since many MCMC methods generate chains where `R_k > 0`, a reasonable criteria is to truncate at the first index where the estimated auto-correlation becomes negative. The arguments `filter_beyond_lag`, `filter_threshold` are filters intended to remove noisy tail terms from `R_k`. They combine in an "OR" manner meaning terms are removed if they were to be filtered under the `filter_beyond_lag` OR `filter_threshold` criteria. """ states_was_list = _is_list_like(states) # Convert all args to lists. if not states_was_list: states = [states] filter_beyond_lag = _broadcast_maybelist_arg(states, filter_beyond_lag, 'filter_beyond_lag') filter_threshold = _broadcast_maybelist_arg(states, filter_threshold, 'filter_threshold') # Process items, one at a time. with tf.compat.v1.name_scope(name, 'effective_sample_size'): ess_list = [ _effective_sample_size_single_state(s, ml, mlt) for (s, ml, mlt) in zip(states, filter_beyond_lag, filter_threshold) ] if states_was_list: return ess_list return ess_list[0]
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. - mask, 0.) auto_corr *= mask # With R[k] := auto_corr[k, ...], # ESS = N / {1 + 2 * Sum_{k=1}^N (N - k) / N * R[k]} # = N / {-1 + 2 * Sum_{k=0}^N (N - k) / N * R[k]} (since R[0] = 1) # approx N / {-1 + 2 * Sum_{k=0}^M (N - k) / N * R[k]} # where M is the filter_beyond_lag truncation point chosen above. # Get the factor (N - k) / N, and give it shape [M, 1,...,1], having total # ndims the same as auto_corr n = _axis_size(states, axis=0) k = tf.range(0., _axis_size(auto_corr, axis=0)) nk_factor = (n - k) / n if auto_corr.shape.ndims is not None: new_shape = [-1] + [1] * (auto_corr.shape.ndims - 1) else: new_shape = tf.concat( ([-1], tf.ones([tf.rank(auto_corr) - 1], dtype=tf.int32)), axis=0) nk_factor = tf.reshape(nk_factor, new_shape) return n / (-1 + 2 * tf.reduce_sum(input_tensor=nk_factor * auto_corr, axis=0))
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 sequence variance, the mean of the chain variances. b_div_n = _reduce_variance( tf.reduce_mean(input_tensor=state, axis=sample_axis, keepdims=True), sample_and_chain_axis, biased=False) w = tf.reduce_mean( input_tensor=_reduce_variance( state, sample_axis, keepdims=True, biased=True), axis=sample_and_chain_axis) # sigma^2_+ is an estimate of the true variance, which would be unbiased if # each chain was drawn from the target. c.f. "law of total variance." sigma_2_plus = w + b_div_n return ((m + 1.) / m) * sigma_2_plus / w - (n - 1.) / (m * n)
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 None: return tf.cast(tf.size(input=x), x.dtype) return tf.cast( tf.reduce_prod(input_tensor=tf.gather(tf.shape(input=x), axis)), x.dtype)
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 ' '`states` ({})'.format(name, len(states))) else: secondary_arg = [secondary_arg] * len(states) return secondary_arg
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` vectors representing the weight associate with each `grid` value. """ with tf.name_scope( name or "vector_diffeomixture_quadrature_gauss_hermite"): grid, probs = np.polynomial.hermite.hermgauss(deg=quadrature_size) npdt = dtype_util.as_numpy_dtype(loc.dtype) grid = grid.astype(npdt) probs = probs.astype(npdt) probs /= np.linalg.norm(probs, ord=1, keepdims=True) probs = tf.convert_to_tensor(value=probs, name="probs", dtype=loc.dtype) # The following maps the broadcast of `loc` and `scale` to each grid # point, i.e., we are creating several log-rates that correspond to the # different Gauss-Hermite quadrature points and (possible) batches of # `loc` and `scale`. grid = (loc[..., tf.newaxis] + np.sqrt(2.) * scale[..., tf.newaxis] * grid) return grid, probs
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 = tf.reshape( edges, shape=tf.concat( [[-1], tf.ones([batch_ndims], dtype=tf.int32)], axis=0)) quantiles = dist.quantile(edges) # Cyclically permute left by one. perm = tf.concat([tf.range(1, 1 + batch_ndims), [0]], axis=0) quantiles = tf.transpose(a=quantiles, perm=perm) return quantiles quantiles = _compute_quantiles() # Compute grid as quantile midpoints. grid = (quantiles[..., :-1] + quantiles[..., 1:]) / 2. # Set shape hints. new_shape = tensorshape_util.concatenate(dist.batch_shape, [quadrature_size]) tensorshape_util.set_shape(grid, new_shape) # By construction probs is constant, i.e., `1 / quadrature_size`. This is # important, because non-constant probs leads to non-reparameterizable # samples. probs = tf.fill( dims=[quadrature_size], value=1. / tf.cast(quadrature_size, dist.dtype)) return grid, probs
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 mapping is None: mapping = _Mapping(x=x, y=y, ildj=ildj, kwargs=kwargs) elif any(arg is not None for arg in [x, y, ildj, kwargs]): raise ValueError("Cannot simultaneously specify mapping and individual " "arguments.") return _Mapping( x=self._merge(self.x, mapping.x), y=self._merge(self.y, mapping.y), ildj=self._merge(self.ildj, mapping.ildj), kwargs=self._merge(self.kwargs, mapping.kwargs, use_equals=True))
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 self.x, y=None if field == "y" else self.y, ildj=self.ildj, kwargs=self.kwargs)
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: return new if new is None: return old if (old == new) if use_equals else (old is new): return old raise ValueError("Incompatible values: %s != %s" % (old, new))
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()))) elif isinstance(x, (list, tuple)): return tuple(map(self._deep_tuple, x)) return x
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]): step_size = tf.convert_to_tensor(value=step_size) dtype = step_size.dtype.base_dtype # Output shape of the left increments tensor. output_shape = tf.concat(([max_doublings + 1], batch_shape), axis=0) # A sample realization of X_k. expand_left = distributions.Bernoulli(0.5, dtype=dtype).sample( sample_shape=output_shape, seed=seed) # The widths of the successive intervals. Starts with 1.0 and ends with # 2^max_doublings. width_multipliers = tf.cast(2 ** tf.range(0, max_doublings+1), dtype=dtype) # Output shape of the `widths` tensor. widths_shape = tf.concat(([max_doublings + 1], tf.ones_like(batch_shape)), axis=0) width_multipliers = tf.reshape(width_multipliers, shape=widths_shape) # Widths shape is [max_doublings + 1, 1, 1, 1...]. widths = width_multipliers * step_size # Take the cumulative sum of the left side increments in slice width to give # the resulting distance from the inital lower bound. left_increments = tf.cumsum(widths * expand_left, exclusive=True, axis=0) return left_increments, widths
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 first set of bounds outside the slice and if there are none, the index of the widest set. """ with tf.compat.v1.name_scope(name, 'find_best_interval_idx', [x]): # Returns max_doublings + 1. Positive int32. k = tf.shape(input=x)[0] dtype = x.dtype.base_dtype # Factors by which to multiply the flag. Corresponds to (2 * k - i) above. mults = tf.range(2 * k, k, -1, dtype=dtype)[:, tf.newaxis] # Factors by which to shift the flag. Corresponds to i above. Ensures the # widest bounds are selected if there are no bounds outside the slice. shifts = tf.range(k, dtype=dtype)[:, tf.newaxis] indices = tf.argmax(input=mults * x + shifts, axis=0, output_type=dtype) return indices
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. lower_bounds: A tensor of same shape and dtype as `x_initial`. Slice lower bounds for each chain. both_ok: A tensor of shape `x_initial` and boolean dtype. Indicates if both the chosen upper and lower bound lie outside of the slice. #### References [1]: Radford M. Neal. Slice Sampling. The Annals of Statistics. 2003, Vol 31, No. 3 , 705-767. https://projecteuclid.org/download/pdf_1/euclid.aos/1056562461 """ with tf.compat.v1.name_scope( name, 'slice_bounds_by_doubling', [x_initial, log_slice_heights, max_doublings, step_size]): seed_gen = distributions.SeedStream(seed, salt='slice_bounds_by_doubling') x_initial = tf.convert_to_tensor(value=x_initial) batch_shape = tf.shape(input=x_initial) dtype = step_size.dtype.base_dtype left_endpoints = x_initial + step_size * tf.random.uniform( batch_shape, minval=-1.0, maxval=0.0, dtype=dtype, seed=seed_gen()) # Compute the increments by which we need to step the upper and lower bounds # part of the doubling procedure. left_increments, widths = _left_doubling_increments( batch_shape, max_doublings, step_size, seed=seed_gen()) # The left and right end points. Shape (max_doublings+1,) + batch_shape. left_endpoints -= left_increments right_endpoints = left_endpoints + widths # Test if these end points lie outside of the slice. # Checks if the end points of the slice are outside the graph of the pdf. left_ep_values = tf.map_fn(target_log_prob, left_endpoints) right_ep_values = tf.map_fn(target_log_prob, right_endpoints) left_ok = left_ep_values < log_slice_heights right_ok = right_ep_values < log_slice_heights both_ok = left_ok & right_ok both_ok_f = tf.reshape(both_ok, [max_doublings + 1, -1]) best_interval_idx = _find_best_interval_idx( tf.cast(both_ok_f, dtype=tf.int32)) # Formats the above index as required to use with gather_nd. point_index_gather = tf.stack( [best_interval_idx, tf.range(tf.size(input=best_interval_idx))], axis=1, name='point_index_gather') left_ep_f = tf.reshape(left_endpoints, [max_doublings + 1, -1]) right_ep_f = tf.reshape(right_endpoints, [max_doublings + 1, -1]) # The x values of the uppper and lower bounds of the slices for each chain. lower_bounds = tf.reshape(tf.gather_nd(left_ep_f, point_index_gather), batch_shape) upper_bounds = tf.reshape(tf.gather_nd(right_ep_f, point_index_gather), batch_shape) both_ok = tf.reduce_any(input_tensor=both_ok, axis=0) return upper_bounds, lower_bounds, both_ok
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. found = tf.zeros_like(x_initial, dtype=tf.bool) cond = lambda found, *ignored_args: ~tf.reduce_all(input_tensor=found) x_next = tf.identity(x_initial) x_initial_shape = tf.shape(input=x_initial) x_initial_dtype = x_initial.dtype.base_dtype def _body(found, left, right, x_next): """Iterates until every chain has found a suitable next state.""" proportions = tf.random.uniform( x_initial_shape, dtype=x_initial_dtype, seed=seed_gen()) x_proposed = tf.where(~found, left + proportions * (right - left), x_next) accept_res = _test_acceptance(x_initial, target_log_prob=target_log_prob, decided=found, log_slice_heights=log_slice_heights, x_proposed=x_proposed, step_size=step_size, lower_bounds=left, upper_bounds=right) boundary_test = log_slice_heights < target_log_prob(x_proposed) can_accept = boundary_test & accept_res next_found = found | can_accept # Note that it might seem that we are moving the left and right end points # even if the point has been accepted (which is contrary to the stated # algorithm in Neal). However, this does not matter because the endpoints # for points that have been already accepted are not used again so it # doesn't matter what we do with them. next_left = tf.where(x_proposed < x_initial, x_proposed, left) next_right = tf.where(x_proposed >= x_initial, x_proposed, right) return next_found, next_left, next_right, x_proposed return tf.while_loop( cond=cond, body=_body, loop_vars=(found, lower_bounds, upper_bounds, x_next))[-1]
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', [x_initial, step_size, max_doublings]): x_initial = tf.convert_to_tensor(value=x_initial) # Obtain the input dtype of the array. dtype = x_initial.dtype.base_dtype # Select the height of the slice. Tensor of shape x_initial.shape. log_slice_heights = target_log_prob(x_initial) - tf.random.gamma( tf.shape(input=x_initial), alpha=1, dtype=dtype, seed=seed) # Given the above x and slice heights, compute the bounds of the slice for # each chain. upper_bounds, lower_bounds, bounds_satisfied = slice_bounds_by_doubling( x_initial, target_log_prob, log_slice_heights, max_doublings, step_size, seed=seed) retval = _sample_with_shrinkage(x_initial, target_log_prob=target_log_prob, log_slice_heights=log_slice_heights, step_size=step_size, lower_bounds=lower_bounds, upper_bounds=upper_bounds, seed=seed) return (retval, target_log_prob(retval), bounds_satisfied, upper_bounds, lower_bounds)
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. variational_model() elbo_loss = -(observed_log_joint_fn(**variational_sample) - variational_log_joint_fn(**variational_sample)) ``` After performing inference by minimizing the variational loss, a value-setting interceptor enables simulation from the posterior predictive distribution: ```python with ed.tape() as posterior_samples: # tape is a map {rv.name : rv} variational_model() with ed.interception(ed.make_value_setter(**posterior_samples)): x = model() # x is a sample from p(X | Z = z') where z' ~ q(z) (the variational model) ``` As another example, using a value setter inside of `ed.tape` enables computing the log joint probability, by setting all variables to posterior values and then accumulating the log probs of those values under the induced parent-conditional distributions. This is one way that we could have implemented `ed.make_log_joint_fn`: ```python def make_log_joint_fn_demo(model): def log_joint_fn(**model_kwargs): with ed.tape() as model_tape: with ed.make_value_setter(**model_kwargs): model() # accumulate sum_i log p(X_i = x_i | X_{:i-1} = x_{:i-1}) log_prob = 0. for rv in model_tape.values(): log_prob += tf.reduce_sum(rv.log_prob(rv.value)) return log_prob return log_joint_fn ``` """ def set_values(f, *args, **kwargs): """Sets random variable values to its aligned value.""" name = kwargs.get("name") if name in model_kwargs: kwargs["value"] = model_kwargs[name] return interceptable(f)(*args, **kwargs) return set_values
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: TypeError: If a random variable in the model has no specified value in `**kwargs`. """ log_probs = [] def interceptor(rv_constructor, *rv_args, **rv_kwargs): """Overrides a random variable's `value` and accumulates its log-prob.""" # Set value to keyword argument indexed by `name` (an input tensor). rv_name = rv_kwargs.get("name") if rv_name is None: raise KeyError("Random variable constructor {} has no name " "in its arguments.".format(rv_constructor.__name__)) # If no value is explicitly passed in for an RV, default to the value # from the RV constructor. This may have been set explicitly by the user # or forwarded from a lower-level interceptor. previously_specified_value = rv_kwargs.get("value") value = kwargs.get(rv_name, previously_specified_value) if value is None: raise LookupError("Keyword argument specifying value for {} is " "missing.".format(rv_name)) rv_kwargs["value"] = value rv = rv_constructor(*rv_args, **rv_kwargs) log_prob = tf.reduce_sum(input_tensor=rv.distribution.log_prob(rv.value)) log_probs.append(log_prob) return rv model_kwargs = _get_function_inputs(model, kwargs) with interception(interceptor): model(*args, **model_kwargs) log_prob = sum(log_probs) return log_prob return log_joint_fn
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 # pylint: disable=protected-access try: # getargspec was deprecated in Python 3.6 argspec = inspect.getfullargspec(f) except AttributeError: argspec = inspect.getargspec(f) fkwargs = {k: v for k, v in six.iteritems(src_kwargs) if k in argspec.args} return fkwargs
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', kernel_posterior_fn=kernel_posterior_fn)(out) out = tf.keras.layers.BatchNormalization()(out) out = tf.keras.layers.Activation('relu')(out) out = tf.keras.layers.MaxPooling2D( pool_size=(2, 2), strides=stride)(out) return out
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, current_grads_target_log_prob=current_grads_target_log_prob, current_momentum=current_momentum, direction=direction, depth=depth - 1, step_size=step_size, log_slice_sample=log_slice_sample, seed=seed_stream()) if continue_trajectory: # If the just-built subtree did not terminate, build a second subtree at # the forward or reverse state, as appropriate. if direction < 0: [ reverse_state, reverse_target_log_prob, reverse_grads_target_log_prob, reverse_momentum, _, _, _, _, far_state, far_target_log_prob, far_grads_target_log_prob, far_num_states, far_continue_trajectory, ] = _build_tree( value_and_gradients_fn=value_and_gradients_fn, current_state=reverse_state, current_target_log_prob=reverse_target_log_prob, current_grads_target_log_prob=reverse_grads_target_log_prob, current_momentum=reverse_momentum, direction=direction, depth=depth - 1, step_size=step_size, log_slice_sample=log_slice_sample, seed=seed_stream()) else: [ _, _, _, _, forward_state, forward_target_log_prob, forward_grads_target_log_prob, forward_momentum, far_state, far_target_log_prob, far_grads_target_log_prob, far_num_states, far_continue_trajectory, ] = _build_tree( value_and_gradients_fn=value_and_gradients_fn, current_state=forward_state, current_target_log_prob=forward_target_log_prob, current_grads_target_log_prob=forward_grads_target_log_prob, current_momentum=forward_momentum, direction=direction, depth=depth - 1, step_size=step_size, log_slice_sample=log_slice_sample, seed=seed_stream()) # Propose either `next_state` (which came from the first subtree and so is # nearby) or the new forward/reverse state (which came from the second # subtree and so is far away). num_states += far_num_states accept_far_state = _random_bernoulli( [], probs=far_num_states / num_states, dtype=tf.bool, seed=seed_stream()) if accept_far_state: next_state = far_state next_target_log_prob = far_target_log_prob next_grads_target_log_prob = far_grads_target_log_prob # Continue the NUTS trajectory if the far subtree did not terminate either, # and if the reverse-most and forward-most states do not exhibit a U-turn. has_no_u_turn = tf.logical_and( _has_no_u_turn(forward_state, reverse_state, forward_momentum), _has_no_u_turn(forward_state, reverse_state, reverse_momentum)) continue_trajectory = far_continue_trajectory and has_no_u_turn return [ 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, ]
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 = value_and_gradients_fn(*args, **kwargs) if any(grad is None for grad in grads): raise ValueError("Gradient is None for a state.") return value, grads return func_wrapped
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) for s1, s2, m in zip(state_one, state_two, momentum) ]) return dot_product > 0
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 = value_and_gradients_fn( *next_state) next_momentum = [ m + 0.5 * step * g for m, step, g in zip(mid_momentum, step_size, next_grads_target_log_prob)] return [ next_state, next_target_log_prob, next_grads_target_log_prob, next_momentum, ]
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 momentum.""" momentum_log_prob = -sum( [tf.reduce_sum(input_tensor=0.5 * (m**2.)) for m in current_momentum]) return current_target_log_prob + momentum_log_prob
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", [shape, probs]): probs = tf.convert_to_tensor(value=probs) random_uniform = tf.random.uniform(shape, dtype=probs.dtype, seed=seed) return tf.cast(tf.less(random_uniform, probs), dtype)
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 asynchronous distributed training. The default (`None`) is to use the `tf.get_variable` default. 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. The default (`None`) is to use the `tf.get_variable` default. Returns: default_loc_scale_fn: Python `callable` which instantiates `loc`, `scale` parameters from args: `dtype, shape, name, trainable, add_variable_fn`. """ def _fn(dtype, shape, name, trainable, add_variable_fn): """Creates `loc`, `scale` parameters.""" loc = add_variable_fn( name=name + '_loc', shape=shape, initializer=loc_initializer, regularizer=loc_regularizer, constraint=loc_constraint, dtype=dtype, trainable=trainable) if is_singular: return loc, None untransformed_scale = add_variable_fn( name=name + '_untransformed_scale', shape=shape, initializer=untransformed_scale_initializer, regularizer=untransformed_scale_regularizer, constraint=untransformed_scale_constraint, dtype=dtype, trainable=trainable) scale = (np.finfo(dtype.as_numpy_dtype).eps + tf.nn.softplus(untransformed_scale)) return loc, scale return _fn
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. Returns: make_normal_fn: Python `callable` which creates a `tfd.Normal` using from args: `dtype, shape, name, trainable, add_variable_fn`. """ loc_scale_fn = default_loc_scale_fn( is_singular=is_singular, loc_initializer=loc_initializer, untransformed_scale_initializer=untransformed_scale_initializer, loc_regularizer=loc_regularizer, untransformed_scale_regularizer=untransformed_scale_regularizer, loc_constraint=loc_constraint, untransformed_scale_constraint=untransformed_scale_constraint) def _fn(dtype, shape, name, trainable, add_variable_fn): """Creates multivariate `Deterministic` or `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 access existing) `tf.Variable`s. Returns: Multivariate `Deterministic` or `Normal` distribution. """ loc, scale = loc_scale_fn(dtype, shape, name, trainable, add_variable_fn) if scale is None: dist = tfd.Deterministic(loc=loc) else: dist = tfd.Normal(loc=loc, scale=scale) batch_ndims = tf.size(input=dist.batch_shape_tensor()) return tfd.Independent(dist, reinterpreted_batch_ndims=batch_ndims) return _fn
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 access existing) `tf.Variable`s. Returns: Multivariate standard `Normal` distribution. """ del name, trainable, add_variable_fn # unused dist = tfd.Normal(loc=tf.zeros(shape, dtype), scale=dtype.as_numpy_dtype(1)) batch_ndims = tf.size(input=dist.batch_shape_tensor()) return tfd.Independent(dist, reinterpreted_batch_ndims=batch_ndims)
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) function = deserialize_function(serial, function_type) assert function(2.3) == 2.3 # function is identity ``` """ if function_type == 'function': # Simple lookup in custom objects function = tf.keras.utils.deserialize_keras_object(serial) elif function_type == 'lambda': # Unsafe deserialization from bytecode function = generic_utils.func_load(serial) else: raise TypeError('Unknown function type:', function_type) return function
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 serialize. Returns: (serial, function_type): Serialized object, which is a tuple of its bytecode (if function is anonymous) or name (if function is named), and its function type. """ if isinstance(func, types.LambdaType): return generic_utils.func_dump(func), 'lambda' return func.__name__, 'function'
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'] b_structure = broadcast_structure(a_structure, 'd') # -> ['d', 'd', 'd'] c_structure = tf.nest.map_structure( lambda a, b: a + b, a_structure, b_structure) # -> ['ad', 'bd', 'cd'] ``` """ from_parts = tf.nest.flatten(from_structure) if len(from_parts) == 1: from_structure = tf.nest.map_structure(lambda _: from_parts[0], to_structure) return from_structure
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 Eager/Graph mode don't agree on the error type. pass # Try converting all of its children. shallow_struct = _get_shallow_structure(struct) return nest.map_structure_up_to( shallow_struct, lambda s: _nested_convert_to_tensor(s, name=name), struct)
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 | |:------------:|:----------:|:------------------:| | `{"a": 1}` | `None` | `{"a": T(1)}` | | `T(1)` | `None` | `T(1)` | | `[1]` | `None` | `[T(1)]` | | `[1]` | `tf.int32` | `T([1])` | | `[[T(1)]]` | `None` | `[T([1])]` | | `[[T(1)]]` | `[[None]]` | `[[T(1)]]` | | `NT(1, 2)` | `None` | `NT(T(1), T(2))` | | `NT(1, 2)` | `tf.int32` | `T([1, 2])` | | `CNT(1, 2)` | `None` | `T(...)` | | `[[1, [2]]]` | `None` | `[[T(1), T([2])]]` | """ if dtype is None: if expand_as_args(args) or _expand_as_kwargs(args): shallow_args = _get_shallow_structure(args) return nest.map_structure_up_to( shallow_args, lambda s: _nested_convert_to_tensor(s, name=name), args) else: return _nested_convert_to_tensor(args, name=name) else: return nest.map_structure_up_to( dtype, lambda s, dtype: _nested_convert_to_tensor(s, dtype, name), args, dtype)
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). args: Arguments to `fn`. Returns: result: Return value of `fn`. """ if expand_as_args(args): return fn(*args) elif _expand_as_kwargs(args): return fn(**args) else: return fn(args)
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)) for attr in tf.Tensor.OVERLOADABLE_OPERATORS.union({'__iter__'})) # Copy some members straight-through. attrs.update((attr, getattr(tf.Tensor, attr)) for attr in {'__nonzero__', '__bool__', '__array_priority__'}) return attrs
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( name="loc", shape=[mixture_components, latent_size]) raw_scale_diag = tf.compat.v1.get_variable( name="raw_scale_diag", shape=[mixture_components, latent_size]) mixture_logits = tf.compat.v1.get_variable( name="mixture_logits", shape=[mixture_components]) return tfd.MixtureSameFamily( components_distribution=tfd.MultivariateNormalDiag( loc=loc, scale_diag=tf.nn.softplus(raw_scale_diag)), mixture_distribution=tfd.Categorical(logits=mixture_logits), name="prior")
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)) batch = tf.shape(input=images)[0] rows = tf.minimum(rows, batch) cols = tf.minimum(batch // rows, cols) images = images[:rows * cols] images = tf.reshape(images, (rows, cols, width, height, depth)) images = tf.transpose(a=images, perm=[0, 2, 1, 3, 4]) images = tf.reshape(images, [1, rows * width, cols * height, depth]) return images
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 if not tf.io.gfile.exists(directory): tf.io.gfile.makedirs(directory) url = os.path.join(ROOT_PATH, filename) print("Downloading %s to %s" % (url, filepath)) urllib.request.urlretrieve(url, 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(): dataset = tf.data.Dataset.from_tensor_slices( random_sample).map(lambda row: (row, 0)).batch(batch_size) return tf.compat.v1.data.make_one_shot_iterator(dataset).get_next() return train_input_fn, 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 ' 'as `bijectors`.') with tf.control_dependencies([ assert_util.assert_equal( tf.size(input=block_sizes), len(bijectors), message=message), assert_util.assert_equal(tf.rank(block_sizes), 1) ]): return tf.identity(block_sizes) else: return block_sizes
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) if all(tensorshape_util.is_fully_defined(s_) for s_ in s): if not all(a == b for a, b in zip(s[1:], s[:-1])): raise ValueError(msg) return flat_xs assertions = [assert_util.assert_equal(a, b, message=msg) for a, b in zip(s[1:], s[:-1])] with tf.control_dependencies(assertions): return tuple(tf.identity(x) 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 # iteration:400 loss:2.82727336884 mse:0.990926623344 # iteration:600 loss:2.82726788521 mse:0.990926682949 # iteration:800 loss:2.82726788521 mse:0.990926682949 # iteration:999 loss:2.82726788521 mse:0.990926682949 ``` Args: x: `Tensor` with floating type. Must have statically defined rank and statically known right-most dimension. dims: Scalar, `int`, `Tensor` indicated the MVN event size, i.e., the created MVN will be distribution over length-`dims` vectors. layer_fn: Python `callable` which takes input `x` and `int` scalar `d` and returns a transformation of `x` with shape `tf.concat([tf.shape(x)[:-1], [d]], axis=0)`. Default value: `tf.layers.dense`. loc_fn: Python `callable` which transforms the `loc` parameter. Takes a (batch of) length-`dims` vectors and returns a `Tensor` of same shape and `dtype`. Default value: `lambda x: x`. scale_fn: Python `callable` which transforms the `scale` parameters. Takes a (batch of) length-`dims * (dims + 1) / 2` vectors and returns a lower-triangular `Tensor` of same batch shape with rightmost dimensions having shape `[dims, dims]`. Default value: `tril_with_diag_softplus_and_shift`. name: A `name_scope` name for operations created by this function. Default value: `None` (i.e., "multivariate_normal_tril"). Returns: mvntril: An instance of `tfd.MultivariateNormalTriL`. """ with tf.compat.v1.name_scope(name, 'multivariate_normal_tril', [x, dims]): x = tf.convert_to_tensor(value=x, name='x') x = layer_fn(x, dims + dims * (dims + 1) // 2) return tfd.MultivariateNormalTriL( loc=loc_fn(x[..., :dims]), scale_tril=scale_fn(x[..., dims:]))
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 # iteration:400 loss:0.440077394247 mse:0.143687844276 # iteration:600 loss:0.440077394247 mse:0.143687844276 # iteration:800 loss:0.440077424049 mse:0.143687844276 # iteration:999 loss:0.440077424049 mse:0.143687844276 ``` Args: x: `Tensor` with floating type. Must have statically defined rank and statically known right-most dimension. layer_fn: Python `callable` which takes input `x` and `int` scalar `d` and returns a transformation of `x` with shape `tf.concat([tf.shape(x)[:-1], [1]], axis=0)`. Default value: `tf.layers.dense`. name: A `name_scope` name for operations created by this function. Default value: `None` (i.e., "bernoulli"). Returns: bernoulli: An instance of `tfd.Bernoulli`. """ with tf.compat.v1.name_scope(name, 'bernoulli', [x]): x = tf.convert_to_tensor(value=x, name='x') logits = tf.squeeze(layer_fn(x, 1), axis=-1) return tfd.Bernoulli(logits=logits)
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 # iteration:800 loss:1.40052902699 mse:0.963181257248 # iteration:999 loss:1.40052902699 mse:0.963181257248 ``` Args: x: `Tensor` with floating type. Must have statically defined rank and statically known right-most dimension. layer_fn: Python `callable` which takes input `x` and `int` scalar `d` and returns a transformation of `x` with shape `tf.concat([tf.shape(x)[:-1], [1]], axis=0)`. Default value: `tf.layers.dense`. loc_fn: Python `callable` which transforms the `loc` parameter. Takes a (batch of) length-`dims` vectors and returns a `Tensor` of same shape and `dtype`. Default value: `lambda x: x`. scale_fn: Python `callable` or `Tensor`. If a `callable` transforms the `scale` parameters; if `Tensor` is the `tfd.Normal` `scale` argument. Takes a (batch of) length-`dims` vectors and returns a `Tensor` of same size. (Taking a `callable` or `Tensor` is how `tf.Variable` intializers behave.) Default value: `1`. name: A `name_scope` name for operations created by this function. Default value: `None` (i.e., "normal"). Returns: normal: An instance of `tfd.Normal`. """ with tf.compat.v1.name_scope(name, 'normal', [x]): x = tf.convert_to_tensor(value=x, name='x') if callable(scale_fn): y = layer_fn(x, 2) loc = loc_fn(y[..., 0]) scale = scale_fn(y[..., 1]) else: y = tf.squeeze(layer_fn(x, 1), axis=-1) loc = loc_fn(y) scale = tf.cast(scale_fn, loc.dtype.base_dtype) return tfd.Normal(loc=loc, scale=scale)
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 loss:1.39027583599 mse:8.77660560608 # iteration:600 loss:1.3902695179 mse:8.78443241119 # iteration:800 loss:1.39026939869 mse:8.78443622589 # iteration:999 loss:1.39026939869 mse:8.78444766998 ``` Args: x: `Tensor` with floating type. Must have statically defined rank and statically known right-most dimension. layer_fn: Python `callable` which takes input `x` and `int` scalar `d` and returns a transformation of `x` with shape `tf.concat([tf.shape(x)[:-1], [1]], axis=0)`. Default value: `tf.layers.dense`. log_rate_fn: Python `callable` which transforms the `log_rate` parameter. Takes a (batch of) length-`dims` vectors and returns a `Tensor` of same shape and `dtype`. Default value: `lambda x: x`. name: A `name_scope` name for operations created by this function. Default value: `None` (i.e., "poisson"). Returns: poisson: An instance of `tfd.Poisson`. """ with tf.compat.v1.name_scope(name, 'poisson', [x]): x = tf.convert_to_tensor(value=x, name='x') log_rate = log_rate_fn(tf.squeeze(layer_fn(x, 1), axis=-1)) return tfd.Poisson(log_rate=log_rate)
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` (i.e., 'mala_euler_method'). Returns: proposed_state_parts: Tensor or Python list of `Tensor`s representing the state(s) of the Markov chain(s) at each result step. Has same shape as input `current_state_parts`. """ with tf.compat.v1.name_scope(name, 'mala_euler_method', [ random_draw_parts, state_parts, drift_parts, step_size_parts, volatility_parts ]): proposed_state_parts = [] for random_draw, state, drift, step_size, volatility in zip( random_draw_parts, state_parts, drift_parts, step_size_parts, volatility_parts): proposal = state + drift + volatility * tf.sqrt(step_size) * random_draw proposed_state_parts.append(proposal) return proposed_state_parts
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. volatility_parts: Python `list` of `Tensor`s representing the value of `volatility_fn(*state_parts)`. grads_volatility: Python list of `Tensor`s representing the value of the gradient of `volatility_parts**2` wrt the state of the chain. grads_target_log_prob: Python list of `Tensor`s representing gradient of `target_log_prob_fn(*state_parts`) wrt `state_parts`. Must have same shape as `volatility_parts`. name: Python `str` name prefixed to Ops created by this function. Default value: `None` (i.e., 'mala_get_drift'). Returns: drift_parts: Tensor or Python list of `Tensor`s representing the state(s) of the Markov chain(s) at each result step. Has same shape as input `current_state_parts`. """ with tf.compat.v1.name_scope(name, 'mala_get_drift', [ step_size_parts, volatility_parts, grads_volatility, grads_target_log_prob ]): drift_parts = [] for step_size, volatility, grad_volatility, grad_target_log_prob in ( zip(step_size_parts, volatility_parts, grads_volatility, grads_target_log_prob)): volatility_squared = tf.square(volatility) drift = 0.5 * step_size * (volatility_squared * grad_target_log_prob + grad_volatility) drift_parts.append(drift) return drift_parts
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, proposed_state_parts, current_volatility_parts, proposed_volatility_parts, current_drift_parts, proposed_drift_parts, step_size_parts, ): axis = tf.range(independent_chain_ndims, tf.rank(current_state)) state_diff = proposed_state - current_state current_volatility *= tf.sqrt(step_size) proposed_energy = (state_diff - current_drift) / current_volatility proposed_volatility *= tf.sqrt(step_size) # Compute part of `q(proposed_state | current_state)` proposed_energy = ( tf.reduce_sum( input_tensor=mcmc_util.safe_sum( [tf.math.log(current_volatility), 0.5 * (proposed_energy**2)]), axis=axis)) proposed_log_density_parts.append(-proposed_energy) # Compute part of `q(current_state | proposed_state)` dual_energy = (state_diff + proposed_drift) / proposed_volatility dual_energy = ( tf.reduce_sum( input_tensor=mcmc_util.safe_sum( [tf.math.log(proposed_volatility), 0.5 * (dual_energy**2)]), axis=axis)) dual_log_density_parts.append(-dual_energy) # Compute `q(proposed_state | current_state)` proposed_log_density_reduce = tf.reduce_sum( input_tensor=tf.stack(proposed_log_density_parts, axis=-1), axis=-1) # Compute `q(current_state | proposed_state)` dual_log_density_reduce = tf.reduce_sum( input_tensor=tf.stack(dual_log_density_parts, axis=-1), axis=-1) return mcmc_util.safe_sum([dual_log_density_reduce, -proposed_log_density_reduce])
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, state_parts) if grads_volatility_fn is None: [ _, grads_volatility_fn, ] = diag_jacobian( xs=state_parts, ys=volatility_fn_results, sample_shape=sample_shape, parallel_iterations=parallel_iterations, fn=volatility_fn) # Compute gradient of `volatility_parts**2` if needs_volatility_fn_gradients: grads_volatility_fn = [ 2. * g * volatility if g is not None else tf.zeros_like( fn_arg, dtype=fn_arg.dtype.base_dtype) for g, volatility, fn_arg in zip( grads_volatility_fn, volatility_fn_results, state_parts) ] return volatility_fn_results, grads_volatility_fn
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 [v + tf.zeros_like(sp, dtype=sp.dtype.base_dtype) for v, sp in zip(volatility_parts, state_parts)]
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]])`. """ top_row = tf.expand_dims(coefficients, -2) coef_shape = dist_util.prefer_static_shape(coefficients) batch_shape, order = coef_shape[:-1], coef_shape[-1] remaining_rows = tf.concat([ tf.eye(order - 1, dtype=coefficients.dtype, batch_shape=batch_shape), tf.zeros(tf.concat([batch_shape, (order - 1, 1)], axis=0), dtype=coefficients.dtype) ], axis=-1) ar_matrix = tf.concat([top_row, remaining_rows], axis=-2) return ar_matrix
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)) sample_ndims = x_ndims - batch_ndims - event_ndims if isinstance(sample_ndims, int): static_sample_shape = x.shape[:sample_ndims] else: static_sample_shape = tf.TensorShape(None) if tensorshape_util.is_fully_defined(static_sample_shape): sample_shape = np.int32(static_sample_shape) else: sample_shape = tf.shape(input=x)[:sample_ndims] return sample_shape, static_sample_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, self._batch_shape_unexpanded, ], axis=0) result = tf.reshape(result, new_shape) if (tensorshape_util.rank(static_sample_shape) is not None and tensorshape_util.rank(self.batch_shape) is not None): new_shape = tensorshape_util.concatenate(static_sample_shape, self.batch_shape) tensorshape_util.set_shape(result, new_shape) return result
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(), new_shape) if (tensorshape_util.rank(self.batch_shape) is not None and tensorshape_util.rank(self.event_shape) is not None): event_shape = tf.TensorShape([]) for rss in static_event_shape_list: event_shape = tensorshape_util.concatenate(event_shape, rss) static_shape = tensorshape_util.concatenate( self.batch_shape, event_shape) tensorshape_util.set_shape(result, static_shape) return result
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 safe backprop/gradients into n, k when # betainc(a = 0, ..) = nan # Write: # where(unsafe, safe_output, betainc(where(unsafe, safe_input, input))) ones = tf.ones_like(n - k) k_eq_n = tf.equal(k, n) safe_dn = tf.where(k_eq_n, ones, n - k) dk = tf.math.betainc(a=safe_dn, b=k + 1, x=1 - p) return tf.where(k_eq_n, ones, dk)
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] else: next_value = actual_distribution.sample( sample_shape=sample_shape if isinstance(d, self.Root) else (), seed=seed()) values_out.append(next_value) index += 1 d = gen.send(next_value) except StopIteration: pass return ds, values_out
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], where each row (topic) denotes the probability of each word being in that topic. Returns: bag_of_words: A random variable capturing a sample from the model, of shape [1, num_words]. It represents one generated document as a bag of words. """ topics = ed.Dirichlet(concentration=concentration, name="topics") word_probs = tf.matmul(topics, topics_words) # The observations are bags of words and therefore not one-hot. However, # log_prob of OneHotCategorical computes the probability correctly in # this case. bag_of_words = ed.OneHotCategorical(probs=word_probs, name="bag_of_words") return bag_of_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( num_topics, activation=tf.nn.softplus, kernel_initializer=tf.compat.v1.glorot_normal_initializer())) def lda_variational(bag_of_words): concentration = _clip_dirichlet_parameters(encoder_net(bag_of_words)) return ed.Dirichlet(concentration=concentration, name="topics_posterior") return lda_variational
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. highest_weight_topics = np.argsort(-alpha, kind="mergesort") top_words = np.argsort(-topics_words, axis=1) res = [] for topic_idx in highest_weight_topics[:topics_to_print]: l = ["index={} alpha={:.2f}".format(topic_idx, alpha[topic_idx])] l += [vocabulary[word] for word in top_words[topic_idx, :words_per_topic]] res.append(" ".join(l)) return np.array(res)
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) # For training, we shuffle each epoch and repeat the epochs. if shuffle_and_repeat: dataset = dataset.shuffle(num_documents).repeat() # Returns a single document as a dense TensorFlow tensor. The dataset is # stored as a sparse matrix outside of the graph. def get_row_py_func(idx): def get_row_python(idx_py): return np.squeeze(np.array(sparse_matrix[idx_py].todense()), axis=0) py_func = tf.compat.v1.py_func( get_row_python, [idx], tf.float32, stateful=False) py_func.set_shape((num_words,)) return py_func dataset = dataset.map(get_row_py_func) return dataset
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() def eval_input_fn(): dataset = tf.data.Dataset.from_tensor_slices(random_sample) dataset = dataset.batch(batch_size) return tf.compat.v1.data.make_one_shot_iterator(dataset).get_next() return train_input_fn, eval_input_fn, vocabulary
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) # Prefetching makes training about 1.5x faster. dataset = dataset.batch(batch_size).prefetch(32) return tf.compat.v1.data.make_one_shot_iterator(dataset).get_next() # Build an iterator over the heldout set. def eval_input_fn(): dataset = newsgroups_dataset( data_dir, "test", num_words, shuffle_and_repeat=False) dataset = dataset.batch(batch_size) return tf.compat.v1.data.make_one_shot_iterator(dataset).get_next() return train_input_fn, eval_input_fn, vocabulary
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). #### References [1]: Jerome Friedman, Trevor Hastie and Rob Tibshirani. Regularization Paths for Generalized Linear Models via Coordinate Descent. _Journal of Statistical Software_, 33(1), 2010. https://www.jstatsoft.org/article/view/v033i01/v33i01.pdf [2]: Guo-Xun Yuan, Chia-Hua Ho and Chih-Jen Lin. An Improved GLMNET for L1-regularized Logistic Regression. _Journal of Machine Learning Research_, 13, 2012. http://www.jmlr.org/papers/volume13/yuan12a/yuan12a.pdf """ graph_deps = [ x_start, l1_regularizer, l2_regularizer, maximum_iterations, maximum_full_sweeps_per_iteration, tolerance, learning_rate, ], with tf.compat.v1.name_scope(name, 'minimize', graph_deps): def _loop_cond(x_start, converged, iter_): del x_start return tf.logical_and(iter_ < maximum_iterations, tf.logical_not(converged)) def _loop_body(x_start, converged, iter_): # pylint: disable=missing-docstring g, h_outer, h_middle = grad_and_hessian_loss_fn(x_start) x_start, converged, _ = minimize_one_step( gradient_unregularized_loss=g, hessian_unregularized_loss_outer=h_outer, hessian_unregularized_loss_middle=h_middle, x_start=x_start, l1_regularizer=l1_regularizer, l2_regularizer=l2_regularizer, maximum_full_sweeps=maximum_full_sweeps_per_iteration, tolerance=tolerance, learning_rate=learning_rate) return x_start, converged, iter_ + 1 return tf.while_loop( cond=_loop_cond, body=_loop_body, loop_vars=[ x_start, tf.zeros([], np.bool, name='converged'), tf.zeros([], np.int32, name='iter'), ])
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, zero_debias=False) updated_ema_means = moving_averages.assign_moving_average( vector_quantizer.ema_means, tf.reduce_sum( input_tensor=tf.expand_dims(codes, 2) * tf.expand_dims(one_hot_assignments, 3), axis=[0, 1]), decay, zero_debias=False) # Add small value to avoid dividing by zero. perturbed_ema_count = updated_ema_count + 1e-5 with tf.control_dependencies([commitment_loss]): update_means = tf.compat.v1.assign( vector_quantizer.codebook, updated_ema_means / perturbed_ema_count[..., tf.newaxis]) with tf.control_dependencies([update_means]): return tf.identity(commitment_loss)
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): ax = fig.add_subplot(1, n, i+1) ax.imshow(x[i].squeeze(), interpolation="none", cmap=cm.get_cmap("binary")) ax.axis("off") canvas.print_figure(fname, format="png") print("saved %s" % fname)
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], os.path.join(log_dir, "{}_inputs.png".format(prefix))) save_imgs(reconstructed_images_val[:viz_n], os.path.join(log_dir, "{}_reconstructions.png".format(prefix))) if random_images_val is not None: save_imgs(random_images_val[:viz_n], os.path.join(log_dir, "{}_prior_samples.png".format(prefix)))
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): booltensor = tf.compat.v1.py_func(str_to_arr, [s], tf.bool) reshaped = tf.reshape(booltensor, [28, 28, 1]) return tf.cast(reshaped, dtype=tf.float32), tf.constant(0, tf.int32) return dataset.map(_parser)
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, 'as_numpy_dtype'): return dtype.as_numpy_dtype return 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, 'base_dtype'): return dtype.base_dtype return 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'): return dtype.is_bool # We use `kind` because: # np.issubdtype(np.uint8, np.bool) == True. return np.dtype(dtype).kind == 'b'
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'): return dtype.is_complex return np.issubdtype(np.dtype(dtype), np.complex)
python
{ "resource": "" }
q266587
max
test
def max(dtype): # pylint: disable=redefined-builtin """Returns the maximum representable value in this data type.""" dtype = tf.as_dtype(dtype) if hasattr(dtype, 'max'): return dtype.max use_finfo = is_floating(dtype) or is_complex(dtype) return np.finfo(dtype).max if use_finfo else np.iinfo(dtype).max
python
{ "resource": "" }
q266588
name
test
def name(dtype): """Returns the string name for this `dtype`.""" dtype = tf.as_dtype(dtype) if hasattr(dtype, 'name'): return dtype.name if hasattr(dtype, '__name__'): return dtype.__name__ return str(dtype)
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, 'size'): return dtype.size return np.dtype(dtype).itemsize
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) if not expected_type: expected_type = item_type original_item_str = get_name(item) elif expected_type != item_type: raise ValueError( '{}, type={}, must be of the same type ({}){}.'.format( get_name(item), item_type, expected_type, ((' as {}'.format(original_item_str)) if original_item_str else ''))) return expected_type # Should be unreachable else: return expected_type
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, the function will return `dtypes.float32`. Args: tensors: Tensors of input values. Can include `None` elements, which will be ignored. dtype: Expected type. Returns: Validated type. Raises: ValueError: if neither `tensors` nor `dtype` is supplied, or result is not float, or the common type of the inputs is not a floating point type. """ if tensors: dtype = _assert_same_base_type(tensors, dtype) if not dtype: dtype = tf.float32 elif not is_floating(dtype): raise ValueError('Expected floating point type, got {}.'.format(dtype)) return dtype
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`. Must be between `0` and `1`. This parameter is the scale by which the simplex is shrunk around the best point when the other steps fail to produce improvements. See, [Press et al(2007)][1] for more details. If not specified, uses the dimension dependent prescription of [Gao and Han(2012][3]. name: (Optional) Python str. The name prefixed to the ops created by this function. If not supplied, the default name 'minimize' is used. Returns: optimizer_results: A namedtuple containing the following items: converged: Scalar boolean tensor indicating whether the minimum was found within tolerance. num_objective_evaluations: The total number of objective evaluations performed. position: A `Tensor` containing the last argument value found during the search. If the search converged, then this value is the argmin of the objective function. objective_value: A tensor containing the value of the objective function at the `position`. If the search converged, then this is the (local) minimum of the objective function. final_simplex: The last simplex constructed before stopping. final_objective_values: The objective function evaluated at the vertices of the final simplex. initial_simplex: The starting simplex. initial_objective_values: The objective function evaluated at the vertices of the initial simplex. num_iterations: The number of iterations of the main algorithm body. Raises: ValueError: If any of the following conditions hold 1. If none or more than one of `initial_simplex` and `initial_vertex` are supplied. 2. If `initial_simplex` and `step_sizes` are both specified. """ with tf.compat.v1.name_scope(name, 'minimize', [ initial_simplex, initial_vertex, step_sizes, objective_at_initial_simplex, objective_at_initial_vertex, func_tolerance, position_tolerance ]): ( dim, _, simplex, objective_at_simplex, num_evaluations ) = _prepare_args(objective_function, initial_simplex, initial_vertex, step_sizes, objective_at_initial_simplex, objective_at_initial_vertex, batch_evaluate_objective) domain_dtype = simplex.dtype ( reflection, expansion, contraction, shrinkage ) = _resolve_parameters(dim, reflection, expansion, contraction, shrinkage, domain_dtype) closure_kwargs = dict( objective_function=objective_function, dim=dim, func_tolerance=func_tolerance, position_tolerance=position_tolerance, batch_evaluate_objective=batch_evaluate_objective, reflection=reflection, expansion=expansion, contraction=contraction, shrinkage=shrinkage) def _loop_body(_, iterations, simplex, objective_at_simplex, num_evaluations): ( converged, next_simplex, next_objective, evaluations ) = nelder_mead_one_step(simplex, objective_at_simplex, **closure_kwargs) return (converged, iterations + 1, next_simplex, next_objective, num_evaluations + evaluations) initial_args = (False, 0, simplex, objective_at_simplex, num_evaluations) # Loop until either we have converged or if the max iterations are supplied # then until we have converged or exhausted the available iteration budget. def _is_converged(converged, num_iterations, *ignored_args): # pylint:disable=unused-argument # It is important to ensure that not_converged is a tensor. If # converged is not a tensor but a Python bool, then the overloaded # op '~' acts as bitwise complement so ~True = -2 and ~False = -1. # In that case, the loop will never terminate. not_converged = tf.logical_not(converged) return (not_converged if max_iterations is None else (not_converged & (num_iterations < max_iterations))) (converged, num_iterations, final_simplex, final_objective_values, final_evaluations) = tf.while_loop( cond=_is_converged, body=_loop_body, loop_vars=initial_args, parallel_iterations=parallel_iterations) order = tf.argsort( final_objective_values, direction='ASCENDING', stable=True) best_index = order[0] # The explicit cast to Tensor below is done to avoid returning a mixture # of Python types and Tensors which cause problems with session.run. # In the eager mode, converged may remain a Python bool. Trying to evaluate # the whole tuple in one evaluate call will raise an exception because # of the presence of non-tensors. This is very annoying so we explicitly # cast those arguments to Tensors. return NelderMeadOptimizerResults( converged=tf.convert_to_tensor(value=converged), num_objective_evaluations=final_evaluations, position=final_simplex[best_index], objective_value=final_objective_values[best_index], final_simplex=final_simplex, final_objective_values=final_objective_values, num_iterations=tf.convert_to_tensor(value=num_iterations), initial_simplex=simplex, initial_objective_values=objective_at_simplex)
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) case2 = do_expansion, expansion_fn do_outside_contraction = ( (objective_at_reflected < worst_objective_value) & (objective_at_reflected >= second_worst_objective_value) ) outside_contraction_fn = _outside_contraction_fn( objective_function, current_simplex, current_objective_values, face_centroid, best_index, worst_index, reflected, objective_at_reflected, contraction, shrinkage, batch_evaluate_objective) case3 = do_outside_contraction, outside_contraction_fn default_fn = _inside_contraction_fn(objective_function, current_simplex, current_objective_values, face_centroid, best_index, worst_index, worst_objective_value, contraction, shrinkage, batch_evaluate_objective) ( converged, next_simplex, next_objective_at_simplex, case_evals) = prefer_static.case([case0, case1, case2, case3], default=default_fn, exclusive=False) next_simplex.set_shape(current_simplex.shape) next_objective_at_simplex.set_shape(current_objective_values.shape) return ( converged, next_simplex, next_objective_at_simplex, num_evaluations + case_evals )
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) next_objective_values = _replace_at_index(objective_values, worst_index, objective_at_reflected) return False, next_simplex, next_objective_values, 0 return _replace_worst_with_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) expanded_is_better = (expanded_objective_value < objective_at_reflected) accept_expanded_fn = lambda: (expanded, expanded_objective_value) accept_reflected_fn = lambda: (reflected, objective_at_reflected) next_pt, next_objective_value = prefer_static.cond( expanded_is_better, accept_expanded_fn, accept_reflected_fn) next_simplex = _replace_at_index(simplex, worst_index, next_pt) next_objective_at_simplex = _replace_at_index(objective_values, worst_index, next_objective_value) return False, next_simplex, next_objective_at_simplex, 1 return _expand_and_maybe_replace
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, objective_at_contracted) return (False, next_simplex, objective_at_next_simplex, 1) def _reject_contraction(): return _shrink_towards_best(objective_function, simplex, best_index, shrinkage, batch_evaluate_objective) return prefer_static.cond(is_contracted_acceptable, _accept_contraction, _reject_contraction) return _contraction
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 objective enough, # the simplex is shrunk towards the best vertex. best_vertex = simplex[best_index] shrunk_simplex = best_vertex + shrinkage * (simplex - best_vertex) objective_at_shrunk_simplex, evals = _evaluate_objective_multiple( objective_function, shrunk_simplex, batch_evaluate_objective) return (False, shrunk_simplex, objective_at_shrunk_simplex, evals)
python
{ "resource": "" }
q266598
_replace_at_index
test
def _replace_at_index(x, index, replacement): """Replaces an element at supplied index.""" x_new = tf.concat([x[:index], tf.expand_dims(replacement, axis=0), x[(index + 1):]], axis=0) return 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 the variation of the objective function value over the simplex. If the variation over the simplex vertices is below this threshold, convergence is True. position_tolerance: Scalar positive `Tensor`. The algorithm stops if the lengths (under the supremum norm) of edges connecting to the best vertex are below this threshold. Returns: has_converged: A scalar boolean `Tensor` indicating whether the algorithm is deemed to have converged. """ objective_convergence = tf.abs(worst_objective - best_objective) < func_tolerance simplex_degeneracy = tf.reduce_max( input_tensor=tf.abs(simplex - best_vertex)) < position_tolerance return objective_convergence | simplex_degeneracy
python
{ "resource": "" }