INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Generates batched data in flat numpy arrays. | def generate_flat_data(self):
"""Generates batched data in flat numpy arrays.
Raises:
ValueError: When too many generate calls are required.
"""
# Construct the string statements.
all_statements = []
all_targets = []
self.sequence_sizes_in = []
self.sequence_sizes_out = []
for... |
Produces the list of integer indices corresponding to a token list. | def tokenize(self, char_input, max_len, by_char=False):
"""Produces the list of integer indices corresponding to a token list.
Args:
char_input: The character string to be tokenized.
max_len: Truncation length.
by_char: If true each character is a token - otherwise alpha-numeric
... |
Returns an operations list based on the specified task index. | def get_task_ops(task_type=TaskType.ALG_CTRL):
"""Returns an operations list based on the specified task index.
Args:
task_type: indicates the task type used.
Returns:
List of the eligible ops.
"""
try:
return LearnToExecuteState.TASK_TYPE_OPS[task_type]
except KeyError:
... |
Generator function for batchifying data for learning to execute. | def make_batch(self):
"""Generator function for batchifying data for learning to execute.
Yields:
tuple:
1. one-hot input tensor, representing programmatic input
2. one-hot target tensor, the vealuation result.
3. one-hot decoder target, start symbol added for sequence decoding.
... |
Returns a human - readable version of a one - hot encoding of words. | def to_human_readable(self, data, label_batch_entries=True, indices=None,
sep="\n"):
"""Returns a human-readable version of a one-hot encoding of words.
Args:
data: (numpy.ndarray S x B x OH). One-hot encoding of words. S is
sequence length, B is batch size, OH is one ho... |
Infers the data format for the fused batch norm. | def _infer_fused_data_format(self, input_batch):
"""Infers the data format for the fused batch norm.
It uses the axis option to infer this information. Specifically, the
axis value (0, 1, 2) corresponds to data format NHWC and the
axis value (0, 2, 3) to data format NCHW.
Args:
input_batch: ... |
Creates a fused batch normalization op. | def _fused_batch_norm_op(self, input_batch, mean, variance, use_batch_stats):
"""Creates a fused batch normalization op."""
# Store the original shape of the mean and variance.
mean_shape = mean.get_shape()
variance_shape = variance.get_shape()
# The fused batch norm expects the mean, variance, gamm... |
Creates a batch normalization op. | def _batch_norm_op(self, input_batch, mean, variance, use_batch_stats,
stat_dtype):
"""Creates a batch normalization op.
It uses the tf.nn.batch_normalization op by default and the
tf.nn.fused_batch_norm op to support fused batch normalization.
Args:
input_batch: A input Ten... |
Sets up optional scale and offset factors. | def _build_scale_offset(self, dtype):
"""Sets up optional scale and offset factors."""
# tf.nn.fused_batch_norm accepts float16 batch data, but not scale/offset.
if self._fused and dtype == tf.float16:
dtype = tf.float32
# The fused batch norm operation needs the beta, gamma variables,
# so ... |
Connects the BatchNorm module into the graph. | def _build(self, input_batch, is_training, test_local_stats=True):
"""Connects the BatchNorm module into the graph.
Args:
input_batch: A Tensor of arbitrary dimension. By default, the final
dimension is not reduced over when computing the minibatch statistics.
is_training: A boolean to indi... |
Produces the list of integer indices corresponding to a token list. | def tokenize(self, token_list):
"""Produces the list of integer indices corresponding to a token list."""
return [
self._vocab_dict.get(token, self._vocab_dict[self.UNK])
for token in token_list
] |
Returns a batch of sequences. | def _get_batch(self):
"""Returns a batch of sequences.
Returns:
obs: np.int32 array of size [Time, Batch]
target: np.int32 array of size [Time, Batch]
"""
batch_indices = np.mod(
np.array([
np.arange(head_index, head_index + self._num_steps + 1) for
head_inde... |
Returns a tuple containing observation and target one - hot tensors. | def _build(self):
"""Returns a tuple containing observation and target one-hot tensors."""
q = tf.FIFOQueue(
self._queue_capacity, [self._dtype, self._dtype],
shapes=[[self._num_steps, self._batch_size, self._vocab_size]]*2)
obs, target = tf.py_func(self._get_batch, [], [tf.int32, tf.int32])... |
Returns cost. | def cost(self, logits, target):
"""Returns cost.
Args:
logits: model output.
target: target.
Returns:
Cross-entropy loss for a sequence of logits. The loss will be averaged
across time steps if time_average_cost was enabled at construction time.
"""
logits = tf.reshape(logi... |
Returns a human - readable version of a one - hot encoding of words. | def to_human_readable(self,
data,
label_batch_entries=True,
indices=None,
sep="\n"):
"""Returns a human-readable version of a one-hot encoding of words.
Args:
data: A tuple with (obs, target). `obs` is a numpy... |
Gets training and testing dataset iterators. | def get_data(name, train_batch_size, test_batch_size):
"""Gets training and testing dataset iterators.
Args:
name: String. Name of dataset, either 'mnist' or 'cifar10'.
train_batch_size: Integer. Batch size for training.
test_batch_size: Integer. Batch size for testing.
Returns:
Dict containing:... |
Returns the name of the variable scope indicated by the given value. | def get_variable_scope_name(value):
"""Returns the name of the variable scope indicated by the given value.
Args:
value: String, variable scope, or object with `variable_scope` attribute
(e.g., Sonnet module).
Returns:
The name (a string) of the corresponding variable scope.
Raises:
ValueErro... |
Returns a tuple tf. Variable s in a scope for a given collection. | def get_variables_in_scope(scope, collection=tf.GraphKeys.TRAINABLE_VARIABLES):
"""Returns a tuple `tf.Variable`s in a scope for a given collection.
Args:
scope: `tf.VariableScope` or string to retrieve variables from.
collection: Collection to restrict query to. By default this is
`tf.Graphkeys.TR... |
Returns tuple of tf. Variable s declared inside an snt. Module. | def get_variables_in_module(module,
collection=tf.GraphKeys.TRAINABLE_VARIABLES):
"""Returns tuple of `tf.Variable`s declared inside an `snt.Module`.
Note that this operates by searching the variable scope a module contains,
and so does not know about any modules which were constructe... |
Checks if all items in the dictionary and in subdictionaries are callables. | def _check_nested_callables(dictionary, object_name):
"""Checks if all items in the dictionary and in subdictionaries are callables.
Args:
dictionary: Dictionary of callables or other dictionaries with callables.
object_name: The name of the object that is expected in the dictionary.
E.g. 'Initialize... |
Raises a TypeError iff maybe_dictlike is not a dictlike object. | def _assert_is_dictlike(maybe_dictlike, valid_keys):
"""Raises a TypeError iff `maybe_dictlike` is not a dictlike object."""
# This covers a common mistake when people use incorrect dictionary nesting
# for initializers / partitioners etc. The previous error message was quite
# opaque, this should be much clear... |
Checks the given initializers. | def check_initializers(initializers, keys):
"""Checks the given initializers.
This checks that `initializers` is a dictionary that only contains keys in
`keys`, and furthermore the entries in `initializers` are functions or
further dictionaries (the latter used, for example, in passing initializers
to module... |
Checks the given partitioners. | def check_partitioners(partitioners, keys):
"""Checks the given partitioners.
This checks that `partitioners` is a dictionary that only contains keys in
`keys`, and furthermore the entries in `partitioners` are functions or
further dictionaries (the latter used, for example, in passing partitioners
to module... |
Checks the given regularizers. | def check_regularizers(regularizers, keys):
"""Checks the given regularizers.
This checks that `regularizers` is a dictionary that only contains keys in
`keys`, and furthermore the entries in `regularizers` are functions or
further dictionaries (the latter used, for example, in passing regularizers
to module... |
Checks that prefix_name is a proper scope prefix of scope_name. | def _is_scope_prefix(scope_name, prefix_name):
"""Checks that `prefix_name` is a proper scope prefix of `scope_name`."""
if not prefix_name:
return True
if not scope_name.endswith("/"):
scope_name += "/"
if not prefix_name.endswith("/"):
prefix_name += "/"
return scope_name.startswith(prefix_n... |
Separates the sliced ( partitioned ) and unsliced variables in var_list. | def _get_sliced_variables(var_list):
"""Separates the sliced (partitioned) and unsliced variables in var_list.
Args:
var_list: a list of variables.
Returns:
A list of unsliced variables in var_list, and a dict mapping names to parts
for the sliced variables in var_list.
"""
unsliced_variables = ... |
Creates a custom getter than matches requests to dict of custom getters. | def custom_getter_router(custom_getter_map, name_fn):
"""Creates a custom getter than matches requests to dict of custom getters.
Custom getters are callables which implement the
[custom getter API]
(https://www.tensorflow.org/versions/r1.0/api_docs/python/tf/get_variable).
The returned custom getter dispat... |
Builds map of tf. Variable s in scope or module with normalized names. | def get_normalized_variable_map(scope_or_module,
collection=tf.GraphKeys.GLOBAL_VARIABLES,
context=None,
group_sliced_variables=True):
"""Builds map of `tf.Variable`s in scope or module with normalized names.
The names ... |
Builds a tf. train. Saver for the scope or module with normalized names. | def get_saver(scope, collections=(tf.GraphKeys.GLOBAL_VARIABLES,), # pylint: disable=redefined-outer-name
context=None, **kwargs):
"""Builds a `tf.train.Saver` for the scope or module, with normalized names.
The names of the variables are normalized to remove the scope prefix.
This allows the same... |
Yields an iterator over ( string variable ) pairs in the variable map. | def variable_map_items(variable_map):
"""Yields an iterator over (string, variable) pairs in the variable map.
In general, variable maps map variable names to either a `tf.Variable`, or
list of `tf.Variable`s (in case of sliced variables).
Args:
variable_map: dict, variable map over which to iterate.
Y... |
Returns a dict mapping variables to the collections they appear in. | def _get_vars_to_collections(variables):
"""Returns a dict mapping variables to the collections they appear in."""
var_to_collections = collections.defaultdict(lambda: [])
if isinstance(variables, dict):
variables = list(v for _, v in variable_map_items(variables))
for graph in set(v.graph for v in variable... |
Returns the device with an annotation specifying ResourceVariable. | def _format_device(var):
"""Returns the device with an annotation specifying `ResourceVariable`.
"legacy" means a normal tf.Variable while "resource" means a ResourceVariable.
For example:
`(legacy)`
`(resource)`
`/job:learner/task:0/device:CPU:* (legacy)`
`/job:learner/task:0/device:CPU:* (resource)`
... |
Takes a collection of variables and formats it as a table. | def format_variables(variables, join_lines=True):
"""Takes a collection of variables and formats it as a table."""
rows = []
rows.append(("Variable", "Shape", "Type", "Collections", "Device"))
var_to_collections = _get_vars_to_collections(variables)
for var in sorted(variables, key=lambda var: var.op.name):
... |
Takes a key - to - variable map and formats it as a table. | def format_variable_map(variable_map, join_lines=True):
"""Takes a key-to-variable map and formats it as a table."""
rows = []
rows.append(("Key", "Variable", "Shape", "Type", "Collections", "Device"))
var_to_collections = _get_vars_to_collections(variable_map)
sort_key = lambda item: (item[0], item[1].name)... |
Logs variable information. | def log_variables(variables=None):
"""Logs variable information.
This function logs the name, shape, type, collections, and device for either
all variables or a given iterable of variables. In the "Device" columns,
the nature of the variable (legacy or resource (for ResourceVariables)) is
also specified in p... |
Returns human readable string of how much memory num_bytes fills. | def _num_bytes_to_human_readable(num_bytes):
"""Returns human readable string of how much memory `num_bytes` fills."""
if num_bytes < (2 ** 10):
return "%d B" % num_bytes
elif num_bytes < (2 ** 20):
return "%.3f KB" % (float(num_bytes) / (2 ** 10))
elif num_bytes < (2 ** 30):
return "%.3f MB" % (flo... |
Logs a summary of variable information. | def summarize_variables(variables=None):
"""Logs a summary of variable information.
This function groups Variables by dtype and prints out the number of Variables
and the total number of scalar values for each datatype, as well as the total
memory consumed.
For Variables of type tf.string, the memory usage ... |
Returns a dict mapping dtypes to number of variables and scalars. | def count_variables_by_type(variables=None):
"""Returns a dict mapping dtypes to number of variables and scalars.
Args:
variables: iterable of `tf.Variable`s, or None. If None is passed, then all
global and local variables in the current graph are used.
Returns:
A dict mapping tf.dtype keys to a d... |
Wraps an arbitrary method so it does variable sharing. | def reuse_variables(method):
"""Wraps an arbitrary method so it does variable sharing.
This decorator creates variables the first time it calls `method`, and reuses
them for subsequent calls. The object that calls `method` provides a
`tf.VariableScope`, either as a `variable_scope` attribute or as the return
... |
Returns a module name for a callable or None if no name can be found. | def name_for_callable(func):
"""Returns a module name for a callable or `None` if no name can be found."""
if isinstance(func, functools.partial):
return name_for_callable(func.func)
try:
name = func.__name__
except AttributeError:
return None
if name == "<lambda>":
return None
else:
r... |
Returns a CamelCase string as a snake_case string. | def to_snake_case(camel_case):
"""Returns a CamelCase string as a snake_case string."""
if not re.match(r"^[A-Za-z_]\w*$", camel_case):
raise ValueError(
"Input string %s is not a valid Python identifier." % camel_case)
# Add underscore at word start and ends.
underscored = re.sub(r"([A-Z][a-z])", ... |
Calls callback ( var ) for all newly created variables. | def notify_about_new_variables(callback):
"""Calls `callback(var)` for all newly created variables.
Callback should not modify the variable passed in. Use cases that require
variables to be modified should use `variable_creator_scope` directly and sit
within the variable creator stack.
>>> variables = []
... |
Recursively gets attributes inside module as specified by path. | def _recursive_getattr(module, path):
"""Recursively gets attributes inside `module` as specified by `path`."""
if "." not in path:
return getattr(module, path)
else:
first, rest = path.split(".", 1)
return _recursive_getattr(getattr(module, first), rest) |
Returns a callable which corresponds to the constructor string. | def parse_string_to_constructor(ctor_string):
"""Returns a callable which corresponds to the constructor string.
Various modules (eg, ConvNet2D) take constructor arguments which are
callables, indicating a submodule to build. These can be passed as
actual constructors, eg `snt.LayerNorm`, however that makes th... |
Determines whether the provided callable supports all the kwargs. | def supports_kwargs(module_or_fn, kwargs_list):
"""Determines whether the provided callable supports all the kwargs.
This is useful when you have a module that might or might not support a
kwarg such as `is_training`. Rather than calling the module and catching the
error, risking the potential modification of ... |
Removes any kwargs not supported by module_or_fn from all_kwargs_dict. | def remove_unsupported_kwargs(module_or_fn, all_kwargs_dict):
"""Removes any kwargs not supported by `module_or_fn` from `all_kwargs_dict`.
A new dict is return with shallow copies of keys & values from
`all_kwargs_dict`, as long as the key is accepted by module_or_fn. The
returned dict can then be used to con... |
Merge the first dimensions of a tensor. | def merge_leading_dims(array_or_tensor, n_dims=2):
"""Merge the first dimensions of a tensor.
Args:
array_or_tensor: Tensor to have its first dimensions merged. Can also
be an array or numerical value, which will be converted to a tensor
for batch application, if needed.
n_dims: Number of d... |
Split the first dimension of a tensor. | def split_leading_dim(tensor, inputs, n_dims=2):
"""Split the first dimension of a tensor.
Args:
tensor: Tensor to have its first dimension split.
inputs: Original reference input to look the dimensions of.
n_dims: Number of dimensions to split.
Returns:
The input tensor, with its first dimensio... |
Returns a default initializer for weights of a linear module. | def create_linear_initializer(input_size, dtype=tf.float32):
"""Returns a default initializer for weights of a linear module."""
stddev = 1 / math.sqrt(input_size)
return tf.truncated_normal_initializer(stddev=stddev, dtype=dtype) |
Calculate bias_shape based on the input_shape and bias_dims. | def calculate_bias_shape(input_shape, bias_dims):
"""Calculate `bias_shape` based on the `input_shape` and `bias_dims`.
Args:
input_shape: Shape of the input being passed into the module. The leading
dimension is the minibatch size.
bias_dims: The dimensions that bias should be applied over. The re... |
Connects the Linear module into the graph with input Tensor inputs. | def _build(self, inputs):
"""Connects the Linear module into the graph, with input Tensor `inputs`.
If this is not the first time the module has been connected to the graph,
the Tensor provided here must have the same final dimension, in order for
the existing variables to be the correct size for the m... |
Returns the module output size. | def output_size(self):
"""Returns the module output size."""
if callable(self._output_size):
self._output_size = self._output_size()
return self._output_size |
Returns a cloned Linear module. | def clone(self, name=None):
"""Returns a cloned `Linear` module.
Args:
name: Optional string assigning name of cloned module. The default name
is constructed by appending "_clone" to `self.module_name`.
Returns:
Cloned `Linear` module.
"""
if name is None:
name = self.m... |
Connects the module into the graph. | def _build(self, inputs_list):
"""Connects the module into the graph.
If this is not the first time the module has been connected to the graph,
the Tensors provided here must have the same final dimensions as when called
the first time, in order for the existing variables to be the correct size
for... |
Connects the Add module into the graph with input Tensor inputs. | def _build(self, inputs, multiplier=1):
"""Connects the Add module into the graph, with input Tensor `inputs`.
Args:
inputs: A Tensor of size `[batch_size, input_size1, ...]`.
multiplier: A scalar or Tensor which the bias term is multiplied by
before adding it to `inputs`. Anything which wo... |
Returns transposed AddBias module. | def transpose(self, name=None):
"""Returns transposed `AddBias` module.
Args:
name: Optional string assigning name of transpose module. The default name
is constructed by appending "_transpose" to `self.module_name`.
Returns:
Transposed `AddBias` module.
"""
if name is None:... |
Replaces the - 1 wildcard in the output shape vector. | def _infer_shape(self, dimensions):
"""Replaces the -1 wildcard in the output shape vector.
This function infers the correct output shape given the input dimensions.
Args:
dimensions: List of input non-batch dimensions.
Returns:
Tuple of non-batch output dimensions.
"""
# Size of ... |
Connects the module into the graph with input Tensor inputs. | def _build(self, inputs):
"""Connects the module into the graph, with input Tensor `inputs`.
Args:
inputs: A Tensor of shape [b_1, b_2, ..., b_preserve_dims,
b_preserve_dims+1, ...].
Returns:
A Tensor of shape [b_1, b_2, ..., b_preserve_dims,
... |
Returns transpose batch reshape. | def transpose(self, name=None):
"""Returns transpose batch reshape."""
if name is None:
name = self.module_name + "_transpose"
return BatchReshape(shape=lambda: self.input_shape,
preserve_dims=self._preserve_dims,
name=name) |
Connects the TrainableTensor module into the graph. | def _build(self):
"""Connects the TrainableTensor module into the graph.
Returns:
A Tensor of shape as determined in the constructor.
"""
if "w" not in self._initializers:
stddev = 1 / math.sqrt(np.prod(self._shape))
self._initializers["w"] = tf.truncated_normal_initializer(stddev=std... |
Connects the BatchApply module into the graph. | def _build(self, *args, **kwargs):
"""Connects the BatchApply module into the graph.
Args:
*args: a Tensor or a nested list or dictionary of Tensors. The input
tensors will have their first dimensions merged, then an op or a
module will be called on the input. The first dimension of t... |
Connects the SliceByDim module into the graph. | def _build(self, inputs):
"""Connects the SliceByDim module into the graph.
Args:
inputs: `Tensor` to slice. Its rank must be greater than the maximum
dimension specified in `dims` (plus one as python is 0 indexed).
Returns:
The sliced tensor.
Raises:
ValueError: If `input... |
Connects the TileByDim module into the graph. | def _build(self, inputs):
"""Connects the `TileByDim` module into the graph.
Args:
inputs: `Tensor` to tile.
Returns:
The tiled tensor.
"""
shape_inputs = inputs.get_shape().as_list()
rank = len(shape_inputs)
# Builds default lists for multiples to pass to `tf.tile`.
full_... |
Connects the MergeDims module into the graph. | def _build(self, inputs):
"""Connects the MergeDims module into the graph.
Args:
inputs: Tensor or a nested list of Tensors to merge. Its rank must be
greater than or equal to `start` + `size`.
Returns:
The merged Tensor or a nested list of merged Tensors.
Raises:
ValueErr... |
Creates the initial memory. | def initial_state(self, batch_size, trainable=False):
"""Creates the initial memory.
We should ensure each row of the memory is initialized to be unique,
so initialize the matrix to be the identity. We then pad or truncate
as necessary so that init_state is of size
(batch_size, self._mem_slots, sel... |
Perform multi - head attention from Attention is All You Need. | def _multihead_attention(self, memory):
"""Perform multi-head attention from 'Attention is All You Need'.
Implementation of the attention mechanism from
https://arxiv.org/abs/1706.03762.
Args:
memory: Memory tensor to perform attention on.
Returns:
new_memory: New memory tensor.
"... |
Create input and forget gates for this step using inputs and memory. | def _create_gates(self, inputs, memory):
"""Create input and forget gates for this step using `inputs` and `memory`.
Args:
inputs: Tensor input.
memory: The current state of memory.
Returns:
input_gate: A LSTM-like insert gate.
forget_gate: A LSTM-like forget gate.
"""
# We... |
Perform multiheaded attention over memory. | def _attend_over_memory(self, memory):
"""Perform multiheaded attention over `memory`.
Args:
memory: Current relational memory.
Returns:
The attended-over memory.
"""
attention_mlp = basic.BatchApply(
mlp.MLP([self._mem_size] * self._attention_mlp_layers))
for _ in range(se... |
Adds relational memory to the TensorFlow graph. | def _build(self, inputs, memory, treat_input_as_matrix=False):
"""Adds relational memory to the TensorFlow graph.
Args:
inputs: Tensor input.
memory: Memory output from the previous time step.
treat_input_as_matrix: Optional, whether to treat `input` as a sequence
of matrices. Default... |
Creates a basic MNIST model using Sonnet then trains and evaluates it. | def train_and_eval(train_batch_size, test_batch_size, num_hidden, learning_rate,
num_train_steps, report_every, test_every):
"""Creates a basic MNIST model using Sonnet, then trains and evaluates it."""
data_dict = dataset_mnist.get_data("mnist", train_batch_size, test_batch_size)
train_data =... |
Returns an initial ( maybe learnable ) state. | def _single_learnable_state(state, state_id=0, learnable=True):
"""Returns an initial (maybe learnable) state.
This function does not create any variable scopes, and it should be called
from a Sonnet module. This function also makes sure that all the rows of its
`state` argument have the same value.
Args:
... |
Creates an initial state consisting of trainable variables. | def trainable_initial_state(batch_size, state_size, dtype, initializers=None,
regularizers=None, name=None):
"""Creates an initial state consisting of trainable variables.
The trainable variables are created with the same shapes as the elements of
`state_size` and are tiled to produce... |
Returns a decorator to copy documentation from the given function. | def with_doc(fn_with_doc_to_copy):
"""Returns a decorator to copy documentation from the given function.
Docstring is copied, including *args and **kwargs documentation.
Args:
fn_with_doc_to_copy: Function whose docstring, including *args and
**kwargs documentation, is to be copied.
Returns:
De... |
Connects the module to the graph. | def _build(self):
"""Connects the module to the graph.
Returns:
The learnable state, which has the same type, structure and shape as
the `initial_state` passed to the constructor.
"""
flat_initial_state = nest.flatten(self._initial_state)
if self._mask is not None:
flat_mask = n... |
Connects the LayerNorm module into the graph. | def _build(self, inputs):
"""Connects the LayerNorm module into the graph.
Args:
inputs: a Tensor of dimensionality >= 2.
Returns:
normalized: layer normalized outputs with same shape as inputs.
Raises:
base.NotSupportedError: If `inputs` has less than 2 dimensions.
"""
if ... |
Perform a differentiable read. | def _build(self, memory, query, memory_mask=None):
"""Perform a differentiable read.
Args:
memory: [batch_size, memory_size, memory_word_size]-shaped Tensor of
dtype float32. This represents, for each example and memory slot, a
single embedding to attend over.
query: [batch_size, qu... |
Builds the statistics part of the graph when using moving variance. | def _build_statistics(self, input_batch, use_batch_stats, stat_dtype):
"""Builds the statistics part of the graph when using moving variance.
Args:
input_batch: Input batch Tensor.
use_batch_stats: Boolean to indicate if batch statistics should be
calculated, otherwise moving averages are r... |
Builds the moving average update ops when using moving variance. | def _build_update_ops(self, mean, variance, is_training):
"""Builds the moving average update ops when using moving variance.
Args:
mean: The mean value to update with.
variance: The variance value to update with.
is_training: Boolean Tensor to indicate if we're currently in
training ... |
Creates a fused batch normalization op. | def _fused_batch_norm_op(self, input_batch, mean, variance, use_batch_stats):
"""Creates a fused batch normalization op."""
# Store the original shape of the mean and variance.
mean_shape = mean.get_shape()
variance_shape = variance.get_shape()
# The fused batch norm expects the mean, variance, gamm... |
Connects the BatchNormV2 module into the graph. | def _build(self,
input_batch,
is_training,
test_local_stats=False):
"""Connects the BatchNormV2 module into the graph.
Args:
input_batch: A Tensor of the same dimension as `len(data_format)`.
is_training: A boolean to indicate if the module should be connected... |
Construct a Tensor whose values are the index along a dimension. | def _range_along_dimension(range_dim, shape):
"""Construct a Tensor whose values are the index along a dimension.
Construct a Tensor that counts the distance along a single dimension. This is
useful, for example, when constructing an identity matrix,
>>> x = _range_along_dimension(0, [2, 2]).eval()
>>> ... |
An initializer for constructing identity convolution kernels. | def identity_kernel_initializer(shape, dtype=tf.float32, partition_info=None):
"""An initializer for constructing identity convolution kernels.
Constructs a convolution kernel such that applying it is the same as an
identity operation on the input. Formally, the kernel has entry [i, j, in,
out] = 1 if in equal... |
Build an initializer for constructing near - identity convolution kernels. | def noisy_identity_kernel_initializer(base_num_channels, stddev=1e-8):
"""Build an initializer for constructing near-identity convolution kernels.
Construct a convolution kernel where in_channels and out_channels are
multiples of base_num_channels, but need not be equal. This initializer is
essentially the sam... |
Build dilation module. | def _build(self, images):
"""Build dilation module.
Args:
images: Tensor of shape [batch_size, height, width, depth]
and dtype float32. Represents a set of images with an arbitrary depth.
Note that when using the default initializer, depth must equal
num_output_classes.
Retur... |
Create a dilated convolution layer. | def _dilated_conv_layer(self, output_channels, dilation_rate, apply_relu,
name):
"""Create a dilated convolution layer.
Args:
output_channels: int. Number of output channels for each pixel.
dilation_rate: int. Represents how many pixels each stride offset will
move... |
Wraps the function and prints a warn - once ( per extra_message ) warning. | def with_deprecation_warning(fn, extra_message=''):
"""Wraps the function and prints a warn-once (per `extra_message`) warning."""
def new_fn(*args, **kwargs):
if extra_message not in _DONE_WARN:
tf.logging.warning(
'Sonnet nest is deprecated. Please use '
'tf.contrib.framework.nest in... |
A custom build method to wrap into a sonnet Module. | def custom_build(inputs, is_training, keep_prob):
"""A custom build method to wrap into a sonnet Module."""
outputs = snt.Conv2D(output_channels=32, kernel_shape=4, stride=2)(inputs)
outputs = snt.BatchNorm()(outputs, is_training=is_training)
outputs = tf.nn.relu(outputs)
outputs = snt.Conv2D(output_channels=... |
Returns a thread local stack uniquified by the given name. | def _get_or_create_stack(name):
"""Returns a thread local stack uniquified by the given name."""
stack = getattr(_LOCAL_STACKS, name, None)
if stack is None:
stack = []
setattr(_LOCAL_STACKS, name, stack)
return stack |
A pre - canned builder for diagonal gaussian posterior distributions. | def diagonal_gaussian_posterior_builder(
getter, name, shape=None, *args, **kwargs):
"""A pre-canned builder for diagonal gaussian posterior distributions.
Given a true `getter` function and arguments forwarded from `tf.get_variable`,
return a distribution object for a diagonal posterior over a variable of t... |
A pre - canned builder for fixed gaussian prior distributions. | def fixed_gaussian_prior_builder(
getter, name, dtype=None, *args, **kwargs):
"""A pre-canned builder for fixed gaussian prior distributions.
Given a true `getter` function and arguments forwarded from `tf.get_variable`,
return a distribution object for a scalar-valued fixed gaussian prior which
will be br... |
A pre - canned builder for adaptive scalar gaussian prior distributions. | def adaptive_gaussian_prior_builder(
getter, name, *args, **kwargs):
"""A pre-canned builder for adaptive scalar gaussian prior distributions.
Given a true `getter` function and arguments forwarded from `tf.get_variable`,
return a distribution object for a scalar-valued adaptive gaussian prior
which will b... |
A pre - canned builder for a ubiquitous stochastic KL estimator. | def stochastic_kl_builder(posterior, prior, sample):
"""A pre-canned builder for a ubiquitous stochastic KL estimator."""
return tf.subtract(
tf.reduce_sum(posterior.log_prob(sample)),
tf.reduce_sum(prior.log_prob(sample))) |
A pre - canned builder for the analytic kl divergence. | def analytic_kl_builder(posterior, prior, sample):
"""A pre-canned builder for the analytic kl divergence."""
del sample
return tf.reduce_sum(tfp.distributions.kl_divergence(posterior, prior)) |
Creates a custom getter which does Bayes by Backprop. | def bayes_by_backprop_getter(
posterior_builder=diagonal_gaussian_posterior_builder,
prior_builder=fixed_gaussian_prior_builder,
kl_builder=stochastic_kl_builder,
sampling_mode_tensor=None,
fresh_noise_per_connection=True,
keep_control_dependencies=False):
"""Creates a custom getter which does... |
Create tensor representing estimate of posterior. | def _produce_posterior_estimate(posterior_dist, posterior_estimate_mode,
raw_var_name):
"""Create tensor representing estimate of posterior.
Args:
posterior_dist: An instance of `tfp.distributions.Distribution`.
The variational posterior from which to produce an estimate... |
Get the total cost for all ( or a subset of ) the stochastic variables. | def get_total_kl_cost(name="total_kl_cost", filter_by_name_substring=None):
"""Get the total cost for all (or a subset of) the stochastic variables.
Args:
name: A name for the tensor representing the total kl cost.
filter_by_name_substring: A string used to filter which variables count
toward the tot... |
The shape of the output matrix. | def output_shape(self):
"""The shape of the output matrix."""
return (self._block_shape[0] * self._block_rows,
self._block_shape[1] * self._block_rows) |
Number of blocks with zeros from the left in block row r. | def _left_zero_blocks(self, r):
"""Number of blocks with zeros from the left in block row `r`."""
if not self._include_off_diagonal:
return r
elif not self._upper:
return 0
elif self._include_diagonal:
return r
else:
return r + 1 |
Number of blocks with zeros from the right in block row r. | def _right_zero_blocks(self, r):
"""Number of blocks with zeros from the right in block row `r`."""
if not self._include_off_diagonal:
return self._block_rows - r - 1
elif self._upper:
return 0
elif self._include_diagonal:
return self._block_rows - r - 1
else:
return self._bl... |
Number of content blocks in block row r. | def _content_blocks(self, r):
"""Number of content blocks in block row `r`."""
return (self._block_rows - self._left_zero_blocks(r)
- self._right_zero_blocks(r)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.