INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Helper to maybe_call_fn_and_grads.
def _value_and_gradients(fn, fn_arg_list, result=None, grads=None, name=None): """Helper to `maybe_call_fn_and_grads`.""" with tf.compat.v1.name_scope(name, 'value_and_gradients', [fn_arg_list, result, grads]): def _convert_to_tensor(x, name): ctt = lambda x_: x_ if x_ is N...
Calls fn and computes the gradient of the result wrt args_list.
def maybe_call_fn_and_grads(fn, fn_arg_list, result=None, grads=None, check_non_none_grads=True, name=None): """Calls `fn` and computes the gradient of the result wrt `args_list`...
Construct a for loop preferring a python loop if n is staticaly known.
def smart_for_loop(loop_num_iter, body_fn, initial_loop_vars, parallel_iterations=10, name=None): """Construct a for loop, preferring a python loop if `n` is staticaly known. Given `loop_num_iter` and `body_fn`, return an op corresponding to executing `body_fn` `loop_num_iter` times, feeding p...
A simplified version of tf. scan that has configurable tracing.
def trace_scan(loop_fn, initial_state, elems, trace_fn, parallel_iterations=10, name=None): """A simplified version of `tf.scan` that has configurable tracing. This function repeatedly calls `loop_fn(state, elem)`, where `state` is the `i...
Wraps a setter so it applies to the inner - most results in kernel_results.
def make_innermost_setter(setter): """Wraps a setter so it applies to the inner-most results in `kernel_results`. The wrapped setter unwraps `kernel_results` and applies `setter` to the first results without an `inner_results` attribute. Args: setter: A callable that takes the kernel results as well as so...
Wraps a getter so it applies to the inner - most results in kernel_results.
def make_innermost_getter(getter): """Wraps a getter so it applies to the inner-most results in `kernel_results`. The wrapped getter unwraps `kernel_results` and returns the return value of `getter` called with the first results without an `inner_results` attribute. Args: getter: A callable that takes Ker...
Enables the store_parameters_in_results parameter in a chain of kernels.
def enable_store_parameters_in_results(kernel): """Enables the `store_parameters_in_results` parameter in a chain of kernels. This is a temporary utility for use during the transition period of the parameter storage methods. Args: kernel: A TransitionKernel. Returns: kernel: The same kernel, but re...
Replaces the rightmost dims in a Tensor representing a shape.
def _replace_event_shape_in_shape_tensor( input_shape, event_shape_in, event_shape_out, validate_args): """Replaces the rightmost dims in a `Tensor` representing a shape. Args: input_shape: a rank-1 `Tensor` of integers event_shape_in: the event shape expected to be present in rightmost dims of `...
Replaces the event shape dims of a TensorShape.
def _replace_event_shape_in_tensorshape( input_tensorshape, event_shape_in, event_shape_out): """Replaces the event shape dims of a `TensorShape`. Args: input_tensorshape: a `TensorShape` instance in which to attempt replacing event shape. event_shape_in: `Tensor` shape representing the event sha...
Check that a shape Tensor is int - type and otherwise sane.
def _maybe_check_valid_shape(shape, validate_args): """Check that a shape Tensor is int-type and otherwise sane.""" if not dtype_util.is_integer(shape.dtype): raise TypeError('{} dtype ({}) should be `int`-like.'.format( shape, dtype_util.name(shape.dtype))) assertions = [] message = '`{}` rank sh...
Calculate the batchwise KL divergence KL ( d1 || d2 ) with d1 and d2 Beta.
def _kl_beta_beta(d1, d2, name=None): """Calculate the batchwise KL divergence KL(d1 || d2) with d1 and d2 Beta. Args: d1: instance of a Beta distribution object. d2: instance of a Beta distribution object. name: (optional) Name to use for created operations. default is "kl_beta_beta". Returns...
Checks the validity of a sample.
def _maybe_assert_valid_sample(self, x): """Checks the validity of a sample.""" if not self.validate_args: return x return distribution_util.with_dependencies([ assert_util.assert_positive(x, message="sample must be positive"), assert_util.assert_less(x, 1., message="sample must be les...
Condition to stop when any batch member converges or all have failed.
def converged_any(converged, failed): """Condition to stop when any batch member converges, or all have failed.""" return (tf.reduce_any(input_tensor=converged) | tf.reduce_all(input_tensor=failed))
Returns a dictionary to populate the initial state of the search procedure.
def get_initial_state_args(value_and_gradients_function, initial_position, grad_tolerance, control_inputs=None): """Returns a dictionary to populate the initial state of the search procedure. Performs an initial convergence check and ...
Performs the line search step of the BFGS search procedure.
def line_search_step(state, value_and_gradients_function, search_direction, grad_tolerance, f_relative_tolerance, x_tolerance, stopping_condition): """Performs the line search step of the BFGS search procedure. Uses hager_zhang line search procedure to compute a suitable s...
Restricts a function in n - dimensions to a given direction.
def _restrict_along_direction(value_and_gradients_function, position, direction): """Restricts a function in n-dimensions to a given direction. Suppose f: R^n -> R. Then given a point x0 and a vector p0 in R^n, the restriction of the function along that...
Updates the state advancing its position by a given position_delta.
def _update_position(state, position_delta, next_objective, next_gradient, grad_tolerance, f_relative_tolerance, x_tolerance): """Updates the state advancing its position by a given position_d...
Compute the norm of the given ( possibly batched ) value.
def norm(value, dims, order=None): """Compute the norm of the given (possibly batched) value. Args: value: A `Tensor` of real dtype. dims: An Python integer with the number of non-batching dimensions in the value, i.e. `dims=0` (scalars), `dims=1` (vectors), `dims=2` (matrices). order: Order of t...
Checks if the algorithm satisfies the convergence criteria.
def _check_convergence(current_position, next_position, current_objective, next_objective, next_gradient, grad_tolerance, f_relative_tolerance, x_tolerance): ...
Broadcast a value to match the batching dimensions of a target.
def _broadcast(value, target): """Broadcast a value to match the batching dimensions of a target. If necessary the value is converted into a tensor. Both value and target should be of the same dtype. Args: value: A value to broadcast. target: A `Tensor` of shape [b1, ..., bn, d]. Returns: A `Te...
Compute the harmonic number from its analytic continuation.
def _harmonic_number(x): """Compute the harmonic number from its analytic continuation. Derivation from [here]( https://en.wikipedia.org/wiki/Digamma_function#Relation_to_harmonic_numbers) and [Euler's constant]( https://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant). Args: x: input float. ...
Compute the n th ( uncentered ) moment.
def _moment(self, n): """Compute the n'th (uncentered) moment.""" total_concentration = self.concentration1 + self.concentration0 expanded_concentration1 = tf.ones_like( total_concentration, dtype=self.dtype) * self.concentration1 expanded_concentration0 = tf.ones_like( total_concentrati...
Validates that target_accept_prob is in ( 0 1 ).
def _maybe_validate_target_accept_prob(target_accept_prob, validate_args): """Validates that target_accept_prob is in (0, 1).""" if not validate_args: return target_accept_prob with tf.control_dependencies([ tf.compat.v1.assert_positive( target_accept_prob, message='`target_accept_prob` must b...
Default exchange proposal function for replica exchange MC.
def default_exchange_proposed_fn(prob_exchange): """Default exchange proposal function, for replica exchange MC. With probability `prob_exchange` propose combinations of replica for exchange. When exchanging, create combinations of adjacent replicas in [Replica Exchange Monte Carlo]( https://en.wikipedia.org...
field_name from kernel_results or kernel_results. accepted_results.
def _get_field(kernel_results, field_name): """field_name from kernel_results or kernel_results.accepted_results.""" if hasattr(kernel_results, field_name): return getattr(kernel_results, field_name) if hasattr(kernel_results, 'accepted_results'): return getattr(kernel_results.accepted_results, field_name...
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 ...
Get list of TensorArrays holding exchanged states and zeros.
def _get_exchanged_states(self, old_states, exchange_proposed, exchange_proposed_n, sampled_replica_states, sampled_replica_results): """Get list of TensorArrays holding exchanged states, and zeros.""" with tf.compat.v1.name_scope('get_exchanged_states'): ...
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...
Helper to _covariance and _variance which computes a shared scale.
def _variance_scale_term(self): """Helper to `_covariance` and `_variance` which computes a shared scale.""" # Expand back the last dim so the shape of _variance_scale_term matches the # shape of self.concentration. c0 = self.total_concentration[..., tf.newaxis] return tf.sqrt((1. + c0 / self.total_...
Checks the validity of the concentration parameter.
def _maybe_assert_valid_concentration(self, concentration, validate_args): """Checks the validity of the concentration parameter.""" if not validate_args: return concentration concentration = distribution_util.embed_check_categorical_event_shape( concentration) return distribution_util.wit...
Check counts for proper shape values then return tensor version.
def _maybe_assert_valid_sample(self, counts): """Check counts for proper shape, values, then return tensor version.""" if not self.validate_args: return counts counts = distribution_util.embed_check_nonnegative_integer_form(counts) return distribution_util.with_dependencies([ assert_util.a...
Makes a function which applies a list of Bijectors log_det_jacobian s.
def forward_log_det_jacobian_fn(bijector): """Makes a function which applies a list of Bijectors' `log_det_jacobian`s.""" if not mcmc_util.is_list_like(bijector): bijector = [bijector] def fn(transformed_state_parts, event_ndims): return sum([ b.forward_log_det_jacobian(sp, event_ndims=e) ...
Makes a function which applies a list of Bijectors forward s.
def forward_transform_fn(bijector): """Makes a function which applies a list of Bijectors' `forward`s.""" if not mcmc_util.is_list_like(bijector): bijector = [bijector] def fn(transformed_state_parts): return [b.forward(sp) for b, sp in zip(bijector, transformed_state_parts)] return fn
Makes a function which applies a list of Bijectors inverse s.
def inverse_transform_fn(bijector): """Makes a function which applies a list of Bijectors' `inverse`s.""" if not mcmc_util.is_list_like(bijector): bijector = [bijector] def fn(state_parts): return [b.inverse(sp) for b, sp in zip(bijector, state_parts)] return fn
Runs one iteration of the Transformed Kernel.
def one_step(self, current_state, previous_kernel_results): """Runs one iteration of the Transformed Kernel. Args: current_state: `Tensor` or Python `list` of `Tensor`s representing the current state(s) of the Markov chain(s), _after_ application of `bijector.forward`. The first `r` ...
Returns an object with the same type as returned by one_step.
def bootstrap_results(self, init_state=None, transformed_init_state=None): """Returns an object with the same type as returned by `one_step`. Unlike other `TransitionKernel`s, `TransformedTransitionKernel.bootstrap_results` has the option of initializing the `TransformedTransitionKernelResults` from ei...
Like tf. where but works on namedtuples.
def val_where(cond, tval, fval): """Like tf.where but works on namedtuples.""" if isinstance(tval, tf.Tensor): return tf.where(cond, tval, fval) elif isinstance(tval, tuple): cls = type(tval) return cls(*(val_where(cond, t, f) for t, f in zip(tval, fval))) else: raise Exception(TypeError)
Performs the secant square procedure of Hager Zhang.
def secant2(value_and_gradients_function, val_0, search_interval, f_lim, sufficient_decrease_param=0.1, curvature_param=0.9, name=None): """Performs the secant square procedure of Hager Zhang. Given an interval that brackets a root, this proce...
Helper function for secant square.
def _secant2_inner(value_and_gradients_function, initial_args, val_0, val_c, f_lim, sufficient_decrease_param, curvature_param): """Helper function for secant square.""" # Apply the `update` function on...
Helper function for secant - square step.
def _secant2_inner_update(value_and_gradients_function, initial_args, val_0, val_c, f_lim, sufficient_decrease_param, curvature_param): """Helper function for sec...
Squeezes a bracketing interval containing the minimum.
def update(value_and_gradients_function, val_left, val_right, val_trial, f_lim, active=None): """Squeezes a bracketing interval containing the minimum. Given an interval which brackets a minimum and a point in that interval, finds a smaller nested interval which also brackets the minimum. If the sup...
Brackets the minimum given an initial starting point.
def bracket(value_and_gradients_function, search_interval, f_lim, max_iterations, expansion_param=5.0): """Brackets the minimum given an initial starting point. Applies the Hager Zhang bracketing algorithm to find an interval containing a region with points satisfy...
Bisects an interval and updates to satisfy opposite slope conditions.
def bisect(value_and_gradients_function, initial_left, initial_right, f_lim): """Bisects an interval and updates to satisfy opposite slope conditions. Corresponds to the step U3 in [Hager and Zhang (2006)][2]. Args: value_and_gradients_function: A Python callable that accept...
Actual implementation of bisect given initial_args in a _BracketResult.
def _bisect(value_and_gradients_function, initial_args, f_lim): """Actual implementation of bisect given initial_args in a _BracketResult.""" def _loop_cond(curr): # TODO(b/112524024): Also take into account max_iterations. return ~tf.reduce_all(input_tensor=curr.stopped) def _loop_body(curr): """Nar...
Checks if the supplied values are finite.
def is_finite(val_1, val_2=None): """Checks if the supplied values are finite. Args: val_1: A namedtuple instance with the function value and derivative, as returned e.g. by value_and_gradients_function evaluations. val_2: (Optional) A namedtuple instance with the function value and derivative,...
Checks whether the Wolfe or approx Wolfe conditions are satisfied.
def _satisfies_wolfe(val_0, val_c, f_lim, sufficient_decrease_param, curvature_param): """Checks whether the Wolfe or approx Wolfe conditions are satisfied. The Wolfe conditions are a set of stopping criteria for an inexact line se...
Returns the secant interpolation for the minimum.
def _secant(val_a, val_b): """Returns the secant interpolation for the minimum. The secant method is a technique for finding roots of nonlinear functions. When finding the minimum, one applies the secant method to the derivative of the function. For an arbitrary function and a bounding interval, the secant a...
Create a function implementing a step - size update policy.
def make_simple_step_size_update_policy(num_adaptation_steps, target_rate=0.75, decrement_multiplier=0.01, increment_multiplier=0.01, step_counter=None): """C...
Applies num_leapfrog_steps of the leapfrog integrator.
def _leapfrog_integrator_one_step( target_log_prob_fn, independent_chain_ndims, step_sizes, current_momentum_parts, current_state_parts, current_target_log_prob, current_target_log_prob_grad_parts, state_gradients_are_stopped=False, name=None): """Applies `num_leapfrog_steps` of th...
Helper to kernel which computes the log acceptance - correction.
def _compute_log_acceptance_correction(current_momentums, proposed_momentums, independent_chain_ndims, name=None): """Helper to `kernel` which computes the log acceptance-correction. A sufficient bu...
Helper which processes input args to meet list - like assumptions.
def _prepare_args(target_log_prob_fn, state, step_size, target_log_prob=None, grads_target_log_prob=None, maybe_expand=False, state_gradients_are_stopped=False): """Helper which processes input args to meet lis...
Computes log ( sum ( x ** 2 )).
def _log_sum_sq(x, axis=None): """Computes log(sum(x**2)).""" return tf.reduce_logsumexp( input_tensor=2. * tf.math.log(tf.abs(x)), axis=axis)
Runs one iteration of Hamiltonian Monte Carlo.
def one_step(self, current_state, previous_kernel_results): """Runs one iteration of Hamiltonian Monte Carlo. 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.ra...
Creates initial previous_kernel_results using a supplied state.
def bootstrap_results(self, init_state): """Creates initial `previous_kernel_results` using a supplied `state`.""" kernel_results = self._impl.bootstrap_results(init_state) if self.step_size_update_fn is not None: step_size_assign = self.step_size_update_fn(self.step_size, None) # pylint: disable=not...
Constructs a ResNet18 model.
def bayesian_resnet(input_shape, num_classes=10, kernel_posterior_scale_mean=-9.0, kernel_posterior_scale_stddev=0.1, kernel_posterior_scale_constraint=0.2): """Constructs a ResNet18 model. Args: input_shape: A `tuple` indicating t...
Network block for ResNet.
def _resnet_block(x, filters, kernel, stride, kernel_posterior_fn): """Network block for ResNet.""" x = tf.keras.layers.BatchNormalization()(x) x = tf.keras.layers.Activation('relu')(x) if stride != 1 or filters != x.shape[1]: shortcut = _projection_shortcut(x, filters, stride, kernel_posterior_fn) else:...
Create the encoder function.
def make_encoder(activation, num_topics, layer_sizes): """Create the encoder function. 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: encoder: A `callable` mapping a bag-of-words `Tensor` ...
Create the decoder function.
def make_decoder(num_topics, num_words): """Create the decoder function. Args: num_topics: The number of topics. num_words: The number of words. Returns: decoder: A `callable` mapping a `Tensor` of encodings to a `tfd.Distribution` instance over words. """ topics_words_logits = tf.compat.v...
Create the prior distribution.
def make_prior(num_topics, initial_value): """Create the prior distribution. Args: num_topics: Number of topics. initial_value: The starting value for the prior parameters. Returns: prior: A `callable` that returns a `tf.distribution.Distribution` instance, the prior distribution. prior_...
Build the model function for use in an estimator.
def model_fn(features, labels, mode, params, config): """Build 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 dictionary...
Implements Markov chain Monte Carlo via repeated TransitionKernel steps.
def sample_chain( num_results, current_state, previous_kernel_results=None, kernel=None, num_burnin_steps=0, num_steps_between_results=0, trace_fn=lambda current_state, kernel_results: kernel_results, return_final_kernel_results=False, parallel_iterations=10, name=None, ): """I...
A multi - layered topic model over a documents - by - terms matrix.
def deep_exponential_family(data_size, feature_size, units, shape): """A multi-layered topic model over a documents-by-terms matrix.""" w2 = ed.Gamma(0.1, 0.3, sample_shape=[units[2], units[1]], name="w2") w1 = ed.Gamma(0.1, 0.3, sample_shape=[units[1], units[0]], name="w1") w0 = ed.Gamma(0.1, 0.3, sample_shape...
Learnable Deterministic distribution over positive reals.
def trainable_positive_deterministic(shape, min_loc=1e-3, name=None): """Learnable Deterministic distribution over positive reals.""" with tf.compat.v1.variable_scope( None, default_name="trainable_positive_deterministic"): unconstrained_loc = tf.compat.v1.get_variable("unconstrained_loc", shape) loc ...
Learnable Gamma via concentration and scale parameterization.
def trainable_gamma(shape, min_concentration=1e-3, min_scale=1e-5, name=None): """Learnable Gamma via concentration and scale parameterization.""" with tf.compat.v1.variable_scope(None, default_name="trainable_gamma"): unconstrained_concentration = tf.compat.v1.get_variable( "unconstrained_concentration...
Posterior approx. for deep exponential family p ( w { 0 1 2 } z { 1 2 3 } | x ).
def deep_exponential_family_variational(data_size, feature_size, units): """Posterior approx. for deep exponential family p(w{0,1,2}, z{1,2,3} | x).""" qw2 = trainable_positive_deterministic([units[2], units[1]], name="qw2") qw1 = trainable_positive_deterministic([units[1], units[0]], name="qw1") qw0 = trainabl...
Loads NIPS 2011 conference papers.
def load_nips2011_papers(path): """Loads NIPS 2011 conference papers. The NIPS 1987-2015 data set is in the form of a 11,463 x 5,812 matrix of per-paper word counts, containing 11,463 words and 5,811 NIPS conference papers (Perrone et al., 2016). We subset to papers in 2011 and words appearing in at least tw...
Shared init logic for amplitude and length_scale params.
def _init_params(self, amplitude, length_scale, validate_args): """Shared init logic for `amplitude` and `length_scale` params. Args: amplitude: `Tensor` (or convertible) or `None` to convert, validate. length_scale: `Tensor` (or convertible) or `None` to convert, validate. validate_args: If ...
Get the KL function registered for classes a and b.
def _registered_kl(type_a, type_b): """Get the KL function registered for classes a and b.""" hierarchy_a = tf_inspect.getmro(type_a) hierarchy_b = tf_inspect.getmro(type_b) dist_to_children = None kl_fn = None for mro_to_a, parent_a in enumerate(hierarchy_a): for mro_to_b, parent_b in enumerate(hierarc...
Get the KL - divergence KL ( distribution_a || distribution_b ).
def kl_divergence(distribution_a, distribution_b, allow_nan_stats=True, name=None): """Get the KL-divergence KL(distribution_a || distribution_b). If there is no KL method registered specifically for `type(distribution_a)` and `type(distribution_b)`, then the class hierarchies of these types ar...
Computes the ( Shannon ) cross entropy.
def cross_entropy(ref, other, allow_nan_stats=True, name=None): """Computes the (Shannon) cross entropy. Denote two distributions by `P` (`ref`) and `Q` (`other`). Assuming `P, Q` are absolutely continuous with respect to one another and permit densities `p(x) dr(x)` and `q(x) dr(x)`, (Shanon...
Returns an image tensor.
def read_image(filepath): """Returns an image tensor.""" im_bytes = tf.io.read_file(filepath) im = tf.image.decode_image(im_bytes, channels=CHANNELS) im = tf.image.convert_image_dtype(im, tf.float32) return im
Downloads the sprites data and returns the saved filepath.
def download_sprites(): """Downloads the sprites data and returns the saved filepath.""" filepath = os.path.join(FLAGS.data_dir, DATA_SPRITES_DIR) if not tf.io.gfile.exists(filepath): if not tf.io.gfile.exists(FLAGS.data_dir): tf.io.gfile.makedirs(FLAGS.data_dir) zip_name = "{}.zip".format(filepath)...
Creates a character sprite from a set of attribute sprites.
def create_character(skin, hair, top, pants): """Creates a character sprite from a set of attribute sprites.""" dtype = skin.dtype hair_mask = tf.cast(hair[..., -1:] <= 0, dtype) top_mask = tf.cast(top[..., -1:] <= 0, dtype) pants_mask = tf.cast(pants[..., -1:] <= 0, dtype) char = (skin * hair_mask) + hair ...
Creates a sequence.
def create_seq(character, action_metadata, direction, length=8, start=0): """Creates a sequence. Args: character: A character sprite tensor. action_metadata: An action metadata tuple. direction: An integer representing the direction, i.e., the row offset within each action group corresponding to ...
Creates a random sequence.
def create_random_seq(character, action_metadata, direction, length=8): """Creates a random sequence.""" start = tf.random.uniform([], maxval=action_metadata[1], dtype=tf.int32) return create_seq(character, action_metadata, direction, length, start)
Creates a tf. data pipeline for the sprites dataset.
def create_sprites_dataset(characters, actions, directions, channels=3, length=8, shuffle=False, fake_data=False): """Creates a tf.data pipeline for the sprites dataset. Args: characters: A list of (skin, hair, top, pants) tuples containing relative paths to the sprite png imag...
Checks that distributions satisfies all assumptions.
def _maybe_validate_distributions(distributions, dtype_override, validate_args): """Checks that `distributions` satisfies all assumptions.""" assertions = [] if not _is_iterable(distributions) or not distributions: raise ValueError('`distributions` must be a list of one or more ' 'distri...
Calculate the batched KL divergence KL ( b0 || b1 ) with b0 and b1 Blockwise distributions.
def _kl_blockwise_blockwise(b0, b1, name=None): """Calculate the batched KL divergence KL(b0 || b1) with b0 and b1 Blockwise distributions. Args: b0: instance of a Blockwise distribution object. b1: instance of a Blockwise distribution object. name: (optional) Name to use for created operations. Defaul...
Calculate the batched KL divergence KL ( a || b ) with a and b HalfNormal.
def _kl_half_normal_half_normal(a, b, name=None): """Calculate the batched KL divergence KL(a || b) with a and b `HalfNormal`. Args: a: Instance of a `HalfNormal` distribution object. b: Instance of a `HalfNormal` distribution object. name: (optional) Name to use for created operations. default i...
Flatten a list of kernels which may contain _SumKernel instances.
def _flatten_summand_list(kernels): """Flatten a list of kernels which may contain _SumKernel instances. Args: kernels: Python list of `PositiveSemidefiniteKernel` instances Returns: Python list containing the elements of kernels, with any _SumKernel instances replaced by their `kernels` property co...
Flatten a list of kernels which may contain _ProductKernel instances.
def _flatten_multiplicand_list(kernels): """Flatten a list of kernels which may contain _ProductKernel instances. Args: kernels: Python list of `PositiveSemidefiniteKernel` instances Returns: Python list containing the elements of kernels, with any _ProductKernel instances replaced by their `kernels...
Build an Iterator switching between train and heldout data.
def build_input_pipeline(x_train, x_test, y_train, y_test, batch_size, valid_size): """Build an Iterator switching between train and heldout data.""" x_train = x_train.astype("float32") x_test = x_test.astype("float32") x_train /= 255 x_test /= 255 y_train = y_train.flatten() y...
Build fake CIFAR10 - style data for unit testing.
def build_fake_data(): """Build fake CIFAR10-style data for unit testing.""" num_examples = 10 x_train = np.random.rand(num_examples, *IMAGE_SHAPE).astype(np.float32) y_train = np.random.permutation(np.arange(num_examples)).astype(np.int32) x_test = np.random.rand(num_examples, *IMAGE_SHAPE).astype(np.float32...
Counts the number of occurrences of each value in an integer array arr.
def count_integers(arr, weights=None, minlength=None, maxlength=None, axis=None, dtype=tf.int32, name=None): """Counts the number of occurrences of each value in an integer array `arr`. Works like `tf....
Bin values into discrete intervals.
def find_bins(x, edges, extend_lower_interval=False, extend_upper_interval=False, dtype=None, name=None): """Bin values into discrete intervals. Given `edges = [c0, ..., cK]`, defining intervals `I0 = [c0, c1)`, `I1 = [c1, c2)`, ..., `I_{K-1} ...
Count how often x falls in intervals defined by edges.
def histogram(x, edges, axis=None, extend_lower_interval=False, extend_upper_interval=False, dtype=None, name=None): """Count how often `x` falls in intervals defined by `edges`. Given `edges = [c0, ..., cK]`, defining intervals ...
Compute the q - th percentile ( s ) of x.
def percentile(x, q, axis=None, interpolation=None, keep_dims=False, validate_args=False, preserve_gradients=True, name=None): """Compute the `q`-th percentile(s) of `x`. Given a vector `x`, the `q`-th percenti...
Compute quantiles of x along axis.
def quantiles(x, num_quantiles, axis=None, interpolation=None, keep_dims=False, validate_args=False, name=None): """Compute quantiles of `x` along `axis`. The quantiles of a distribution are cut points dividing the range into int...
Get static number of dimensions and assert that some expectations are met.
def _get_static_ndims(x, expect_static=False, expect_ndims=None, expect_ndims_no_more_than=None, expect_ndims_at_least=None): """Get static number of dimensions and assert that some expectations are met. This function returns t...
Get static ndims if possible. Fallback on tf. rank ( x ).
def _get_best_effort_ndims(x, expect_ndims=None, expect_ndims_at_least=None, expect_ndims_no_more_than=None): """Get static ndims if possible. Fallback on `tf.rank(x)`.""" ndims_static = _get_static_ndims( x, expect_ndims=...
Insert the dims in axis back as singletons after being removed.
def _insert_back_keep_dims(x, axis): """Insert the dims in `axis` back as singletons after being removed. Args: x: `Tensor`. axis: Python list of integers. Returns: `Tensor` with same values as `x`, but additional singleton dimensions. """ for i in sorted(axis): x = tf.expand_dims(x, axis=...
Convert possibly negatively indexed axis to non - negative list of ints.
def _make_static_axis_non_negative_list(axis, ndims): """Convert possibly negatively indexed axis to non-negative list of ints. Args: axis: Integer Tensor. ndims: Number of dimensions into which axis indexes. Returns: A list of non-negative Python integers. Raises: ValueError: If `axis` is ...
Move dims corresponding to axis in x to the end then flatten.
def _move_dims_to_flat_end(x, axis, x_ndims, right_end=True): """Move dims corresponding to `axis` in `x` to the end, then flatten. Args: x: `Tensor` with shape `[B0,B1,...,Bb]`. axis: Python list of indices into dimensions of `x`. x_ndims: Python integer holding number of dimensions in `x`. righ...
Use top_k to sort a Tensor along the last dimension.
def _sort_tensor(tensor): """Use `top_k` to sort a `Tensor` along the last dimension.""" sorted_, _ = tf.nn.top_k(tensor, k=tf.shape(input=tensor)[-1]) sorted_.set_shape(tensor.shape) return sorted_
Build an ordered list of Distribution instances for component models.
def make_component_state_space_models(self, num_timesteps, param_vals, initial_step=0): """Build an ordered list of Distribution instances for component models. Args: num_timesteps: Pyt...
The Amari - alpha Csiszar - function in log - space.
def amari_alpha(logu, alpha=1., self_normalized=False, name=None): """The Amari-alpha 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 Amari-alpha Csiszar-function is: ```none f(u) = { -log(u) + (u - 1), ...
The reverse Kullback - Leibler Csiszar - function in log - space.
def kl_reverse(logu, self_normalized=False, name=None): """The reverse Kullback-Leibler 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 KL-reverse Csiszar-function is: ```none f(u) = -log(u) + (u - 1) `...
The Jensen - Shannon Csiszar - function in log - space.
def jensen_shannon(logu, self_normalized=False, name=None): """The Jensen-Shannon 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 Jensen-Shannon Csiszar-function is: ```none f(u) = u log(u) - (1 + u) log(...
The Pearson Csiszar - function in log - space.
def pearson(logu, name=None): """The Pearson Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` The Pearson Csiszar-function is: ```none f(u) = (u - 1)**2 ``` Warning: this function makes non-log-space calculations and may therefore be ...
The Squared - Hellinger Csiszar - function in log - space.
def squared_hellinger(logu, name=None): """The Squared-Hellinger Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` The Squared-Hellinger Csiszar-function is: ```none f(u) = (sqrt(u) - 1)**2 ``` This Csiszar-function induces a symmetric ...