repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
deepmind/sonnet
sonnet/python/modules/batch_norm_v2.py
BatchNormV2._build_statistics
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...
python
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...
[ "def", "_build_statistics", "(", "self", ",", "input_batch", ",", "use_batch_stats", ",", "stat_dtype", ")", ":", "# Set up our moving statistics. When connecting in parallel, this is shared.", "if", "self", ".", "MOVING_MEAN", "not", "in", "self", ".", "_initializers", "...
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 returned. stat_dtype: TensorFlow datatype to use for the moving mean and ...
[ "Builds", "the", "statistics", "part", "of", "the", "graph", "when", "using", "moving", "variance", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/batch_norm_v2.py#L217-L285
train
deepmind/sonnet
sonnet/python/modules/batch_norm_v2.py
BatchNormV2._build_update_ops
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 ...
python
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 ...
[ "def", "_build_update_ops", "(", "self", ",", "mean", ",", "variance", ",", "is_training", ")", ":", "def", "build_update_ops", "(", ")", ":", "\"\"\"Builds the exponential moving average update ops.\"\"\"", "update_mean_op", "=", "moving_averages", ".", "assign_moving_av...
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 mode. Returns: Tuple of `(update_mean_op, update_varia...
[ "Builds", "the", "moving", "average", "update", "ops", "when", "using", "moving", "variance", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/batch_norm_v2.py#L287-L334
train
deepmind/sonnet
sonnet/python/modules/batch_norm_v2.py
BatchNormV2._fused_batch_norm_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...
python
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...
[ "def", "_fused_batch_norm_op", "(", "self", ",", "input_batch", ",", "mean", ",", "variance", ",", "use_batch_stats", ")", ":", "# Store the original shape of the mean and variance.", "mean_shape", "=", "mean", ".", "get_shape", "(", ")", "variance_shape", "=", "varia...
Creates a fused batch normalization op.
[ "Creates", "a", "fused", "batch", "normalization", "op", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/batch_norm_v2.py#L336-L404
train
deepmind/sonnet
sonnet/python/modules/batch_norm_v2.py
BatchNormV2._build
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...
python
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...
[ "def", "_build", "(", "self", ",", "input_batch", ",", "is_training", ",", "test_local_stats", "=", "False", ")", ":", "input_shape", "=", "input_batch", ".", "get_shape", "(", ")", "if", "not", "self", ".", "_data_format", ":", "if", "len", "(", "input_sh...
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 in training mode, meaning the moving averages are updated. Can be a Tensor. test_local_stats: A boo...
[ "Connects", "the", "BatchNormV2", "module", "into", "the", "graph", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/batch_norm_v2.py#L496-L583
train
deepmind/sonnet
sonnet/python/modules/nets/dilation.py
_range_along_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() >>> ...
python
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() >>> ...
[ "def", "_range_along_dimension", "(", "range_dim", ",", "shape", ")", ":", "rank", "=", "len", "(", "shape", ")", "if", "range_dim", ">=", "rank", ":", "raise", "ValueError", "(", "\"Cannot calculate range along non-existent index.\"", ")", "indices", "=", "tf", ...
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() >>> x array([[0, 0], [1, 1]], dtype=int3...
[ "Construct", "a", "Tensor", "whose", "values", "are", "the", "index", "along", "a", "dimension", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/dilation.py#L32-L70
train
deepmind/sonnet
sonnet/python/modules/nets/dilation.py
identity_kernel_initializer
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...
python
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...
[ "def", "identity_kernel_initializer", "(", "shape", ",", "dtype", "=", "tf", ".", "float32", ",", "partition_info", "=", "None", ")", ":", "if", "len", "(", "shape", ")", "!=", "4", ":", "raise", "ValueError", "(", "\"Convolution kernels must be rank 4.\"", ")...
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 equals out and i and j are the middle of the kernel and 0 otherwise. Args: shape...
[ "An", "initializer", "for", "constructing", "identity", "convolution", "kernels", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/dilation.py#L74-L118
train
deepmind/sonnet
sonnet/python/modules/nets/dilation.py
noisy_identity_kernel_initializer
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...
python
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...
[ "def", "noisy_identity_kernel_initializer", "(", "base_num_channels", ",", "stddev", "=", "1e-8", ")", ":", "# pylint: disable=unused-argument", "def", "_noisy_identity_kernel_initializer", "(", "shape", ",", "dtype", "=", "tf", ".", "float32", ",", "partition_info", "=...
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 same as identity_kernel_initializer, except that magnitude is "spread out" ac...
[ "Build", "an", "initializer", "for", "constructing", "near", "-", "identity", "convolution", "kernels", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/dilation.py#L121-L194
train
deepmind/sonnet
sonnet/python/modules/nets/dilation.py
Dilation._build
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...
python
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...
[ "def", "_build", "(", "self", ",", "images", ")", ":", "num_classes", "=", "self", ".", "_num_output_classes", "if", "len", "(", "images", ".", "get_shape", "(", ")", ")", "!=", "4", ":", "raise", "base", ".", "IncompatibleShapeError", "(", "\"'images' mus...
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. Returns: Tensor of shape [batch_...
[ "Build", "dilation", "module", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/dilation.py#L257-L319
train
deepmind/sonnet
sonnet/python/modules/nets/dilation.py
Dilation._dilated_conv_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...
python
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...
[ "def", "_dilated_conv_layer", "(", "self", ",", "output_channels", ",", "dilation_rate", ",", "apply_relu", ",", "name", ")", ":", "layer_components", "=", "[", "conv", ".", "Conv2D", "(", "output_channels", ",", "[", "3", ",", "3", "]", ",", "initializers",...
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. A value of 1 indicates a standard convolution. apply_relu: bool. If True, a ReLU non-linearlity is added. ...
[ "Create", "a", "dilated", "convolution", "layer", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/dilation.py#L321-L345
train
deepmind/sonnet
sonnet/python/ops/nest.py
with_deprecation_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...
python
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...
[ "def", "with_deprecation_warning", "(", "fn", ",", "extra_message", "=", "''", ")", ":", "def", "new_fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "extra_message", "not", "in", "_DONE_WARN", ":", "tf", ".", "logging", ".", "warning", ...
Wraps the function and prints a warn-once (per `extra_message`) warning.
[ "Wraps", "the", "function", "and", "prints", "a", "warn", "-", "once", "(", "per", "extra_message", ")", "warning", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/ops/nest.py#L33-L44
train
deepmind/sonnet
sonnet/examples/module_with_build_args.py
custom_build
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=...
python
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=...
[ "def", "custom_build", "(", "inputs", ",", "is_training", ",", "keep_prob", ")", ":", "outputs", "=", "snt", ".", "Conv2D", "(", "output_channels", "=", "32", ",", "kernel_shape", "=", "4", ",", "stride", "=", "2", ")", "(", "inputs", ")", "outputs", "...
A custom build method to wrap into a sonnet Module.
[ "A", "custom", "build", "method", "to", "wrap", "into", "a", "sonnet", "Module", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/module_with_build_args.py#L41-L52
train
deepmind/sonnet
sonnet/python/modules/base.py
_get_or_create_stack
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
python
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
[ "def", "_get_or_create_stack", "(", "name", ")", ":", "stack", "=", "getattr", "(", "_LOCAL_STACKS", ",", "name", ",", "None", ")", "if", "stack", "is", "None", ":", "stack", "=", "[", "]", "setattr", "(", "_LOCAL_STACKS", ",", "name", ",", "stack", ")...
Returns a thread local stack uniquified by the given name.
[ "Returns", "a", "thread", "local", "stack", "uniquified", "by", "the", "given", "name", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/base.py#L60-L66
train
deepmind/sonnet
sonnet/python/custom_getters/bayes_by_backprop.py
diagonal_gaussian_posterior_builder
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...
python
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...
[ "def", "diagonal_gaussian_posterior_builder", "(", "getter", ",", "name", ",", "shape", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Please see the documentation for", "# `tfp.distributions.param_static_shapes`.", "parameter_shapes", "=", "tfp", ...
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 the requisite shape. Args: getter: The `getter` passed to a `custom_getter`. Please se...
[ "A", "pre", "-", "canned", "builder", "for", "diagonal", "gaussian", "posterior", "distributions", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/custom_getters/bayes_by_backprop.py#L148-L183
train
deepmind/sonnet
sonnet/python/custom_getters/bayes_by_backprop.py
fixed_gaussian_prior_builder
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...
python
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...
[ "def", "fixed_gaussian_prior_builder", "(", "getter", ",", "name", ",", "dtype", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "del", "getter", "# Unused.", "del", "args", "# Unused.", "del", "kwargs", "# Unused.", "loc", "=", "tf", "...
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 broadcast over a variable of the requisite shape. Args: getter: The `getter` passe...
[ "A", "pre", "-", "canned", "builder", "for", "fixed", "gaussian", "prior", "distributions", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/custom_getters/bayes_by_backprop.py#L188-L214
train
deepmind/sonnet
sonnet/python/custom_getters/bayes_by_backprop.py
adaptive_gaussian_prior_builder
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...
python
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...
[ "def", "adaptive_gaussian_prior_builder", "(", "getter", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"shape\"", "]", "=", "(", ")", "loc_var", "=", "getter", "(", "name", "+", "\"_prior_loc\"", ",", "*", "args", "...
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 be broadcast over a variable of the requisite shape. This prior's parameters ...
[ "A", "pre", "-", "canned", "builder", "for", "adaptive", "scalar", "gaussian", "prior", "distributions", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/custom_getters/bayes_by_backprop.py#L218-L247
train
deepmind/sonnet
sonnet/python/custom_getters/bayes_by_backprop.py
stochastic_kl_builder
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)))
python
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)))
[ "def", "stochastic_kl_builder", "(", "posterior", ",", "prior", ",", "sample", ")", ":", "return", "tf", ".", "subtract", "(", "tf", ".", "reduce_sum", "(", "posterior", ".", "log_prob", "(", "sample", ")", ")", ",", "tf", ".", "reduce_sum", "(", "prior"...
A pre-canned builder for a ubiquitous stochastic KL estimator.
[ "A", "pre", "-", "canned", "builder", "for", "a", "ubiquitous", "stochastic", "KL", "estimator", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/custom_getters/bayes_by_backprop.py#L250-L254
train
deepmind/sonnet
sonnet/python/custom_getters/bayes_by_backprop.py
analytic_kl_builder
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))
python
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))
[ "def", "analytic_kl_builder", "(", "posterior", ",", "prior", ",", "sample", ")", ":", "del", "sample", "return", "tf", ".", "reduce_sum", "(", "tfp", ".", "distributions", ".", "kl_divergence", "(", "posterior", ",", "prior", ")", ")" ]
A pre-canned builder for the analytic kl divergence.
[ "A", "pre", "-", "canned", "builder", "for", "the", "analytic", "kl", "divergence", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/custom_getters/bayes_by_backprop.py#L257-L260
train
deepmind/sonnet
sonnet/python/custom_getters/bayes_by_backprop.py
bayes_by_backprop_getter
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...
python
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...
[ "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_c...
Creates a custom getter which does Bayes by Backprop. Please see `tf.get_variable` for general documentation on custom getters. All arguments are optional. If nothing is configued, then a diagonal gaussian posterior will be used, and a fixed N(0, 0.01) prior will be used. Please see the default `posterior_bui...
[ "Creates", "a", "custom", "getter", "which", "does", "Bayes", "by", "Backprop", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/custom_getters/bayes_by_backprop.py#L263-L452
train
deepmind/sonnet
sonnet/python/custom_getters/bayes_by_backprop.py
_produce_posterior_estimate
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...
python
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...
[ "def", "_produce_posterior_estimate", "(", "posterior_dist", ",", "posterior_estimate_mode", ",", "raw_var_name", ")", ":", "conds", "=", "[", "tf", ".", "equal", "(", "posterior_estimate_mode", ",", "tf", ".", "constant", "(", "EstimatorModes", ".", "sample", ")"...
Create tensor representing estimate of posterior. Args: posterior_dist: An instance of `tfp.distributions.Distribution`. The variational posterior from which to produce an estimate of the variable in question. posterior_estimate_mode: A `Tensor` of dtype `tf.string`, which determines ...
[ "Create", "tensor", "representing", "estimate", "of", "posterior", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/custom_getters/bayes_by_backprop.py#L455-L505
train
deepmind/sonnet
sonnet/python/custom_getters/bayes_by_backprop.py
get_total_kl_cost
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...
python
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...
[ "def", "get_total_kl_cost", "(", "name", "=", "\"total_kl_cost\"", ",", "filter_by_name_substring", "=", "None", ")", ":", "all_variable_metadata", "=", "get_variable_metadata", "(", "filter_by_name_substring", ")", "if", "not", "all_variable_metadata", ":", "tf", ".", ...
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 total KL cost. By default, this argument is `None`, and all variables trained ...
[ "Get", "the", "total", "cost", "for", "all", "(", "or", "a", "subset", "of", ")", "the", "stochastic", "variables", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/custom_getters/bayes_by_backprop.py#L508-L527
train
deepmind/sonnet
sonnet/python/modules/block_matrix.py
BlockTriangularMatrix.output_shape
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)
python
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)
[ "def", "output_shape", "(", "self", ")", ":", "return", "(", "self", ".", "_block_shape", "[", "0", "]", "*", "self", ".", "_block_rows", ",", "self", ".", "_block_shape", "[", "1", "]", "*", "self", ".", "_block_rows", ")" ]
The shape of the output matrix.
[ "The", "shape", "of", "the", "output", "matrix", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/block_matrix.py#L106-L109
train
deepmind/sonnet
sonnet/python/modules/block_matrix.py
BlockTriangularMatrix._left_zero_blocks
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
python
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
[ "def", "_left_zero_blocks", "(", "self", ",", "r", ")", ":", "if", "not", "self", ".", "_include_off_diagonal", ":", "return", "r", "elif", "not", "self", ".", "_upper", ":", "return", "0", "elif", "self", ".", "_include_diagonal", ":", "return", "r", "e...
Number of blocks with zeros from the left in block row `r`.
[ "Number", "of", "blocks", "with", "zeros", "from", "the", "left", "in", "block", "row", "r", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/block_matrix.py#L160-L169
train
deepmind/sonnet
sonnet/python/modules/block_matrix.py
BlockTriangularMatrix._right_zero_blocks
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...
python
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...
[ "def", "_right_zero_blocks", "(", "self", ",", "r", ")", ":", "if", "not", "self", ".", "_include_off_diagonal", ":", "return", "self", ".", "_block_rows", "-", "r", "-", "1", "elif", "self", ".", "_upper", ":", "return", "0", "elif", "self", ".", "_in...
Number of blocks with zeros from the right in block row `r`.
[ "Number", "of", "blocks", "with", "zeros", "from", "the", "right", "in", "block", "row", "r", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/block_matrix.py#L171-L180
train
deepmind/sonnet
sonnet/python/modules/block_matrix.py
BlockTriangularMatrix._content_blocks
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))
python
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))
[ "def", "_content_blocks", "(", "self", ",", "r", ")", ":", "return", "(", "self", ".", "_block_rows", "-", "self", ".", "_left_zero_blocks", "(", "r", ")", "-", "self", ".", "_right_zero_blocks", "(", "r", ")", ")" ]
Number of content blocks in block row `r`.
[ "Number", "of", "content", "blocks", "in", "block", "row", "r", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/block_matrix.py#L182-L185
train
deepmind/sonnet
sonnet/examples/rmc_nth_farthest.py
build_and_train
def build_and_train(iterations, log_stride, test=False): """Construct the data, model, loss and optimizer then train.""" # Test mode settings. batch_size = 2 if test else FLAGS.batch_size num_mems = 2 if test else FLAGS.num_mems num_heads = 1 if test else FLAGS.num_mems num_blocks = 1 if test else FLAGS.nu...
python
def build_and_train(iterations, log_stride, test=False): """Construct the data, model, loss and optimizer then train.""" # Test mode settings. batch_size = 2 if test else FLAGS.batch_size num_mems = 2 if test else FLAGS.num_mems num_heads = 1 if test else FLAGS.num_mems num_blocks = 1 if test else FLAGS.nu...
[ "def", "build_and_train", "(", "iterations", ",", "log_stride", ",", "test", "=", "False", ")", ":", "# Test mode settings.", "batch_size", "=", "2", "if", "test", "else", "FLAGS", ".", "batch_size", "num_mems", "=", "2", "if", "test", "else", "FLAGS", ".", ...
Construct the data, model, loss and optimizer then train.
[ "Construct", "the", "data", "model", "loss", "and", "optimizer", "then", "train", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/rmc_nth_farthest.py#L93-L202
train
deepmind/sonnet
sonnet/examples/rmc_nth_farthest.py
SequenceModel._build
def _build(self, inputs): """Dynamic unroll across input objects. Args: inputs: tensor (batch x num_objects x feature). Objects to sort. Returns: Tensor (batch x num_objects); logits indicating the reference objects. """ batch_size = inputs.get_shape()[0] output_sequence, _ = tf.nn...
python
def _build(self, inputs): """Dynamic unroll across input objects. Args: inputs: tensor (batch x num_objects x feature). Objects to sort. Returns: Tensor (batch x num_objects); logits indicating the reference objects. """ batch_size = inputs.get_shape()[0] output_sequence, _ = tf.nn...
[ "def", "_build", "(", "self", ",", "inputs", ")", ":", "batch_size", "=", "inputs", ".", "get_shape", "(", ")", "[", "0", "]", "output_sequence", ",", "_", "=", "tf", ".", "nn", ".", "dynamic_rnn", "(", "cell", "=", "self", ".", "_core", ",", "inpu...
Dynamic unroll across input objects. Args: inputs: tensor (batch x num_objects x feature). Objects to sort. Returns: Tensor (batch x num_objects); logits indicating the reference objects.
[ "Dynamic", "unroll", "across", "input", "objects", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/rmc_nth_farthest.py#L70-L90
train
deepmind/sonnet
sonnet/python/modules/clip_gradient.py
_clip_gradient_op
def _clip_gradient_op(dtype): """Create an op that clips gradients using a Defun. The tensorflow Defun decorator creates an op and tensorflow caches these op automatically according to `func_name`. Using a Defun decorator twice with the same `func_name` does not create a new op, instead the cached op is used. ...
python
def _clip_gradient_op(dtype): """Create an op that clips gradients using a Defun. The tensorflow Defun decorator creates an op and tensorflow caches these op automatically according to `func_name`. Using a Defun decorator twice with the same `func_name` does not create a new op, instead the cached op is used. ...
[ "def", "_clip_gradient_op", "(", "dtype", ")", ":", "def", "clip_gradient_backward", "(", "op", ",", "grad", ")", ":", "clip_value_min", "=", "op", ".", "inputs", "[", "1", "]", "clip_value_max", "=", "op", ".", "inputs", "[", "2", "]", "clipped_grad", "...
Create an op that clips gradients using a Defun. The tensorflow Defun decorator creates an op and tensorflow caches these op automatically according to `func_name`. Using a Defun decorator twice with the same `func_name` does not create a new op, instead the cached op is used. This method produces a new op th...
[ "Create", "an", "op", "that", "clips", "gradients", "using", "a", "Defun", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/clip_gradient.py#L25-L59
train
deepmind/sonnet
sonnet/python/modules/clip_gradient.py
clip_gradient
def clip_gradient(net, clip_value_min, clip_value_max, name=None): """Clips respective gradients of a given tensor. Acts as identity for the forward pass, but clips gradient tensor element-wise by value during the backward pass. Any gradient values less than `clip_value_min` or greater than `clip_values_max` a...
python
def clip_gradient(net, clip_value_min, clip_value_max, name=None): """Clips respective gradients of a given tensor. Acts as identity for the forward pass, but clips gradient tensor element-wise by value during the backward pass. Any gradient values less than `clip_value_min` or greater than `clip_values_max` a...
[ "def", "clip_gradient", "(", "net", ",", "clip_value_min", ",", "clip_value_max", ",", "name", "=", "None", ")", ":", "if", "not", "net", ".", "dtype", ".", "is_floating", ":", "raise", "ValueError", "(", "\"clip_gradient does not support non-float `net` inputs.\"",...
Clips respective gradients of a given tensor. Acts as identity for the forward pass, but clips gradient tensor element-wise by value during the backward pass. Any gradient values less than `clip_value_min` or greater than `clip_values_max` are set to the respective limit values. Args: net: A `tf.Tensor`...
[ "Clips", "respective", "gradients", "of", "a", "given", "tensor", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/clip_gradient.py#L62-L94
train
deepmind/sonnet
sonnet/examples/ptb_reader.py
ptb_raw_data
def ptb_raw_data(data_path): """Load PTB raw data from data directory "data_path". Reads PTB text files, converts strings to integer ids, and performs mini-batching of the inputs. The PTB dataset comes from Tomas Mikolov's webpage: http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz Args: da...
python
def ptb_raw_data(data_path): """Load PTB raw data from data directory "data_path". Reads PTB text files, converts strings to integer ids, and performs mini-batching of the inputs. The PTB dataset comes from Tomas Mikolov's webpage: http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz Args: da...
[ "def", "ptb_raw_data", "(", "data_path", ")", ":", "train_path", "=", "os", ".", "path", ".", "join", "(", "data_path", ",", "\"ptb.train.txt\"", ")", "valid_path", "=", "os", ".", "path", ".", "join", "(", "data_path", ",", "\"ptb.valid.txt\"", ")", "test...
Load PTB raw data from data directory "data_path". Reads PTB text files, converts strings to integer ids, and performs mini-batching of the inputs. The PTB dataset comes from Tomas Mikolov's webpage: http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz Args: data_path: string path to the direct...
[ "Load", "PTB", "raw", "data", "from", "data", "directory", "data_path", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/ptb_reader.py#L55-L82
train
deepmind/sonnet
sonnet/python/modules/nets/convnet.py
ConvNet2D._check_and_assign_normalization_members
def _check_and_assign_normalization_members(self, normalization_ctor, normalization_kwargs): """Checks that the normalization constructor is callable.""" if isinstance(normalization_ctor, six.string_types): normalization_ctor = util.parse_string_to_constructor...
python
def _check_and_assign_normalization_members(self, normalization_ctor, normalization_kwargs): """Checks that the normalization constructor is callable.""" if isinstance(normalization_ctor, six.string_types): normalization_ctor = util.parse_string_to_constructor...
[ "def", "_check_and_assign_normalization_members", "(", "self", ",", "normalization_ctor", ",", "normalization_kwargs", ")", ":", "if", "isinstance", "(", "normalization_ctor", ",", "six", ".", "string_types", ")", ":", "normalization_ctor", "=", "util", ".", "parse_st...
Checks that the normalization constructor is callable.
[ "Checks", "that", "the", "normalization", "constructor", "is", "callable", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/convnet.py#L252-L262
train
deepmind/sonnet
sonnet/python/modules/nets/convnet.py
ConvNet2D._parse_normalization_kwargs
def _parse_normalization_kwargs(self, use_batch_norm, batch_norm_config, normalization_ctor, normalization_kwargs): """Sets up normalization, checking old and new flags.""" if use_batch_norm is not None: # Delete this whole block when deprecation is done. util.depre...
python
def _parse_normalization_kwargs(self, use_batch_norm, batch_norm_config, normalization_ctor, normalization_kwargs): """Sets up normalization, checking old and new flags.""" if use_batch_norm is not None: # Delete this whole block when deprecation is done. util.depre...
[ "def", "_parse_normalization_kwargs", "(", "self", ",", "use_batch_norm", ",", "batch_norm_config", ",", "normalization_ctor", ",", "normalization_kwargs", ")", ":", "if", "use_batch_norm", "is", "not", "None", ":", "# Delete this whole block when deprecation is done.", "ut...
Sets up normalization, checking old and new flags.
[ "Sets", "up", "normalization", "checking", "old", "and", "new", "flags", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/convnet.py#L264-L286
train
deepmind/sonnet
sonnet/python/modules/nets/convnet.py
ConvNet2D._instantiate_layers
def _instantiate_layers(self): """Instantiates all the convolutional modules used in the network.""" # Here we are entering the module's variable scope to name our submodules # correctly (not to create variables). As such it's safe to not check # whether we're in the same graph. This is important if we...
python
def _instantiate_layers(self): """Instantiates all the convolutional modules used in the network.""" # Here we are entering the module's variable scope to name our submodules # correctly (not to create variables). As such it's safe to not check # whether we're in the same graph. This is important if we...
[ "def", "_instantiate_layers", "(", "self", ")", ":", "# Here we are entering the module's variable scope to name our submodules", "# correctly (not to create variables). As such it's safe to not check", "# whether we're in the same graph. This is important if we're constructing", "# the module in ...
Instantiates all the convolutional modules used in the network.
[ "Instantiates", "all", "the", "convolutional", "modules", "used", "in", "the", "network", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/convnet.py#L288-L309
train
deepmind/sonnet
sonnet/python/modules/nets/convnet.py
ConvNet2D._build
def _build(self, inputs, **normalization_build_kwargs): """Assembles the `ConvNet2D` and connects it to the graph. Args: inputs: A 4D Tensor of shape `[batch_size, input_height, input_width, input_channels]`. **normalization_build_kwargs: kwargs passed to the normalization module at...
python
def _build(self, inputs, **normalization_build_kwargs): """Assembles the `ConvNet2D` and connects it to the graph. Args: inputs: A 4D Tensor of shape `[batch_size, input_height, input_width, input_channels]`. **normalization_build_kwargs: kwargs passed to the normalization module at...
[ "def", "_build", "(", "self", ",", "inputs", ",", "*", "*", "normalization_build_kwargs", ")", ":", "if", "(", "self", ".", "_normalization_ctor", "in", "{", "batch_norm", ".", "BatchNorm", ",", "batch_norm_v2", ".", "BatchNormV2", "}", "and", "\"is_training\"...
Assembles the `ConvNet2D` and connects it to the graph. Args: inputs: A 4D Tensor of shape `[batch_size, input_height, input_width, input_channels]`. **normalization_build_kwargs: kwargs passed to the normalization module at _build time. Returns: A 4D Tensor of shape `[batch_...
[ "Assembles", "the", "ConvNet2D", "and", "connects", "it", "to", "the", "graph", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/convnet.py#L311-L361
train
deepmind/sonnet
sonnet/python/modules/nets/convnet.py
ConvNet2D._transpose
def _transpose(self, transpose_constructor, name=None, output_channels=None, kernel_shapes=None, strides=None, paddings=None, activation=None, activate_final=None, nor...
python
def _transpose(self, transpose_constructor, name=None, output_channels=None, kernel_shapes=None, strides=None, paddings=None, activation=None, activate_final=None, nor...
[ "def", "_transpose", "(", "self", ",", "transpose_constructor", ",", "name", "=", "None", ",", "output_channels", "=", "None", ",", "kernel_shapes", "=", "None", ",", "strides", "=", "None", ",", "paddings", "=", "None", ",", "activation", "=", "None", ","...
Returns transposed version of this network. Args: transpose_constructor: A method that creates an instance of the transposed network type. The method must accept the same kwargs as this methods with the exception of the `transpose_constructor` argument. name: Optional string specifying ...
[ "Returns", "transposed", "version", "of", "this", "network", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/convnet.py#L445-L585
train
deepmind/sonnet
sonnet/python/modules/nets/convnet.py
ConvNet2D.transpose
def transpose(self, name=None, output_channels=None, kernel_shapes=None, strides=None, paddings=None, activation=None, activate_final=None, normalization_ctor=None, normalizati...
python
def transpose(self, name=None, output_channels=None, kernel_shapes=None, strides=None, paddings=None, activation=None, activate_final=None, normalization_ctor=None, normalizati...
[ "def", "transpose", "(", "self", ",", "name", "=", "None", ",", "output_channels", "=", "None", ",", "kernel_shapes", "=", "None", ",", "strides", "=", "None", ",", "paddings", "=", "None", ",", "activation", "=", "None", ",", "activate_final", "=", "Non...
Returns transposed version of this network. Args: name: Optional string specifying the name of the transposed module. The default name is constructed by appending "_transpose" to `self.module_name`. output_channels: Optional iterable of numbers of output channels. kernel_shapes: O...
[ "Returns", "transposed", "version", "of", "this", "network", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/convnet.py#L588-L712
train
deepmind/sonnet
sonnet/python/modules/nets/convnet.py
ConvNet2DTranspose.transpose
def transpose(self, name=None, output_channels=None, kernel_shapes=None, strides=None, paddings=None, activation=None, activate_final=None, normalization_ctor=None, normalizati...
python
def transpose(self, name=None, output_channels=None, kernel_shapes=None, strides=None, paddings=None, activation=None, activate_final=None, normalization_ctor=None, normalizati...
[ "def", "transpose", "(", "self", ",", "name", "=", "None", ",", "output_channels", "=", "None", ",", "kernel_shapes", "=", "None", ",", "strides", "=", "None", ",", "paddings", "=", "None", ",", "activation", "=", "None", ",", "activate_final", "=", "Non...
Returns transposed version of this network. Args: name: Optional string specifying the name of the transposed module. The default name is constructed by appending "_transpose" to `self.module_name`. output_channels: Optional iterable of numbers of output channels. kernel_shapes: O...
[ "Returns", "transposed", "version", "of", "this", "network", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/convnet.py#L880-L994
train
deepmind/sonnet
sonnet/examples/brnn_ptb.py
_get_raw_data
def _get_raw_data(subset): """Loads the data or reads it from cache.""" raw_data = _LOADED.get(subset) if raw_data is not None: return raw_data, _LOADED["vocab"] else: train_data, valid_data, test_data, vocab = ptb_reader.ptb_raw_data( FLAGS.data_path) _LOADED.update({ "train": np.ar...
python
def _get_raw_data(subset): """Loads the data or reads it from cache.""" raw_data = _LOADED.get(subset) if raw_data is not None: return raw_data, _LOADED["vocab"] else: train_data, valid_data, test_data, vocab = ptb_reader.ptb_raw_data( FLAGS.data_path) _LOADED.update({ "train": np.ar...
[ "def", "_get_raw_data", "(", "subset", ")", ":", "raw_data", "=", "_LOADED", ".", "get", "(", "subset", ")", "if", "raw_data", "is", "not", "None", ":", "return", "raw_data", ",", "_LOADED", "[", "\"vocab\"", "]", "else", ":", "train_data", ",", "valid_d...
Loads the data or reads it from cache.
[ "Loads", "the", "data", "or", "reads", "it", "from", "cache", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/brnn_ptb.py#L89-L103
train
deepmind/sonnet
sonnet/examples/brnn_ptb.py
custom_scale_mixture_prior_builder
def custom_scale_mixture_prior_builder(getter, name, *args, **kwargs): """A builder for the gaussian scale-mixture prior of Fortunato et al. Please see https://arxiv.org/abs/1704.02798, section 7.1 Args: getter: The `getter` passed to a `custom_getter`. Please see the documentation for `tf.get_variabl...
python
def custom_scale_mixture_prior_builder(getter, name, *args, **kwargs): """A builder for the gaussian scale-mixture prior of Fortunato et al. Please see https://arxiv.org/abs/1704.02798, section 7.1 Args: getter: The `getter` passed to a `custom_getter`. Please see the documentation for `tf.get_variabl...
[ "def", "custom_scale_mixture_prior_builder", "(", "getter", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# This specific prior formulation doesn't need any of the arguments forwarded", "# from `get_variable`.", "del", "getter", "del", "name", "del", ...
A builder for the gaussian scale-mixture prior of Fortunato et al. Please see https://arxiv.org/abs/1704.02798, section 7.1 Args: getter: The `getter` passed to a `custom_getter`. Please see the documentation for `tf.get_variable`. name: The `name` argument passed to `tf.get_variable`. *args: Po...
[ "A", "builder", "for", "the", "gaussian", "scale", "-", "mixture", "prior", "of", "Fortunato", "et", "al", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/brnn_ptb.py#L181-L204
train
deepmind/sonnet
sonnet/examples/brnn_ptb.py
lstm_posterior_builder
def lstm_posterior_builder(getter, name, *args, **kwargs): """A builder for a particular diagonal gaussian posterior. Args: getter: The `getter` passed to a `custom_getter`. Please see the documentation for `tf.get_variable`. name: The `name` argument passed to `tf.get_variable`. *args: Positiona...
python
def lstm_posterior_builder(getter, name, *args, **kwargs): """A builder for a particular diagonal gaussian posterior. Args: getter: The `getter` passed to a `custom_getter`. Please see the documentation for `tf.get_variable`. name: The `name` argument passed to `tf.get_variable`. *args: Positiona...
[ "def", "lstm_posterior_builder", "(", "getter", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "del", "args", "parameter_shapes", "=", "tfp", ".", "distributions", ".", "Normal", ".", "param_static_shapes", "(", "kwargs", "[", "\"shape\"",...
A builder for a particular diagonal gaussian posterior. Args: getter: The `getter` passed to a `custom_getter`. Please see the documentation for `tf.get_variable`. name: The `name` argument passed to `tf.get_variable`. *args: Positional arguments forwarded by `tf.get_variable`. **kwargs: Keywor...
[ "A", "builder", "for", "a", "particular", "diagonal", "gaussian", "posterior", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/brnn_ptb.py#L207-L245
train
deepmind/sonnet
sonnet/examples/brnn_ptb.py
build_modules
def build_modules(is_training, vocab_size): """Construct the modules used in the graph.""" # Construct the custom getter which implements Bayes by Backprop. if is_training: estimator_mode = tf.constant(bbb.EstimatorModes.sample) else: estimator_mode = tf.constant(bbb.EstimatorModes.mean) lstm_bbb_cus...
python
def build_modules(is_training, vocab_size): """Construct the modules used in the graph.""" # Construct the custom getter which implements Bayes by Backprop. if is_training: estimator_mode = tf.constant(bbb.EstimatorModes.sample) else: estimator_mode = tf.constant(bbb.EstimatorModes.mean) lstm_bbb_cus...
[ "def", "build_modules", "(", "is_training", ",", "vocab_size", ")", ":", "# Construct the custom getter which implements Bayes by Backprop.", "if", "is_training", ":", "estimator_mode", "=", "tf", ".", "constant", "(", "bbb", ".", "EstimatorModes", ".", "sample", ")", ...
Construct the modules used in the graph.
[ "Construct", "the", "modules", "used", "in", "the", "graph", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/brnn_ptb.py#L289-L330
train
deepmind/sonnet
sonnet/examples/brnn_ptb.py
build_logits
def build_logits(data_ops, embed_layer, rnn_core, output_linear, name_prefix): """This is the core model logic. Unrolls a Bayesian RNN over the given sequence. Args: data_ops: A `sequence_data.SequenceDataOps` namedtuple. embed_layer: A `snt.Embed` instance. rnn_core: A `snt.RNNCore` instance. o...
python
def build_logits(data_ops, embed_layer, rnn_core, output_linear, name_prefix): """This is the core model logic. Unrolls a Bayesian RNN over the given sequence. Args: data_ops: A `sequence_data.SequenceDataOps` namedtuple. embed_layer: A `snt.Embed` instance. rnn_core: A `snt.RNNCore` instance. o...
[ "def", "build_logits", "(", "data_ops", ",", "embed_layer", ",", "rnn_core", ",", "output_linear", ",", "name_prefix", ")", ":", "# Embed the input index sequence.", "embedded_input_seq", "=", "snt", ".", "BatchApply", "(", "embed_layer", ",", "name", "=", "\"input_...
This is the core model logic. Unrolls a Bayesian RNN over the given sequence. Args: data_ops: A `sequence_data.SequenceDataOps` namedtuple. embed_layer: A `snt.Embed` instance. rnn_core: A `snt.RNNCore` instance. output_linear: A `snt.Linear` instance. name_prefix: A string to use to prefix lo...
[ "This", "is", "the", "core", "model", "logic", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/brnn_ptb.py#L333-L376
train
deepmind/sonnet
sonnet/examples/brnn_ptb.py
build_loss
def build_loss(model_logits, sparse_targets): """Compute the log loss given predictions and targets.""" time_major_shape = [FLAGS.unroll_steps, FLAGS.batch_size] flat_batch_shape = [FLAGS.unroll_steps * FLAGS.batch_size, -1] xent = tf.nn.sparse_softmax_cross_entropy_with_logits( logits=tf.reshape(model_lo...
python
def build_loss(model_logits, sparse_targets): """Compute the log loss given predictions and targets.""" time_major_shape = [FLAGS.unroll_steps, FLAGS.batch_size] flat_batch_shape = [FLAGS.unroll_steps * FLAGS.batch_size, -1] xent = tf.nn.sparse_softmax_cross_entropy_with_logits( logits=tf.reshape(model_lo...
[ "def", "build_loss", "(", "model_logits", ",", "sparse_targets", ")", ":", "time_major_shape", "=", "[", "FLAGS", ".", "unroll_steps", ",", "FLAGS", ".", "batch_size", "]", "flat_batch_shape", "=", "[", "FLAGS", ".", "unroll_steps", "*", "FLAGS", ".", "batch_s...
Compute the log loss given predictions and targets.
[ "Compute", "the", "log", "loss", "given", "predictions", "and", "targets", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/brnn_ptb.py#L379-L390
train
deepmind/sonnet
sonnet/examples/brnn_ptb.py
train
def train(logdir): """Run a network on the PTB training set, checkpointing the weights.""" ptb_train = PTB( name="ptb_train", subset="train", seq_len=FLAGS.unroll_steps, batch_size=FLAGS.batch_size) # Connect to training set. data_ops = ptb_train() embed_layer, rnn_core, output_linea...
python
def train(logdir): """Run a network on the PTB training set, checkpointing the weights.""" ptb_train = PTB( name="ptb_train", subset="train", seq_len=FLAGS.unroll_steps, batch_size=FLAGS.batch_size) # Connect to training set. data_ops = ptb_train() embed_layer, rnn_core, output_linea...
[ "def", "train", "(", "logdir", ")", ":", "ptb_train", "=", "PTB", "(", "name", "=", "\"ptb_train\"", ",", "subset", "=", "\"train\"", ",", "seq_len", "=", "FLAGS", ".", "unroll_steps", ",", "batch_size", "=", "FLAGS", ".", "batch_size", ")", "# Connect to ...
Run a network on the PTB training set, checkpointing the weights.
[ "Run", "a", "network", "on", "the", "PTB", "training", "set", "checkpointing", "the", "weights", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/brnn_ptb.py#L393-L541
train
deepmind/sonnet
sonnet/__init__.py
_ensure_dependency_available_at_version
def _ensure_dependency_available_at_version(package_name, min_version): """Throw helpful error if required dependencies not available.""" try: pkg = importlib.import_module(package_name) except ImportError: pip_name = package_name.replace('_', '-') raise SystemError( 'Sonnet requires %s (mini...
python
def _ensure_dependency_available_at_version(package_name, min_version): """Throw helpful error if required dependencies not available.""" try: pkg = importlib.import_module(package_name) except ImportError: pip_name = package_name.replace('_', '-') raise SystemError( 'Sonnet requires %s (mini...
[ "def", "_ensure_dependency_available_at_version", "(", "package_name", ",", "min_version", ")", ":", "try", ":", "pkg", "=", "importlib", ".", "import_module", "(", "package_name", ")", "except", "ImportError", ":", "pip_name", "=", "package_name", ".", "replace", ...
Throw helpful error if required dependencies not available.
[ "Throw", "helpful", "error", "if", "required", "dependencies", "not", "available", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/__init__.py#L43-L61
train
deepmind/sonnet
sonnet/python/modules/scale_gradient.py
_scale_gradient_op
def _scale_gradient_op(dtype): """Create an op that scales gradients using a Defun. The tensorflow Defun decorator creates an op and tensorflow caches these ops automatically according to `func_name`. Using a Defun decorator twice with the same `func_name` does not create a new op, instead the cached op is use...
python
def _scale_gradient_op(dtype): """Create an op that scales gradients using a Defun. The tensorflow Defun decorator creates an op and tensorflow caches these ops automatically according to `func_name`. Using a Defun decorator twice with the same `func_name` does not create a new op, instead the cached op is use...
[ "def", "_scale_gradient_op", "(", "dtype", ")", ":", "def", "scale_gradient_backward", "(", "op", ",", "grad", ")", ":", "scale", "=", "op", ".", "inputs", "[", "1", "]", "scaled_grad", "=", "grad", "*", "scale", "return", "scaled_grad", ",", "None", "# ...
Create an op that scales gradients using a Defun. The tensorflow Defun decorator creates an op and tensorflow caches these ops automatically according to `func_name`. Using a Defun decorator twice with the same `func_name` does not create a new op, instead the cached op is used. This method produces a new op ...
[ "Create", "an", "op", "that", "scales", "gradients", "using", "a", "Defun", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/scale_gradient.py#L27-L61
train
deepmind/sonnet
sonnet/python/modules/scale_gradient.py
scale_gradient
def scale_gradient(net, scale, name="scale_gradient"): """Scales gradients for the backwards pass. This might be used to, for example, allow one part of a model to learn at a lower rate than the rest. WARNING: Think carefully about how your optimizer works. If, for example, you use rmsprop, the gradient is ...
python
def scale_gradient(net, scale, name="scale_gradient"): """Scales gradients for the backwards pass. This might be used to, for example, allow one part of a model to learn at a lower rate than the rest. WARNING: Think carefully about how your optimizer works. If, for example, you use rmsprop, the gradient is ...
[ "def", "scale_gradient", "(", "net", ",", "scale", ",", "name", "=", "\"scale_gradient\"", ")", ":", "if", "tf", ".", "executing_eagerly", "(", ")", ":", "if", "not", "callable", "(", "net", ")", ":", "raise", "ValueError", "(", "\"In eager mode `net` must b...
Scales gradients for the backwards pass. This might be used to, for example, allow one part of a model to learn at a lower rate than the rest. WARNING: Think carefully about how your optimizer works. If, for example, you use rmsprop, the gradient is always rescaled (with some additional epsilon) towards uni...
[ "Scales", "gradients", "for", "the", "backwards", "pass", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/scale_gradient.py#L64-L113
train
deepmind/sonnet
sonnet/examples/rmc_learn_to_execute.py
build_and_train
def build_and_train(iterations, log_stride, test=False): """Construct the data, model, loss and optimizer then train.""" # Test mode settings. batch_size = 2 if test else FLAGS.batch_size num_mems = 2 if test else FLAGS.num_mems num_heads = 1 if test else FLAGS.num_mems num_blocks = 1 if test else FLAGS.nu...
python
def build_and_train(iterations, log_stride, test=False): """Construct the data, model, loss and optimizer then train.""" # Test mode settings. batch_size = 2 if test else FLAGS.batch_size num_mems = 2 if test else FLAGS.num_mems num_heads = 1 if test else FLAGS.num_mems num_blocks = 1 if test else FLAGS.nu...
[ "def", "build_and_train", "(", "iterations", ",", "log_stride", ",", "test", "=", "False", ")", ":", "# Test mode settings.", "batch_size", "=", "2", "if", "test", "else", "FLAGS", ".", "batch_size", "num_mems", "=", "2", "if", "test", "else", "FLAGS", ".", ...
Construct the data, model, loss and optimizer then train.
[ "Construct", "the", "data", "model", "loss", "and", "optimizer", "then", "train", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/rmc_learn_to_execute.py#L110-L227
train
deepmind/sonnet
sonnet/examples/rmc_learn_to_execute.py
SequenceModel._build
def _build( self, inputs, targets, input_sequence_length, output_sequence_length): """Dynamic unroll across input objects. Args: inputs: tensor (input_sequence_length x batch x feature_size). Encoder sequence. targets: tensor (output_sequence_length x batch x feature_size). Decoder ...
python
def _build( self, inputs, targets, input_sequence_length, output_sequence_length): """Dynamic unroll across input objects. Args: inputs: tensor (input_sequence_length x batch x feature_size). Encoder sequence. targets: tensor (output_sequence_length x batch x feature_size). Decoder ...
[ "def", "_build", "(", "self", ",", "inputs", ",", "targets", ",", "input_sequence_length", ",", "output_sequence_length", ")", ":", "# Connect decoding steps.", "batch_size", "=", "inputs", ".", "get_shape", "(", ")", "[", "1", "]", "initial_state", "=", "self",...
Dynamic unroll across input objects. Args: inputs: tensor (input_sequence_length x batch x feature_size). Encoder sequence. targets: tensor (output_sequence_length x batch x feature_size). Decoder sequence. input_sequence_length: tensor (batch). Size of each batched input ...
[ "Dynamic", "unroll", "across", "input", "objects", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/rmc_learn_to_execute.py#L69-L107
train
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
lstm_with_recurrent_dropout
def lstm_with_recurrent_dropout(hidden_size, keep_prob=0.5, **kwargs): """LSTM with recurrent dropout. Args: hidden_size: the LSTM hidden size. keep_prob: the probability to keep an entry when applying dropout. **kwargs: Extra keyword arguments to pass to the LSTM. Returns: A tuple (train_lstm, ...
python
def lstm_with_recurrent_dropout(hidden_size, keep_prob=0.5, **kwargs): """LSTM with recurrent dropout. Args: hidden_size: the LSTM hidden size. keep_prob: the probability to keep an entry when applying dropout. **kwargs: Extra keyword arguments to pass to the LSTM. Returns: A tuple (train_lstm, ...
[ "def", "lstm_with_recurrent_dropout", "(", "hidden_size", ",", "keep_prob", "=", "0.5", ",", "*", "*", "kwargs", ")", ":", "lstm", "=", "LSTM", "(", "hidden_size", ",", "*", "*", "kwargs", ")", "return", "RecurrentDropoutWrapper", "(", "lstm", ",", "LSTMStat...
LSTM with recurrent dropout. Args: hidden_size: the LSTM hidden size. keep_prob: the probability to keep an entry when applying dropout. **kwargs: Extra keyword arguments to pass to the LSTM. Returns: A tuple (train_lstm, test_lstm) where train_lstm is an LSTM with recurrent dropout enabled to...
[ "LSTM", "with", "recurrent", "dropout", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L433-L448
train
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
lstm_with_zoneout
def lstm_with_zoneout(hidden_size, keep_prob_c=0.5, keep_prob_h=0.95, **kwargs): """LSTM with recurrent dropout. Args: hidden_size: the LSTM hidden size. keep_prob_c: the probability to use the new value of the cell state rather than freezing it. keep_prob_h: the probability to use the new value ...
python
def lstm_with_zoneout(hidden_size, keep_prob_c=0.5, keep_prob_h=0.95, **kwargs): """LSTM with recurrent dropout. Args: hidden_size: the LSTM hidden size. keep_prob_c: the probability to use the new value of the cell state rather than freezing it. keep_prob_h: the probability to use the new value ...
[ "def", "lstm_with_zoneout", "(", "hidden_size", ",", "keep_prob_c", "=", "0.5", ",", "keep_prob_h", "=", "0.95", ",", "*", "*", "kwargs", ")", ":", "lstm", "=", "LSTM", "(", "hidden_size", ",", "*", "*", "kwargs", ")", "keep_probs", "=", "LSTMState", "("...
LSTM with recurrent dropout. Args: hidden_size: the LSTM hidden size. keep_prob_c: the probability to use the new value of the cell state rather than freezing it. keep_prob_h: the probability to use the new value of the hidden state rather than freezing it. **kwargs: Extra keyword argumen...
[ "LSTM", "with", "recurrent", "dropout", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L519-L540
train
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
highway_core_with_recurrent_dropout
def highway_core_with_recurrent_dropout( hidden_size, num_layers, keep_prob=0.5, **kwargs): """Highway core with recurrent dropout. Args: hidden_size: (int) Hidden size dimensionality. num_layers: (int) Number of highway layers. keep_prob: the probability to keep an entry when applying ...
python
def highway_core_with_recurrent_dropout( hidden_size, num_layers, keep_prob=0.5, **kwargs): """Highway core with recurrent dropout. Args: hidden_size: (int) Hidden size dimensionality. num_layers: (int) Number of highway layers. keep_prob: the probability to keep an entry when applying ...
[ "def", "highway_core_with_recurrent_dropout", "(", "hidden_size", ",", "num_layers", ",", "keep_prob", "=", "0.5", ",", "*", "*", "kwargs", ")", ":", "core", "=", "HighwayCore", "(", "hidden_size", ",", "num_layers", ",", "*", "*", "kwargs", ")", "return", "...
Highway core with recurrent dropout. Args: hidden_size: (int) Hidden size dimensionality. num_layers: (int) Number of highway layers. keep_prob: the probability to keep an entry when applying dropout. **kwargs: Extra keyword arguments to pass to the highway core. Returns: A tuple (train_core, ...
[ "Highway", "core", "with", "recurrent", "dropout", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L1748-L1768
train
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
LSTM.get_possible_initializer_keys
def get_possible_initializer_keys(cls, use_peepholes=False, use_projection=False): """Returns the keys the dictionary of variable initializers may contain. The set of all possible initializer keys are: w_gates: weight for gates b_gates: bias of gates w_f_...
python
def get_possible_initializer_keys(cls, use_peepholes=False, use_projection=False): """Returns the keys the dictionary of variable initializers may contain. The set of all possible initializer keys are: w_gates: weight for gates b_gates: bias of gates w_f_...
[ "def", "get_possible_initializer_keys", "(", "cls", ",", "use_peepholes", "=", "False", ",", "use_projection", "=", "False", ")", ":", "possible_keys", "=", "cls", ".", "POSSIBLE_INITIALIZER_KEYS", ".", "copy", "(", ")", "if", "not", "use_peepholes", ":", "possi...
Returns the keys the dictionary of variable initializers may contain. The set of all possible initializer keys are: w_gates: weight for gates b_gates: bias of gates w_f_diag: weight for prev_cell -> forget gate peephole w_i_diag: weight for prev_cell -> input gate peephole w_o_diag:...
[ "Returns", "the", "keys", "the", "dictionary", "of", "variable", "initializers", "may", "contain", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L178-L207
train
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
LSTM._build
def _build(self, inputs, prev_state): """Connects the LSTM module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as inputs and state must have the same final dimension, in order for the existing variables to be the correct size for the...
python
def _build(self, inputs, prev_state): """Connects the LSTM module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as inputs and state must have the same final dimension, in order for the existing variables to be the correct size for the...
[ "def", "_build", "(", "self", ",", "inputs", ",", "prev_state", ")", ":", "prev_hidden", ",", "prev_cell", "=", "prev_state", "# pylint: disable=invalid-unary-operand-type", "if", "self", ".", "_hidden_clip_value", "is", "not", "None", ":", "prev_hidden", "=", "tf...
Connects the LSTM module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as inputs and state must have the same final dimension, in order for the existing variables to be the correct size for their corresponding multiplications. The batch s...
[ "Connects", "the", "LSTM", "module", "into", "the", "graph", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L209-L276
train
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
LSTM._create_gate_variables
def _create_gate_variables(self, input_shape, dtype): """Initialize the variables used for the gates.""" if len(input_shape) != 2: raise ValueError( "Rank of shape must be {} not: {}".format(2, len(input_shape))) equiv_input_size = self._hidden_state_size + input_shape.dims[1].value ini...
python
def _create_gate_variables(self, input_shape, dtype): """Initialize the variables used for the gates.""" if len(input_shape) != 2: raise ValueError( "Rank of shape must be {} not: {}".format(2, len(input_shape))) equiv_input_size = self._hidden_state_size + input_shape.dims[1].value ini...
[ "def", "_create_gate_variables", "(", "self", ",", "input_shape", ",", "dtype", ")", ":", "if", "len", "(", "input_shape", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"Rank of shape must be {} not: {}\"", ".", "format", "(", "2", ",", "len", "(", "inp...
Initialize the variables used for the gates.
[ "Initialize", "the", "variables", "used", "for", "the", "gates", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L278-L310
train
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
LSTM._create_peephole_variables
def _create_peephole_variables(self, dtype): """Initialize the variables used for the peephole connections.""" self._w_f_diag = tf.get_variable( self.W_F_DIAG, shape=[self._hidden_size], dtype=dtype, initializer=self._initializers.get(self.W_F_DIAG), partitioner=self._par...
python
def _create_peephole_variables(self, dtype): """Initialize the variables used for the peephole connections.""" self._w_f_diag = tf.get_variable( self.W_F_DIAG, shape=[self._hidden_size], dtype=dtype, initializer=self._initializers.get(self.W_F_DIAG), partitioner=self._par...
[ "def", "_create_peephole_variables", "(", "self", ",", "dtype", ")", ":", "self", ".", "_w_f_diag", "=", "tf", ".", "get_variable", "(", "self", ".", "W_F_DIAG", ",", "shape", "=", "[", "self", ".", "_hidden_size", "]", ",", "dtype", "=", "dtype", ",", ...
Initialize the variables used for the peephole connections.
[ "Initialize", "the", "variables", "used", "for", "the", "peephole", "connections", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L312-L334
train
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
LSTM.state_size
def state_size(self): """Tuple of `tf.TensorShape`s indicating the size of state tensors.""" return LSTMState(tf.TensorShape([self._hidden_state_size]), tf.TensorShape([self._hidden_size]))
python
def state_size(self): """Tuple of `tf.TensorShape`s indicating the size of state tensors.""" return LSTMState(tf.TensorShape([self._hidden_state_size]), tf.TensorShape([self._hidden_size]))
[ "def", "state_size", "(", "self", ")", ":", "return", "LSTMState", "(", "tf", ".", "TensorShape", "(", "[", "self", ".", "_hidden_state_size", "]", ")", ",", "tf", ".", "TensorShape", "(", "[", "self", ".", "_hidden_size", "]", ")", ")" ]
Tuple of `tf.TensorShape`s indicating the size of state tensors.
[ "Tuple", "of", "tf", ".", "TensorShape", "s", "indicating", "the", "size", "of", "state", "tensors", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L337-L340
train
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
RecurrentDropoutWrapper.initial_state
def initial_state(self, batch_size, dtype=tf.float32, trainable=False, trainable_initializers=None, trainable_regularizers=None, name=None): """Builds the default start state tensor of zeros.""" core_initial_state = self._core.initial_state( batch_size, dtype=dtyp...
python
def initial_state(self, batch_size, dtype=tf.float32, trainable=False, trainable_initializers=None, trainable_regularizers=None, name=None): """Builds the default start state tensor of zeros.""" core_initial_state = self._core.initial_state( batch_size, dtype=dtyp...
[ "def", "initial_state", "(", "self", ",", "batch_size", ",", "dtype", "=", "tf", ".", "float32", ",", "trainable", "=", "False", ",", "trainable_initializers", "=", "None", ",", "trainable_regularizers", "=", "None", ",", "name", "=", "None", ")", ":", "co...
Builds the default start state tensor of zeros.
[ "Builds", "the", "default", "start", "state", "tensor", "of", "zeros", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L404-L422
train
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
ZoneoutWrapper.initial_state
def initial_state(self, batch_size, dtype=tf.float32, trainable=False, trainable_initializers=None, trainable_regularizers=None, name=None): """Builds the default start state tensor of zeros.""" return self._core.initial_state( batch_size, dtype=dtype, trainable=t...
python
def initial_state(self, batch_size, dtype=tf.float32, trainable=False, trainable_initializers=None, trainable_regularizers=None, name=None): """Builds the default start state tensor of zeros.""" return self._core.initial_state( batch_size, dtype=dtype, trainable=t...
[ "def", "initial_state", "(", "self", ",", "batch_size", ",", "dtype", "=", "tf", ".", "float32", ",", "trainable", "=", "False", ",", "trainable_initializers", "=", "None", ",", "trainable_regularizers", "=", "None", ",", "name", "=", "None", ")", ":", "re...
Builds the default start state tensor of zeros.
[ "Builds", "the", "default", "start", "state", "tensor", "of", "zeros", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L501-L508
train
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
BatchNormLSTM.with_batch_norm_control
def with_batch_norm_control(self, is_training, test_local_stats=True): """Wraps this RNNCore with the additional control input to the `BatchNorm`s. Example usage: lstm = snt.BatchNormLSTM(4) is_training = tf.placeholder(tf.bool) rnn_input = ... my_rnn = rnn.rnn(lstm.with_batch_norm_con...
python
def with_batch_norm_control(self, is_training, test_local_stats=True): """Wraps this RNNCore with the additional control input to the `BatchNorm`s. Example usage: lstm = snt.BatchNormLSTM(4) is_training = tf.placeholder(tf.bool) rnn_input = ... my_rnn = rnn.rnn(lstm.with_batch_norm_con...
[ "def", "with_batch_norm_control", "(", "self", ",", "is_training", ",", "test_local_stats", "=", "True", ")", ":", "return", "BatchNormLSTM", ".", "CoreWithExtraBuildArgs", "(", "self", ",", "is_training", "=", "is_training", ",", "test_local_stats", "=", "test_loca...
Wraps this RNNCore with the additional control input to the `BatchNorm`s. Example usage: lstm = snt.BatchNormLSTM(4) is_training = tf.placeholder(tf.bool) rnn_input = ... my_rnn = rnn.rnn(lstm.with_batch_norm_control(is_training), rnn_input) Args: is_training: Boolean that indic...
[ "Wraps", "this", "RNNCore", "with", "the", "additional", "control", "input", "to", "the", "BatchNorm", "s", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L742-L767
train
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
BatchNormLSTM.get_possible_initializer_keys
def get_possible_initializer_keys( cls, use_peepholes=False, use_batch_norm_h=True, use_batch_norm_x=False, use_batch_norm_c=False): """Returns the keys the dictionary of variable initializers may contain. The set of all possible initializer keys are: w_gates: weight for gates b_gates:...
python
def get_possible_initializer_keys( cls, use_peepholes=False, use_batch_norm_h=True, use_batch_norm_x=False, use_batch_norm_c=False): """Returns the keys the dictionary of variable initializers may contain. The set of all possible initializer keys are: w_gates: weight for gates b_gates:...
[ "def", "get_possible_initializer_keys", "(", "cls", ",", "use_peepholes", "=", "False", ",", "use_batch_norm_h", "=", "True", ",", "use_batch_norm_x", "=", "False", ",", "use_batch_norm_c", "=", "False", ")", ":", "possible_keys", "=", "cls", ".", "POSSIBLE_INITIA...
Returns the keys the dictionary of variable initializers may contain. The set of all possible initializer keys are: w_gates: weight for gates b_gates: bias of gates w_f_diag: weight for prev_cell -> forget gate peephole w_i_diag: weight for prev_cell -> input gate peephole w_o_diag:...
[ "Returns", "the", "keys", "the", "dictionary", "of", "variable", "initializers", "may", "contain", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L770-L814
train
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
BatchNormLSTM._build
def _build(self, inputs, prev_state, is_training=None, test_local_stats=True): """Connects the LSTM module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as inputs and state must have the same final dimension, in order for the existing var...
python
def _build(self, inputs, prev_state, is_training=None, test_local_stats=True): """Connects the LSTM module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as inputs and state must have the same final dimension, in order for the existing var...
[ "def", "_build", "(", "self", ",", "inputs", ",", "prev_state", ",", "is_training", "=", "None", ",", "test_local_stats", "=", "True", ")", ":", "if", "is_training", "is", "None", ":", "raise", "ValueError", "(", "\"Boolean is_training flag must be explicitly spec...
Connects the LSTM module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as inputs and state must have the same final dimension, in order for the existing variables to be the correct size for their corresponding multiplications. The batch s...
[ "Connects", "the", "LSTM", "module", "into", "the", "graph", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L816-L920
train
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
BatchNormLSTM._create_batch_norm_variables
def _create_batch_norm_variables(self, dtype): """Initialize the variables used for the `BatchNorm`s (if any).""" # The paper recommends a value of 0.1 for good gradient flow through the # tanh nonlinearity (although doesn't say whether this is for all gammas, # or just some). gamma_initializer = tf...
python
def _create_batch_norm_variables(self, dtype): """Initialize the variables used for the `BatchNorm`s (if any).""" # The paper recommends a value of 0.1 for good gradient flow through the # tanh nonlinearity (although doesn't say whether this is for all gammas, # or just some). gamma_initializer = tf...
[ "def", "_create_batch_norm_variables", "(", "self", ",", "dtype", ")", ":", "# The paper recommends a value of 0.1 for good gradient flow through the", "# tanh nonlinearity (although doesn't say whether this is for all gammas,", "# or just some).", "gamma_initializer", "=", "tf", ".", ...
Initialize the variables used for the `BatchNorm`s (if any).
[ "Initialize", "the", "variables", "used", "for", "the", "BatchNorm", "s", "(", "if", "any", ")", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L922-L959
train
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
BatchNormLSTM._create_gate_variables
def _create_gate_variables(self, input_shape, dtype): """Initialize the variables used for the gates.""" if len(input_shape) != 2: raise ValueError( "Rank of shape must be {} not: {}".format(2, len(input_shape))) input_size = input_shape.dims[1].value b_shape = [4 * self._hidden_size] ...
python
def _create_gate_variables(self, input_shape, dtype): """Initialize the variables used for the gates.""" if len(input_shape) != 2: raise ValueError( "Rank of shape must be {} not: {}".format(2, len(input_shape))) input_size = input_shape.dims[1].value b_shape = [4 * self._hidden_size] ...
[ "def", "_create_gate_variables", "(", "self", ",", "input_shape", ",", "dtype", ")", ":", "if", "len", "(", "input_shape", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"Rank of shape must be {} not: {}\"", ".", "format", "(", "2", ",", "len", "(", "inp...
Initialize the variables used for the gates.
[ "Initialize", "the", "variables", "used", "for", "the", "gates", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L961-L1002
train
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
BatchNormLSTM.initial_state
def initial_state(self, batch_size, dtype=tf.float32, trainable=False, trainable_initializers=None, trainable_regularizers=None, name=None): """Builds the default start state tensor of zeros. Args: batch_size: An int, float or scalar Tensor representing the batch s...
python
def initial_state(self, batch_size, dtype=tf.float32, trainable=False, trainable_initializers=None, trainable_regularizers=None, name=None): """Builds the default start state tensor of zeros. Args: batch_size: An int, float or scalar Tensor representing the batch s...
[ "def", "initial_state", "(", "self", ",", "batch_size", ",", "dtype", "=", "tf", ".", "float32", ",", "trainable", "=", "False", ",", "trainable_initializers", "=", "None", ",", "trainable_regularizers", "=", "None", ",", "name", "=", "None", ")", ":", "if...
Builds the default start state tensor of zeros. Args: batch_size: An int, float or scalar Tensor representing the batch size. dtype: The data type to use for the state. trainable: Boolean that indicates whether to learn the initial state. trainable_initializers: An optional pair of initiali...
[ "Builds", "the", "default", "start", "state", "tensor", "of", "zeros", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L1028-L1074
train
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
BatchNormLSTM.state_size
def state_size(self): """Tuple of `tf.TensorShape`s indicating the size of state tensors.""" if self._max_unique_stats == 1: return (tf.TensorShape([self._hidden_size]), tf.TensorShape([self._hidden_size])) else: return (tf.TensorShape([self._hidden_size]), tf.TensorS...
python
def state_size(self): """Tuple of `tf.TensorShape`s indicating the size of state tensors.""" if self._max_unique_stats == 1: return (tf.TensorShape([self._hidden_size]), tf.TensorShape([self._hidden_size])) else: return (tf.TensorShape([self._hidden_size]), tf.TensorS...
[ "def", "state_size", "(", "self", ")", ":", "if", "self", ".", "_max_unique_stats", "==", "1", ":", "return", "(", "tf", ".", "TensorShape", "(", "[", "self", ".", "_hidden_size", "]", ")", ",", "tf", ".", "TensorShape", "(", "[", "self", ".", "_hidd...
Tuple of `tf.TensorShape`s indicating the size of state tensors.
[ "Tuple", "of", "tf", ".", "TensorShape", "s", "indicating", "the", "size", "of", "state", "tensors", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L1077-L1085
train
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
ConvLSTM._new_convolution
def _new_convolution(self, use_bias): """Returns new convolution. Args: use_bias: Use bias in convolutions. If False, clean_dict removes bias entries from initializers, partitioners and regularizers passed to the constructor of the convolution. """ def clean_dict(input_dict): ...
python
def _new_convolution(self, use_bias): """Returns new convolution. Args: use_bias: Use bias in convolutions. If False, clean_dict removes bias entries from initializers, partitioners and regularizers passed to the constructor of the convolution. """ def clean_dict(input_dict): ...
[ "def", "_new_convolution", "(", "self", ",", "use_bias", ")", ":", "def", "clean_dict", "(", "input_dict", ")", ":", "if", "input_dict", "and", "not", "use_bias", ":", "cleaned_dict", "=", "input_dict", ".", "copy", "(", ")", "cleaned_dict", ".", "pop", "(...
Returns new convolution. Args: use_bias: Use bias in convolutions. If False, clean_dict removes bias entries from initializers, partitioners and regularizers passed to the constructor of the convolution.
[ "Returns", "new", "convolution", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L1321-L1345
train
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
ConvLSTM.state_size
def state_size(self): """Tuple of `tf.TensorShape`s indicating the size of state tensors.""" hidden_size = tf.TensorShape( self._input_shape[:-1] + (self._output_channels,)) return (hidden_size, hidden_size)
python
def state_size(self): """Tuple of `tf.TensorShape`s indicating the size of state tensors.""" hidden_size = tf.TensorShape( self._input_shape[:-1] + (self._output_channels,)) return (hidden_size, hidden_size)
[ "def", "state_size", "(", "self", ")", ":", "hidden_size", "=", "tf", ".", "TensorShape", "(", "self", ".", "_input_shape", "[", ":", "-", "1", "]", "+", "(", "self", ".", "_output_channels", ",", ")", ")", "return", "(", "hidden_size", ",", "hidden_si...
Tuple of `tf.TensorShape`s indicating the size of state tensors.
[ "Tuple", "of", "tf", ".", "TensorShape", "s", "indicating", "the", "size", "of", "state", "tensors", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L1352-L1356
train
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
GRU._build
def _build(self, inputs, prev_state): """Connects the GRU module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as inputs and state must have the same final dimension, in order for the existing variables to be the correct size for thei...
python
def _build(self, inputs, prev_state): """Connects the GRU module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as inputs and state must have the same final dimension, in order for the existing variables to be the correct size for thei...
[ "def", "_build", "(", "self", ",", "inputs", ",", "prev_state", ")", ":", "input_size", "=", "inputs", ".", "get_shape", "(", ")", "[", "1", "]", "weight_shape", "=", "(", "input_size", ",", "self", ".", "_hidden_size", ")", "u_shape", "=", "(", "self"...
Connects the GRU module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as inputs and state must have the same final dimension, in order for the existing variables to be the correct size for their corresponding multiplications. The batch si...
[ "Connects", "the", "GRU", "module", "into", "the", "graph", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L1509-L1583
train
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
HighwayCore.get_possible_initializer_keys
def get_possible_initializer_keys(cls, num_layers): """Returns the keys the dictionary of variable initializers may contain. The set of all possible initializer keys are: wt: weight for input -> T gate wh: weight for input -> H gate wtL: weight for prev state -> T gate for layer L (indexed fr...
python
def get_possible_initializer_keys(cls, num_layers): """Returns the keys the dictionary of variable initializers may contain. The set of all possible initializer keys are: wt: weight for input -> T gate wh: weight for input -> H gate wtL: weight for prev state -> T gate for layer L (indexed fr...
[ "def", "get_possible_initializer_keys", "(", "cls", ",", "num_layers", ")", ":", "keys", "=", "[", "cls", ".", "WT", ",", "cls", ".", "WH", "]", "for", "layer_index", "in", "xrange", "(", "num_layers", ")", ":", "layer_str", "=", "str", "(", "layer_index...
Returns the keys the dictionary of variable initializers may contain. The set of all possible initializer keys are: wt: weight for input -> T gate wh: weight for input -> H gate wtL: weight for prev state -> T gate for layer L (indexed from 0) whL: weight for prev state -> H gate for layer ...
[ "Returns", "the", "keys", "the", "dictionary", "of", "variable", "initializers", "may", "contain", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L1661-L1686
train
deepmind/sonnet
sonnet/python/modules/gated_rnn.py
HighwayCore._build
def _build(self, inputs, prev_state): """Connects the highway core module into the graph. Args: inputs: Tensor of size `[batch_size, input_size]`. prev_state: Tensor of size `[batch_size, hidden_size]`. Returns: A tuple (output, next_state) where `output` is a Tensor of size `[batc...
python
def _build(self, inputs, prev_state): """Connects the highway core module into the graph. Args: inputs: Tensor of size `[batch_size, input_size]`. prev_state: Tensor of size `[batch_size, hidden_size]`. Returns: A tuple (output, next_state) where `output` is a Tensor of size `[batc...
[ "def", "_build", "(", "self", ",", "inputs", ",", "prev_state", ")", ":", "input_size", "=", "inputs", ".", "get_shape", "(", ")", "[", "1", "]", "weight_shape", "=", "(", "input_size", ",", "self", ".", "_hidden_size", ")", "u_shape", "=", "(", "self"...
Connects the highway core module into the graph. Args: inputs: Tensor of size `[batch_size, input_size]`. prev_state: Tensor of size `[batch_size, hidden_size]`. Returns: A tuple (output, next_state) where `output` is a Tensor of size `[batch_size, hidden_size]` and `next_state` is a T...
[ "Connects", "the", "highway", "core", "module", "into", "the", "graph", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L1688-L1737
train
deepmind/sonnet
sonnet/python/modules/basic_rnn.py
_get_flat_core_sizes
def _get_flat_core_sizes(cores): """Obtains the list flattened output sizes of a list of cores. Args: cores: list of cores to get the shapes from. Returns: List of lists that, for each core, contains the list of its output dimensions. """ core_sizes_lists = [] for core in cores: flat_out...
python
def _get_flat_core_sizes(cores): """Obtains the list flattened output sizes of a list of cores. Args: cores: list of cores to get the shapes from. Returns: List of lists that, for each core, contains the list of its output dimensions. """ core_sizes_lists = [] for core in cores: flat_out...
[ "def", "_get_flat_core_sizes", "(", "cores", ")", ":", "core_sizes_lists", "=", "[", "]", "for", "core", "in", "cores", ":", "flat_output_size", "=", "nest", ".", "flatten", "(", "core", ".", "output_size", ")", "core_sizes_lists", ".", "append", "(", "[", ...
Obtains the list flattened output sizes of a list of cores. Args: cores: list of cores to get the shapes from. Returns: List of lists that, for each core, contains the list of its output dimensions.
[ "Obtains", "the", "list", "flattened", "output", "sizes", "of", "a", "list", "of", "cores", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic_rnn.py#L39-L54
train
deepmind/sonnet
sonnet/python/modules/basic_rnn.py
_get_shape_without_batch_dimension
def _get_shape_without_batch_dimension(tensor_nest): """Converts Tensor nest to a TensorShape nest, removing batch dimension.""" def _strip_batch_and_convert_to_shape(tensor): return tensor.get_shape()[1:] return nest.map_structure(_strip_batch_and_convert_to_shape, tensor_nest)
python
def _get_shape_without_batch_dimension(tensor_nest): """Converts Tensor nest to a TensorShape nest, removing batch dimension.""" def _strip_batch_and_convert_to_shape(tensor): return tensor.get_shape()[1:] return nest.map_structure(_strip_batch_and_convert_to_shape, tensor_nest)
[ "def", "_get_shape_without_batch_dimension", "(", "tensor_nest", ")", ":", "def", "_strip_batch_and_convert_to_shape", "(", "tensor", ")", ":", "return", "tensor", ".", "get_shape", "(", ")", "[", "1", ":", "]", "return", "nest", ".", "map_structure", "(", "_str...
Converts Tensor nest to a TensorShape nest, removing batch dimension.
[ "Converts", "Tensor", "nest", "to", "a", "TensorShape", "nest", "removing", "batch", "dimension", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic_rnn.py#L57-L61
train
deepmind/sonnet
sonnet/python/modules/basic_rnn.py
VanillaRNN._build
def _build(self, input_, prev_state): """Connects the VanillaRNN module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as input_ and state must have the same final dimension, in order for the existing variables to be the correct size for ...
python
def _build(self, input_, prev_state): """Connects the VanillaRNN module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as input_ and state must have the same final dimension, in order for the existing variables to be the correct size for ...
[ "def", "_build", "(", "self", ",", "input_", ",", "prev_state", ")", ":", "self", ".", "_in_to_hidden_linear", "=", "basic", ".", "Linear", "(", "self", ".", "_hidden_size", ",", "name", "=", "\"in_to_hidden\"", ",", "initializers", "=", "self", ".", "_ini...
Connects the VanillaRNN module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as input_ and state must have the same final dimension, in order for the existing variables to be the correct size for their corresponding multiplications. The b...
[ "Connects", "the", "VanillaRNN", "module", "into", "the", "graph", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic_rnn.py#L110-L149
train
deepmind/sonnet
sonnet/python/modules/basic_rnn.py
DeepRNN._check_cores_output_sizes
def _check_cores_output_sizes(self): """Checks the output_sizes of the cores of the DeepRNN module. Raises: ValueError: if the outputs of the cores cannot be concatenated along their first dimension. """ for core_sizes in zip(*tuple(_get_flat_core_sizes(self._cores))): first_core_li...
python
def _check_cores_output_sizes(self): """Checks the output_sizes of the cores of the DeepRNN module. Raises: ValueError: if the outputs of the cores cannot be concatenated along their first dimension. """ for core_sizes in zip(*tuple(_get_flat_core_sizes(self._cores))): first_core_li...
[ "def", "_check_cores_output_sizes", "(", "self", ")", ":", "for", "core_sizes", "in", "zip", "(", "*", "tuple", "(", "_get_flat_core_sizes", "(", "self", ".", "_cores", ")", ")", ")", ":", "first_core_list", "=", "core_sizes", "[", "0", "]", "[", "1", ":...
Checks the output_sizes of the cores of the DeepRNN module. Raises: ValueError: if the outputs of the cores cannot be concatenated along their first dimension.
[ "Checks", "the", "output_sizes", "of", "the", "cores", "of", "the", "DeepRNN", "module", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic_rnn.py#L294-L309
train
deepmind/sonnet
sonnet/python/modules/basic_rnn.py
DeepRNN._build
def _build(self, inputs, prev_state, **kwargs): """Connects the DeepRNN module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as input_ and state must have the same final dimension, in order for the existing variables to be the correct siz...
python
def _build(self, inputs, prev_state, **kwargs): """Connects the DeepRNN module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as input_ and state must have the same final dimension, in order for the existing variables to be the correct siz...
[ "def", "_build", "(", "self", ",", "inputs", ",", "prev_state", ",", "*", "*", "kwargs", ")", ":", "current_input", "=", "inputs", "next_states", "=", "[", "]", "outputs", "=", "[", "]", "recurrent_idx", "=", "0", "concatenate", "=", "lambda", "*", "ar...
Connects the DeepRNN module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as input_ and state must have the same final dimension, in order for the existing variables to be the correct size for their corresponding multiplications. The batc...
[ "Connects", "the", "DeepRNN", "module", "into", "the", "graph", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic_rnn.py#L311-L370
train
deepmind/sonnet
sonnet/python/modules/basic_rnn.py
DeepRNN.initial_state
def initial_state(self, batch_size, dtype=tf.float32, trainable=False, trainable_initializers=None, trainable_regularizers=None, name=None): """Builds the default start state for a DeepRNN. Args: batch_size: An int, float or scalar Tensor representing the batch siz...
python
def initial_state(self, batch_size, dtype=tf.float32, trainable=False, trainable_initializers=None, trainable_regularizers=None, name=None): """Builds the default start state for a DeepRNN. Args: batch_size: An int, float or scalar Tensor representing the batch siz...
[ "def", "initial_state", "(", "self", ",", "batch_size", ",", "dtype", "=", "tf", ".", "float32", ",", "trainable", "=", "False", ",", "trainable_initializers", "=", "None", ",", "trainable_regularizers", "=", "None", ",", "name", "=", "None", ")", ":", "in...
Builds the default start state for a DeepRNN. Args: batch_size: An int, float or scalar Tensor representing the batch size. dtype: The data type to use for the state. trainable: Boolean that indicates whether to learn the initial state. trainable_initializers: An initializer function or nes...
[ "Builds", "the", "default", "start", "state", "for", "a", "DeepRNN", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic_rnn.py#L372-L426
train
deepmind/sonnet
sonnet/python/modules/basic_rnn.py
ModelRNN._build
def _build(self, inputs, prev_state): """Connects the ModelRNN module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as input_ and state must have the same final dimension, in order for the existing variables to be the correct size for ...
python
def _build(self, inputs, prev_state): """Connects the ModelRNN module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as input_ and state must have the same final dimension, in order for the existing variables to be the correct size for ...
[ "def", "_build", "(", "self", ",", "inputs", ",", "prev_state", ")", ":", "next_state", "=", "self", ".", "_model", "(", "prev_state", ")", "# For ModelRNN, the next state of the RNN is the same as the output", "return", "next_state", ",", "next_state" ]
Connects the ModelRNN module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as input_ and state must have the same final dimension, in order for the existing variables to be the correct size for their corresponding multiplications. The bat...
[ "Connects", "the", "ModelRNN", "module", "into", "the", "graph", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic_rnn.py#L517-L537
train
deepmind/sonnet
sonnet/python/modules/basic_rnn.py
BidirectionalRNN._build
def _build(self, input_sequence, state): """Connects the BidirectionalRNN module into the graph. Args: input_sequence: tensor (time, batch, [feature_1, ..]). It must be time_major. state: tuple of states for the forward and backward cores. Returns: A dict with forward/backard s...
python
def _build(self, input_sequence, state): """Connects the BidirectionalRNN module into the graph. Args: input_sequence: tensor (time, batch, [feature_1, ..]). It must be time_major. state: tuple of states for the forward and backward cores. Returns: A dict with forward/backard s...
[ "def", "_build", "(", "self", ",", "input_sequence", ",", "state", ")", ":", "input_shape", "=", "input_sequence", ".", "get_shape", "(", ")", "if", "input_shape", "[", "0", "]", "is", "None", ":", "raise", "ValueError", "(", "\"Time dimension of input (dim 0)...
Connects the BidirectionalRNN module into the graph. Args: input_sequence: tensor (time, batch, [feature_1, ..]). It must be time_major. state: tuple of states for the forward and backward cores. Returns: A dict with forward/backard states and output sequences: "outputs":{...
[ "Connects", "the", "BidirectionalRNN", "module", "into", "the", "graph", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic_rnn.py#L583-L649
train
deepmind/sonnet
sonnet/python/modules/basic_rnn.py
BidirectionalRNN.initial_state
def initial_state(self, batch_size, dtype=tf.float32, trainable=False, trainable_initializers=None, trainable_regularizers=None, name=None): """Builds the default start state for a BidirectionalRNN. The Bidirectional RNN flattens the states of its forward and backward co...
python
def initial_state(self, batch_size, dtype=tf.float32, trainable=False, trainable_initializers=None, trainable_regularizers=None, name=None): """Builds the default start state for a BidirectionalRNN. The Bidirectional RNN flattens the states of its forward and backward co...
[ "def", "initial_state", "(", "self", ",", "batch_size", ",", "dtype", "=", "tf", ".", "float32", ",", "trainable", "=", "False", ",", "trainable_initializers", "=", "None", ",", "trainable_regularizers", "=", "None", ",", "name", "=", "None", ")", ":", "na...
Builds the default start state for a BidirectionalRNN. The Bidirectional RNN flattens the states of its forward and backward cores and concatentates them. Args: batch_size: An int, float or scalar Tensor representing the batch size. dtype: The data type to use for the state. trainable: B...
[ "Builds", "the", "default", "start", "state", "for", "a", "BidirectionalRNN", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic_rnn.py#L651-L686
train
deepmind/sonnet
sonnet/python/modules/nets/mlp.py
MLP._instantiate_layers
def _instantiate_layers(self): """Instantiates all the linear modules used in the network. Layers are instantiated in the constructor, as opposed to the build function, because MLP implements the Transposable interface, and the transpose function can be called before the module is actually connected ...
python
def _instantiate_layers(self): """Instantiates all the linear modules used in the network. Layers are instantiated in the constructor, as opposed to the build function, because MLP implements the Transposable interface, and the transpose function can be called before the module is actually connected ...
[ "def", "_instantiate_layers", "(", "self", ")", ":", "# Here we are entering the module's variable scope to name our submodules", "# correctly (not to create variables). As such it's safe to not check", "# whether we're in the same graph. This is important if we're constructing", "# the module in ...
Instantiates all the linear modules used in the network. Layers are instantiated in the constructor, as opposed to the build function, because MLP implements the Transposable interface, and the transpose function can be called before the module is actually connected to the graph and build is called. ...
[ "Instantiates", "all", "the", "linear", "modules", "used", "in", "the", "network", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/mlp.py#L112-L139
train
deepmind/sonnet
sonnet/python/modules/nets/mlp.py
MLP._build
def _build(self, inputs, is_training=True, dropout_keep_prob=0.5): """Assembles the `MLP` and connects it to the graph. Args: inputs: A 2D Tensor of size `[batch_size, input_size]`. is_training: A bool or tf.Bool Tensor. Indicates whether we are currently training. Defaults to `True`. ...
python
def _build(self, inputs, is_training=True, dropout_keep_prob=0.5): """Assembles the `MLP` and connects it to the graph. Args: inputs: A 2D Tensor of size `[batch_size, input_size]`. is_training: A bool or tf.Bool Tensor. Indicates whether we are currently training. Defaults to `True`. ...
[ "def", "_build", "(", "self", ",", "inputs", ",", "is_training", "=", "True", ",", "dropout_keep_prob", "=", "0.5", ")", ":", "self", ".", "_input_shape", "=", "tuple", "(", "inputs", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", ")", "net", ...
Assembles the `MLP` and connects it to the graph. Args: inputs: A 2D Tensor of size `[batch_size, input_size]`. is_training: A bool or tf.Bool Tensor. Indicates whether we are currently training. Defaults to `True`. dropout_keep_prob: The probability that each element is kept when ...
[ "Assembles", "the", "MLP", "and", "connects", "it", "to", "the", "graph", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/mlp.py#L145-L174
train
deepmind/sonnet
sonnet/python/modules/nets/mlp.py
MLP.output_sizes
def output_sizes(self): """Returns a tuple of all output sizes of all the layers.""" return tuple([l() if callable(l) else l for l in self._output_sizes])
python
def output_sizes(self): """Returns a tuple of all output sizes of all the layers.""" return tuple([l() if callable(l) else l for l in self._output_sizes])
[ "def", "output_sizes", "(", "self", ")", ":", "return", "tuple", "(", "[", "l", "(", ")", "if", "callable", "(", "l", ")", "else", "l", "for", "l", "in", "self", ".", "_output_sizes", "]", ")" ]
Returns a tuple of all output sizes of all the layers.
[ "Returns", "a", "tuple", "of", "all", "output", "sizes", "of", "all", "the", "layers", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/mlp.py#L182-L184
train
deepmind/sonnet
sonnet/python/modules/nets/mlp.py
MLP.transpose
def transpose(self, name=None, activate_final=None): """Returns transposed `MLP`. Args: name: Optional string specifying the name of the transposed module. The default name is constructed by appending "_transpose" to `self.module_name`. activate_final: Optional boolean determining i...
python
def transpose(self, name=None, activate_final=None): """Returns transposed `MLP`. Args: name: Optional string specifying the name of the transposed module. The default name is constructed by appending "_transpose" to `self.module_name`. activate_final: Optional boolean determining i...
[ "def", "transpose", "(", "self", ",", "name", "=", "None", ",", "activate_final", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "self", ".", "module_name", "+", "\"_transpose\"", "if", "activate_final", "is", "None", ":", "activate...
Returns transposed `MLP`. Args: name: Optional string specifying the name of the transposed module. The default name is constructed by appending "_transpose" to `self.module_name`. activate_final: Optional boolean determining if the activation and batch normalization, if turned ...
[ "Returns", "transposed", "MLP", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/mlp.py#L237-L265
train
deepmind/sonnet
sonnet/python/modules/nets/mlp.py
MLP.clone
def clone(self, name=None): """Creates a new MLP with the same structure. Args: name: Optional string specifying the name of the new module. The default name is constructed by appending "_clone" to the original name. Returns: A cloned `MLP` module. """ if name is None: n...
python
def clone(self, name=None): """Creates a new MLP with the same structure. Args: name: Optional string specifying the name of the new module. The default name is constructed by appending "_clone" to the original name. Returns: A cloned `MLP` module. """ if name is None: n...
[ "def", "clone", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "self", ".", "module_name", "+", "\"_clone\"", "return", "MLP", "(", "name", "=", "name", ",", "output_sizes", "=", "self", ".", "output_si...
Creates a new MLP with the same structure. Args: name: Optional string specifying the name of the new module. The default name is constructed by appending "_clone" to the original name. Returns: A cloned `MLP` module.
[ "Creates", "a", "new", "MLP", "with", "the", "same", "structure", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/mlp.py#L267-L289
train
deepmind/sonnet
sonnet/python/modules/nets/alexnet.py
AlexNet._calc_min_size
def _calc_min_size(self, conv_layers): """Calculates the minimum size of the input layer. Given a set of convolutional layers, calculate the minimum value of the `input_height` and `input_width`, i.e. such that the output has size 1x1. Assumes snt.VALID padding. Args: conv_layers: List of tu...
python
def _calc_min_size(self, conv_layers): """Calculates the minimum size of the input layer. Given a set of convolutional layers, calculate the minimum value of the `input_height` and `input_width`, i.e. such that the output has size 1x1. Assumes snt.VALID padding. Args: conv_layers: List of tu...
[ "def", "_calc_min_size", "(", "self", ",", "conv_layers", ")", ":", "input_size", "=", "1", "for", "_", ",", "conv_params", ",", "max_pooling", "in", "reversed", "(", "conv_layers", ")", ":", "if", "max_pooling", "is", "not", "None", ":", "kernel_size", ",...
Calculates the minimum size of the input layer. Given a set of convolutional layers, calculate the minimum value of the `input_height` and `input_width`, i.e. such that the output has size 1x1. Assumes snt.VALID padding. Args: conv_layers: List of tuples `(output_channels, (kernel_size, stride),...
[ "Calculates", "the", "minimum", "size", "of", "the", "input", "layer", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/alexnet.py#L154-L179
train
deepmind/sonnet
sonnet/python/modules/nets/alexnet.py
AlexNet._build
def _build(self, inputs, keep_prob=None, is_training=None, test_local_stats=True): """Connects the AlexNet module into the graph. The is_training flag only controls the batch norm settings, if `False` it does not force no dropout by overriding any input `keep_prob`. To avoid any confusion ...
python
def _build(self, inputs, keep_prob=None, is_training=None, test_local_stats=True): """Connects the AlexNet module into the graph. The is_training flag only controls the batch norm settings, if `False` it does not force no dropout by overriding any input `keep_prob`. To avoid any confusion ...
[ "def", "_build", "(", "self", ",", "inputs", ",", "keep_prob", "=", "None", ",", "is_training", "=", "None", ",", "test_local_stats", "=", "True", ")", ":", "# Check input shape", "if", "(", "self", ".", "_use_batch_norm", "or", "keep_prob", "is", "not", "...
Connects the AlexNet module into the graph. The is_training flag only controls the batch norm settings, if `False` it does not force no dropout by overriding any input `keep_prob`. To avoid any confusion this may cause, if `is_training=False` and `keep_prob` would cause dropout to be applied, an error ...
[ "Connects", "the", "AlexNet", "module", "into", "the", "graph", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/alexnet.py#L181-L291
train
deepmind/sonnet
sonnet/examples/dataset_nth_farthest.py
NthFarthest._get_single_set
def _get_single_set(self, num_objects, num_features): """Generate one input sequence and output label. Each sequences of objects has a feature that consists of the feature vector for that object plus the encoding for its ID, the reference vector ID and the n-th value relative ID for a total feature siz...
python
def _get_single_set(self, num_objects, num_features): """Generate one input sequence and output label. Each sequences of objects has a feature that consists of the feature vector for that object plus the encoding for its ID, the reference vector ID and the n-th value relative ID for a total feature siz...
[ "def", "_get_single_set", "(", "self", ",", "num_objects", ",", "num_features", ")", ":", "# Generate random binary vectors", "data", "=", "np", ".", "random", ".", "uniform", "(", "-", "1", ",", "1", ",", "size", "=", "(", "num_objects", ",", "num_features"...
Generate one input sequence and output label. Each sequences of objects has a feature that consists of the feature vector for that object plus the encoding for its ID, the reference vector ID and the n-th value relative ID for a total feature size of: `num_objects` * 3 + `num_features` Args: ...
[ "Generate", "one", "input", "sequence", "and", "output", "label", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/dataset_nth_farthest.py#L51-L97
train
deepmind/sonnet
sonnet/examples/dataset_nth_farthest.py
NthFarthest._get_batch_data
def _get_batch_data(self, batch_size, num_objects, num_features): """Assembles a batch of input tensors and output labels. Args: batch_size: int. number of sequence batches. num_objects: int. number of objects in the sequence. num_features: int. feature size of each object. Returns: ...
python
def _get_batch_data(self, batch_size, num_objects, num_features): """Assembles a batch of input tensors and output labels. Args: batch_size: int. number of sequence batches. num_objects: int. number of objects in the sequence. num_features: int. feature size of each object. Returns: ...
[ "def", "_get_batch_data", "(", "self", ",", "batch_size", ",", "num_objects", ",", "num_features", ")", ":", "all_inputs", "=", "[", "]", "all_labels", "=", "[", "]", "for", "_", "in", "six", ".", "moves", ".", "range", "(", "batch_size", ")", ":", "in...
Assembles a batch of input tensors and output labels. Args: batch_size: int. number of sequence batches. num_objects: int. number of objects in the sequence. num_features: int. feature size of each object. Returns: 1. np.ndarray (`batch_size`, `num_objects`, (`num_...
[ "Assembles", "a", "batch", "of", "input", "tensors", "and", "output", "labels", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/dataset_nth_farthest.py#L99-L120
train
deepmind/sonnet
sonnet/examples/dataset_nth_farthest.py
NthFarthest.get_batch
def get_batch(self): """Returns set of nth-farthest input tensors and labels. Returns: 1. tf.Tensor (`batch_size`, `num_objects`, (`num_features` + 3 * `num_objects`)). 2. tf.Tensor (`batch_size`). Output object reference label. """ params = [self._batch_size, self._num...
python
def get_batch(self): """Returns set of nth-farthest input tensors and labels. Returns: 1. tf.Tensor (`batch_size`, `num_objects`, (`num_features` + 3 * `num_objects`)). 2. tf.Tensor (`batch_size`). Output object reference label. """ params = [self._batch_size, self._num...
[ "def", "get_batch", "(", "self", ")", ":", "params", "=", "[", "self", ".", "_batch_size", ",", "self", ".", "_num_objects", ",", "self", ".", "_num_features", "]", "inputs", ",", "labels", "=", "tf", ".", "py_func", "(", "self", ".", "_get_batch_data", ...
Returns set of nth-farthest input tensors and labels. Returns: 1. tf.Tensor (`batch_size`, `num_objects`, (`num_features` + 3 * `num_objects`)). 2. tf.Tensor (`batch_size`). Output object reference label.
[ "Returns", "set", "of", "nth", "-", "farthest", "input", "tensors", "and", "labels", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/dataset_nth_farthest.py#L122-L136
train
deepmind/sonnet
sonnet/python/modules/conv.py
_default_transpose_size
def _default_transpose_size(input_shape, stride, kernel_shape=None, padding=SAME): """Returns default (maximal) output shape for a transpose convolution. In general, there are multiple possible output shapes that a transpose convolution with a given `input_shape` can map to. This func...
python
def _default_transpose_size(input_shape, stride, kernel_shape=None, padding=SAME): """Returns default (maximal) output shape for a transpose convolution. In general, there are multiple possible output shapes that a transpose convolution with a given `input_shape` can map to. This func...
[ "def", "_default_transpose_size", "(", "input_shape", ",", "stride", ",", "kernel_shape", "=", "None", ",", "padding", "=", "SAME", ")", ":", "if", "not", "input_shape", ":", "raise", "TypeError", "(", "\"input_shape is None; if using Sonnet, are you sure you \"", "\"...
Returns default (maximal) output shape for a transpose convolution. In general, there are multiple possible output shapes that a transpose convolution with a given `input_shape` can map to. This function returns the output shape which evenly divides the stride to produce the input shape in a forward convolutio...
[ "Returns", "default", "(", "maximal", ")", "output", "shape", "for", "a", "transpose", "convolution", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/conv.py#L63-L107
train
deepmind/sonnet
sonnet/python/modules/conv.py
_fill_shape
def _fill_shape(x, n): """Converts a dimension to a tuple of dimensions of a given size. This is used to allow shorthand notation for various configuration parameters. A user can provide either, for example, `2` or `[2, 2]` as a kernel shape, and this function returns `(2, 2)` in both cases. Passing `[1, 2]` w...
python
def _fill_shape(x, n): """Converts a dimension to a tuple of dimensions of a given size. This is used to allow shorthand notation for various configuration parameters. A user can provide either, for example, `2` or `[2, 2]` as a kernel shape, and this function returns `(2, 2)` in both cases. Passing `[1, 2]` w...
[ "def", "_fill_shape", "(", "x", ",", "n", ")", ":", "if", "not", "isinstance", "(", "n", ",", "numbers", ".", "Integral", ")", "or", "n", "<", "1", ":", "raise", "TypeError", "(", "\"n must be a positive integer\"", ")", "if", "(", "isinstance", "(", "...
Converts a dimension to a tuple of dimensions of a given size. This is used to allow shorthand notation for various configuration parameters. A user can provide either, for example, `2` or `[2, 2]` as a kernel shape, and this function returns `(2, 2)` in both cases. Passing `[1, 2]` will return `(1, 2)`. Ar...
[ "Converts", "a", "dimension", "to", "a", "tuple", "of", "dimensions", "of", "a", "given", "size", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/conv.py#L110-L145
train
deepmind/sonnet
sonnet/python/modules/conv.py
_fill_and_verify_parameter_shape
def _fill_and_verify_parameter_shape(x, n, parameter_label): """Expands x if necessary into a `n`-D kernel shape and reports errors.""" try: return _fill_shape(x, n) except TypeError as e: raise base.IncompatibleShapeError("Invalid " + parameter_label + " shape: " "{}...
python
def _fill_and_verify_parameter_shape(x, n, parameter_label): """Expands x if necessary into a `n`-D kernel shape and reports errors.""" try: return _fill_shape(x, n) except TypeError as e: raise base.IncompatibleShapeError("Invalid " + parameter_label + " shape: " "{}...
[ "def", "_fill_and_verify_parameter_shape", "(", "x", ",", "n", ",", "parameter_label", ")", ":", "try", ":", "return", "_fill_shape", "(", "x", ",", "n", ")", "except", "TypeError", "as", "e", ":", "raise", "base", ".", "IncompatibleShapeError", "(", "\"Inva...
Expands x if necessary into a `n`-D kernel shape and reports errors.
[ "Expands", "x", "if", "necessary", "into", "a", "n", "-", "D", "kernel", "shape", "and", "reports", "errors", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/conv.py#L148-L154
train
deepmind/sonnet
sonnet/python/modules/conv.py
_fill_and_verify_padding
def _fill_and_verify_padding(padding, n): """Verifies that the provided padding is supported and expands to size n. Args: padding: One of ALLOWED_PADDINGS, or an iterable of them. n: An integer, the size of the desired output list. Returns: If `padding` is one of ALLOWED_PADDINGS, a tuple of size `n...
python
def _fill_and_verify_padding(padding, n): """Verifies that the provided padding is supported and expands to size n. Args: padding: One of ALLOWED_PADDINGS, or an iterable of them. n: An integer, the size of the desired output list. Returns: If `padding` is one of ALLOWED_PADDINGS, a tuple of size `n...
[ "def", "_fill_and_verify_padding", "(", "padding", ",", "n", ")", ":", "if", "not", "isinstance", "(", "n", ",", "numbers", ".", "Integral", ")", "or", "n", "<", "1", ":", "raise", "TypeError", "(", "\"n must be a positive integer\"", ")", "if", "isinstance"...
Verifies that the provided padding is supported and expands to size n. Args: padding: One of ALLOWED_PADDINGS, or an iterable of them. n: An integer, the size of the desired output list. Returns: If `padding` is one of ALLOWED_PADDINGS, a tuple of size `n` containing `n` copies of `padding`. I...
[ "Verifies", "that", "the", "provided", "padding", "is", "supported", "and", "expands", "to", "size", "n", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/conv.py#L176-L206
train
deepmind/sonnet
sonnet/python/modules/conv.py
_padding_to_conv_op_padding
def _padding_to_conv_op_padding(padding): """Whether to use SAME or VALID for the underlying convolution op. Args: padding: A tuple of members of ALLOWED_PADDINGS, e.g. as returned from `_fill_and_verify_padding`. Returns: One of CONV_OP_ALLOWED_PADDINGS, the padding method to use for the unde...
python
def _padding_to_conv_op_padding(padding): """Whether to use SAME or VALID for the underlying convolution op. Args: padding: A tuple of members of ALLOWED_PADDINGS, e.g. as returned from `_fill_and_verify_padding`. Returns: One of CONV_OP_ALLOWED_PADDINGS, the padding method to use for the unde...
[ "def", "_padding_to_conv_op_padding", "(", "padding", ")", ":", "if", "not", "isinstance", "(", "padding", ",", "tuple", ")", ":", "raise", "ValueError", "(", "\"padding should be a tuple.\"", ")", "if", "all", "(", "p", "==", "SAME", "for", "p", "in", "padd...
Whether to use SAME or VALID for the underlying convolution op. Args: padding: A tuple of members of ALLOWED_PADDINGS, e.g. as returned from `_fill_and_verify_padding`. Returns: One of CONV_OP_ALLOWED_PADDINGS, the padding method to use for the underlying convolution op. Raises: ValueErro...
[ "Whether", "to", "use", "SAME", "or", "VALID", "for", "the", "underlying", "convolution", "op", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/conv.py#L209-L233
train
deepmind/sonnet
sonnet/python/modules/conv.py
_fill_and_one_pad_stride
def _fill_and_one_pad_stride(stride, n, data_format=DATA_FORMAT_NHWC): """Expands the provided stride to size n and pads it with 1s.""" if isinstance(stride, numbers.Integral) or ( isinstance(stride, collections.Iterable) and len(stride) <= n): if data_format.startswith("NC"): return (1, 1,) + _fill...
python
def _fill_and_one_pad_stride(stride, n, data_format=DATA_FORMAT_NHWC): """Expands the provided stride to size n and pads it with 1s.""" if isinstance(stride, numbers.Integral) or ( isinstance(stride, collections.Iterable) and len(stride) <= n): if data_format.startswith("NC"): return (1, 1,) + _fill...
[ "def", "_fill_and_one_pad_stride", "(", "stride", ",", "n", ",", "data_format", "=", "DATA_FORMAT_NHWC", ")", ":", "if", "isinstance", "(", "stride", ",", "numbers", ".", "Integral", ")", "or", "(", "isinstance", "(", "stride", ",", "collections", ".", "Iter...
Expands the provided stride to size n and pads it with 1s.
[ "Expands", "the", "provided", "stride", "to", "size", "n", "and", "pads", "it", "with", "1s", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/conv.py#L236-L253
train
deepmind/sonnet
sonnet/python/modules/conv.py
_verify_inputs
def _verify_inputs(inputs, channel_index, data_format): """Verifies `inputs` is semantically correct. Args: inputs: An input tensor provided by the user. channel_index: The index of the channel dimension. data_format: The format of the data in `inputs`. Raises: base.IncompatibleShapeError: If th...
python
def _verify_inputs(inputs, channel_index, data_format): """Verifies `inputs` is semantically correct. Args: inputs: An input tensor provided by the user. channel_index: The index of the channel dimension. data_format: The format of the data in `inputs`. Raises: base.IncompatibleShapeError: If th...
[ "def", "_verify_inputs", "(", "inputs", ",", "channel_index", ",", "data_format", ")", ":", "# Check shape.", "input_shape", "=", "tuple", "(", "inputs", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", ")", "if", "len", "(", "input_shape", ")", "!=",...
Verifies `inputs` is semantically correct. Args: inputs: An input tensor provided by the user. channel_index: The index of the channel dimension. data_format: The format of the data in `inputs`. Raises: base.IncompatibleShapeError: If the shape of `inputs` doesn't match `data_format`. ba...
[ "Verifies", "inputs", "is", "semantically", "correct", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/conv.py#L256-L292
train
deepmind/sonnet
sonnet/python/modules/conv.py
create_weight_initializer
def create_weight_initializer(fan_in_shape, dtype=tf.float32): """Returns a default initializer for the weights of a convolutional module.""" stddev = 1 / math.sqrt(np.prod(fan_in_shape)) return tf.truncated_normal_initializer(stddev=stddev, dtype=dtype)
python
def create_weight_initializer(fan_in_shape, dtype=tf.float32): """Returns a default initializer for the weights of a convolutional module.""" stddev = 1 / math.sqrt(np.prod(fan_in_shape)) return tf.truncated_normal_initializer(stddev=stddev, dtype=dtype)
[ "def", "create_weight_initializer", "(", "fan_in_shape", ",", "dtype", "=", "tf", ".", "float32", ")", ":", "stddev", "=", "1", "/", "math", ".", "sqrt", "(", "np", ".", "prod", "(", "fan_in_shape", ")", ")", "return", "tf", ".", "truncated_normal_initiali...
Returns a default initializer for the weights of a convolutional module.
[ "Returns", "a", "default", "initializer", "for", "the", "weights", "of", "a", "convolutional", "module", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/conv.py#L295-L298
train
deepmind/sonnet
sonnet/python/modules/conv.py
_find_channel_index
def _find_channel_index(data_format): """Returns the index of the channel dimension. Args: data_format: A string of characters corresponding to Tensor dimensionality. Returns: channel_index: An integer indicating the channel dimension. Raises: ValueError: If no channel dimension was found. """ ...
python
def _find_channel_index(data_format): """Returns the index of the channel dimension. Args: data_format: A string of characters corresponding to Tensor dimensionality. Returns: channel_index: An integer indicating the channel dimension. Raises: ValueError: If no channel dimension was found. """ ...
[ "def", "_find_channel_index", "(", "data_format", ")", ":", "for", "i", ",", "c", "in", "enumerate", "(", "data_format", ")", ":", "if", "c", "==", "\"C\"", ":", "return", "i", "raise", "ValueError", "(", "\"data_format requires a channel dimension. Got: {}\"", ...
Returns the index of the channel dimension. Args: data_format: A string of characters corresponding to Tensor dimensionality. Returns: channel_index: An integer indicating the channel dimension. Raises: ValueError: If no channel dimension was found.
[ "Returns", "the", "index", "of", "the", "channel", "dimension", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/conv.py#L306-L322
train
deepmind/sonnet
sonnet/python/modules/conv.py
_apply_bias
def _apply_bias(inputs, outputs, channel_index, data_format, output_channels, initializers, partitioners, regularizers): """Initialize and apply a bias to the outputs. Figures out the shape of the bias vector, initialize it, and applies it. Args: inputs: A Tensor of shape `data_format`. ...
python
def _apply_bias(inputs, outputs, channel_index, data_format, output_channels, initializers, partitioners, regularizers): """Initialize and apply a bias to the outputs. Figures out the shape of the bias vector, initialize it, and applies it. Args: inputs: A Tensor of shape `data_format`. ...
[ "def", "_apply_bias", "(", "inputs", ",", "outputs", ",", "channel_index", ",", "data_format", ",", "output_channels", ",", "initializers", ",", "partitioners", ",", "regularizers", ")", ":", "bias_shape", "=", "(", "output_channels", ",", ")", "if", "\"b\"", ...
Initialize and apply a bias to the outputs. Figures out the shape of the bias vector, initialize it, and applies it. Args: inputs: A Tensor of shape `data_format`. outputs: A Tensor of shape `data_format`. channel_index: The index of the channel dimension in `inputs`. data_format: Format of `input...
[ "Initialize", "and", "apply", "a", "bias", "to", "the", "outputs", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/conv.py#L325-L369
train
deepmind/sonnet
sonnet/python/modules/conv.py
_ConvND._build
def _build(self, inputs): """Connects the _ConvND module into the graph, with input Tensor `inputs`. If this is not the first time the module has been connected to the graph, the input Tensor provided here must have the same number of channels, in order for the existing variables to be the correct size...
python
def _build(self, inputs): """Connects the _ConvND module into the graph, with input Tensor `inputs`. If this is not the first time the module has been connected to the graph, the input Tensor provided here must have the same number of channels, in order for the existing variables to be the correct size...
[ "def", "_build", "(", "self", ",", "inputs", ")", ":", "_verify_inputs", "(", "inputs", ",", "self", ".", "_channel_index", ",", "self", ".", "_data_format", ")", "self", ".", "_input_shape", "=", "tuple", "(", "inputs", ".", "get_shape", "(", ")", ".", ...
Connects the _ConvND module into the graph, with input Tensor `inputs`. If this is not the first time the module has been connected to the graph, the input Tensor provided here must have the same number of channels, in order for the existing variables to be the correct size for the multiplication; the ...
[ "Connects", "the", "_ConvND", "module", "into", "the", "graph", "with", "input", "Tensor", "inputs", "." ]
00612ca3178964d86b556e062694d808ff81fcca
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/conv.py#L520-L570
train