INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Helper to validate block sizes. | def _validate_block_sizes(block_sizes, bijectors, validate_args):
"""Helper to validate block sizes."""
block_sizes_shape = block_sizes.shape
if tensorshape_util.is_fully_defined(block_sizes_shape):
if (tensorshape_util.rank(block_sizes_shape) != 1 or
(tensorshape_util.num_elements(block_sizes_shape) ... |
Verifies that parts don t broadcast. | def maybe_check_wont_broadcast(flat_xs, validate_args):
"""Verifies that `parts` don't broadcast."""
flat_xs = tuple(flat_xs) # So we can receive generators.
if not validate_args:
# Note: we don't try static validation because it is theoretically
# possible that a user wants to take advantage of broadcas... |
Converts ( batch of ) scalars to ( batch of ) positive valued scalars. | def softplus_and_shift(x, shift=1e-5, name=None):
"""Converts (batch of) scalars to (batch of) positive valued scalars.
Args:
x: (Batch of) `float`-like `Tensor` representing scalars which will be
transformed into positive elements.
shift: `Tensor` added to `softplus` transformation of elements.
... |
Converts ( batch of ) vectors to ( batch of ) lower - triangular scale matrices. | def tril_with_diag_softplus_and_shift(x, diag_shift=1e-5, name=None):
"""Converts (batch of) vectors to (batch of) lower-triangular scale matrices.
Args:
x: (Batch of) `float`-like `Tensor` representing vectors which will be
transformed into lower-triangular scale matrices with positive diagonal
el... |
Constructs a trainable tfd. MultivariateNormalTriL distribution. | def multivariate_normal_tril(x,
dims,
layer_fn=tf.compat.v1.layers.dense,
loc_fn=lambda x: x,
scale_fn=tril_with_diag_softplus_and_shift,
name=None):
"""Constructs a trainab... |
Constructs a trainable tfd. Bernoulli distribution. | def bernoulli(x, layer_fn=tf.compat.v1.layers.dense, name=None):
"""Constructs a trainable `tfd.Bernoulli` distribution.
This function creates a Bernoulli distribution parameterized by logits.
Using default args, this function is mathematically equivalent to:
```none
Y = Bernoulli(logits=matmul(W, x) + b)
... |
Constructs a trainable tfd. Normal distribution. | def normal(x,
layer_fn=tf.compat.v1.layers.dense,
loc_fn=lambda x: x,
scale_fn=1.,
name=None):
"""Constructs a trainable `tfd.Normal` distribution.
This function creates a Normal distribution parameterized by loc and scale.
Using default args, this function is mathema... |
Constructs a trainable tfd. Poisson distribution. | def poisson(x,
layer_fn=tf.compat.v1.layers.dense,
log_rate_fn=lambda x: x,
name=None):
"""Constructs a trainable `tfd.Poisson` distribution.
This function creates a Poisson distribution parameterized by log rate.
Using default args, this function is mathematically equivalent ... |
r Finds root ( s ) of a function of single variable using the secant method. | def secant_root(objective_fn,
initial_position,
next_position=None,
value_at_position=None,
position_tolerance=1e-8,
value_tolerance=1e-8,
max_iterations=50,
stopping_policy_fn=tf.reduce_all,
... |
Applies one step of Euler - Maruyama method. | def _euler_method(random_draw_parts,
state_parts,
drift_parts,
step_size_parts,
volatility_parts,
name=None):
"""Applies one step of Euler-Maruyama method.
Generates proposal of the form:
```python
tfd.Normal(loc=state_p... |
Compute diffusion drift at the current location current_state. | def _get_drift(step_size_parts, volatility_parts, grads_volatility,
grads_target_log_prob,
name=None):
"""Compute diffusion drift at the current location `current_state`.
The drift of the diffusion at is computed as
```none
0.5 * `step_size` * volatility_parts * `target_log_prob_... |
r Helper to kernel which computes the log acceptance - correction. | def _compute_log_acceptance_correction(current_state_parts,
proposed_state_parts,
current_volatility_parts,
proposed_volatility_parts,
current_drift_parts,
... |
Helper which computes volatility_fn results and grads if needed. | def _maybe_call_volatility_fn_and_grads(volatility_fn,
state,
volatility_fn_results=None,
grads_volatility_fn=None,
sample_shape=None,
... |
Helper to broadcast volatility_parts to the shape of state_parts. | def _maybe_broadcast_volatility(volatility_parts,
state_parts):
"""Helper to broadcast `volatility_parts` to the shape of `state_parts`."""
return [v + tf.zeros_like(sp, dtype=sp.dtype.base_dtype)
for v, sp in zip(volatility_parts, state_parts)] |
Helper which processes input args to meet list - like assumptions. | def _prepare_args(target_log_prob_fn,
volatility_fn,
state,
step_size,
target_log_prob=None,
grads_target_log_prob=None,
volatility=None,
grads_volatility_fn=None,
diffusion_dr... |
Build transition matrix for an autoregressive StateSpaceModel. | def make_ar_transition_matrix(coefficients):
"""Build transition matrix for an autoregressive StateSpaceModel.
When applied to a vector of previous values, this matrix computes
the expected new value (summing the previous states according to the
autoregressive coefficients) in the top dimension of the state sp... |
Computes diagonal of the Jacobian matrix of ys = fn ( xs ) wrt xs. | def diag_jacobian(xs,
ys=None,
sample_shape=None,
fn=None,
parallel_iterations=10,
name=None):
"""Computes diagonal of the Jacobian matrix of `ys=fn(xs)` wrt `xs`.
If `ys` is a tensor or a list of tensors of the form `(ys_1... |
Calculates the reshaped dimensions ( replacing up to one - 1 in reshape ). | def calculate_reshape(original_shape, new_shape, validate=False, name=None):
"""Calculates the reshaped dimensions (replacing up to one -1 in reshape)."""
batch_shape_static = tensorshape_util.constant_value_as_shape(new_shape)
if tensorshape_util.is_fully_defined(batch_shape_static):
return np.int32(batch_sh... |
Helper to __init__ which makes or raises assertions. | def validate_init_args_statically(distribution, batch_shape):
"""Helper to __init__ which makes or raises assertions."""
if tensorshape_util.rank(batch_shape.shape) is not None:
if tensorshape_util.rank(batch_shape.shape) != 1:
raise ValueError("`batch_shape` must be a vector "
"(sa... |
Computes graph and static sample_shape. | def _sample_shape(self, x):
"""Computes graph and static `sample_shape`."""
x_ndims = (
tf.rank(x) if tensorshape_util.rank(x.shape) is None else
tensorshape_util.rank(x.shape))
event_ndims = (
tf.size(input=self.event_shape_tensor())
if tensorshape_util.rank(self.event_shape... |
Calls fn appropriately reshaping its input x and output. | def _call_reshape_input_output(self, fn, x, extra_kwargs=None):
"""Calls `fn`, appropriately reshaping its input `x` and output."""
# Note: we take `extra_kwargs` as a dict rather than `**extra_kwargs`
# because it is possible the user provided extra kwargs would itself
# have `fn` and/or `x` as a key.
... |
Calls fn and appropriately reshapes its output. | def _call_and_reshape_output(
self,
fn,
event_shape_list=None,
static_event_shape_list=None,
extra_kwargs=None):
"""Calls `fn` and appropriately reshapes its output."""
# Note: we take `extra_kwargs` as a dict rather than `**extra_kwargs`
# because it is possible the user provi... |
Helper which validates sample arg e. g. input to log_prob. | def _validate_sample_arg(self, x):
"""Helper which validates sample arg, e.g., input to `log_prob`."""
with tf.name_scope("validate_sample_arg"):
x_ndims = (
tf.rank(x) if tensorshape_util.rank(x.shape) is None else
tensorshape_util.rank(x.shape))
event_ndims = (
tf.siz... |
The binomial cumulative distribution function. | def _bdtr(k, n, p):
"""The binomial cumulative distribution function.
Args:
k: floating point `Tensor`.
n: floating point `Tensor`.
p: floating point `Tensor`.
Returns:
`sum_{j=0}^k p^j (1 - p)^(n - j)`.
"""
# Trick for getting safe backprop/gradients into n, k when
# betainc(a = 0, ..) ... |
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... |
Executes model creating both samples and distributions. | def _flat_sample_distributions(self, sample_shape=(), seed=None, value=None):
"""Executes `model`, creating both samples and distributions."""
ds = []
values_out = []
seed = seed_stream.SeedStream('JointDistributionCoroutine', seed)
gen = self._model()
index = 0
d = next(gen)
try:
... |
Calculate the batched KL divergence KL ( a || b ) with a and b Pareto. | def _kl_pareto_pareto(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a and b Pareto.
Args:
a: instance of a Pareto distribution object.
b: instance of a Pareto distribution object.
name: (optional) Name to use for created operations.
default is "kl_pareto_pareto".
Ret... |
Returns f ( x ) if x is in the support and alt otherwise. | def _extend_support(self, x, f, alt):
"""Returns `f(x)` if x is in the support, and `alt` otherwise.
Given `f` which is defined on the support of this distribution
(e.g. x > scale), extend the function definition to the real line
by defining `f(x) = alt` for `x < scale`.
Args:
x: Floating-po... |
Latent Dirichlet Allocation in terms of its generative process. | def latent_dirichlet_allocation(concentration, topics_words):
"""Latent Dirichlet Allocation in terms of its generative process.
The model posits a distribution over bags of words and is parameterized by
a concentration and the topic-word probabilities. It collapses per-word
topic assignments.
Args:
con... |
Creates the variational distribution for LDA. | def make_lda_variational(activation, num_topics, layer_sizes):
"""Creates the variational distribution for LDA.
Args:
activation: Activation function to use.
num_topics: The number of topics.
layer_sizes: The number of hidden units per layer in the encoder.
Returns:
lda_variational: A function t... |
Builds the model function for use in an Estimator. | def model_fn(features, labels, mode, params, config):
"""Builds the model function for use in an Estimator.
Arguments:
features: The input features for the Estimator.
labels: The labels, unused here.
mode: Signifies whether it is train or test or predict.
params: Some hyperparameters as a dictionar... |
Returns the summary of the learned topics. | def get_topics_strings(topics_words, alpha, vocabulary,
topics_to_print=10, words_per_topic=10):
"""Returns the summary of the learned topics.
Arguments:
topics_words: KxV tensor with topics as rows and words as columns.
alpha: 1xK tensor of prior Dirichlet concentrations for the
... |
20 newsgroups as a tf. data. Dataset. | def newsgroups_dataset(directory, split_name, num_words, shuffle_and_repeat):
"""20 newsgroups as a tf.data.Dataset."""
data = np.load(download(directory, FILE_TEMPLATE.format(split=split_name)))
# The last row is empty in both train and test.
data = data[:-1]
# Each row is a list of word ids in the document... |
Builds fake data for unit testing. | def build_fake_input_fns(batch_size):
"""Builds fake data for unit testing."""
num_words = 1000
vocabulary = [str(i) for i in range(num_words)]
random_sample = np.random.randint(
10, size=(batch_size, num_words)).astype(np.float32)
def train_input_fn():
dataset = tf.data.Dataset.from_tensor_slices... |
Builds iterators for train and evaluation data. | def build_input_fns(data_dir, batch_size):
"""Builds iterators for train and evaluation data.
Each object is represented as a bag-of-words vector.
Arguments:
data_dir: Folder in which to store the data.
batch_size: Batch size for both train and evaluation.
Returns:
train_input_fn: A function that... |
Calculate the batched KL divergence KL ( a || b ) with a and b Chi. | def _kl_chi_chi(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a and b Chi.
Args:
a: instance of a Chi distribution object.
b: instance of a Chi distribution object.
name: (optional) Name to use for created operations.
default is "kl_chi_chi".
Returns:
Batchwise K... |
Returns a ( dense ) column of a Tensor or SparseTensor. | def _sparse_or_dense_matmul_onehot(sparse_or_dense_matrix, col_index):
"""Returns a (dense) column of a Tensor or SparseTensor.
Args:
sparse_or_dense_matrix: matrix-shaped, `float` `Tensor` or `SparseTensor`.
col_index: scalar, `int` `Tensor` representing the index of the desired
column.
Returns:
... |
One step of ( the outer loop of ) the minimization algorithm. | def minimize_one_step(gradient_unregularized_loss,
hessian_unregularized_loss_outer,
hessian_unregularized_loss_middle,
x_start,
tolerance,
l1_regularizer,
l2_regularizer=None,
... |
Minimize using Hessian - informed proximal gradient descent. | def minimize(grad_and_hessian_loss_fn,
x_start,
tolerance,
l1_regularizer,
l2_regularizer=None,
maximum_iterations=1,
maximum_full_sweeps_per_iteration=1,
learning_rate=None,
name=None):
"""Minimize using Hessian-i... |
Creates the encoder function. | def make_encoder(base_depth, activation, latent_size, code_size):
"""Creates the encoder function.
Args:
base_depth: Layer base depth in encoder net.
activation: Activation function in hidden layers.
latent_size: The number of latent variables in the code.
code_size: The dimensionality of each late... |
Creates the decoder function. | def make_decoder(base_depth, activation, input_size, output_shape):
"""Creates the decoder function.
Args:
base_depth: Layer base depth in decoder net.
activation: Activation function in hidden layers.
input_size: The flattened latent input shape as an int.
output_shape: The output image shape as a... |
Add control dependencies to the commmitment loss to update the codebook. | def add_ema_control_dependencies(vector_quantizer,
one_hot_assignments,
codes,
commitment_loss,
decay):
"""Add control dependencies to the commmitment loss to update the codebook.
Arg... |
Helper method to save a grid of images to a PNG file. | def save_imgs(x, fname):
"""Helper method to save a grid of images to a PNG file.
Args:
x: A numpy array of shape [n_images, height, width].
fname: The filename to write to (including extension).
"""
n = x.shape[0]
fig = figure.Figure(figsize=(n, 1), frameon=False)
canvas = backend_agg.FigureCanvas... |
Helper method to save images visualizing model reconstructions. | def visualize_training(images_val,
reconstructed_images_val,
random_images_val,
log_dir, prefix, viz_n=10):
"""Helper method to save images visualizing model reconstructions.
Args:
images_val: Numpy array containing a batch of input images.
... |
Returns Hugo Larochelle s binary static MNIST tf. data. Dataset. | def load_bernoulli_mnist_dataset(directory, split_name):
"""Returns Hugo Larochelle's binary static MNIST tf.data.Dataset."""
amat_file = download(directory, FILE_TEMPLATE.format(split=split_name))
dataset = tf.data.TextLineDataset(amat_file)
str_to_arr = lambda string: np.array([c == b"1" for c in string.split... |
Builds an Iterator switching between train and heldout data. | def build_input_pipeline(data_dir, batch_size, heldout_size, mnist_type):
"""Builds an Iterator switching between train and heldout data."""
# Build an iterator over training batches.
if mnist_type in [MnistType.FAKE_DATA, MnistType.THRESHOLD]:
if mnist_type == MnistType.FAKE_DATA:
mnist_data = build_fa... |
Returns a np. dtype based on this dtype. | def as_numpy_dtype(dtype):
"""Returns a `np.dtype` based on this `dtype`."""
dtype = tf.as_dtype(dtype)
if hasattr(dtype, 'as_numpy_dtype'):
return dtype.as_numpy_dtype
return dtype |
Returns a non - reference dtype based on this dtype. | def base_dtype(dtype):
"""Returns a non-reference `dtype` based on this `dtype`."""
dtype = tf.as_dtype(dtype)
if hasattr(dtype, 'base_dtype'):
return dtype.base_dtype
return dtype |
Returns whether this is a boolean data type. | def is_bool(dtype):
"""Returns whether this is a boolean data type."""
dtype = tf.as_dtype(dtype)
if hasattr(dtype, 'is_bool'):
return dtype.is_bool
# We use `kind` because:
# np.issubdtype(np.uint8, np.bool) == True.
return np.dtype(dtype).kind == 'b' |
Returns whether this is a complex floating point type. | def is_complex(dtype):
"""Returns whether this is a complex floating point type."""
dtype = tf.as_dtype(dtype)
if hasattr(dtype, 'is_complex'):
return dtype.is_complex
return np.issubdtype(np.dtype(dtype), np.complex) |
Returns whether this is a ( non - quantized real ) floating point type. | def is_floating(dtype):
"""Returns whether this is a (non-quantized, real) floating point type."""
dtype = tf.as_dtype(dtype)
if hasattr(dtype, 'is_floating'):
return dtype.is_floating
return np.issubdtype(np.dtype(dtype), np.float) |
Returns whether this is a ( non - quantized ) integer type. | def is_integer(dtype):
"""Returns whether this is a (non-quantized) integer type."""
dtype = tf.as_dtype(dtype)
if hasattr(dtype, 'is_integer'):
return dtype.is_integer
return np.issubdtype(np.dtype(dtype), np.integer) |
Returns the maximum representable value in this data type. | def max(dtype): # pylint: disable=redefined-builtin
"""Returns the maximum representable value in this data type."""
dtype = tf.as_dtype(dtype)
if hasattr(dtype, 'max'):
return dtype.max
use_finfo = is_floating(dtype) or is_complex(dtype)
return np.finfo(dtype).max if use_finfo else np.iinfo(dtype).max |
Returns the string name for this dtype. | def name(dtype):
"""Returns the string name for this `dtype`."""
dtype = tf.as_dtype(dtype)
if hasattr(dtype, 'name'):
return dtype.name
if hasattr(dtype, '__name__'):
return dtype.__name__
return str(dtype) |
Returns the number of bytes to represent this dtype. | def size(dtype):
"""Returns the number of bytes to represent this `dtype`."""
dtype = tf.as_dtype(dtype)
if hasattr(dtype, 'size'):
return dtype.size
return np.dtype(dtype).itemsize |
r Asserts all items are of the same base type. | def _assert_same_base_type(items, expected_type=None):
r"""Asserts all items are of the same base type.
Args:
items: List of graph items (e.g., `Variable`, `Tensor`, `SparseTensor`,
`Operation`, or `IndexedSlices`). Can include `None` elements, which
will be ignored.
expected_type: Expected... |
Validate and return float type based on tensors and dtype. | def assert_same_float_dtype(tensors=None, dtype=None):
"""Validate and return float type based on `tensors` and `dtype`.
For ops such as matrix multiplication, inputs and weights must be of the
same float type. This function validates that all `tensors` are the same type,
validates that type is `dtype` (if sup... |
Calculate the batched KL divergence KL ( a || b ) with a b OneHotCategorical. | def _kl_categorical_categorical(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a, b OneHotCategorical.
Args:
a: instance of a OneHotCategorical distribution object.
b: instance of a OneHotCategorical distribution object.
name: (optional) Name to use for created operations.
... |
Minimum of the objective function using the Nelder Mead simplex algorithm. | def minimize(objective_function,
initial_simplex=None,
initial_vertex=None,
step_sizes=None,
objective_at_initial_simplex=None,
objective_at_initial_vertex=None,
batch_evaluate_objective=False,
func_tolerance=1e-8,
p... |
A single iteration of the Nelder Mead algorithm. | def nelder_mead_one_step(current_simplex,
current_objective_values,
objective_function=None,
dim=None,
func_tolerance=None,
position_tolerance=None,
batch_evaluate_object... |
Creates the condition function pair for a reflection to be accepted. | def _accept_reflected_fn(simplex,
objective_values,
worst_index,
reflected,
objective_at_reflected):
"""Creates the condition function pair for a reflection to be accepted."""
def _replace_worst_with_reflected():
... |
Creates the condition function pair for an expansion. | def _expansion_fn(objective_function,
simplex,
objective_values,
worst_index,
reflected,
objective_at_reflected,
face_centroid,
expansion):
"""Creates the condition function pair for an expans... |
Creates the condition function pair for an outside contraction. | def _outside_contraction_fn(objective_function,
simplex,
objective_values,
face_centroid,
best_index,
worst_index,
reflected,
... |
Shrinks the simplex around the best vertex. | def _shrink_towards_best(objective_function,
simplex,
best_index,
shrinkage,
batch_evaluate_objective):
"""Shrinks the simplex around the best vertex."""
# If the contraction step fails to improve the average object... |
Replaces an element at supplied index. | def _replace_at_index(x, index, replacement):
"""Replaces an element at supplied index."""
x_new = tf.concat([x[:index], tf.expand_dims(replacement, axis=0),
x[(index + 1):]], axis=0)
return x_new |
Returns True if the simplex has converged. | def _check_convergence(simplex,
best_vertex,
best_objective,
worst_objective,
func_tolerance,
position_tolerance):
"""Returns True if the simplex has converged.
If the simplex size is smaller than the... |
Computes the initial simplex and the objective values at the simplex. | def _prepare_args(objective_function,
initial_simplex,
initial_vertex,
step_sizes,
objective_at_initial_simplex,
objective_at_initial_vertex,
batch_evaluate_objective):
"""Computes the initial simplex and the o... |
Chooses default step sizes according to [ Gao and Han ( 2010 ) ] [ 3 ]. | def _default_step_sizes(reference_vertex):
"""Chooses default step sizes according to [Gao and Han(2010)][3]."""
# Step size to choose when the coordinate is zero.
small_sizes = tf.ones_like(reference_vertex) * 0.00025
# Step size to choose when the coordinate is non-zero.
large_sizes = reference_vertex * 0.0... |
Evaluates the objective function at the specified initial simplex. | def _prepare_args_with_initial_simplex(objective_function,
initial_simplex,
objective_at_initial_simplex,
batch_evaluate_objective):
"""Evaluates the objective function at the specified initial simplex... |
Constructs a standard axes aligned simplex. | def _prepare_args_with_initial_vertex(objective_function,
initial_vertex,
step_sizes,
objective_at_initial_vertex,
batch_evaluate_objective):
"""Constructs a standard... |
Applies the [ Gao and Han ] [ 3 ] presciption to the unspecified parameters. | def _resolve_parameters(dim,
reflection,
expansion,
contraction,
shrinkage,
dtype):
"""Applies the [Gao and Han][3] presciption to the unspecified parameters."""
dim = tf.cast(dim, dtype=dtype)
... |
Evaluates the objective function on a batch of points. | def _evaluate_objective_multiple(objective_function, arg_batch,
batch_evaluate_objective):
"""Evaluates the objective function on a batch of points.
If `batch_evaluate_objective` is True, returns
`objective function(arg_batch)` else it maps the `objective_function`
across the `... |
Save a PNG plot with histograms of weight means and stddevs. | def plot_weight_posteriors(names, qm_vals, qs_vals, fname):
"""Save a PNG plot with histograms of weight means and stddevs.
Args:
names: A Python `iterable` of `str` variable names.
qm_vals: A Python `iterable`, the same length as `names`,
whose elements are Numpy `array`s, of any shape, containing
... |
Save a PNG plot visualizing posterior uncertainty on heldout data. | def plot_heldout_prediction(input_vals, probs,
fname, n=10, title=""):
"""Save a PNG plot visualizing posterior uncertainty on heldout data.
Args:
input_vals: A `float`-like Numpy `array` of shape
`[num_heldout] + IMAGE_SHAPE`, containing heldout input images.
probs: A `fl... |
Build an Iterator switching between train and heldout data. | def build_input_pipeline(mnist_data, batch_size, heldout_size):
"""Build an Iterator switching between train and heldout data."""
# Build an iterator over training batches.
training_dataset = tf.data.Dataset.from_tensor_slices(
(mnist_data.train.images, np.int32(mnist_data.train.labels)))
training_batche... |
Build fake MNIST - style data for unit testing. | def build_fake_data(num_examples=10):
"""Build fake MNIST-style data for unit testing."""
class Dummy(object):
pass
num_examples = 10
mnist_data = Dummy()
mnist_data.train = Dummy()
mnist_data.train.images = np.float32(np.random.randn(
num_examples, *IMAGE_SHAPE))
mnist_data.train.labels = np.... |
Calculate the batched KL divergence KL ( a || b ) with a and b Bernoulli. | def _kl_bernoulli_bernoulli(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a and b Bernoulli.
Args:
a: instance of a Bernoulli distribution object.
b: instance of a Bernoulli distribution object.
name: (optional) Name to use for created operations.
default is "kl_bernoul... |
Returns initializer configuration as a JSON - serializable dict. | def get_config(self):
"""Returns initializer configuration as a JSON-serializable dict."""
return {
'initializers': [
tf.compat.v2.initializers.serialize(
tf.keras.initializers.get(init))
for init in self.initializers
],
'sizes': self.sizes,
... |
Instantiates an initializer from a configuration dictionary. | def from_config(cls, config):
"""Instantiates an initializer from a configuration dictionary."""
return cls(**{
'initializers': [tf.compat.v2.initializers.deserialize(init)
for init in config.get('initializers', [])],
'sizes': config.get('sizes', []),
'validate_a... |
Numpy matmul wrapper. | def _matmul(a, b,
transpose_a=False, transpose_b=False,
adjoint_a=False, adjoint_b=False,
a_is_sparse=False, b_is_sparse=False,
name=None): # pylint: disable=unused-argument
"""Numpy matmul wrapper."""
if a_is_sparse or b_is_sparse:
raise NotImplementedError('Num... |
Helper to compute stddev covariance and variance. | def _std_var_helper(self, statistic, statistic_name, statistic_ndims,
df_factor_fn):
"""Helper to compute stddev, covariance and variance."""
df = tf.reshape(
self.df,
tf.concat([
tf.shape(input=self.df),
tf.ones([statistic_ndims], dtype=tf.int32)
... |
Compute exponentially weighted moving { mean variance } of a streaming value. | def assign_moving_mean_variance(
mean_var, variance_var, value, decay, name=None):
"""Compute exponentially weighted moving {mean,variance} of a streaming value.
The `value` updated exponentially weighted moving `mean_var` and
`variance_var` are given by the following recurrence relations:
```python
var... |
Compute the log of the exponentially weighted moving mean of the exp. | def assign_log_moving_mean_exp(
log_mean_exp_var, log_value, decay, name=None):
"""Compute the log of the exponentially weighted moving mean of the exp.
If `log_value` is a draw from a stationary random variable, this function
approximates `log(E[exp(log_value)])`, i.e., a weighted log-sum-exp. More
precis... |
Compute exponentially weighted moving { mean variance } of a streaming value. | def moving_mean_variance(value, decay, name=None):
"""Compute exponentially weighted moving {mean,variance} of a streaming value.
The exponentially-weighting moving `mean_var` and `variance_var` are updated
by `value` according to the following recurrence:
```python
variance_var = decay * (variance_var + (1... |
Ensures non - scalar input has at least one column. | def _make_columnar(self, x):
"""Ensures non-scalar input has at least one column.
Example:
If `x = [1, 2, 3]` then the output is `[[1], [2], [3]]`.
If `x = [[1, 2, 3], [4, 5, 6]]` then the output is unchanged.
If `x = 1` then the output is unchanged.
Args:
x: `Tensor`.
Retur... |
Calculate the batched KL divergence KL ( a || b ) with a and b Laplace. | def _kl_laplace_laplace(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a and b Laplace.
Args:
a: instance of a Laplace distribution object.
b: instance of a Laplace distribution object.
name: (optional) Name to use for created operations.
default is "kl_laplace_laplace".... |
Generates Tensor consisting of - 1 or + 1 chosen uniformly at random. | def random_rademacher(shape, dtype=tf.float32, seed=None, name=None):
"""Generates `Tensor` consisting of `-1` or `+1`, chosen uniformly at random.
For more details, see [Rademacher distribution](
https://en.wikipedia.org/wiki/Rademacher_distribution).
Args:
shape: Vector-shaped, `int` `Tensor` representi... |
Generates Tensor of positive reals drawn from a Rayleigh distributions. | def random_rayleigh(shape, scale=None, dtype=tf.float32, seed=None, name=None):
"""Generates `Tensor` of positive reals drawn from a Rayleigh distributions.
The probability density function of a Rayleigh distribution with `scale`
parameter is given by:
```none
f(x) = x scale**-2 exp(-x**2 0.5 scale**-2)
`... |
Convenience function which chooses the condition based on the predicate. | def _pick_scalar_condition(pred, cond_true, cond_false):
"""Convenience function which chooses the condition based on the predicate."""
# Note: This function is only valid if all of pred, cond_true, and cond_false
# are scalars. This means its semantics are arguably more like tf.cond than
# tf.where even though... |
Finish computation of log_prob on one element of the inverse image. | def _finish_log_prob_for_one_fiber(self, y, x, ildj, event_ndims,
**distribution_kwargs):
"""Finish computation of log_prob on one element of the inverse image."""
x = self._maybe_rotate_dims(x, rotate_right=True)
log_prob = self.distribution.log_prob(x, **distribution_k... |
Finish computation of prob on one element of the inverse image. | def _finish_prob_for_one_fiber(self, y, x, ildj, event_ndims,
**distribution_kwargs):
"""Finish computation of prob on one element of the inverse image."""
x = self._maybe_rotate_dims(x, rotate_right=True)
prob = self.distribution.prob(x, **distribution_kwargs)
if self._... |
Helper to __init__ which ensures override batch/ event_shape are valid. | def _maybe_validate_shape_override(self, override_shape, base_is_scalar,
validate_args, name):
"""Helper to __init__ which ensures override batch/event_shape are valid."""
if override_shape is None:
override_shape = []
override_shape = tf.convert_to_tensor(
... |
Helper which rolls left event_dims left or right event_dims right. | def _maybe_rotate_dims(self, x, rotate_right=False):
"""Helper which rolls left event_dims left or right event_dims right."""
needs_rotation_const = tf.get_static_value(self._needs_rotation)
if needs_rotation_const is not None and not needs_rotation_const:
return x
ndims = prefer_static.rank(x)
... |
r Inverse of tf. nn. batch_normalization. | def _undo_batch_normalization(x,
mean,
variance,
offset,
scale,
variance_epsilon,
name=None):
r"""Inverse of tf.nn.batch_normalization.
... |
Check for valid BatchNormalization layer. | def _validate_bn_layer(self, layer):
"""Check for valid BatchNormalization layer.
Args:
layer: Instance of `tf.layers.BatchNormalization`.
Raises:
ValueError: If batchnorm_layer argument is not an instance of
`tf.layers.BatchNormalization`, or if `batchnorm_layer.renorm=True` or
if ... |
Slices a single parameter of a distribution. | def _slice_single_param(param, param_event_ndims, slices, dist_batch_shape):
"""Slices a single parameter of a distribution.
Args:
param: A `Tensor`, the original parameter to slice.
param_event_ndims: `int` event parameterization rank for this parameter.
slices: A `tuple` of normalized slices.
dis... |
Computes the override dictionary of sliced parameters. | def _slice_params_to_dict(dist, params_event_ndims, slices):
"""Computes the override dictionary of sliced parameters.
Args:
dist: The tfd.Distribution being batch-sliced.
params_event_ndims: Per-event parameter ranks, a `str->int` `dict`.
slices: Slices as received by __getitem__.
Returns:
over... |
Applies a single slicing step to dist returning a new instance. | def _apply_single_step(dist, params_event_ndims, slices, params_overrides):
"""Applies a single slicing step to `dist`, returning a new instance."""
if len(slices) == 1 and slices[0] == Ellipsis:
# The path used by Distribution.copy: batch_slice(...args..., Ellipsis)
override_dict = {}
else:
override_... |
Applies a sequence of slice or copy - with - overrides operations to dist. | def _apply_slice_sequence(dist, params_event_ndims, slice_overrides_seq):
"""Applies a sequence of slice or copy-with-overrides operations to `dist`."""
for slices, overrides in slice_overrides_seq:
dist = _apply_single_step(dist, params_event_ndims, slices, overrides)
return dist |
Slices dist along its batch dimensions. Helper for tfd. Distribution. | def batch_slice(dist, params_event_ndims, params_overrides, slices):
"""Slices `dist` along its batch dimensions. Helper for tfd.Distribution.
Args:
dist: A `tfd.Distribution` instance.
params_event_ndims: A `dict` of `str->int` indicating the number of
dimensions of a given parameter required to par... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.