INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Asymptotic expansion version of Log [ cdf ( x ) ] appropriate for x<< - 1.
def _log_ndtr_lower(x, series_order): """Asymptotic expansion version of `Log[cdf(x)]`, appropriate for `x<<-1`.""" x_2 = tf.square(x) # Log of the term multiplying (1 + sum) log_scale = -0.5 * x_2 - tf.math.log(-x) - 0.5 * np.log(2. * np.pi) return log_scale + tf.math.log(_log_ndtr_asymptotic_series(x, serie...
Calculates the asymptotic series used in log_ndtr.
def _log_ndtr_asymptotic_series(x, series_order): """Calculates the asymptotic series used in log_ndtr.""" npdt = dtype_util.as_numpy_dtype(x.dtype) if series_order <= 0: return npdt(1) x_2 = tf.square(x) even_sum = tf.zeros_like(x) odd_sum = tf.zeros_like(x) x_2n = x_2 # Start with x^{2*1} = x^{2*n}...
The inverse function for erf the error function.
def erfinv(x, name="erfinv"): """The inverse function for erf, the error function. Args: x: `Tensor` of type `float32`, `float64`. name: Python string. A name for the operation (default="erfinv"). Returns: x: `Tensor` with `dtype=x.dtype`. Raises: TypeError: if `x` is not floating-type. """...
Log Laplace distribution function.
def log_cdf_laplace(x, name="log_cdf_laplace"): """Log Laplace distribution function. This function calculates `Log[L(x)]`, where `L(x)` is the cumulative distribution function of the Laplace distribution, i.e. ```L(x) := 0.5 * int_{-infty}^x e^{-|t|} dt``` For numerical accuracy, `L(x)` is computed in dif...
Joint log probability function.
def text_messages_joint_log_prob(count_data, lambda_1, lambda_2, tau): """Joint log probability function.""" alpha = (1. / tf.reduce_mean(input_tensor=count_data)) rv_lambda = tfd.Exponential(rate=alpha) rv_tau = tfd.Uniform() lambda_ = tf.gather( [lambda_1, lambda_2], indices=tf.cast( ...
Runs HMC on the text - messages unnormalized posterior.
def benchmark_text_messages_hmc( num_results=int(3e3), num_burnin_steps=int(3e3), num_leapfrog_steps=3): """Runs HMC on the text-messages unnormalized posterior.""" if not tf.executing_eagerly(): tf.compat.v1.reset_default_graph() # Build a static, pretend dataset. count_data = tf.cast( ...
True if the given index_points would yield a univariate marginal.
def _is_univariate_marginal(self, index_points): """True if the given index_points would yield a univariate marginal. Args: index_points: the set of index set locations at which to compute the marginal Gaussian distribution. If this set is of size 1, the marginal is univariate. Returns: ...
Compute the marginal of this GP over function values at index_points.
def get_marginal_distribution(self, index_points=None): """Compute the marginal of this GP over function values at `index_points`. Args: index_points: `float` `Tensor` representing finite (batch of) vector(s) of points in the index set over which the GP is defined. Shape has the form `[b1...
Return index_points if not None else self. _index_points.
def _get_index_points(self, index_points=None): """Return `index_points` if not None, else `self._index_points`. Args: index_points: if given, this is what is returned; else, `self._index_points` Returns: index_points: the given arg, if not None, else the class member `self._index_...
Stable evaluation of Log [ exp { big } - exp { small } ].
def _logsum_expbig_minus_expsmall(big, small): """Stable evaluation of `Log[exp{big} - exp{small}]`. To work correctly, we should have the pointwise relation: `small <= big`. Args: big: Floating-point `Tensor` small: Floating-point `Tensor` with same `dtype` as `big` and broadcastable shape. R...
Compute log_prob ( y ) using log survival_function and cdf together.
def _log_prob_with_logsf_and_logcdf(self, y): """Compute log_prob(y) using log survival_function and cdf together.""" # There are two options that would be equal if we had infinite precision: # Log[ sf(y - 1) - sf(y) ] # = Log[ exp{logsf(y - 1)} - exp{logsf(y)} ] # Log[ cdf(y) - cdf(y - 1) ] #...
Creates an stacked IAF bijector.
def make_iaf_stack(total_event_size, num_hidden_layers=2, seed=None, dtype=tf.float32): """Creates an stacked IAF bijector. This bijector operates on vector-valued events. Args: total_event_size: Number of dimensions to operate over. num_hidden_la...
Runs one iteration of NeuTra.
def one_step(self, current_state, previous_kernel_results): """Runs one iteration of NeuTra. Args: current_state: `Tensor` or Python `list` of `Tensor`s representing the current state(s) of the Markov chain(s). The first `r` dimensions index independent chains, `r = tf.rank(target_log_pro...
Trains the bijector and creates initial previous_kernel_results.
def bootstrap_results(self, state): """Trains the bijector and creates initial `previous_kernel_results`. The supplied `state` is only used to determine the number of chains to run in parallel_iterations Args: state: `Tensor` or Python `list` of `Tensor`s representing the initial state(s...
Computes E [ log ( det ( X )) ] under this Wishart distribution.
def mean_log_det(self, name="mean_log_det"): """Computes E[log(det(X))] under this Wishart distribution.""" with self._name_scope(name): return (self._multi_digamma(0.5 * self.df, self.dimension) + self.dimension * math.log(2.) + 2 * self.scale_operator.log_abs_determinant())
Computes the log normalizing constant log ( Z ).
def log_normalization(self, name="log_normalization"): """Computes the log normalizing constant, log(Z).""" with self._name_scope(name): return (self.df * self.scale_operator.log_abs_determinant() + 0.5 * self.df * self.dimension * math.log(2.) + self._multi_lgamma(0.5 * self.d...
Creates sequence used in multivariate ( di ) gamma ; shape = shape ( a ) + [ p ].
def _multi_gamma_sequence(self, a, p, name="multi_gamma_sequence"): """Creates sequence used in multivariate (di)gamma; shape = shape(a)+[p].""" with self._name_scope(name): # Linspace only takes scalars, so we'll add in the offset afterwards. seq = tf.linspace( tf.constant(0., dtype=self....
Computes the log multivariate gamma function ; log ( Gamma_p ( a )).
def _multi_lgamma(self, a, p, name="multi_lgamma"): """Computes the log multivariate gamma function; log(Gamma_p(a)).""" with self._name_scope(name): seq = self._multi_gamma_sequence(a, p) return (0.25 * p * (p - 1.) * math.log(math.pi) + tf.reduce_sum(input_tensor=tf.math.lgamma(seq),...
Computes the multivariate digamma function ; Psi_p ( a ).
def _multi_digamma(self, a, p, name="multi_digamma"): """Computes the multivariate digamma function; Psi_p(a).""" with self._name_scope(name): seq = self._multi_gamma_sequence(a, p) return tf.reduce_sum(input_tensor=tf.math.digamma(seq), axis=[-1])
Convenience function analogous to tf. squared_difference.
def _outer_squared_difference(x, y): """Convenience function analogous to tf.squared_difference.""" z = x - y return z[..., tf.newaxis, :] * z[..., tf.newaxis]
Enables uniform interface to value and batch jacobian calculation.
def _value_and_batch_jacobian(f, x): """Enables uniform interface to value and batch jacobian calculation. Works in both eager and graph modes. Arguments: f: The scalar function to evaluate. x: The value at which to compute the value and the batch jacobian. Returns: A tuple (f(x), J(x)), where J(...
Disables computation of the second derivatives for a tensor.
def _prevent_2nd_derivative(x): """Disables computation of the second derivatives for a tensor. NB: you need to apply a non-identity function to the output tensor for the exception to be raised. Arguments: x: A tensor. Returns: A tensor with the same value and the same derivative as x, but that rai...
Adds reparameterization ( pathwise ) gradients to samples of the mixture.
def _reparameterize_sample(self, x): """Adds reparameterization (pathwise) gradients to samples of the mixture. Implicit reparameterization gradients are dx/dphi = -(d transform(x, phi) / dx)^-1 * d transform(x, phi) / dphi, where transform(x, phi) is distributional transform that removes all pa...
Performs distributional transform of the mixture samples.
def _distributional_transform(self, x): """Performs distributional transform of the mixture samples. Distributional transform removes the parameters from samples of a multivariate distribution by applying conditional CDFs: (F(x_1), F(x_2 | x1_), ..., F(x_d | x_1, ..., x_d-1)) (the indexing is ove...
Split a covariance matrix into block - diagonal marginals of given sizes.
def _split_covariance_into_marginals(covariance, block_sizes): """Split a covariance matrix into block-diagonal marginals of given sizes.""" start_dim = 0 marginals = [] for size in block_sizes: end_dim = start_dim + size marginals.append(covariance[..., start_dim:end_dim, start_dim:end_dim]) start_...
Utility method to decompose a joint posterior into components.
def _decompose_from_posterior_marginals( model, posterior_means, posterior_covs, parameter_samples): """Utility method to decompose a joint posterior into components. Args: model: `tfp.sts.Sum` instance defining an additive STS model. posterior_means: float `Tensor` of shape `concat( [[num_poster...
Decompose an observed time series into contributions from each component.
def decompose_by_component(model, observed_time_series, parameter_samples): """Decompose an observed time series into contributions from each component. This method decomposes a time series according to the posterior represention of a structural time series model. In particular, it: - Computes the posterior ...
Decompose a forecast distribution into contributions from each component.
def decompose_forecast_by_component(model, forecast_dist, parameter_samples): """Decompose a forecast distribution into contributions from each component. Args: model: An instance of `tfp.sts.Sum` representing a structural time series model. forecast_dist: A `Distribution` instance returned by `tfp.s...
Converts dense Tensor to SparseTensor dropping ignore_value cells.
def dense_to_sparse(x, ignore_value=None, name=None): """Converts dense `Tensor` to `SparseTensor`, dropping `ignore_value` cells. Args: x: A `Tensor`. ignore_value: Entries in `x` equal to this value will be absent from the return `SparseTensor`. If `None`, default value of `x` dtype will be u...
Defers an operator overload to attr.
def _operator(attr): """Defers an operator overload to `attr`. Args: attr: Operator attribute to use. Returns: Function calling operator attribute. """ @functools.wraps(attr) def func(a, *args): return attr(a.value, *args) return func
Human - readable representation of a tensor s numpy value.
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
Sample shape of random variable as a TensorShape.
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)
Sample shape of random variable as a 1 - D Tensor.
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): retur...
Get tensor that the random variable corresponds to.
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 e...
In a session computes and returns the value of this random variable.
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...
Value as NumPy array only available for TF Eager.
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()
Posterior Normal distribution with conjugate prior on the mean.
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 scal...
Build a scale - and - shift function using a multi - layer neural network.
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...
Returns a batch of points chosen uniformly from the unit hypersphere.
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), s...
Replicate the input tensor n times along a new ( major ) dimension.
def _replicate(n, tensor): """Replicate the input tensor n times along a new (major) dimension.""" # TODO(axch) Does this already exist somewhere? Should it get contributed? multiples = tf.concat([[n], tf.ones_like(tensor.shape)], axis=0) return tf.tile(tf.expand_dims(tensor, axis=0), multiples)
Returns a Tensor of samples from an LKJ distribution.
def _sample_n(self, num_samples, seed=None, name=None): """Returns a Tensor of samples from an LKJ distribution. Args: num_samples: Python `int`. The number of samples to draw. seed: Python integer seed for RNG name: Python `str` name prefixed to Ops created by this function. Returns: ...
Returns the unnormalized log density of an LKJ distribution.
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`...
Returns the log normalization of an LKJ distribution.
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...
Returns explict dtype from args_list if exists else preferred_dtype.
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')...
Factory for implementing summary statistics eg mean stddev mode.
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...
Batched KL divergence KL ( a || b ) for Sample distributions.
def _kl_sample(a, b, name='kl_sample'): """Batched KL divergence `KL(a || b)` for Sample distributions. We can leverage the fact that: ``` KL(Sample(a) || Sample(b)) = sum(KL(a || b)) ``` where the sum is over the `sample_shape` dims. Args: a: Instance of `Sample` distribution. b: Instance of ...
Helper to broadcast a tensor using a list of target tensors.
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
Pdf evaluated at the peak.
def _pdf_at_peak(self): """Pdf evaluated at the peak.""" return (self.peak - self.low) / (self.high - self.low)
Estimate a lower bound on effective sample size for each independent chain.
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 i...
ESS computation for one single Tensor argument.
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]): ...
Gelman and Rubin ( 1992 ) s potential scale reduction for chain convergence.
def potential_scale_reduction(chains_states, independent_chain_ndims=1, name=None): """Gelman and Rubin (1992)'s potential scale reduction for chain convergence. Given `N > 1` states from each of `C > 1` independent chains, the potential scale reduction...
potential_scale_reduction for one single state Tensor.
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 inde...
Get number of elements of x in axis as type x. dtype.
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)
Broadcast a listable secondary_arg to that of states.
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` ({})'.fo...
Use Gauss - Hermite quadrature to form quadrature on positive - reals.
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 `quadratur...
Use LogNormal quantiles to form quadrature on positive - reals.
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 (bat...
Returns new _Mapping with args merged with self.
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) i...
To support weak referencing removes cache key from the cache value.
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)
Helper to merge which handles merging one value.
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))
Converts nested tuple list or dict to nested tuple.
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
Computes the doubling increments for the left end point.
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 w...
Finds the index of the optimal set of bounds for each chain.
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...
Returns the bounds of the slice at each stage of doubling procedure.
def slice_bounds_by_doubling(x_initial, target_log_prob, log_slice_heights, max_doublings, step_size, seed=None, name=None): """Returns the boun...
Samples from the slice by applying shrinkage for rejected points.
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 ...
For a given x position in each Markov chain returns the next x.
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...
Runs annealed importance sampling ( AIS ) to estimate normalizing constants.
def sample_annealed_importance_chain( num_steps, proposal_log_prob_fn, target_log_prob_fn, current_state, make_kernel_fn, parallel_iterations=10, name=None): """Runs annealed importance sampling (AIS) to estimate normalizing constants. This function uses an MCMC transition operator (e.g...
Creates a value - setting interceptor.
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 bui...
Takes Edward probabilistic program and returns its log joint function.
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 ...
Filters inputs to be compatible with function f s signature.
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` whic...
Network block for VGG.
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.Acti...
Computes the output shape of the layer.
def compute_output_shape(self, input_shape): """Computes the output shape of the layer. Args: input_shape: Shape tuple (tuple of integers) or list of shape tuples (one per output tensor of the layer). Shape tuples can include None for free dimensions, instead of an integer. Returns: ...
Returns the config of the layer.
def get_config(self): """Returns the config of the layer. A layer config is a Python dictionary (serializable) containing the configuration of a layer. The same layer can be reinstantiated later (without its trained weights) from this configuration. Returns: config: A Python dictionary of cl...
Simulates a No - U - Turn Sampler ( NUTS ) trajectory.
def kernel(target_log_prob_fn, current_state, step_size, seed=None, current_target_log_prob=None, current_grads_target_log_prob=None, name=None): """Simulates a No-U-Turn Sampler (NUTS) trajectory. Args: target_log_prob_fn: Python callable which...
Builds a tree at a given tree depth and at a given state.
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, ...
Wraps value and gradients function to assist with None gradients.
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...
If two given states and momentum do not exhibit a U - turn pattern.
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
Runs one step of leapfrog integration.
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, cu...
Log - joint probability given a state s log - probability and momentum.
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
Returns samples from a Bernoulli distribution.
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=...
Makes closure which creates loc scale params from tf. get_variable.
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=Non...
Creates a function to build Normal distributions with trainable params.
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_constr...
Creates multivariate standard Normal distribution.
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` n...
Deserializes the Keras - serialized function.
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...
Serializes function for Keras.
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 sc...
Broadcasts from_structure to to_structure.
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`...
Returns True if args should be expanded as * args.
def expand_as_args(args): """Returns `True` if `args` should be expanded as `*args`.""" return (isinstance(args, collections.Sequence) and not _is_namedtuple(args) and not _force_leaf(args))
Eagerly converts struct to Tensor recursing upon failure.
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 s...
Converts args to Tensor s.
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`...
Calls fn with args possibly expanding args.
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...
Replaces member function s first arg self to self. _value ().
def _wrap_method(cls, attr): """Replaces member function's first arg, `self`, to `self._value()`. This function is used by `_get_tensor_like_attributes` to take existing `Tensor` member functions and make them operate on `self._value()`, i.e., the concretization of a `Distribution`. Args: cls: The `clas...
Returns Tensor attributes related to shape and Python builtins.
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. ...
Get the value returned by tf. convert_to_tensor ( distribution ).
def _value(self, dtype=None, name=None, as_ref=False): # pylint: disable=g-doc-args """Get the value returned by `tf.convert_to_tensor(distribution)`. Note: this function may mutate the distribution instance state by caching the concretized `Tensor` value. Args: dtype: Must return a `Tensor` with the giv...
Creates the encoder function.
def make_encoder(activation, latent_size, base_depth): """Creates the encoder function. Args: activation: Activation function in hidden layers. latent_size: The dimensionality of the encoding. base_depth: The lowest depth for a layer. Returns: encoder: A `callable` mapping a `Tensor` of images t...
Creates the decoder function.
def make_decoder(activation, latent_size, output_shape, base_depth): """Creates the decoder function. Args: activation: Activation function in hidden layers. latent_size: Dimensionality of the encoding. output_shape: The output image shape. base_depth: Smallest depth for a layer. Returns: de...
Creates the mixture of Gaussians prior distribution.
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 representin...
Helper utility to make a field of images.
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....
Builds the model function for use in an estimator.
def model_fn(features, labels, mode, params, config): """Builds the model function for use in an estimator. Arguments: features: The input features for the estimator. labels: The labels, unused here. mode: Signifies whether it is train or test or predict. params: Some hyperparameters as a dictionar...
Downloads a file.
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, ...
Builds fake MNIST - style data for unit testing.
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()...
Builds an Iterator switching between train and heldout data.
def build_input_fns(data_dir, batch_size): """Builds an Iterator switching between train and heldout data.""" # Build an iterator over training batches. def train_input_fn(): dataset = static_mnist_dataset(data_dir, "train") dataset = dataset.shuffle(50000).repeat().batch(batch_size) return tf.compat...