_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q266700 | choose | test | def choose(is_accepted, accepted, rejected, name=None):
"""Helper which expand_dims `is_accepted` then applies tf.where."""
if not is_namedtuple_like(accepted):
return _choose_base_case(is_accepted, accepted, rejected, name=name)
if not isinstance(accepted, type(rejected)):
raise TypeError('Type of `accep... | python | {
"resource": ""
} |
q266701 | safe_sum | test | def safe_sum(x, alt_value=-np.inf, name=None):
"""Elementwise adds list members, replacing non-finite results with alt_value.
Typically the `alt_value` is chosen so the `MetropolisHastings`
`TransitionKernel` always rejects the proposal.
Args:
x: Python `list` of `Tensors` to elementwise add.
alt_valu... | python | {
"resource": ""
} |
q266702 | _value_and_gradients | test | 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... | python | {
"resource": ""
} |
q266703 | maybe_call_fn_and_grads | test | 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`... | python | {
"resource": ""
} |
q266704 | smart_for_loop | test | 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... | python | {
"resource": ""
} |
q266705 | trace_scan | test | 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... | python | {
"resource": ""
} |
q266706 | make_innermost_setter | test | 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... | python | {
"resource": ""
} |
q266707 | make_innermost_getter | test | 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... | python | {
"resource": ""
} |
q266708 | enable_store_parameters_in_results | test | 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... | python | {
"resource": ""
} |
q266709 | _replace_event_shape_in_shape_tensor | test | 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 `... | python | {
"resource": ""
} |
q266710 | _replace_event_shape_in_tensorshape | test | 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... | python | {
"resource": ""
} |
q266711 | _maybe_check_valid_shape | test | 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... | python | {
"resource": ""
} |
q266712 | converged_any | test | 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)) | python | {
"resource": ""
} |
q266713 | get_initial_state_args | test | 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 ... | python | {
"resource": ""
} |
q266714 | line_search_step | test | 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... | python | {
"resource": ""
} |
q266715 | _restrict_along_direction | test | 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... | python | {
"resource": ""
} |
q266716 | _update_position | test | 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... | python | {
"resource": ""
} |
q266717 | _check_convergence | test | def _check_convergence(current_position,
next_position,
current_objective,
next_objective,
next_gradient,
grad_tolerance,
f_relative_tolerance,
x_tolerance):
... | python | {
"resource": ""
} |
q266718 | _broadcast | test | 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... | python | {
"resource": ""
} |
q266719 | _harmonic_number | test | 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.
... | python | {
"resource": ""
} |
q266720 | default_exchange_proposed_fn | test | 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... | python | {
"resource": ""
} |
q266721 | _get_field | test | 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... | python | {
"resource": ""
} |
q266722 | ReplicaExchangeMC._get_exchanged_states | test | 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'):
... | python | {
"resource": ""
} |
q266723 | DirichletMultinomial._variance_scale_term | test | 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_... | python | {
"resource": ""
} |
q266724 | forward_log_det_jacobian_fn | test | 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)
... | python | {
"resource": ""
} |
q266725 | forward_transform_fn | test | 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 | python | {
"resource": ""
} |
q266726 | inverse_transform_fn | test | 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 | python | {
"resource": ""
} |
q266727 | TransformedTransitionKernel.one_step | test | 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`
... | python | {
"resource": ""
} |
q266728 | val_where | test | 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) | python | {
"resource": ""
} |
q266729 | secant2 | test | 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... | python | {
"resource": ""
} |
q266730 | _secant2_inner | test | 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... | python | {
"resource": ""
} |
q266731 | _secant2_inner_update | test | 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... | python | {
"resource": ""
} |
q266732 | update | test | 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... | python | {
"resource": ""
} |
q266733 | bracket | test | 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... | python | {
"resource": ""
} |
q266734 | bisect | test | 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... | python | {
"resource": ""
} |
q266735 | _bisect | test | 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... | python | {
"resource": ""
} |
q266736 | is_finite | test | 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,... | python | {
"resource": ""
} |
q266737 | _satisfies_wolfe | test | 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... | python | {
"resource": ""
} |
q266738 | _secant | test | 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... | python | {
"resource": ""
} |
q266739 | make_simple_step_size_update_policy | test | 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... | python | {
"resource": ""
} |
q266740 | _leapfrog_integrator_one_step | test | 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... | python | {
"resource": ""
} |
q266741 | _compute_log_acceptance_correction | test | 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... | python | {
"resource": ""
} |
q266742 | HamiltonianMonteCarlo.one_step | test | 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... | python | {
"resource": ""
} |
q266743 | HamiltonianMonteCarlo.bootstrap_results | test | 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... | python | {
"resource": ""
} |
q266744 | bayesian_resnet | test | 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... | python | {
"resource": ""
} |
q266745 | _resnet_block | test | 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:... | python | {
"resource": ""
} |
q266746 | make_encoder | test | 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` ... | python | {
"resource": ""
} |
q266747 | make_decoder | test | 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... | python | {
"resource": ""
} |
q266748 | make_prior | test | 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_... | python | {
"resource": ""
} |
q266749 | sample_chain | test | 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... | python | {
"resource": ""
} |
q266750 | deep_exponential_family | test | 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... | python | {
"resource": ""
} |
q266751 | trainable_positive_deterministic | test | 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 ... | python | {
"resource": ""
} |
q266752 | trainable_gamma | test | 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... | python | {
"resource": ""
} |
q266753 | load_nips2011_papers | test | 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... | python | {
"resource": ""
} |
q266754 | _AmplitudeLengthScaleMixin._init_params | test | 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 ... | python | {
"resource": ""
} |
q266755 | _registered_kl | test | 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... | python | {
"resource": ""
} |
q266756 | read_image | test | 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 | python | {
"resource": ""
} |
q266757 | download_sprites | test | 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)... | python | {
"resource": ""
} |
q266758 | create_character | test | 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
... | python | {
"resource": ""
} |
q266759 | create_seq | test | 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 ... | python | {
"resource": ""
} |
q266760 | create_random_seq | test | 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) | python | {
"resource": ""
} |
q266761 | create_sprites_dataset | test | 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... | python | {
"resource": ""
} |
q266762 | _maybe_validate_distributions | test | 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... | python | {
"resource": ""
} |
q266763 | _flatten_summand_list | test | 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... | python | {
"resource": ""
} |
q266764 | _flatten_multiplicand_list | test | 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... | python | {
"resource": ""
} |
q266765 | build_fake_data | test | 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... | python | {
"resource": ""
} |
q266766 | count_integers | test | 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.... | python | {
"resource": ""
} |
q266767 | find_bins | test | 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} ... | python | {
"resource": ""
} |
q266768 | histogram | test | 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
... | python | {
"resource": ""
} |
q266769 | quantiles | test | 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... | python | {
"resource": ""
} |
q266770 | _get_static_ndims | test | 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... | python | {
"resource": ""
} |
q266771 | _insert_back_keep_dims | test | 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=... | python | {
"resource": ""
} |
q266772 | _make_static_axis_non_negative_list | test | 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 ... | python | {
"resource": ""
} |
q266773 | _move_dims_to_flat_end | test | 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... | python | {
"resource": ""
} |
q266774 | _sort_tensor | test | 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_ | python | {
"resource": ""
} |
q266775 | Sum.make_component_state_space_models | test | 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... | python | {
"resource": ""
} |
q266776 | amari_alpha | test | 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), ... | python | {
"resource": ""
} |
q266777 | kl_reverse | test | 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)
`... | python | {
"resource": ""
} |
q266778 | jensen_shannon | test | 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(... | python | {
"resource": ""
} |
q266779 | pearson | test | 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
... | python | {
"resource": ""
} |
q266780 | squared_hellinger | test | 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 ... | python | {
"resource": ""
} |
q266781 | triangular | test | 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... | python | {
"resource": ""
} |
q266782 | t_power | test | 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 <... | python | {
"resource": ""
} |
q266783 | log1p_abs | test | 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... | python | {
"resource": ""
} |
q266784 | jeffreys | test | 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... | python | {
"resource": ""
} |
q266785 | modified_gan | test | 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(... | python | {
"resource": ""
} |
q266786 | dual_csiszar_function | test | 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... | python | {
"resource": ""
} |
q266787 | symmetrized_csiszar_function | test | 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... | python | {
"resource": ""
} |
q266788 | monte_carlo_csiszar_f_divergence | test | 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... | python | {
"resource": ""
} |
q266789 | csiszar_vimco_helper | test | 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... | python | {
"resource": ""
} |
q266790 | _assert_ndims_statically | test | 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:
... | python | {
"resource": ""
} |
q266791 | _batch_gather_with_broadcast | test | 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... | python | {
"resource": ""
} |
q266792 | _broadcast_cat_event_and_params | test | 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... | python | {
"resource": ""
} |
q266793 | expectation_importance_sampler_logspace | test | 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... | python | {
"resource": ""
} |
q266794 | _broadcast_event_and_samples | test | 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... | python | {
"resource": ""
} |
q266795 | minimize | test | 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=... | python | {
"resource": ""
} |
q266796 | _inv_hessian_control_inputs | test | 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... | python | {
"resource": ""
} |
q266797 | _update_inv_hessian | test | 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... | python | {
"resource": ""
} |
q266798 | _bfgs_inv_hessian_update | test | 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... | python | {
"resource": ""
} |
q266799 | _mul_right | test | 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_... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.