INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
The Triangular Csiszar - function in log - space.
def triangular(logu, name=None): """The Triangular Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` The Triangular Csiszar-function is: ```none f(u) = (u - 1)**2 / (1 + u) ``` This Csiszar-function induces a symmetric f-Divergence, i.e...
The T - Power Csiszar - function in log - space.
def t_power(logu, t, self_normalized=False, name=None): """The T-Power Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` When `self_normalized = True` the T-Power Csiszar-function is: ```none f(u) = s [ u**t - 1 - t(u - 1) ] s = { -1 0 <...
The log1p - abs Csiszar - function in log - space.
def log1p_abs(logu, name=None): """The log1p-abs Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` The Log1p-Abs Csiszar-function is: ```none f(u) = u**(sign(u-1)) - 1 ``` This function is so-named because it was invented from the follo...
The Jeffreys Csiszar - function in log - space.
def jeffreys(logu, name=None): """The Jeffreys Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` The Jeffreys Csiszar-function is: ```none f(u) = 0.5 ( u log(u) - log(u) ) = 0.5 kl_forward + 0.5 kl_reverse = symmetrized_csiszar...
The Modified - GAN Csiszar - function in log - space.
def modified_gan(logu, self_normalized=False, name=None): """The Modified-GAN Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` When `self_normalized = True` the modified-GAN (Generative/Adversarial Network) Csiszar-function is: ```none f(...
Calculates the dual Csiszar - function in log - space.
def dual_csiszar_function(logu, csiszar_function, name=None): """Calculates the dual Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` The Csiszar-dual is defined as: ```none f^*(u) = u f(1 / u) ``` where `f` is some other Csiszar-funct...
Symmetrizes a Csiszar - function in log - space.
def symmetrized_csiszar_function(logu, csiszar_function, name=None): """Symmetrizes a Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` The symmetrized Csiszar-function is defined as: ```none f_g(u) = 0.5 g(u) + 0.5 u g (1 / u) ``` wher...
Monte - Carlo approximation of the Csiszar f - Divergence.
def monte_carlo_csiszar_f_divergence( f, p_log_prob, q, num_draws, use_reparametrization=None, seed=None, name=None): """Monte-Carlo approximation of the Csiszar f-Divergence. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` The Csiszar f-Divergenc...
Use VIMCO to lower the variance of gradient [ csiszar_function ( Avg ( logu )) ].
def csiszar_vimco(f, p_log_prob, q, num_draws, num_batch_draws=1, seed=None, name=None): """Use VIMCO to lower the variance of gradient[csiszar_function(Avg(logu))]. This function generalizes VIMCO [(Mnih an...
Helper to csiszar_vimco ; computes log_avg_u log_sooavg_u.
def csiszar_vimco_helper(logu, name=None): """Helper to `csiszar_vimco`; computes `log_avg_u`, `log_sooavg_u`. `axis = 0` of `logu` is presumed to correspond to iid samples from `q`, i.e., ```none logu[j] = log(u[j]) u[j] = p(x, h[j]) / q(h[j] | x) h[j] iid~ q(H | x) ``` Args: logu: Floating-type...
1 - D interpolation that works with/ without batching.
def _interp_regular_1d_grid_impl(x, x_ref_min, x_ref_max, y_ref, axis=-1, batch_y_ref=False, fill_value='constant_extensio...
Linear 1 - D interpolation on a regular ( constant spacing ) grid.
def interp_regular_1d_grid(x, x_ref_min, x_ref_max, y_ref, axis=-1, fill_value='constant_extension', fill_value_below=None, fill_va...
Linear 1 - D interpolation on a regular ( constant spacing ) grid.
def batch_interp_regular_1d_grid(x, x_ref_min, x_ref_max, y_ref, axis=-1, fill_value='constant_extension', fill_value_belo...
Multi - linear interpolation on a regular ( constant spacing ) grid.
def batch_interp_regular_nd_grid(x, x_ref_min, x_ref_max, y_ref, axis, fill_value='constant_extension', name=None): """M...
N - D interpolation that works with leading batch dims.
def _batch_interp_with_gather_nd(x, x_ref_min, x_ref_max, y_ref, nd, fill_value, batch_dims): """N-D interpolation that works with leading batch dims.""" dtype = x.dtype # In this function, # x.shape = [A1, ..., An, D, nd], where n = batch_dims # and # y_ref.shape = [A1, .....
Assert that Tensor x has expected number of dimensions.
def _assert_ndims_statically(x, expect_ndims=None, expect_ndims_at_least=None, expect_static=False): """Assert that Tensor x has expected number of dimensions.""" ndims = x.shape.ndims if ndims is None: if expect_static: ...
Make func to expand left/ right ( of axis ) dims of tensors shaped like x.
def _make_expand_x_fn_for_non_batch_interpolation(y_ref, axis): """Make func to expand left/right (of axis) dims of tensors shaped like x.""" # This expansion is to help x broadcast with `y`, the output. # In the non-batch case, the output shape is going to be # y_ref.shape[:axis] + x.shape + y_ref.shape[axis...
Make func to expand left/ right ( of axis ) dims of tensors shaped like x.
def _make_expand_x_fn_for_batch_interpolation(y_ref, axis): """Make func to expand left/right (of axis) dims of tensors shaped like x.""" # This expansion is to help x broadcast with `y`, the output. # In the batch case, the output shape is going to be # Broadcast(y_ref.shape[:axis], x.shape[:-1]) + # x.s...
Like batch_gather but broadcasts to the left of axis.
def _batch_gather_with_broadcast(params, indices, axis): """Like batch_gather, but broadcasts to the left of axis.""" # batch_gather assumes... # params.shape = [A1,...,AN, B1,...,BM] # indices.shape = [A1,...,AN, C] # which gives output of shape # [A1,...,AN, C, B1,...,BM] # Here w...
Broadcasts the event or distribution parameters.
def _broadcast_cat_event_and_params(event, params, base_dtype): """Broadcasts the event or distribution parameters.""" if dtype_util.is_integer(event.dtype): pass elif dtype_util.is_floating(event.dtype): # When `validate_args=True` we've already ensured int/float casting # is closed. event = tf.c...
r Monte Carlo estimate of \\ ( E_p [ f ( Z ) ] = E_q [ f ( Z ) p ( Z )/ q ( Z ) ] \\ ).
def expectation_importance_sampler(f, log_p, sampling_dist_q, z=None, n=None, seed=None, name='expectation_imp...
r Importance sampling with a positive function in log - space.
def expectation_importance_sampler_logspace( log_f, log_p, sampling_dist_q, z=None, n=None, seed=None, name='expectation_importance_sampler_logspace'): r"""Importance sampling with a positive function, in log-space. With \\(p(z) := exp^{log_p(z)}\\), and \\(f(z) = exp{log_f(z)}\\), th...
Evaluate Log [ E [ values ]] in a stable manner.
def _logspace_mean(log_values): """Evaluate `Log[E[values]]` in a stable manner. Args: log_values: `Tensor` holding `Log[values]`. Returns: `Tensor` of same `dtype` as `log_values`, reduced across dim 0. `Log[Mean[values]]`. """ # center = Max[Log[values]], with stop-gradient # The center ...
Broadcasts the event or samples.
def _broadcast_event_and_samples(event, samples, event_ndims): """Broadcasts the event or samples.""" # This is the shape of self.samples, without the samples axis, i.e. the shape # of the result of a call to dist.sample(). This way we can broadcast it with # event to get a properly-sized event, then add the si...
Takes one step of the TransitionKernel.
def one_step(self, current_state, previous_kernel_results): """Takes one step of the TransitionKernel. Args: current_state: `Tensor` or Python `list` of `Tensor`s representing the current state(s) of the Markov chain(s). previous_kernel_results: A (possibly nested) `tuple`, `namedtuple` or ...
Returns an object with the same type as returned by one_step.
def bootstrap_results(self, init_state): """Returns an object with the same type as returned by `one_step`. Args: init_state: `Tensor` or Python `list` of `Tensor`s representing the initial state(s) of the Markov chain(s). Returns: kernel_results: A (possibly nested) `tuple`, `namedtup...
Applies the BFGS algorithm to minimize a differentiable function.
def minimize(value_and_gradients_function, initial_position, tolerance=1e-8, x_tolerance=0, f_relative_tolerance=0, initial_inverse_hessian_estimate=None, max_iterations=50, parallel_iterations=1, stopping_condition=...
Computes control inputs to validate a provided inverse Hessian.
def _inv_hessian_control_inputs(inv_hessian): """Computes control inputs to validate a provided inverse Hessian. These ensure that the provided inverse Hessian is positive definite and symmetric. Args: inv_hessian: The starting estimate for the inverse of the Hessian at the initial point. Returns...
Update the BGFS state by computing the next inverse hessian estimate.
def _update_inv_hessian(prev_state, next_state): """Update the BGFS state by computing the next inverse hessian estimate.""" # Only update the inverse Hessian if not already failed or converged. should_update = ~next_state.converged & ~next_state.failed # Compute the normalization term (y^T . s), should not up...
Applies the BFGS update to the inverse Hessian estimate.
def _bfgs_inv_hessian_update(grad_delta, position_delta, normalization_factor, inv_hessian_estimate): """Applies the BFGS update to the inverse Hessian estimate. The BFGS update rule is (note A^T denotes the transpose of a vector/matrix A). ```None rho = 1/(grad_delta^T * positi...
Computes the product of a matrix with a vector on the right.
def _mul_right(mat, vec): """Computes the product of a matrix with a vector on the right. Note this supports dynamic shapes and batched computation. Examples: M = tf.reshape(tf.range(6), shape=(3, 2)) # => [[0, 1], # [2, 3], # [4, 5]] v = tf.constant([1, 2]) # Shape: (2,) _mul_...
Computes the outer product of two possibly batched vectors.
def _tensor_product(t1, t2): """Computes the outer product of two possibly batched vectors. Args: t1: A `tf.Tensor` of shape `[..., n]`. t2: A `tf.Tensor` of shape `[..., m]`. Returns: A tensor of shape `[..., n, m]` with matching batch dimensions, let's call it `r`, whose components are: `...
Transpose a possibly batched matrix.
def _batch_transpose(mat): """Transpose a possibly batched matrix. Args: mat: A `tf.Tensor` of shape `[..., n, m]`. Returns: A tensor of shape `[..., m, n]` with matching batch dimensions. """ n = distribution_util.prefer_static_rank(mat) perm = tf.range(n) perm = tf.concat([perm[:-2], [perm[-1]...
Maybe add ndims ones to x. shape on the right.
def pad_shape_right_with_ones(x, ndims): """Maybe add `ndims` ones to `x.shape` on the right. If `ndims` is zero, this is a no-op; otherwise, we will create and return a new `Tensor` whose shape is that of `x` with `ndims` ones concatenated on the right side. If the shape of `x` is known statically, the shape ...
Return Tensor with right - most ndims summed.
def sum_rightmost_ndims_preserving_shape(x, ndims): """Return `Tensor` with right-most ndims summed. Args: x: the `Tensor` whose right-most `ndims` dimensions to sum ndims: number of right-most dimensions to sum. Returns: A `Tensor` resulting from calling `reduce_sum` on the `ndims` right-most d...
A sqrt function whose gradient at zero is very large but finite.
def sqrt_with_finite_grads(x, name=None): """A sqrt function whose gradient at zero is very large but finite. Args: x: a `Tensor` whose sqrt is to be computed. name: a Python `str` prefixed to all ops created by this function. Default `None` (i.e., "sqrt_with_finite_grads"). Returns: sqrt: the...
Return common dtype of arg_list or None.
def maybe_get_common_dtype(arg_list): """Return common dtype of arg_list, or None. Args: arg_list: an iterable of items which are either `None` or have a `dtype` property. Returns: dtype: The common dtype of items in `arg_list`, or `None` if the list is empty or all items are `None`. """ ...
Applies the L - BFGS algorithm to minimize a differentiable function.
def minimize(value_and_gradients_function, initial_position, num_correction_pairs=10, tolerance=1e-8, x_tolerance=0, f_relative_tolerance=0, initial_inverse_hessian_estimate=None, max_iterations=50, parallel_iteratio...
Create LBfgsOptimizerResults with initial state of search procedure.
def _get_initial_state(value_and_gradients_function, initial_position, num_correction_pairs, tolerance): """Create LBfgsOptimizerResults with initial state of search procedure.""" init_args = bfgs_utils.get_initial_state_args( value_and_grad...
Computes the search direction to follow at the current state.
def _get_search_direction(state): """Computes the search direction to follow at the current state. On the `k`-th iteration of the main L-BFGS algorithm, the state has collected the most recent `m` correction pairs in position_deltas and gradient_deltas, where `k = state.num_iterations` and `m = min(k, num_corr...
Creates a tf. Tensor suitable to hold k element - shaped tensors.
def _make_empty_queue_for(k, element): """Creates a `tf.Tensor` suitable to hold `k` element-shaped tensors. For example: ```python element = tf.constant([[0., 1., 2., 3., 4.], [5., 6., 7., 8., 9.]]) # A queue capable of holding 3 elements. _make_empty_queue_for(3, elemen...
Conditionally push new vectors into a batch of first - in - first - out queues.
def _queue_push(queue, should_update, new_vecs): """Conditionally push new vectors into a batch of first-in-first-out queues. The `queue` of shape `[k, ..., n]` can be thought of as a batch of queues, each holding `k` n-D vectors; while `new_vecs` of shape `[..., n]` is a fresh new batch of n-D vectors. The `s...
Computes whether each square matrix in the input is positive semi - definite.
def _psd_mask(x): """Computes whether each square matrix in the input is positive semi-definite. Args: x: A floating-point `Tensor` of shape `[B1, ..., Bn, M, M]`. Returns: mask: A floating-point `Tensor` of shape `[B1, ... Bn]`. Each scalar is 1 if the corresponding matrix was PSD, otherwise 0. ...
Returns whether the input matches the given determinant limit.
def _det_large_enough_mask(x, det_bounds): """Returns whether the input matches the given determinant limit. Args: x: A floating-point `Tensor` of shape `[B1, ..., Bn, M, M]`. det_bounds: A floating-point `Tensor` that must broadcast to shape `[B1, ..., Bn]`, giving the desired lower bound on the ...
Returns a uniformly random Tensor of correlation - like matrices.
def _uniform_correlation_like_matrix(num_rows, batch_shape, dtype, seed): """Returns a uniformly random `Tensor` of "correlation-like" matrices. A "correlation-like" matrix is a symmetric square matrix with all entries between -1 and 1 (inclusive) and 1s on the main diagonal. Of these, the ones that are posit...
Returns rejection samples from trying to get good correlation matrices.
def correlation_matrix_volume_rejection_samples( det_bounds, dim, sample_shape, dtype, seed): """Returns rejection samples from trying to get good correlation matrices. The proposal being rejected from is the uniform distribution on "correlation-like" matrices. We say a matrix is "correlation-like" if it ...
Computes a confidence interval for the mean of the given 1 - D distribution.
def _clopper_pearson_confidence_interval(samples, error_rate): """Computes a confidence interval for the mean of the given 1-D distribution. Assumes (and checks) that the given distribution is Bernoulli, i.e., takes only two values. This licenses using the CDF of the binomial distribution for the confidence, ...
Returns confidence intervals for the desired correlation matrix volumes.
def compute_true_volumes( det_bounds, dim, num_samples, error_rate=1e-6, seed=42): """Returns confidence intervals for the desired correlation matrix volumes. The confidence intervals are computed by the [Clopper-Pearson method] (https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval). Args...
Batchwise KL divergence KL ( d1 || d2 ) with d1 and d2 von Mises.
def _kl_von_mises_von_mises(d1, d2, name=None): """Batchwise KL divergence KL(d1 || d2) with d1 and d2 von Mises. Args: d1: instance of a von Mises distribution object. d2: instance of a a von Mises distribution object. name: (optional) Name to use for created operations. default is "kl_von_mises...
Computes the cumulative density function ( CDF ) of von Mises distribution.
def von_mises_cdf(x, concentration): """Computes the cumulative density function (CDF) of von Mises distribution. Denote the density of vonMises(loc=0, concentration=concentration) by p(t). Note that p(t) is periodic, p(t) = p(t + 2 pi). The CDF at the point x is defined as int_{-pi}^x p(t) dt. Thus, when x ...
Computes the von Mises CDF and its derivative via series expansion.
def _von_mises_cdf_series(x, concentration, num_terms, dtype): """Computes the von Mises CDF and its derivative via series expansion.""" # Keep the number of terms as a float. It should be a small integer, so # exactly representable as a float. num_terms = tf.cast(num_terms, dtype=dtype) def loop_body(n, rn,...
Computes the von Mises CDF and its derivative via Normal approximation.
def _von_mises_cdf_normal(x, concentration, dtype): """Computes the von Mises CDF and its derivative via Normal approximation.""" def cdf_func(concentration): """A helper function that is passed to value_and_gradient.""" # z is an "almost Normally distributed" random variable. z = ((np.sqrt(2. / np.pi)...
Samples from the standardized von Mises distribution.
def random_von_mises(shape, concentration, dtype=tf.float32, seed=None): """Samples from the standardized von Mises distribution. The distribution is vonMises(loc=0, concentration=concentration), so the mean is zero. The location can then be changed by adding it to the samples. The sampling algorithm is rej...
Performs one step of the differential evolution algorithm.
def one_step( objective_function, population, population_values=None, differential_weight=0.5, crossover_prob=0.9, seed=None, name=None): """Performs one step of the differential evolution algorithm. Args: objective_function: A Python callable that accepts a batch of possible ...
Applies the Differential evolution algorithm to minimize a function.
def minimize(objective_function, initial_population=None, initial_position=None, population_size=50, population_stddev=1., max_iterations=100, func_tolerance=0, position_tolerance=1e-8, differential_weight=0.5, ...
Processes initial args.
def _get_initial_args(objective_function, initial_population, initial_position, population_size, population_stddev, max_iterations, func_tolerance, position_tolerance...
Checks if all the population values are NaN/ infinite.
def _check_failure(population_values): """Checks if all the population values are NaN/infinite.""" return tf.math.reduce_all(input_tensor=tf.math.is_inf(population_values))
Finds the population member with the lowest value.
def _find_best_in_population(population, values): """Finds the population member with the lowest value.""" best_value = tf.math.reduce_min(input_tensor=values) best_index = tf.where(tf.math.equal(values, best_value))[0, 0] return ([population_part[best_index] for population_part in population], best_...
Checks whether the convergence criteria have been met.
def _check_convergence(population, population_values, func_tolerance, position_tolerance): """Checks whether the convergence criteria have been met.""" # Check func tolerance value_range = tf.math.abs( tf.math.reduce_max(input_tensor=popul...
Constructs the initial population.
def _get_starting_population(initial_population, initial_position, population_size, population_stddev, seed): """Constructs the initial population. If an initial population is not already provided, t...
Performs recombination by binary crossover for the current population.
def _binary_crossover(population, population_size, mutants, crossover_prob, seed): """Performs recombination by binary crossover for the current population. Let v_i denote the i'th component of the member v and m_i the correspo...
Computes the mutatated vectors for each population member.
def _get_mutants(population, population_size, mixing_indices, differential_weight): """Computes the mutatated vectors for each population member. Args: population: Python `list` of `Tensor`s representing the current population vectors. Each `Tensor` mus...
Generates an array of indices suitable for mutation operation.
def _get_mixing_indices(size, seed=None, name=None): """Generates an array of indices suitable for mutation operation. The mutation operation in differential evolution requires that for every element of the population, three distinct other elements be chosen to produce a trial candidate. This function generate...
Converts the input arg to a list if it is not a list already.
def _ensure_list(tensor_or_list): """Converts the input arg to a list if it is not a list already. Args: tensor_or_list: A `Tensor` or a Python list of `Tensor`s. The argument to convert to a list of `Tensor`s. Returns: A tuple of two elements. The first is a Python list of `Tensor`s containing ...
Gets a Tensor of type dtype 0 if tol is None validation optional.
def _get_tol(tol, dtype, validate_args): """Gets a Tensor of type `dtype`, 0 if `tol` is None, validation optional.""" if tol is None: return tf.convert_to_tensor(value=0, dtype=dtype) tol = tf.convert_to_tensor(value=tol, dtype=dtype) if validate_args: tol = distribution_util.with_dependencies([ ...
Calculate the batched KL divergence KL ( a || b ) with a Deterministic.
def _kl_deterministic_distribution(a, b, name=None): """Calculate the batched KL divergence `KL(a || b)` with `a` Deterministic. Args: a: instance of a Deterministic distribution object. b: instance of a Distribution distribution object. name: (optional) Name to use for created operations. Default is ...
Implementation of sqrt ( 1 + x ** 2 ) which is stable despite large x.
def _sqrtx2p1(x): """Implementation of `sqrt(1 + x**2)` which is stable despite large `x`.""" sqrt_eps = np.sqrt(np.finfo(dtype_util.as_numpy_dtype(x.dtype)).eps) return tf.where( tf.abs(x) * sqrt_eps <= 1., tf.sqrt(x**2. + 1.), # For large x, calculating x**2 can overflow. This can be alleviate...
Numerically stable calculation of log ( 1 + x ** 2 ) for small or large |x|.
def log1psquare(x, name=None): """Numerically stable calculation of `log(1 + x**2)` for small or large `|x|`. For sufficiently large `x` we use the following observation: ```none log(1 + x**2) = 2 log(|x|) + log(1 + 1 / x**2) --> 2 log(|x|) as x --> inf ``` Numerically, `log(1 + 1 / x*...
Soft Thresholding operator.
def soft_threshold(x, threshold, name=None): """Soft Thresholding operator. This operator is defined by the equations ```none { x[i] - gamma, x[i] > gamma SoftThreshold(x, gamma)[i] = { 0, x[i] == gamma { x[i] + gamma, x[i] < -...
Clips values to a specified min and max while leaving gradient unaltered.
def clip_by_value_preserve_gradient(t, clip_value_min, clip_value_max, name=None): """Clips values to a specified min and max while leaving gradient unaltered. Like `tf.clip_by_value`, this function returns a tensor of the same type and shape as input `t` but with values clamp...
Build an iterator over training batches.
def build_input_pipeline(train_images, batch_size): """Build an iterator over training batches.""" training_dataset = tf.data.Dataset.from_tensor_slices(train_images) training_batches = training_dataset.shuffle( 50000, reshuffle_each_iteration=True).repeat().batch(batch_size) training_iterator = tf.compa...
Save a synthetic image as a PNG file.
def plot_generated_images(images, fname): """Save a synthetic image as a PNG file. Args: images: samples of synthetic images generated by the generative network. fname: Python `str`, filename to save the plot to. """ fig = plt.figure(figsize=(4, 4)) canvas = backend_agg.FigureCanvasAgg(fig) for i,...
Converts a sequence of productions into a string of terminal symbols.
def convert_to_string(self, productions): """Converts a sequence of productions into a string of terminal symbols. Args: productions: Tensor of shape [1, num_productions, num_production_rules]. Slices along the `num_productions` dimension represent one-hot vectors. Returns: str that co...
Produces a masking tensor for ( in ) valid production rules.
def mask(self, symbol, on_value, off_value): """Produces a masking tensor for (in)valid production rules. Args: symbol: str, a symbol in the grammar. on_value: Value to use for a valid production rule. off_value: Value to use for an invalid production rule. Returns: Tensor of shape...
Runs the model forward to generate a sequence of productions.
def call(self, inputs): """Runs the model forward to generate a sequence of productions. Args: inputs: Unused. Returns: productions: Tensor of shape [1, num_productions, num_production_rules]. Slices along the `num_productions` dimension represent one-hot vectors. """ del input...
Runs the model forward to return a stochastic encoding.
def call(self, inputs): """Runs the model forward to return a stochastic encoding. Args: inputs: Tensor of shape [1, num_productions, num_production_rules]. It is a sequence of productions of length `num_productions`. Each production is a one-hot vector of length `num_production_rules`: i...
Integral of the hat function used for sampling.
def _hat_integral(self, x): """Integral of the `hat` function, used for sampling. We choose a `hat` function, h(x) = x^(-power), which is a continuous (unnormalized) density touching each positive integer at the (unnormalized) pmf. This function implements `hat` integral: H(x) = int_x^inf h(t) dt; ...
Inverse function of _hat_integral.
def _hat_integral_inverse(self, x): """Inverse function of _hat_integral.""" x = tf.cast(x, self.power.dtype) t = self.power - 1. return tf.math.expm1(-(tf.math.log(t) + tf.math.log(x)) / t)
Compute the matrix rank ; the number of non - zero SVD singular values.
def matrix_rank(a, tol=None, validate_args=False, name=None): """Compute the matrix rank; the number of non-zero SVD singular values. Arguments: a: (Batch of) `float`-like matrix-shaped `Tensor`(s) which are to be pseudo-inverted. tol: Threshold below which the singular value is counted as "zero". ...
Concatenates chol @ chol. T with additional rows and columns.
def cholesky_concat(chol, cols, name=None): """Concatenates `chol @ chol.T` with additional rows and columns. This operation is conceptually identical to: ```python def cholesky_concat_slow(chol, cols): # cols shaped (n + m) x m = z x m mat = tf.matmul(chol, chol, adjoint_b=True) # batch of n x n # C...
Swaps m and i on axis - 1. ( Helper for pivoted_cholesky. )
def _swap_m_with_i(vecs, m, i): """Swaps `m` and `i` on axis -1. (Helper for pivoted_cholesky.) Given a batch of int64 vectors `vecs`, scalar index `m`, and compatibly shaped per-vector indices `i`, this function swaps elements `m` and `i` in each vector. For the use-case below, these are permutation vectors. ...
Computes the ( partial ) pivoted cholesky decomposition of matrix.
def pivoted_cholesky(matrix, max_rank, diag_rtol=1e-3, name=None): """Computes the (partial) pivoted cholesky decomposition of `matrix`. The pivoted Cholesky is a low rank approximation of the Cholesky decomposition of `matrix`, i.e. as described in [(Harbrecht et al., 2012)][1]. The currently-worst-approximat...
Compute the Moore - Penrose pseudo - inverse of a matrix.
def pinv(a, rcond=None, validate_args=False, name=None): """Compute the Moore-Penrose pseudo-inverse of a matrix. Calculate the [generalized inverse of a matrix]( https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse) using its singular-value decomposition (SVD) and including all large singular values. ...
Solves systems of linear eqns A X = RHS given LU factorizations.
def lu_solve(lower_upper, perm, rhs, validate_args=False, name=None): """Solves systems of linear eqns `A X = RHS`, given LU factorizations. Note: this function does not verify the implied matrix is actually invertible nor is this condition checked even when `validate_args=True`. Arg...
Computes a matrix inverse given the matrix s LU decomposition.
def lu_matrix_inverse(lower_upper, perm, validate_args=False, name=None): """Computes a matrix inverse given the matrix's LU decomposition. This op is conceptually identical to, ````python inv_X = tf.lu_matrix_inverse(*tf.linalg.lu(X)) tf.assert_near(tf.matrix_inverse(X), inv_X) # ==> True ``` Note: ...
The inverse LU decomposition X == lu_reconstruct ( * tf. linalg. lu ( X )).
def lu_reconstruct(lower_upper, perm, validate_args=False, name=None): """The inverse LU decomposition, `X == lu_reconstruct(*tf.linalg.lu(X))`. Args: lower_upper: `lu` as returned by `tf.linalg.lu`, i.e., if `matmul(P, matmul(L, U)) = X` then `lower_upper = L + U - eye`. perm: `p` as returned by `tf...
Returns list of assertions related to lu_reconstruct assumptions.
def _lu_reconstruct_assertions(lower_upper, perm, validate_args): """Returns list of assertions related to `lu_reconstruct` assumptions.""" assertions = [] message = 'Input `lower_upper` must have at least 2 dimensions.' if lower_upper.shape.ndims is not None: if lower_upper.shape.ndims < 2: raise Va...
Returns list of assertions related to lu_solve assumptions.
def _lu_solve_assertions(lower_upper, perm, rhs, validate_args): """Returns list of assertions related to `lu_solve` assumptions.""" assertions = _lu_reconstruct_assertions(lower_upper, perm, validate_args) message = 'Input `rhs` must have at least 2 dimensions.' if rhs.shape.ndims is not None: if rhs.shap...
Returns ( batched ) matmul of a SparseTensor ( or Tensor ) with a Tensor.
def sparse_or_dense_matmul(sparse_or_dense_a, dense_b, validate_args=False, name=None, **kwargs): """Returns (batched) matmul of a SparseTensor (or Tensor) with a Tensor. Args: sparse_or_dense_a: `Sparse...
Returns ( batched ) matmul of a ( sparse ) matrix with a column vector.
def sparse_or_dense_matvecmul(sparse_or_dense_matrix, dense_vector, validate_args=False, name=None, **kwargs): """Returns (batched) matmul of a (sparse) matrix with a column vector. Args: spa...
Returns ( batched ) matmul of a SparseTensor with a Tensor.
def _sparse_tensor_dense_matmul(sp_a, b, **kwargs): """Returns (batched) matmul of a SparseTensor with a Tensor. Args: sp_a: `SparseTensor` representing a (batch of) matrices. b: `Tensor` representing a (batch of) matrices, with the same batch shape of `sp_a`. The shape must be compatible with the sh...
Returns a block diagonal rank 2 SparseTensor from a batch of SparseTensors.
def _sparse_block_diag(sp_a): """Returns a block diagonal rank 2 SparseTensor from a batch of SparseTensors. Args: sp_a: A rank 3 `SparseTensor` representing a batch of matrices. Returns: sp_block_diag_a: matrix-shaped, `float` `SparseTensor` with the same dtype as `sparse_or_matrix`, of shape [B * ...
Checks that input is a float matrix.
def _maybe_validate_matrix(a, validate_args): """Checks that input is a `float` matrix.""" assertions = [] if not a.dtype.is_floating: raise TypeError('Input `a` must have `float`-like `dtype` ' '(saw {}).'.format(a.dtype.name)) if a.shape.ndims is not None: if a.shape.ndims < 2: ...
Computes the neg - log - likelihood gradient and Fisher information for a GLM.
def _grad_neg_log_likelihood_and_fim(model_matrix, linear_response, response, model): """Computes the neg-log-likelihood gradient and Fisher information for a GLM. Note that Fisher information is related to the Hessian of the log-likelihood by the equation ```none Fisher...
One step of ( the outer loop of ) the GLM fitting algorithm.
def fit_sparse_one_step(model_matrix, response, model, model_coefficients_start, tolerance, l1_regularizer, l2_regularizer=None, maximum_full_sweeps=Non...
r Fits a GLM using coordinate - wise FIM - informed proximal gradient descent.
def fit_sparse(model_matrix, response, model, model_coefficients_start, tolerance, l1_regularizer, l2_regularizer=None, maximum_iterations=None, maximum_full_sweeps_per_iteration=1, lea...
Generate the slices for building an autoregressive mask.
def _gen_slices(num_blocks, n_in, n_out, mask_type=MASK_EXCLUSIVE): """Generate the slices for building an autoregressive mask.""" # TODO(b/67594795): Better support of dynamic shape. slices = [] col = 0 d_in = n_in // num_blocks d_out = n_out // num_blocks row = d_out if mask_type == MASK_EXCLUSIVE else ...
Generate the mask for building an autoregressive dense layer.
def _gen_mask(num_blocks, n_in, n_out, mask_type=MASK_EXCLUSIVE, dtype=tf.float32): """Generate the mask for building an autoregressive dense layer.""" # TODO(b/67594795): Better support of dynamic shape. mask = np.zeros([n_out, n_in], dtype=dtype.as_numpy_d...
A autoregressively masked dense layer. Analogous to tf. layers. dense.
def masked_dense(inputs, units, num_blocks=None, exclusive=False, kernel_initializer=None, reuse=None, name=None, *args, # pylint: disable=keyword-arg-before-vararg **kwargs): """A ...
Build the Masked Autoregressive Density Estimator ( Germain et al. 2015 ).
def masked_autoregressive_default_template(hidden_layers, shift_only=False, activation=tf.nn.relu, log_scale_min_clip=-5., log_scale_max_clip=3., ...