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
tensorflow/tensor2tensor
tensor2tensor/utils/metrics.py
create_eager_metrics_internal
def create_eager_metrics_internal(metric_fns, weights_fn=common_layers.weights_all): """Create metrics accumulators and averager for Eager mode. Args: metric_fns: dict<metric name, metric function> weights_fn: function that takes labels and returns a weights mask. Defaults...
python
def create_eager_metrics_internal(metric_fns, weights_fn=common_layers.weights_all): """Create metrics accumulators and averager for Eager mode. Args: metric_fns: dict<metric name, metric function> weights_fn: function that takes labels and returns a weights mask. Defaults...
[ "def", "create_eager_metrics_internal", "(", "metric_fns", ",", "weights_fn", "=", "common_layers", ".", "weights_all", ")", ":", "tfe_metrics", "=", "{", "}", "for", "name", "in", "metric_fns", ":", "tfe_metrics", "[", "name", "]", "=", "tfe", ".", "metrics",...
Create metrics accumulators and averager for Eager mode. Args: metric_fns: dict<metric name, metric function> weights_fn: function that takes labels and returns a weights mask. Defaults to weights of all 1, i.e. common_layers.weights_all. Use common_layers.weights_nonzero if labels have 0-padding...
[ "Create", "metrics", "accumulators", "and", "averager", "for", "Eager", "mode", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L670-L701
train
tensorflow/tensor2tensor
tensor2tensor/utils/metrics.py
word_error_rate
def word_error_rate(raw_predictions, labels, lookup=None, weights_fn=common_layers.weights_nonzero): """Calculate word error rate. Args: raw_predictions: The raw predictions. labels: The actual labels. lookup: A tf.constant mapping indices to ...
python
def word_error_rate(raw_predictions, labels, lookup=None, weights_fn=common_layers.weights_nonzero): """Calculate word error rate. Args: raw_predictions: The raw predictions. labels: The actual labels. lookup: A tf.constant mapping indices to ...
[ "def", "word_error_rate", "(", "raw_predictions", ",", "labels", ",", "lookup", "=", "None", ",", "weights_fn", "=", "common_layers", ".", "weights_nonzero", ")", ":", "def", "from_tokens", "(", "raw", ",", "lookup_", ")", ":", "gathered", "=", "tf", ".", ...
Calculate word error rate. Args: raw_predictions: The raw predictions. labels: The actual labels. lookup: A tf.constant mapping indices to output tokens. weights_fn: Weighting function. Returns: The word error rate.
[ "Calculate", "word", "error", "rate", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L704-L761
train
tensorflow/tensor2tensor
tensor2tensor/utils/metrics.py
pearson_correlation_coefficient
def pearson_correlation_coefficient(predictions, labels, weights_fn=None): """Calculate pearson correlation coefficient. Args: predictions: The raw predictions. labels: The actual labels. weights_fn: Weighting function. Returns: The pearson correlation coefficient. """ del weights_fn _, pe...
python
def pearson_correlation_coefficient(predictions, labels, weights_fn=None): """Calculate pearson correlation coefficient. Args: predictions: The raw predictions. labels: The actual labels. weights_fn: Weighting function. Returns: The pearson correlation coefficient. """ del weights_fn _, pe...
[ "def", "pearson_correlation_coefficient", "(", "predictions", ",", "labels", ",", "weights_fn", "=", "None", ")", ":", "del", "weights_fn", "_", ",", "pearson", "=", "tf", ".", "contrib", ".", "metrics", ".", "streaming_pearson_correlation", "(", "predictions", ...
Calculate pearson correlation coefficient. Args: predictions: The raw predictions. labels: The actual labels. weights_fn: Weighting function. Returns: The pearson correlation coefficient.
[ "Calculate", "pearson", "correlation", "coefficient", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L764-L778
train
tensorflow/tensor2tensor
tensor2tensor/models/research/attention_lm.py
attention_lm_prepare_decoder
def attention_lm_prepare_decoder(targets, hparams): """Prepare one shard of the model for the decoder. Args: targets: a Tensor. hparams: run hyperparameters Returns: decoder_input: a Tensor, bottom of decoder stack decoder_self_attention_bias: a Tensor, containing large negative values to im...
python
def attention_lm_prepare_decoder(targets, hparams): """Prepare one shard of the model for the decoder. Args: targets: a Tensor. hparams: run hyperparameters Returns: decoder_input: a Tensor, bottom of decoder stack decoder_self_attention_bias: a Tensor, containing large negative values to im...
[ "def", "attention_lm_prepare_decoder", "(", "targets", ",", "hparams", ")", ":", "if", "hparams", ".", "prepend_mode", "==", "\"prepend_inputs_full_attention\"", ":", "decoder_self_attention_bias", "=", "(", "common_attention", ".", "attention_bias_prepend_inputs_full_attenti...
Prepare one shard of the model for the decoder. Args: targets: a Tensor. hparams: run hyperparameters Returns: decoder_input: a Tensor, bottom of decoder stack decoder_self_attention_bias: a Tensor, containing large negative values to implement masked attention and possibly biases for diagonal...
[ "Prepare", "one", "shard", "of", "the", "model", "for", "the", "decoder", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm.py#L66-L89
train
tensorflow/tensor2tensor
tensor2tensor/models/research/attention_lm.py
attention_lm_decoder
def attention_lm_decoder(decoder_input, decoder_self_attention_bias, hparams, name="decoder"): """A stack of attention_lm layers. Args: decoder_input: a Tensor decoder_self_attention_bias: bias Tensor for self-attention (see c...
python
def attention_lm_decoder(decoder_input, decoder_self_attention_bias, hparams, name="decoder"): """A stack of attention_lm layers. Args: decoder_input: a Tensor decoder_self_attention_bias: bias Tensor for self-attention (see c...
[ "def", "attention_lm_decoder", "(", "decoder_input", ",", "decoder_self_attention_bias", ",", "hparams", ",", "name", "=", "\"decoder\"", ")", ":", "x", "=", "decoder_input", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "for", "layer", "in", "ra...
A stack of attention_lm layers. Args: decoder_input: a Tensor decoder_self_attention_bias: bias Tensor for self-attention (see common_attention.attention_bias()) hparams: hyperparameters for model name: a string Returns: y: a Tensors
[ "A", "stack", "of", "attention_lm", "layers", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm.py#L92-L127
train
tensorflow/tensor2tensor
tensor2tensor/models/research/attention_lm.py
attention_lm_base
def attention_lm_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.hidden_size = 1024 hparams.batch_size = 8192 hparams.max_length = 256 hparams.dropout = 0.0 hparams.clip_grad_norm = 0. # i.e. no gradient clipping hparams.optimizer_adam_epsilon = 1e-9 hparams.lea...
python
def attention_lm_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.hidden_size = 1024 hparams.batch_size = 8192 hparams.max_length = 256 hparams.dropout = 0.0 hparams.clip_grad_norm = 0. # i.e. no gradient clipping hparams.optimizer_adam_epsilon = 1e-9 hparams.lea...
[ "def", "attention_lm_base", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "hidden_size", "=", "1024", "hparams", ".", "batch_size", "=", "8192", "hparams", ".", "max_length", "=", "256", "hparams", ".", "dro...
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm.py#L131-L163
train
tensorflow/tensor2tensor
tensor2tensor/models/research/attention_lm.py
attention_lm_small
def attention_lm_small(): """Cheap model. on lm1b_32k: 45M params 2 steps/sec on [GeForce GTX TITAN X] Returns: an hparams object. """ hparams = attention_lm_base() hparams.num_hidden_layers = 4 hparams.hidden_size = 512 hparams.filter_size = 2048 hparams.layer_prepostprocess_dropout ...
python
def attention_lm_small(): """Cheap model. on lm1b_32k: 45M params 2 steps/sec on [GeForce GTX TITAN X] Returns: an hparams object. """ hparams = attention_lm_base() hparams.num_hidden_layers = 4 hparams.hidden_size = 512 hparams.filter_size = 2048 hparams.layer_prepostprocess_dropout ...
[ "def", "attention_lm_small", "(", ")", ":", "hparams", "=", "attention_lm_base", "(", ")", "hparams", ".", "num_hidden_layers", "=", "4", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", "filter_size", "=", "2048", "hparams", ".", "layer_prepostprocess...
Cheap model. on lm1b_32k: 45M params 2 steps/sec on [GeForce GTX TITAN X] Returns: an hparams object.
[ "Cheap", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm.py#L167-L182
train
tensorflow/tensor2tensor
tensor2tensor/models/research/attention_lm.py
attention_lm_translation
def attention_lm_translation(): """Version to use for seq2seq.""" hparams = attention_lm_base() hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" hparams.learning_rate = 0.4 hparams.prepend_mode = "prepend_inputs_masked_attention" hparams.max_length = 512 hparams.label_sm...
python
def attention_lm_translation(): """Version to use for seq2seq.""" hparams = attention_lm_base() hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" hparams.learning_rate = 0.4 hparams.prepend_mode = "prepend_inputs_masked_attention" hparams.max_length = 512 hparams.label_sm...
[ "def", "attention_lm_translation", "(", ")", ":", "hparams", "=", "attention_lm_base", "(", ")", "hparams", ".", "layer_preprocess_sequence", "=", "\"n\"", "hparams", ".", "layer_postprocess_sequence", "=", "\"da\"", "hparams", ".", "learning_rate", "=", "0.4", "hpa...
Version to use for seq2seq.
[ "Version", "to", "use", "for", "seq2seq", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm.py#L186-L196
train
tensorflow/tensor2tensor
tensor2tensor/utils/bleu_hook.py
_get_ngrams
def _get_ngrams(segment, max_order): """Extracts all n-grams up to a given maximum order from an input segment. Args: segment: text segment from which n-grams will be extracted. max_order: maximum length in tokens of the n-grams returned by this methods. Returns: The Counter containing all n...
python
def _get_ngrams(segment, max_order): """Extracts all n-grams up to a given maximum order from an input segment. Args: segment: text segment from which n-grams will be extracted. max_order: maximum length in tokens of the n-grams returned by this methods. Returns: The Counter containing all n...
[ "def", "_get_ngrams", "(", "segment", ",", "max_order", ")", ":", "ngram_counts", "=", "collections", ".", "Counter", "(", ")", "for", "order", "in", "range", "(", "1", ",", "max_order", "+", "1", ")", ":", "for", "i", "in", "range", "(", "0", ",", ...
Extracts all n-grams up to a given maximum order from an input segment. Args: segment: text segment from which n-grams will be extracted. max_order: maximum length in tokens of the n-grams returned by this methods. Returns: The Counter containing all n-grams up to max_order in segment with...
[ "Extracts", "all", "n", "-", "grams", "up", "to", "a", "given", "maximum", "order", "from", "an", "input", "segment", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L40-L57
train
tensorflow/tensor2tensor
tensor2tensor/utils/bleu_hook.py
bleu_score
def bleu_score(predictions, labels, **unused_kwargs): """BLEU score computation between labels and predictions. An approximate BLEU scoring method since we do not glue word pieces or decode the ids and tokenize the output. By default, we use ngram order of 4 and use brevity penalty. Also, this does not have be...
python
def bleu_score(predictions, labels, **unused_kwargs): """BLEU score computation between labels and predictions. An approximate BLEU scoring method since we do not glue word pieces or decode the ids and tokenize the output. By default, we use ngram order of 4 and use brevity penalty. Also, this does not have be...
[ "def", "bleu_score", "(", "predictions", ",", "labels", ",", "*", "*", "unused_kwargs", ")", ":", "outputs", "=", "tf", ".", "to_int32", "(", "tf", ".", "argmax", "(", "predictions", ",", "axis", "=", "-", "1", ")", ")", "# Convert the outputs and labels t...
BLEU score computation between labels and predictions. An approximate BLEU scoring method since we do not glue word pieces or decode the ids and tokenize the output. By default, we use ngram order of 4 and use brevity penalty. Also, this does not have beam search. Args: predictions: tensor, model predicti...
[ "BLEU", "score", "computation", "between", "labels", "and", "predictions", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L132-L152
train
tensorflow/tensor2tensor
tensor2tensor/utils/bleu_hook.py
bleu_tokenize
def bleu_tokenize(string): r"""Tokenize a string following the official BLEU implementation. See https://github.com/moses-smt/mosesdecoder/" "blob/master/scripts/generic/mteval-v14.pl#L954-L983 In our case, the input string is expected to be just one line and no HTML entities de-escaping is needed. ...
python
def bleu_tokenize(string): r"""Tokenize a string following the official BLEU implementation. See https://github.com/moses-smt/mosesdecoder/" "blob/master/scripts/generic/mteval-v14.pl#L954-L983 In our case, the input string is expected to be just one line and no HTML entities de-escaping is needed. ...
[ "def", "bleu_tokenize", "(", "string", ")", ":", "string", "=", "uregex", ".", "nondigit_punct_re", ".", "sub", "(", "r\"\\1 \\2 \"", ",", "string", ")", "string", "=", "uregex", ".", "punct_nondigit_re", ".", "sub", "(", "r\" \\1 \\2\"", ",", "string", ")",...
r"""Tokenize a string following the official BLEU implementation. See https://github.com/moses-smt/mosesdecoder/" "blob/master/scripts/generic/mteval-v14.pl#L954-L983 In our case, the input string is expected to be just one line and no HTML entities de-escaping is needed. So we just tokenize on punc...
[ "r", "Tokenize", "a", "string", "following", "the", "official", "BLEU", "implementation", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L172-L199
train
tensorflow/tensor2tensor
tensor2tensor/utils/bleu_hook.py
bleu_wrapper
def bleu_wrapper(ref_filename, hyp_filename, case_sensitive=False): """Compute BLEU for two files (reference and hypothesis translation).""" ref_lines = text_encoder.native_to_unicode( tf.gfile.Open(ref_filename, "r").read()).split("\n") hyp_lines = text_encoder.native_to_unicode( tf.gfile.Open(hyp_fi...
python
def bleu_wrapper(ref_filename, hyp_filename, case_sensitive=False): """Compute BLEU for two files (reference and hypothesis translation).""" ref_lines = text_encoder.native_to_unicode( tf.gfile.Open(ref_filename, "r").read()).split("\n") hyp_lines = text_encoder.native_to_unicode( tf.gfile.Open(hyp_fi...
[ "def", "bleu_wrapper", "(", "ref_filename", ",", "hyp_filename", ",", "case_sensitive", "=", "False", ")", ":", "ref_lines", "=", "text_encoder", ".", "native_to_unicode", "(", "tf", ".", "gfile", ".", "Open", "(", "ref_filename", ",", "\"r\"", ")", ".", "re...
Compute BLEU for two files (reference and hypothesis translation).
[ "Compute", "BLEU", "for", "two", "files", "(", "reference", "and", "hypothesis", "translation", ")", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L202-L215
train
tensorflow/tensor2tensor
tensor2tensor/utils/bleu_hook.py
_try_twice_tf_glob
def _try_twice_tf_glob(pattern): """Glob twice, first time possibly catching `NotFoundError`. tf.gfile.Glob may crash with ``` tensorflow.python.framework.errors_impl.NotFoundError: xy/model.ckpt-1130761_temp_9cb4cb0b0f5f4382b5ea947aadfb7a40; No such file or directory ``` Standard glob.glob does not ...
python
def _try_twice_tf_glob(pattern): """Glob twice, first time possibly catching `NotFoundError`. tf.gfile.Glob may crash with ``` tensorflow.python.framework.errors_impl.NotFoundError: xy/model.ckpt-1130761_temp_9cb4cb0b0f5f4382b5ea947aadfb7a40; No such file or directory ``` Standard glob.glob does not ...
[ "def", "_try_twice_tf_glob", "(", "pattern", ")", ":", "try", ":", "return", "tf", ".", "gfile", ".", "Glob", "(", "pattern", ")", "except", "tf", ".", "errors", ".", "NotFoundError", ":", "return", "tf", ".", "gfile", ".", "Glob", "(", "pattern", ")" ...
Glob twice, first time possibly catching `NotFoundError`. tf.gfile.Glob may crash with ``` tensorflow.python.framework.errors_impl.NotFoundError: xy/model.ckpt-1130761_temp_9cb4cb0b0f5f4382b5ea947aadfb7a40; No such file or directory ``` Standard glob.glob does not have this bug, but does not handle mul...
[ "Glob", "twice", "first", "time", "possibly", "catching", "NotFoundError", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L221-L245
train
tensorflow/tensor2tensor
tensor2tensor/utils/bleu_hook.py
_read_stepfiles_list
def _read_stepfiles_list(path_prefix, path_suffix=".index", min_steps=0): """Return list of StepFiles sorted by step from files at path_prefix.""" stepfiles = [] for filename in _try_twice_tf_glob(path_prefix + "*-[0-9]*" + path_suffix): basename = filename[:-len(path_suffix)] if path_suffix else filename ...
python
def _read_stepfiles_list(path_prefix, path_suffix=".index", min_steps=0): """Return list of StepFiles sorted by step from files at path_prefix.""" stepfiles = [] for filename in _try_twice_tf_glob(path_prefix + "*-[0-9]*" + path_suffix): basename = filename[:-len(path_suffix)] if path_suffix else filename ...
[ "def", "_read_stepfiles_list", "(", "path_prefix", ",", "path_suffix", "=", "\".index\"", ",", "min_steps", "=", "0", ")", ":", "stepfiles", "=", "[", "]", "for", "filename", "in", "_try_twice_tf_glob", "(", "path_prefix", "+", "\"*-[0-9]*\"", "+", "path_suffix"...
Return list of StepFiles sorted by step from files at path_prefix.
[ "Return", "list", "of", "StepFiles", "sorted", "by", "step", "from", "files", "at", "path_prefix", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L248-L264
train
tensorflow/tensor2tensor
tensor2tensor/utils/bleu_hook.py
stepfiles_iterator
def stepfiles_iterator(path_prefix, wait_minutes=0, min_steps=0, path_suffix=".index", sleep_sec=10): """Continuously yield new files with steps in filename as they appear. This is useful for checkpoint files or other files whose names differ just in an integer marking the number of steps ...
python
def stepfiles_iterator(path_prefix, wait_minutes=0, min_steps=0, path_suffix=".index", sleep_sec=10): """Continuously yield new files with steps in filename as they appear. This is useful for checkpoint files or other files whose names differ just in an integer marking the number of steps ...
[ "def", "stepfiles_iterator", "(", "path_prefix", ",", "wait_minutes", "=", "0", ",", "min_steps", "=", "0", ",", "path_suffix", "=", "\".index\"", ",", "sleep_sec", "=", "10", ")", ":", "# Wildcard D*-[0-9]* does not match D/x-1, so if D is a directory let", "# path_pre...
Continuously yield new files with steps in filename as they appear. This is useful for checkpoint files or other files whose names differ just in an integer marking the number of steps and match the wildcard path_prefix + "*-[0-9]*" + path_suffix. Unlike `tf.contrib.training.checkpoints_iterator`, this implem...
[ "Continuously", "yield", "new", "files", "with", "steps", "in", "filename", "as", "they", "appear", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L267-L317
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/vqa.py
_get_vqa_v2_annotations
def _get_vqa_v2_annotations(directory, annotation_url, annotation_filename="vqa_v2.tar.gz"): """Extract the VQA V2 annotation files to directory unless it's there.""" annotation_file = generator_utils.maybe_download_from_drive( directory, annotation_file...
python
def _get_vqa_v2_annotations(directory, annotation_url, annotation_filename="vqa_v2.tar.gz"): """Extract the VQA V2 annotation files to directory unless it's there.""" annotation_file = generator_utils.maybe_download_from_drive( directory, annotation_file...
[ "def", "_get_vqa_v2_annotations", "(", "directory", ",", "annotation_url", ",", "annotation_filename", "=", "\"vqa_v2.tar.gz\"", ")", ":", "annotation_file", "=", "generator_utils", ".", "maybe_download_from_drive", "(", "directory", ",", "annotation_filename", ",", "anno...
Extract the VQA V2 annotation files to directory unless it's there.
[ "Extract", "the", "VQA", "V2", "annotation", "files", "to", "directory", "unless", "it", "s", "there", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa.py#L44-L51
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/vqa.py
_get_vqa_v2_image_raw_dataset
def _get_vqa_v2_image_raw_dataset(directory, image_root_url, image_urls): """Extract the VQA V2 image data set to directory unless it's there.""" for url in image_urls: filename = os.path.basename(url) download_url = os.path.join(image_root_url, url) path = generator_utils.maybe_download(directory, file...
python
def _get_vqa_v2_image_raw_dataset(directory, image_root_url, image_urls): """Extract the VQA V2 image data set to directory unless it's there.""" for url in image_urls: filename = os.path.basename(url) download_url = os.path.join(image_root_url, url) path = generator_utils.maybe_download(directory, file...
[ "def", "_get_vqa_v2_image_raw_dataset", "(", "directory", ",", "image_root_url", ",", "image_urls", ")", ":", "for", "url", "in", "image_urls", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "url", ")", "download_url", "=", "os", ".", "path",...
Extract the VQA V2 image data set to directory unless it's there.
[ "Extract", "the", "VQA", "V2", "image", "data", "set", "to", "directory", "unless", "it", "s", "there", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa.py#L54-L62
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/vqa.py
_get_vqa_v2_image_feature_dataset
def _get_vqa_v2_image_feature_dataset( directory, feature_url, feature_filename="mscoco_feat.tar.gz"): """Extract the VQA V2 feature data set to directory unless it's there.""" feature_file = generator_utils.maybe_download_from_drive( directory, feature_filename, feature_url) with tarfile.open(feature_f...
python
def _get_vqa_v2_image_feature_dataset( directory, feature_url, feature_filename="mscoco_feat.tar.gz"): """Extract the VQA V2 feature data set to directory unless it's there.""" feature_file = generator_utils.maybe_download_from_drive( directory, feature_filename, feature_url) with tarfile.open(feature_f...
[ "def", "_get_vqa_v2_image_feature_dataset", "(", "directory", ",", "feature_url", ",", "feature_filename", "=", "\"mscoco_feat.tar.gz\"", ")", ":", "feature_file", "=", "generator_utils", ".", "maybe_download_from_drive", "(", "directory", ",", "feature_filename", ",", "f...
Extract the VQA V2 feature data set to directory unless it's there.
[ "Extract", "the", "VQA", "V2", "feature", "data", "set", "to", "directory", "unless", "it", "s", "there", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa.py#L65-L71
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
_parse_fail
def _parse_fail(name, var_type, value, values): """Helper function for raising a value error for bad assignment.""" raise ValueError( 'Could not parse hparam \'%s\' of type \'%s\' with value \'%s\' in %s' % (name, var_type.__name__, value, values))
python
def _parse_fail(name, var_type, value, values): """Helper function for raising a value error for bad assignment.""" raise ValueError( 'Could not parse hparam \'%s\' of type \'%s\' with value \'%s\' in %s' % (name, var_type.__name__, value, values))
[ "def", "_parse_fail", "(", "name", ",", "var_type", ",", "value", ",", "values", ")", ":", "raise", "ValueError", "(", "'Could not parse hparam \\'%s\\' of type \\'%s\\' with value \\'%s\\' in %s'", "%", "(", "name", ",", "var_type", ".", "__name__", ",", "value", "...
Helper function for raising a value error for bad assignment.
[ "Helper", "function", "for", "raising", "a", "value", "error", "for", "bad", "assignment", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L42-L46
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
_process_scalar_value
def _process_scalar_value(name, parse_fn, var_type, m_dict, values, results_dictionary): """Update results_dictionary with a scalar value. Used to update the results_dictionary to be returned by parse_values when encountering a clause with a scalar RHS (e.g. "s=5" or "arr[0]=5".) Mu...
python
def _process_scalar_value(name, parse_fn, var_type, m_dict, values, results_dictionary): """Update results_dictionary with a scalar value. Used to update the results_dictionary to be returned by parse_values when encountering a clause with a scalar RHS (e.g. "s=5" or "arr[0]=5".) Mu...
[ "def", "_process_scalar_value", "(", "name", ",", "parse_fn", ",", "var_type", ",", "m_dict", ",", "values", ",", "results_dictionary", ")", ":", "try", ":", "parsed_value", "=", "parse_fn", "(", "m_dict", "[", "'val'", "]", ")", "except", "ValueError", ":",...
Update results_dictionary with a scalar value. Used to update the results_dictionary to be returned by parse_values when encountering a clause with a scalar RHS (e.g. "s=5" or "arr[0]=5".) Mutates results_dictionary. Args: name: Name of variable in assignment ("s" or "arr"). parse_fn: Function for p...
[ "Update", "results_dictionary", "with", "a", "scalar", "value", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L55-L101
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
_process_list_value
def _process_list_value(name, parse_fn, var_type, m_dict, values, results_dictionary): """Update results_dictionary from a list of values. Used to update results_dictionary to be returned by parse_values when encountering a clause with a list RHS (e.g. "arr=[1,2,3]".) Mutates results_...
python
def _process_list_value(name, parse_fn, var_type, m_dict, values, results_dictionary): """Update results_dictionary from a list of values. Used to update results_dictionary to be returned by parse_values when encountering a clause with a list RHS (e.g. "arr=[1,2,3]".) Mutates results_...
[ "def", "_process_list_value", "(", "name", ",", "parse_fn", ",", "var_type", ",", "m_dict", ",", "values", ",", "results_dictionary", ")", ":", "if", "m_dict", "[", "'index'", "]", "is", "not", "None", ":", "raise", "ValueError", "(", "'Assignment of a list to...
Update results_dictionary from a list of values. Used to update results_dictionary to be returned by parse_values when encountering a clause with a list RHS (e.g. "arr=[1,2,3]".) Mutates results_dictionary. Args: name: Name of variable in assignment ("arr"). parse_fn: Function for parsing individual...
[ "Update", "results_dictionary", "from", "a", "list", "of", "values", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L104-L135
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
_cast_to_type_if_compatible
def _cast_to_type_if_compatible(name, param_type, value): """Cast hparam to the provided type, if compatible. Args: name: Name of the hparam to be cast. param_type: The type of the hparam. value: The value to be cast, if compatible. Returns: The result of casting `value` to `param_type`. Rais...
python
def _cast_to_type_if_compatible(name, param_type, value): """Cast hparam to the provided type, if compatible. Args: name: Name of the hparam to be cast. param_type: The type of the hparam. value: The value to be cast, if compatible. Returns: The result of casting `value` to `param_type`. Rais...
[ "def", "_cast_to_type_if_compatible", "(", "name", ",", "param_type", ",", "value", ")", ":", "fail_msg", "=", "(", "\"Could not cast hparam '%s' of type '%s' from value %r\"", "%", "(", "name", ",", "param_type", ",", "value", ")", ")", "# Some callers use None, for wh...
Cast hparam to the provided type, if compatible. Args: name: Name of the hparam to be cast. param_type: The type of the hparam. value: The value to be cast, if compatible. Returns: The result of casting `value` to `param_type`. Raises: ValueError: If the type of `value` is not compatible wi...
[ "Cast", "hparam", "to", "the", "provided", "type", "if", "compatible", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L138-L183
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
parse_values
def parse_values(values, type_map, ignore_unknown=False): """Parses hyperparameter values from a string into a python map. `values` is a string containing comma-separated `name=value` pairs. For each pair, the value of the hyperparameter named `name` is set to `value`. If a hyperparameter name appears multi...
python
def parse_values(values, type_map, ignore_unknown=False): """Parses hyperparameter values from a string into a python map. `values` is a string containing comma-separated `name=value` pairs. For each pair, the value of the hyperparameter named `name` is set to `value`. If a hyperparameter name appears multi...
[ "def", "parse_values", "(", "values", ",", "type_map", ",", "ignore_unknown", "=", "False", ")", ":", "results_dictionary", "=", "{", "}", "pos", "=", "0", "while", "pos", "<", "len", "(", "values", ")", ":", "m", "=", "PARAM_RE", ".", "match", "(", ...
Parses hyperparameter values from a string into a python map. `values` is a string containing comma-separated `name=value` pairs. For each pair, the value of the hyperparameter named `name` is set to `value`. If a hyperparameter name appears multiple times in `values`, a ValueError is raised (e.g. 'a=1,a=2'...
[ "Parses", "hyperparameter", "values", "from", "a", "string", "into", "a", "python", "map", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L186-L298
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
HParams.add_hparam
def add_hparam(self, name, value): """Adds {name, value} pair to hyperparameters. Args: name: Name of the hyperparameter. value: Value of the hyperparameter. Can be one of the following types: int, float, string, int list, float list, or string list. Raises: ValueError: if one of...
python
def add_hparam(self, name, value): """Adds {name, value} pair to hyperparameters. Args: name: Name of the hyperparameter. value: Value of the hyperparameter. Can be one of the following types: int, float, string, int list, float list, or string list. Raises: ValueError: if one of...
[ "def", "add_hparam", "(", "self", ",", "name", ",", "value", ")", ":", "# Keys in kwargs are unique, but 'name' could the name of a pre-existing", "# attribute of this object. In that case we refuse to use it as a", "# hyperparameter name.", "if", "getattr", "(", "self", ",", "n...
Adds {name, value} pair to hyperparameters. Args: name: Name of the hyperparameter. value: Value of the hyperparameter. Can be one of the following types: int, float, string, int list, float list, or string list. Raises: ValueError: if one of the arguments is invalid.
[ "Adds", "{", "name", "value", "}", "pair", "to", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L418-L441
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
HParams.set_hparam
def set_hparam(self, name, value): """Set the value of an existing hyperparameter. This function verifies that the type of the value matches the type of the existing hyperparameter. Args: name: Name of the hyperparameter. value: New value of the hyperparameter. Raises: KeyError:...
python
def set_hparam(self, name, value): """Set the value of an existing hyperparameter. This function verifies that the type of the value matches the type of the existing hyperparameter. Args: name: Name of the hyperparameter. value: New value of the hyperparameter. Raises: KeyError:...
[ "def", "set_hparam", "(", "self", ",", "name", ",", "value", ")", ":", "param_type", ",", "is_list", "=", "self", ".", "_hparam_types", "[", "name", "]", "if", "isinstance", "(", "value", ",", "list", ")", ":", "if", "not", "is_list", ":", "raise", "...
Set the value of an existing hyperparameter. This function verifies that the type of the value matches the type of the existing hyperparameter. Args: name: Name of the hyperparameter. value: New value of the hyperparameter. Raises: KeyError: If the hyperparameter doesn't exist. ...
[ "Set", "the", "value", "of", "an", "existing", "hyperparameter", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L443-L468
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
HParams.del_hparam
def del_hparam(self, name): """Removes the hyperparameter with key 'name'. Does nothing if it isn't present. Args: name: Name of the hyperparameter. """ if hasattr(self, name): delattr(self, name) del self._hparam_types[name]
python
def del_hparam(self, name): """Removes the hyperparameter with key 'name'. Does nothing if it isn't present. Args: name: Name of the hyperparameter. """ if hasattr(self, name): delattr(self, name) del self._hparam_types[name]
[ "def", "del_hparam", "(", "self", ",", "name", ")", ":", "if", "hasattr", "(", "self", ",", "name", ")", ":", "delattr", "(", "self", ",", "name", ")", "del", "self", ".", "_hparam_types", "[", "name", "]" ]
Removes the hyperparameter with key 'name'. Does nothing if it isn't present. Args: name: Name of the hyperparameter.
[ "Removes", "the", "hyperparameter", "with", "key", "name", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L470-L480
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
HParams.parse
def parse(self, values): """Override existing hyperparameter values, parsing new values from a string. See parse_values for more detail on the allowed format for values. Args: values: String. Comma separated list of `name=value` pairs where 'value' must follow the syntax described above. ...
python
def parse(self, values): """Override existing hyperparameter values, parsing new values from a string. See parse_values for more detail on the allowed format for values. Args: values: String. Comma separated list of `name=value` pairs where 'value' must follow the syntax described above. ...
[ "def", "parse", "(", "self", ",", "values", ")", ":", "type_map", "=", "{", "}", "for", "name", ",", "t", "in", "self", ".", "_hparam_types", ".", "items", "(", ")", ":", "param_type", ",", "_", "=", "t", "type_map", "[", "name", "]", "=", "param...
Override existing hyperparameter values, parsing new values from a string. See parse_values for more detail on the allowed format for values. Args: values: String. Comma separated list of `name=value` pairs where 'value' must follow the syntax described above. Returns: The `HParams` ...
[ "Override", "existing", "hyperparameter", "values", "parsing", "new", "values", "from", "a", "string", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L482-L504
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
HParams.override_from_dict
def override_from_dict(self, values_dict): """Override existing hyperparameter values, parsing new values from a dictionary. Args: values_dict: Dictionary of name:value pairs. Returns: The `HParams` instance. Raises: KeyError: If a hyperparameter in `values_dict` doesn't exist. ...
python
def override_from_dict(self, values_dict): """Override existing hyperparameter values, parsing new values from a dictionary. Args: values_dict: Dictionary of name:value pairs. Returns: The `HParams` instance. Raises: KeyError: If a hyperparameter in `values_dict` doesn't exist. ...
[ "def", "override_from_dict", "(", "self", ",", "values_dict", ")", ":", "for", "name", ",", "value", "in", "values_dict", ".", "items", "(", ")", ":", "self", ".", "set_hparam", "(", "name", ",", "value", ")", "return", "self" ]
Override existing hyperparameter values, parsing new values from a dictionary. Args: values_dict: Dictionary of name:value pairs. Returns: The `HParams` instance. Raises: KeyError: If a hyperparameter in `values_dict` doesn't exist. ValueError: If `values_dict` cannot be parsed.
[ "Override", "existing", "hyperparameter", "values", "parsing", "new", "values", "from", "a", "dictionary", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L506-L521
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
HParams.to_json
def to_json(self, indent=None, separators=None, sort_keys=False): """Serializes the hyperparameters into JSON. Args: indent: If a non-negative integer, JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, or negative, will only insert...
python
def to_json(self, indent=None, separators=None, sort_keys=False): """Serializes the hyperparameters into JSON. Args: indent: If a non-negative integer, JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, or negative, will only insert...
[ "def", "to_json", "(", "self", ",", "indent", "=", "None", ",", "separators", "=", "None", ",", "sort_keys", "=", "False", ")", ":", "def", "remove_callables", "(", "x", ")", ":", "\"\"\"Omit callable elements from input with arbitrary nesting.\"\"\"", "if", "isin...
Serializes the hyperparameters into JSON. Args: indent: If a non-negative integer, JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, or negative, will only insert newlines. `None` (the default) selects the most compact represen...
[ "Serializes", "the", "hyperparameters", "into", "JSON", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L529-L556
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
HParams.parse_json
def parse_json(self, values_json): """Override existing hyperparameter values, parsing new values from a json object. Args: values_json: String containing a json object of name:value pairs. Returns: The `HParams` instance. Raises: KeyError: If a hyperparameter in `values_json` doesn...
python
def parse_json(self, values_json): """Override existing hyperparameter values, parsing new values from a json object. Args: values_json: String containing a json object of name:value pairs. Returns: The `HParams` instance. Raises: KeyError: If a hyperparameter in `values_json` doesn...
[ "def", "parse_json", "(", "self", ",", "values_json", ")", ":", "values_map", "=", "json", ".", "loads", "(", "values_json", ")", "return", "self", ".", "override_from_dict", "(", "values_map", ")" ]
Override existing hyperparameter values, parsing new values from a json object. Args: values_json: String containing a json object of name:value pairs. Returns: The `HParams` instance. Raises: KeyError: If a hyperparameter in `values_json` doesn't exist. ValueError: If `values_jso...
[ "Override", "existing", "hyperparameter", "values", "parsing", "new", "values", "from", "a", "json", "object", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L558-L572
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
HParams.values
def values(self): """Return the hyperparameter values as a Python dictionary. Returns: A dictionary with hyperparameter names as keys. The values are the hyperparameter values. """ return {n: getattr(self, n) for n in self._hparam_types.keys()}
python
def values(self): """Return the hyperparameter values as a Python dictionary. Returns: A dictionary with hyperparameter names as keys. The values are the hyperparameter values. """ return {n: getattr(self, n) for n in self._hparam_types.keys()}
[ "def", "values", "(", "self", ")", ":", "return", "{", "n", ":", "getattr", "(", "self", ",", "n", ")", "for", "n", "in", "self", ".", "_hparam_types", ".", "keys", "(", ")", "}" ]
Return the hyperparameter values as a Python dictionary. Returns: A dictionary with hyperparameter names as keys. The values are the hyperparameter values.
[ "Return", "the", "hyperparameter", "values", "as", "a", "Python", "dictionary", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L574-L581
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
HParams.get
def get(self, key, default=None): """Returns the value of `key` if it exists, else `default`.""" if key in self._hparam_types: # Ensure that default is compatible with the parameter type. if default is not None: param_type, is_param_list = self._hparam_types[key] type_str = 'list<%s>...
python
def get(self, key, default=None): """Returns the value of `key` if it exists, else `default`.""" if key in self._hparam_types: # Ensure that default is compatible with the parameter type. if default is not None: param_type, is_param_list = self._hparam_types[key] type_str = 'list<%s>...
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "if", "key", "in", "self", ".", "_hparam_types", ":", "# Ensure that default is compatible with the parameter type.", "if", "default", "is", "not", "None", ":", "param_type", ",", "i...
Returns the value of `key` if it exists, else `default`.
[ "Returns", "the", "value", "of", "key", "if", "it", "exists", "else", "default", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L583-L608
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparam.py
HParams._get_kind_name
def _get_kind_name(param_type, is_list): """Returns the field name given parameter type and is_list. Args: param_type: Data type of the hparam. is_list: Whether this is a list. Returns: A string representation of the field name. Raises: ValueError: If parameter type is not rec...
python
def _get_kind_name(param_type, is_list): """Returns the field name given parameter type and is_list. Args: param_type: Data type of the hparam. is_list: Whether this is a list. Returns: A string representation of the field name. Raises: ValueError: If parameter type is not rec...
[ "def", "_get_kind_name", "(", "param_type", ",", "is_list", ")", ":", "if", "issubclass", "(", "param_type", ",", "bool", ")", ":", "# This check must happen before issubclass(param_type, six.integer_types),", "# since Python considers bool to be a subclass of int.", "typename", ...
Returns the field name given parameter type and is_list. Args: param_type: Data type of the hparam. is_list: Whether this is a list. Returns: A string representation of the field name. Raises: ValueError: If parameter type is not recognized.
[ "Returns", "the", "field", "name", "given", "parameter", "type", "and", "is_list", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L620-L651
train
tensorflow/tensor2tensor
tensor2tensor/insights/transformer_model.py
TransformerModel.process
def process(self, query): """Returns the visualizations for query. Args: query: The query to process. Returns: A dictionary of results with processing and graph visualizations. """ tf.logging.info("Processing new query [%s]" %query) # Create the new TFDBG hook directory. hook_...
python
def process(self, query): """Returns the visualizations for query. Args: query: The query to process. Returns: A dictionary of results with processing and graph visualizations. """ tf.logging.info("Processing new query [%s]" %query) # Create the new TFDBG hook directory. hook_...
[ "def", "process", "(", "self", ",", "query", ")", ":", "tf", ".", "logging", ".", "info", "(", "\"Processing new query [%s]\"", "%", "query", ")", "# Create the new TFDBG hook directory.", "hook_dir", "=", "\"/tmp/t2t_server_dump/request_%d\"", "%", "int", "(", "tim...
Returns the visualizations for query. Args: query: The query to process. Returns: A dictionary of results with processing and graph visualizations.
[ "Returns", "the", "visualizations", "for", "query", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/insights/transformer_model.py#L141-L301
train
tensorflow/tensor2tensor
tensor2tensor/trax/trainer.py
_default_output_dir
def _default_output_dir(): """Default output directory.""" try: dataset_name = gin.query_parameter("inputs.dataset_name") except ValueError: dataset_name = "random" dir_name = "{model_name}_{dataset_name}_{timestamp}".format( model_name=gin.query_parameter("train.model").configurable.name, d...
python
def _default_output_dir(): """Default output directory.""" try: dataset_name = gin.query_parameter("inputs.dataset_name") except ValueError: dataset_name = "random" dir_name = "{model_name}_{dataset_name}_{timestamp}".format( model_name=gin.query_parameter("train.model").configurable.name, d...
[ "def", "_default_output_dir", "(", ")", ":", "try", ":", "dataset_name", "=", "gin", ".", "query_parameter", "(", "\"inputs.dataset_name\"", ")", "except", "ValueError", ":", "dataset_name", "=", "\"random\"", "dir_name", "=", "\"{model_name}_{dataset_name}_{timestamp}\...
Default output directory.
[ "Default", "output", "directory", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trainer.py#L48-L62
train
tensorflow/tensor2tensor
tensor2tensor/trax/trainer.py
_setup_gin
def _setup_gin(): """Setup gin configuration.""" # Imports for configurables # pylint: disable=g-import-not-at-top,unused-import,g-bad-import-order,reimported,unused-variable from tensor2tensor.trax import models as _trax_models from tensor2tensor.trax import optimizers as _trax_opt # pylint: disable=g-impo...
python
def _setup_gin(): """Setup gin configuration.""" # Imports for configurables # pylint: disable=g-import-not-at-top,unused-import,g-bad-import-order,reimported,unused-variable from tensor2tensor.trax import models as _trax_models from tensor2tensor.trax import optimizers as _trax_opt # pylint: disable=g-impo...
[ "def", "_setup_gin", "(", ")", ":", "# Imports for configurables", "# pylint: disable=g-import-not-at-top,unused-import,g-bad-import-order,reimported,unused-variable", "from", "tensor2tensor", ".", "trax", "import", "models", "as", "_trax_models", "from", "tensor2tensor", ".", "t...
Setup gin configuration.
[ "Setup", "gin", "configuration", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trainer.py#L65-L81
train
tensorflow/tensor2tensor
tensor2tensor/v2/t2t.py
train_and_eval_dataset
def train_and_eval_dataset(dataset_name, data_dir): """Return train and evaluation datasets, feature info and supervised keys. Args: dataset_name: a string, the name of the dataset; if it starts with "v1_" then we'll search T2T Problem registry for it, otherwise we assume it is a dataset from TFDS ...
python
def train_and_eval_dataset(dataset_name, data_dir): """Return train and evaluation datasets, feature info and supervised keys. Args: dataset_name: a string, the name of the dataset; if it starts with "v1_" then we'll search T2T Problem registry for it, otherwise we assume it is a dataset from TFDS ...
[ "def", "train_and_eval_dataset", "(", "dataset_name", ",", "data_dir", ")", ":", "if", "dataset_name", ".", "startswith", "(", "\"v1_\"", ")", ":", "return", "_train_and_eval_dataset_v1", "(", "dataset_name", "[", "3", ":", "]", ",", "data_dir", ")", "dataset_bu...
Return train and evaluation datasets, feature info and supervised keys. Args: dataset_name: a string, the name of the dataset; if it starts with "v1_" then we'll search T2T Problem registry for it, otherwise we assume it is a dataset from TFDS and load it from there. data_dir: directory where the...
[ "Return", "train", "and", "evaluation", "datasets", "feature", "info", "and", "supervised", "keys", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L48-L83
train
tensorflow/tensor2tensor
tensor2tensor/v2/t2t.py
_make_info
def _make_info(shape_list, num_classes): """Create an info-like tuple for feature given some shapes and vocab size.""" feature_info = collections.namedtuple("FeatureInfo", ["shape", "num_classes"]) cur_shape = list(shape_list[0]) # We need to merge the provided shapes, put None where they disagree. for shape ...
python
def _make_info(shape_list, num_classes): """Create an info-like tuple for feature given some shapes and vocab size.""" feature_info = collections.namedtuple("FeatureInfo", ["shape", "num_classes"]) cur_shape = list(shape_list[0]) # We need to merge the provided shapes, put None where they disagree. for shape ...
[ "def", "_make_info", "(", "shape_list", ",", "num_classes", ")", ":", "feature_info", "=", "collections", ".", "namedtuple", "(", "\"FeatureInfo\"", ",", "[", "\"shape\"", ",", "\"num_classes\"", "]", ")", "cur_shape", "=", "list", "(", "shape_list", "[", "0",...
Create an info-like tuple for feature given some shapes and vocab size.
[ "Create", "an", "info", "-", "like", "tuple", "for", "feature", "given", "some", "shapes", "and", "vocab", "size", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L86-L98
train
tensorflow/tensor2tensor
tensor2tensor/v2/t2t.py
_select_features
def _select_features(example, feature_list=None): """Select a subset of features from the example dict.""" feature_list = feature_list or ["inputs", "targets"] return {f: example[f] for f in feature_list}
python
def _select_features(example, feature_list=None): """Select a subset of features from the example dict.""" feature_list = feature_list or ["inputs", "targets"] return {f: example[f] for f in feature_list}
[ "def", "_select_features", "(", "example", ",", "feature_list", "=", "None", ")", ":", "feature_list", "=", "feature_list", "or", "[", "\"inputs\"", ",", "\"targets\"", "]", "return", "{", "f", ":", "example", "[", "f", "]", "for", "f", "in", "feature_list...
Select a subset of features from the example dict.
[ "Select", "a", "subset", "of", "features", "from", "the", "example", "dict", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L101-L104
train
tensorflow/tensor2tensor
tensor2tensor/v2/t2t.py
_train_and_eval_dataset_v1
def _train_and_eval_dataset_v1(problem_name, data_dir): """Return train and evaluation datasets, feature info and supervised keys.""" problem = problems.problem(problem_name) train_dataset = problem.dataset(tf.estimator.ModeKeys.TRAIN, data_dir) train_dataset = train_dataset.map(_select_features) eval_dataset...
python
def _train_and_eval_dataset_v1(problem_name, data_dir): """Return train and evaluation datasets, feature info and supervised keys.""" problem = problems.problem(problem_name) train_dataset = problem.dataset(tf.estimator.ModeKeys.TRAIN, data_dir) train_dataset = train_dataset.map(_select_features) eval_dataset...
[ "def", "_train_and_eval_dataset_v1", "(", "problem_name", ",", "data_dir", ")", ":", "problem", "=", "problems", ".", "problem", "(", "problem_name", ")", "train_dataset", "=", "problem", ".", "dataset", "(", "tf", ".", "estimator", ".", "ModeKeys", ".", "TRAI...
Return train and evaluation datasets, feature info and supervised keys.
[ "Return", "train", "and", "evaluation", "datasets", "feature", "info", "and", "supervised", "keys", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L107-L126
train
tensorflow/tensor2tensor
tensor2tensor/v2/t2t.py
batch_fn
def batch_fn(dataset, training, shapes, target_names, batch_size=32, eval_batch_size=32, bucket_batch_length=32, bucket_max_length=256, bucket_min_length=8, bucket_length_step=1.1, buckets=None): """Batching function.""" del target_names # If bucketing is not specified, chec...
python
def batch_fn(dataset, training, shapes, target_names, batch_size=32, eval_batch_size=32, bucket_batch_length=32, bucket_max_length=256, bucket_min_length=8, bucket_length_step=1.1, buckets=None): """Batching function.""" del target_names # If bucketing is not specified, chec...
[ "def", "batch_fn", "(", "dataset", ",", "training", ",", "shapes", ",", "target_names", ",", "batch_size", "=", "32", ",", "eval_batch_size", "=", "32", ",", "bucket_batch_length", "=", "32", ",", "bucket_max_length", "=", "256", ",", "bucket_min_length", "=",...
Batching function.
[ "Batching", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L140-L174
train
tensorflow/tensor2tensor
tensor2tensor/v2/t2t.py
shuffle_and_batch_data
def shuffle_and_batch_data(dataset, target_names, features_info, training): """Shuffle and batch the given dataset.""" def append_targets(example): """Append targets to the example dictionary. Needed for Keras.""" if len(target_names) == 1: return (example, example[target_names[0]]) targets = {} ...
python
def shuffle_and_batch_data(dataset, target_names, features_info, training): """Shuffle and batch the given dataset.""" def append_targets(example): """Append targets to the example dictionary. Needed for Keras.""" if len(target_names) == 1: return (example, example[target_names[0]]) targets = {} ...
[ "def", "shuffle_and_batch_data", "(", "dataset", ",", "target_names", ",", "features_info", ",", "training", ")", ":", "def", "append_targets", "(", "example", ")", ":", "\"\"\"Append targets to the example dictionary. Needed for Keras.\"\"\"", "if", "len", "(", "target_n...
Shuffle and batch the given dataset.
[ "Shuffle", "and", "batch", "the", "given", "dataset", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L177-L195
train
tensorflow/tensor2tensor
tensor2tensor/v2/t2t.py
optimize_fn
def optimize_fn(model, optimizer=None, learning_rate_schedule=None, loss=None, metrics=None): """Compile the model in Keras.""" learning_rate_schedule = learning_rate_schedule or T2TLearningRateSchedule() if optimizer: optimizer = optimizer(learn...
python
def optimize_fn(model, optimizer=None, learning_rate_schedule=None, loss=None, metrics=None): """Compile the model in Keras.""" learning_rate_schedule = learning_rate_schedule or T2TLearningRateSchedule() if optimizer: optimizer = optimizer(learn...
[ "def", "optimize_fn", "(", "model", ",", "optimizer", "=", "None", ",", "learning_rate_schedule", "=", "None", ",", "loss", "=", "None", ",", "metrics", "=", "None", ")", ":", "learning_rate_schedule", "=", "learning_rate_schedule", "or", "T2TLearningRateSchedule"...
Compile the model in Keras.
[ "Compile", "the", "model", "in", "Keras", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L233-L253
train
tensorflow/tensor2tensor
tensor2tensor/v2/t2t.py
train_fn
def train_fn(data_dir=None, output_dir=None, model_class=gin.REQUIRED, dataset=gin.REQUIRED, input_names=None, target_names=None, train_steps=1000, eval_steps=1, eval_frequency=100): """Train the given model on the given dataset. Args: data_dir: Directory where the data i...
python
def train_fn(data_dir=None, output_dir=None, model_class=gin.REQUIRED, dataset=gin.REQUIRED, input_names=None, target_names=None, train_steps=1000, eval_steps=1, eval_frequency=100): """Train the given model on the given dataset. Args: data_dir: Directory where the data i...
[ "def", "train_fn", "(", "data_dir", "=", "None", ",", "output_dir", "=", "None", ",", "model_class", "=", "gin", ".", "REQUIRED", ",", "dataset", "=", "gin", ".", "REQUIRED", ",", "input_names", "=", "None", ",", "target_names", "=", "None", ",", "train_...
Train the given model on the given dataset. Args: data_dir: Directory where the data is located. output_dir: Directory where to put the logs and checkpoints. model_class: The model class to train. dataset: The name of the dataset to train on. input_names: List of strings with the names of the fea...
[ "Train", "the", "given", "model", "on", "the", "given", "dataset", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L259-L324
train
tensorflow/tensor2tensor
tensor2tensor/v2/t2t.py
t2t_train
def t2t_train(model_name, dataset_name, data_dir=None, output_dir=None, config_file=None, config=None): """Main function to train the given model on the given dataset. Args: model_name: The name of the model to train. dataset_name: The name of the dataset to train on. data_dir: Directory ...
python
def t2t_train(model_name, dataset_name, data_dir=None, output_dir=None, config_file=None, config=None): """Main function to train the given model on the given dataset. Args: model_name: The name of the model to train. dataset_name: The name of the dataset to train on. data_dir: Directory ...
[ "def", "t2t_train", "(", "model_name", ",", "dataset_name", ",", "data_dir", "=", "None", ",", "output_dir", "=", "None", ",", "config_file", "=", "None", ",", "config", "=", "None", ")", ":", "if", "model_name", "not", "in", "_MODEL_REGISTRY", ":", "raise...
Main function to train the given model on the given dataset. Args: model_name: The name of the model to train. dataset_name: The name of the dataset to train on. data_dir: Directory where the data is located. output_dir: Directory where to put the logs and checkpoints. config_file: the gin config...
[ "Main", "function", "to", "train", "the", "given", "model", "on", "the", "given", "dataset", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L327-L347
train
tensorflow/tensor2tensor
tensor2tensor/bin/t2t_decoder.py
decode
def decode(estimator, hparams, decode_hp): """Decode from estimator. Interactive, from file, or from dataset.""" if FLAGS.decode_interactive: if estimator.config.use_tpu: raise ValueError("TPU can only decode from dataset.") decoding.decode_interactively(estimator, hparams, decode_hp, ...
python
def decode(estimator, hparams, decode_hp): """Decode from estimator. Interactive, from file, or from dataset.""" if FLAGS.decode_interactive: if estimator.config.use_tpu: raise ValueError("TPU can only decode from dataset.") decoding.decode_interactively(estimator, hparams, decode_hp, ...
[ "def", "decode", "(", "estimator", ",", "hparams", ",", "decode_hp", ")", ":", "if", "FLAGS", ".", "decode_interactive", ":", "if", "estimator", ".", "config", ".", "use_tpu", ":", "raise", "ValueError", "(", "\"TPU can only decode from dataset.\"", ")", "decodi...
Decode from estimator. Interactive, from file, or from dataset.
[ "Decode", "from", "estimator", ".", "Interactive", "from", "file", "or", "from", "dataset", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_decoder.py#L82-L104
train
tensorflow/tensor2tensor
tensor2tensor/bin/t2t_decoder.py
score_file
def score_file(filename): """Score each line in a file and return the scores.""" # Prepare model. hparams = create_hparams() encoders = registry.problem(FLAGS.problem).feature_encoders(FLAGS.data_dir) has_inputs = "inputs" in encoders # Prepare features for feeding into the model. if has_inputs: inpu...
python
def score_file(filename): """Score each line in a file and return the scores.""" # Prepare model. hparams = create_hparams() encoders = registry.problem(FLAGS.problem).feature_encoders(FLAGS.data_dir) has_inputs = "inputs" in encoders # Prepare features for feeding into the model. if has_inputs: inpu...
[ "def", "score_file", "(", "filename", ")", ":", "# Prepare model.", "hparams", "=", "create_hparams", "(", ")", "encoders", "=", "registry", ".", "problem", "(", "FLAGS", ".", "problem", ")", ".", "feature_encoders", "(", "FLAGS", ".", "data_dir", ")", "has_...
Score each line in a file and return the scores.
[ "Score", "each", "line", "in", "a", "file", "and", "return", "the", "scores", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_decoder.py#L107-L164
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
time_to_channels
def time_to_channels(embedded_video): """Put time dimension on channels in an embedded video.""" video_shape = common_layers.shape_list(embedded_video) if len(video_shape) != 5: raise ValueError("Assuming videos given as tensors in the format " "[batch, time, height, width, channels] but ...
python
def time_to_channels(embedded_video): """Put time dimension on channels in an embedded video.""" video_shape = common_layers.shape_list(embedded_video) if len(video_shape) != 5: raise ValueError("Assuming videos given as tensors in the format " "[batch, time, height, width, channels] but ...
[ "def", "time_to_channels", "(", "embedded_video", ")", ":", "video_shape", "=", "common_layers", ".", "shape_list", "(", "embedded_video", ")", "if", "len", "(", "video_shape", ")", "!=", "5", ":", "raise", "ValueError", "(", "\"Assuming videos given as tensors in t...
Put time dimension on channels in an embedded video.
[ "Put", "time", "dimension", "on", "channels", "in", "an", "embedded", "video", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L38-L49
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_basic
def autoencoder_basic(): """Basic autoencoder model.""" hparams = common_hparams.basic_params1() hparams.optimizer = "adam" hparams.learning_rate_constant = 0.0002 hparams.learning_rate_warmup_steps = 500 hparams.learning_rate_schedule = "constant * linear_warmup" hparams.label_smoothing = 0.0 hparams.b...
python
def autoencoder_basic(): """Basic autoencoder model.""" hparams = common_hparams.basic_params1() hparams.optimizer = "adam" hparams.learning_rate_constant = 0.0002 hparams.learning_rate_warmup_steps = 500 hparams.learning_rate_schedule = "constant * linear_warmup" hparams.label_smoothing = 0.0 hparams.b...
[ "def", "autoencoder_basic", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "optimizer", "=", "\"adam\"", "hparams", ".", "learning_rate_constant", "=", "0.0002", "hparams", ".", "learning_rate_warmup_steps", "=", "...
Basic autoencoder model.
[ "Basic", "autoencoder", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1027-L1069
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_autoregressive
def autoencoder_autoregressive(): """Autoregressive autoencoder model.""" hparams = autoencoder_basic() hparams.add_hparam("autoregressive_forget_base", False) hparams.add_hparam("autoregressive_mode", "none") hparams.add_hparam("autoregressive_decode_steps", 0) hparams.add_hparam("autoregressive_eval_pure_...
python
def autoencoder_autoregressive(): """Autoregressive autoencoder model.""" hparams = autoencoder_basic() hparams.add_hparam("autoregressive_forget_base", False) hparams.add_hparam("autoregressive_mode", "none") hparams.add_hparam("autoregressive_decode_steps", 0) hparams.add_hparam("autoregressive_eval_pure_...
[ "def", "autoencoder_autoregressive", "(", ")", ":", "hparams", "=", "autoencoder_basic", "(", ")", "hparams", ".", "add_hparam", "(", "\"autoregressive_forget_base\"", ",", "False", ")", "hparams", ".", "add_hparam", "(", "\"autoregressive_mode\"", ",", "\"none\"", ...
Autoregressive autoencoder model.
[ "Autoregressive", "autoencoder", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1073-L1081
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_residual
def autoencoder_residual(): """Residual autoencoder model.""" hparams = autoencoder_autoregressive() hparams.optimizer = "Adafactor" hparams.clip_grad_norm = 1.0 hparams.learning_rate_constant = 0.5 hparams.learning_rate_warmup_steps = 500 hparams.learning_rate_schedule = "constant * linear_warmup * rsqrt...
python
def autoencoder_residual(): """Residual autoencoder model.""" hparams = autoencoder_autoregressive() hparams.optimizer = "Adafactor" hparams.clip_grad_norm = 1.0 hparams.learning_rate_constant = 0.5 hparams.learning_rate_warmup_steps = 500 hparams.learning_rate_schedule = "constant * linear_warmup * rsqrt...
[ "def", "autoencoder_residual", "(", ")", ":", "hparams", "=", "autoencoder_autoregressive", "(", ")", "hparams", ".", "optimizer", "=", "\"Adafactor\"", "hparams", ".", "clip_grad_norm", "=", "1.0", "hparams", ".", "learning_rate_constant", "=", "0.5", "hparams", ...
Residual autoencoder model.
[ "Residual", "autoencoder", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1085-L1103
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_residual_text
def autoencoder_residual_text(): """Residual autoencoder model for text.""" hparams = autoencoder_residual() hparams.bottleneck_bits = 32 hparams.batch_size = 1024 hparams.hidden_size = 64 hparams.max_hidden_size = 512 hparams.bottleneck_noise = 0.0 hparams.bottom = { "inputs": modalities.identity...
python
def autoencoder_residual_text(): """Residual autoencoder model for text.""" hparams = autoencoder_residual() hparams.bottleneck_bits = 32 hparams.batch_size = 1024 hparams.hidden_size = 64 hparams.max_hidden_size = 512 hparams.bottleneck_noise = 0.0 hparams.bottom = { "inputs": modalities.identity...
[ "def", "autoencoder_residual_text", "(", ")", ":", "hparams", "=", "autoencoder_residual", "(", ")", "hparams", ".", "bottleneck_bits", "=", "32", "hparams", ".", "batch_size", "=", "1024", "hparams", ".", "hidden_size", "=", "64", "hparams", ".", "max_hidden_si...
Residual autoencoder model for text.
[ "Residual", "autoencoder", "model", "for", "text", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1107-L1124
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_basic_discrete
def autoencoder_basic_discrete(): """Basic autoencoder model.""" hparams = autoencoder_autoregressive() hparams.num_hidden_layers = 5 hparams.hidden_size = 64 hparams.bottleneck_bits = 1024 hparams.bottleneck_noise = 0.1 hparams.add_hparam("discretize_warmup_steps", 16000) return hparams
python
def autoencoder_basic_discrete(): """Basic autoencoder model.""" hparams = autoencoder_autoregressive() hparams.num_hidden_layers = 5 hparams.hidden_size = 64 hparams.bottleneck_bits = 1024 hparams.bottleneck_noise = 0.1 hparams.add_hparam("discretize_warmup_steps", 16000) return hparams
[ "def", "autoencoder_basic_discrete", "(", ")", ":", "hparams", "=", "autoencoder_autoregressive", "(", ")", "hparams", ".", "num_hidden_layers", "=", "5", "hparams", ".", "hidden_size", "=", "64", "hparams", ".", "bottleneck_bits", "=", "1024", "hparams", ".", "...
Basic autoencoder model.
[ "Basic", "autoencoder", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1128-L1136
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_residual_discrete
def autoencoder_residual_discrete(): """Residual discrete autoencoder model.""" hparams = autoencoder_residual() hparams.bottleneck_bits = 1024 hparams.bottleneck_noise = 0.05 hparams.add_hparam("discretize_warmup_steps", 16000) hparams.add_hparam("bottleneck_kind", "tanh_discrete") hparams.add_hparam("is...
python
def autoencoder_residual_discrete(): """Residual discrete autoencoder model.""" hparams = autoencoder_residual() hparams.bottleneck_bits = 1024 hparams.bottleneck_noise = 0.05 hparams.add_hparam("discretize_warmup_steps", 16000) hparams.add_hparam("bottleneck_kind", "tanh_discrete") hparams.add_hparam("is...
[ "def", "autoencoder_residual_discrete", "(", ")", ":", "hparams", "=", "autoencoder_residual", "(", ")", "hparams", ".", "bottleneck_bits", "=", "1024", "hparams", ".", "bottleneck_noise", "=", "0.05", "hparams", ".", "add_hparam", "(", "\"discretize_warmup_steps\"", ...
Residual discrete autoencoder model.
[ "Residual", "discrete", "autoencoder", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1140-L1153
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_residual_discrete_big
def autoencoder_residual_discrete_big(): """Residual discrete autoencoder model, big version.""" hparams = autoencoder_residual_discrete() hparams.hidden_size = 128 hparams.max_hidden_size = 4096 hparams.bottleneck_noise = 0.1 hparams.residual_dropout = 0.4 return hparams
python
def autoencoder_residual_discrete_big(): """Residual discrete autoencoder model, big version.""" hparams = autoencoder_residual_discrete() hparams.hidden_size = 128 hparams.max_hidden_size = 4096 hparams.bottleneck_noise = 0.1 hparams.residual_dropout = 0.4 return hparams
[ "def", "autoencoder_residual_discrete_big", "(", ")", ":", "hparams", "=", "autoencoder_residual_discrete", "(", ")", "hparams", ".", "hidden_size", "=", "128", "hparams", ".", "max_hidden_size", "=", "4096", "hparams", ".", "bottleneck_noise", "=", "0.1", "hparams"...
Residual discrete autoencoder model, big version.
[ "Residual", "discrete", "autoencoder", "model", "big", "version", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1157-L1164
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_ordered_discrete
def autoencoder_ordered_discrete(): """Ordered discrete autoencoder model.""" hparams = autoencoder_residual_discrete() hparams.bottleneck_noise = 0.05 # Use 0.8 for ordered. hparams.gan_loss_factor = 0.05 hparams.add_hparam("unordered", True) return hparams
python
def autoencoder_ordered_discrete(): """Ordered discrete autoencoder model.""" hparams = autoencoder_residual_discrete() hparams.bottleneck_noise = 0.05 # Use 0.8 for ordered. hparams.gan_loss_factor = 0.05 hparams.add_hparam("unordered", True) return hparams
[ "def", "autoencoder_ordered_discrete", "(", ")", ":", "hparams", "=", "autoencoder_residual_discrete", "(", ")", "hparams", ".", "bottleneck_noise", "=", "0.05", "# Use 0.8 for ordered.", "hparams", ".", "gan_loss_factor", "=", "0.05", "hparams", ".", "add_hparam", "(...
Ordered discrete autoencoder model.
[ "Ordered", "discrete", "autoencoder", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1168-L1174
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_ordered_discrete_image64
def autoencoder_ordered_discrete_image64(): """Ordered discrete autoencoder model.""" hparams = autoencoder_ordered_discrete() hparams.batch_size = 32 hparams.num_hidden_layers = 6 hparams.bottleneck_warmup_steps *= 2 hparams.gan_codes_warmup_steps *= 2 return hparams
python
def autoencoder_ordered_discrete_image64(): """Ordered discrete autoencoder model.""" hparams = autoencoder_ordered_discrete() hparams.batch_size = 32 hparams.num_hidden_layers = 6 hparams.bottleneck_warmup_steps *= 2 hparams.gan_codes_warmup_steps *= 2 return hparams
[ "def", "autoencoder_ordered_discrete_image64", "(", ")", ":", "hparams", "=", "autoencoder_ordered_discrete", "(", ")", "hparams", ".", "batch_size", "=", "32", "hparams", ".", "num_hidden_layers", "=", "6", "hparams", ".", "bottleneck_warmup_steps", "*=", "2", "hpa...
Ordered discrete autoencoder model.
[ "Ordered", "discrete", "autoencoder", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1178-L1186
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_ordered_text
def autoencoder_ordered_text(): """Ordered discrete autoencoder model for text.""" hparams = autoencoder_ordered_discrete() hparams.bottleneck_bits = 1024 hparams.bottleneck_shared_bits = 1024-64 hparams.bottleneck_shared_bits_start_warmup = 75000 hparams.bottleneck_shared_bits_stop_warmup = 275000 hparam...
python
def autoencoder_ordered_text(): """Ordered discrete autoencoder model for text.""" hparams = autoencoder_ordered_discrete() hparams.bottleneck_bits = 1024 hparams.bottleneck_shared_bits = 1024-64 hparams.bottleneck_shared_bits_start_warmup = 75000 hparams.bottleneck_shared_bits_stop_warmup = 275000 hparam...
[ "def", "autoencoder_ordered_text", "(", ")", ":", "hparams", "=", "autoencoder_ordered_discrete", "(", ")", "hparams", ".", "bottleneck_bits", "=", "1024", "hparams", ".", "bottleneck_shared_bits", "=", "1024", "-", "64", "hparams", ".", "bottleneck_shared_bits_start_...
Ordered discrete autoencoder model for text.
[ "Ordered", "discrete", "autoencoder", "model", "for", "text", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1214-L1234
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_ordered_text_small
def autoencoder_ordered_text_small(): """Ordered discrete autoencoder model for text, small version.""" hparams = autoencoder_ordered_text() hparams.bottleneck_bits = 32 hparams.num_hidden_layers = 3 hparams.hidden_size = 64 hparams.max_hidden_size = 512 hparams.bottleneck_noise = 0.0 hparams.autoregres...
python
def autoencoder_ordered_text_small(): """Ordered discrete autoencoder model for text, small version.""" hparams = autoencoder_ordered_text() hparams.bottleneck_bits = 32 hparams.num_hidden_layers = 3 hparams.hidden_size = 64 hparams.max_hidden_size = 512 hparams.bottleneck_noise = 0.0 hparams.autoregres...
[ "def", "autoencoder_ordered_text_small", "(", ")", ":", "hparams", "=", "autoencoder_ordered_text", "(", ")", "hparams", ".", "bottleneck_bits", "=", "32", "hparams", ".", "num_hidden_layers", "=", "3", "hparams", ".", "hidden_size", "=", "64", "hparams", ".", "...
Ordered discrete autoencoder model for text, small version.
[ "Ordered", "discrete", "autoencoder", "model", "for", "text", "small", "version", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1238-L1248
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_discrete_pong
def autoencoder_discrete_pong(): """Discrete autoencoder model for compressing pong frames.""" hparams = autoencoder_ordered_discrete() hparams.num_hidden_layers = 3 hparams.bottleneck_bits = 24 hparams.batch_size = 2 hparams.gan_loss_factor = 0.01 hparams.bottleneck_l2_factor = 0.001 hparams.add_hparam...
python
def autoencoder_discrete_pong(): """Discrete autoencoder model for compressing pong frames.""" hparams = autoencoder_ordered_discrete() hparams.num_hidden_layers = 3 hparams.bottleneck_bits = 24 hparams.batch_size = 2 hparams.gan_loss_factor = 0.01 hparams.bottleneck_l2_factor = 0.001 hparams.add_hparam...
[ "def", "autoencoder_discrete_pong", "(", ")", ":", "hparams", "=", "autoencoder_ordered_discrete", "(", ")", "hparams", ".", "num_hidden_layers", "=", "3", "hparams", ".", "bottleneck_bits", "=", "24", "hparams", ".", "batch_size", "=", "2", "hparams", ".", "gan...
Discrete autoencoder model for compressing pong frames.
[ "Discrete", "autoencoder", "model", "for", "compressing", "pong", "frames", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1261-L1270
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_discrete_tiny
def autoencoder_discrete_tiny(): """Discrete autoencoder model for compressing pong frames for testing.""" hparams = autoencoder_ordered_discrete() hparams.num_hidden_layers = 2 hparams.bottleneck_bits = 24 hparams.batch_size = 2 hparams.gan_loss_factor = 0. hparams.bottleneck_l2_factor = 0.001 hparams....
python
def autoencoder_discrete_tiny(): """Discrete autoencoder model for compressing pong frames for testing.""" hparams = autoencoder_ordered_discrete() hparams.num_hidden_layers = 2 hparams.bottleneck_bits = 24 hparams.batch_size = 2 hparams.gan_loss_factor = 0. hparams.bottleneck_l2_factor = 0.001 hparams....
[ "def", "autoencoder_discrete_tiny", "(", ")", ":", "hparams", "=", "autoencoder_ordered_discrete", "(", ")", "hparams", ".", "num_hidden_layers", "=", "2", "hparams", ".", "bottleneck_bits", "=", "24", "hparams", ".", "batch_size", "=", "2", "hparams", ".", "gan...
Discrete autoencoder model for compressing pong frames for testing.
[ "Discrete", "autoencoder", "model", "for", "compressing", "pong", "frames", "for", "testing", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1274-L1286
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_discrete_cifar
def autoencoder_discrete_cifar(): """Discrete autoencoder model for compressing cifar.""" hparams = autoencoder_ordered_discrete() hparams.bottleneck_noise = 0.0 hparams.bottleneck_bits = 90 hparams.num_hidden_layers = 2 hparams.hidden_size = 256 hparams.num_residual_layers = 4 hparams.batch_size = 32 ...
python
def autoencoder_discrete_cifar(): """Discrete autoencoder model for compressing cifar.""" hparams = autoencoder_ordered_discrete() hparams.bottleneck_noise = 0.0 hparams.bottleneck_bits = 90 hparams.num_hidden_layers = 2 hparams.hidden_size = 256 hparams.num_residual_layers = 4 hparams.batch_size = 32 ...
[ "def", "autoencoder_discrete_cifar", "(", ")", ":", "hparams", "=", "autoencoder_ordered_discrete", "(", ")", "hparams", ".", "bottleneck_noise", "=", "0.0", "hparams", ".", "bottleneck_bits", "=", "90", "hparams", ".", "num_hidden_layers", "=", "2", "hparams", "....
Discrete autoencoder model for compressing cifar.
[ "Discrete", "autoencoder", "model", "for", "compressing", "cifar", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1290-L1300
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
autoencoder_range
def autoencoder_range(rhp): """Tuning grid of the main autoencoder params.""" rhp.set_float("dropout", 0.01, 0.3) rhp.set_float("gan_loss_factor", 0.01, 0.1) rhp.set_float("bottleneck_l2_factor", 0.001, 0.1, scale=rhp.LOG_SCALE) rhp.set_discrete("bottleneck_warmup_steps", [200, 2000]) rhp.set_float("gumbel_...
python
def autoencoder_range(rhp): """Tuning grid of the main autoencoder params.""" rhp.set_float("dropout", 0.01, 0.3) rhp.set_float("gan_loss_factor", 0.01, 0.1) rhp.set_float("bottleneck_l2_factor", 0.001, 0.1, scale=rhp.LOG_SCALE) rhp.set_discrete("bottleneck_warmup_steps", [200, 2000]) rhp.set_float("gumbel_...
[ "def", "autoencoder_range", "(", "rhp", ")", ":", "rhp", ".", "set_float", "(", "\"dropout\"", ",", "0.01", ",", "0.3", ")", "rhp", ".", "set_float", "(", "\"gan_loss_factor\"", ",", "0.01", ",", "0.1", ")", "rhp", ".", "set_float", "(", "\"bottleneck_l2_f...
Tuning grid of the main autoencoder params.
[ "Tuning", "grid", "of", "the", "main", "autoencoder", "params", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1304-L1311
train
tensorflow/tensor2tensor
tensor2tensor/models/research/vqa_attention.py
image_encoder
def image_encoder(image_feat, hparams, name="image_encoder", save_weights_to=None, make_image_summary=True): """A stack of self attention layers.""" x = image_feat with tf.variable_scope(name): for layer in range(hparams.num_encoder_laye...
python
def image_encoder(image_feat, hparams, name="image_encoder", save_weights_to=None, make_image_summary=True): """A stack of self attention layers.""" x = image_feat with tf.variable_scope(name): for layer in range(hparams.num_encoder_laye...
[ "def", "image_encoder", "(", "image_feat", ",", "hparams", ",", "name", "=", "\"image_encoder\"", ",", "save_weights_to", "=", "None", ",", "make_image_summary", "=", "True", ")", ":", "x", "=", "image_feat", "with", "tf", ".", "variable_scope", "(", "name", ...
A stack of self attention layers.
[ "A", "stack", "of", "self", "attention", "layers", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/vqa_attention.py#L182-L232
train
tensorflow/tensor2tensor
tensor2tensor/models/research/vqa_attention.py
question_encoder
def question_encoder(question, hparams, name="encoder"): """Question encoder, run LSTM encoder and get the last output as encoding.""" with tf.variable_scope(name, "encoder", values=[question]): question = common_layers.flatten4d3d(question) padding = common_attention.embedding_to_padding(question) leng...
python
def question_encoder(question, hparams, name="encoder"): """Question encoder, run LSTM encoder and get the last output as encoding.""" with tf.variable_scope(name, "encoder", values=[question]): question = common_layers.flatten4d3d(question) padding = common_attention.embedding_to_padding(question) leng...
[ "def", "question_encoder", "(", "question", ",", "hparams", ",", "name", "=", "\"encoder\"", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "\"encoder\"", ",", "values", "=", "[", "question", "]", ")", ":", "question", "=", "common_layers...
Question encoder, run LSTM encoder and get the last output as encoding.
[ "Question", "encoder", "run", "LSTM", "encoder", "and", "get", "the", "last", "output", "as", "encoding", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/vqa_attention.py#L245-L295
train
tensorflow/tensor2tensor
tensor2tensor/models/research/vqa_attention.py
attn
def attn(image_feat, query, hparams, name="attn"): """Attention on image feature with question as query.""" with tf.variable_scope(name, "attn", values=[image_feat, query]): attn_dim = hparams.attn_dim num_glimps = hparams.num_glimps num_channels = common_layers.shape_list(image_feat)[-1] if len(com...
python
def attn(image_feat, query, hparams, name="attn"): """Attention on image feature with question as query.""" with tf.variable_scope(name, "attn", values=[image_feat, query]): attn_dim = hparams.attn_dim num_glimps = hparams.num_glimps num_channels = common_layers.shape_list(image_feat)[-1] if len(com...
[ "def", "attn", "(", "image_feat", ",", "query", ",", "hparams", ",", "name", "=", "\"attn\"", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "\"attn\"", ",", "values", "=", "[", "image_feat", ",", "query", "]", ")", ":", "attn_dim", ...
Attention on image feature with question as query.
[ "Attention", "on", "image", "feature", "with", "question", "as", "query", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/vqa_attention.py#L298-L318
train
tensorflow/tensor2tensor
tensor2tensor/models/research/vqa_attention.py
mlp
def mlp(feature, hparams, name="mlp"): """Multi layer perceptron with dropout and relu activation.""" with tf.variable_scope(name, "mlp", values=[feature]): num_mlp_layers = hparams.num_mlp_layers mlp_dim = hparams.mlp_dim for _ in range(num_mlp_layers): feature = common_layers.dense(feature, mlp_...
python
def mlp(feature, hparams, name="mlp"): """Multi layer perceptron with dropout and relu activation.""" with tf.variable_scope(name, "mlp", values=[feature]): num_mlp_layers = hparams.num_mlp_layers mlp_dim = hparams.mlp_dim for _ in range(num_mlp_layers): feature = common_layers.dense(feature, mlp_...
[ "def", "mlp", "(", "feature", ",", "hparams", ",", "name", "=", "\"mlp\"", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "\"mlp\"", ",", "values", "=", "[", "feature", "]", ")", ":", "num_mlp_layers", "=", "hparams", ".", "num_mlp_la...
Multi layer perceptron with dropout and relu activation.
[ "Multi", "layer", "perceptron", "with", "dropout", "and", "relu", "activation", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/vqa_attention.py#L321-L329
train
tensorflow/tensor2tensor
tensor2tensor/models/research/vqa_attention.py
vqa_attention_base
def vqa_attention_base(): """VQA attention baseline hparams.""" hparams = common_hparams.basic_params1() hparams.batch_size = 128 hparams.use_fixed_batch_size = True, hparams.optimizer = "adam" hparams.optimizer_adam_beta1 = 0.9 hparams.optimizer_adam_beta2 = 0.999 hparams.optimizer_adam_epsilon = 1e-8 ...
python
def vqa_attention_base(): """VQA attention baseline hparams.""" hparams = common_hparams.basic_params1() hparams.batch_size = 128 hparams.use_fixed_batch_size = True, hparams.optimizer = "adam" hparams.optimizer_adam_beta1 = 0.9 hparams.optimizer_adam_beta2 = 0.999 hparams.optimizer_adam_epsilon = 1e-8 ...
[ "def", "vqa_attention_base", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "batch_size", "=", "128", "hparams", ".", "use_fixed_batch_size", "=", "True", ",", "hparams", ".", "optimizer", "=", "\"adam\"", "hpa...
VQA attention baseline hparams.
[ "VQA", "attention", "baseline", "hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/vqa_attention.py#L333-L400
train
tensorflow/tensor2tensor
tensor2tensor/models/research/vqa_attention.py
vqa_attention_base_range
def vqa_attention_base_range(rhp): """Small range of hyperparameters.""" # After starting from base, set intervals for some parameters. rhp.set_float("learning_rate", 0.1, 1.0, scale=rhp.LOG_SCALE) rhp.set_float("clip_grad_norm", 0.1, 10, scale=rhp.LOG_SCALE) rhp.set_discrete("batch_size", [128, 256, 512, 102...
python
def vqa_attention_base_range(rhp): """Small range of hyperparameters.""" # After starting from base, set intervals for some parameters. rhp.set_float("learning_rate", 0.1, 1.0, scale=rhp.LOG_SCALE) rhp.set_float("clip_grad_norm", 0.1, 10, scale=rhp.LOG_SCALE) rhp.set_discrete("batch_size", [128, 256, 512, 102...
[ "def", "vqa_attention_base_range", "(", "rhp", ")", ":", "# After starting from base, set intervals for some parameters.", "rhp", ".", "set_float", "(", "\"learning_rate\"", ",", "0.1", ",", "1.0", ",", "scale", "=", "rhp", ".", "LOG_SCALE", ")", "rhp", ".", "set_fl...
Small range of hyperparameters.
[ "Small", "range", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/vqa_attention.py#L580-L587
train
tensorflow/tensor2tensor
tensor2tensor/trax/history.py
History.append
def append(self, mode, metric, step, value): """Append (step, value) pair to history for the given mode and metric.""" if mode not in self._values: self._values[mode] = collections.defaultdict(list) self._values[mode][metric].append((step, value))
python
def append(self, mode, metric, step, value): """Append (step, value) pair to history for the given mode and metric.""" if mode not in self._values: self._values[mode] = collections.defaultdict(list) self._values[mode][metric].append((step, value))
[ "def", "append", "(", "self", ",", "mode", ",", "metric", ",", "step", ",", "value", ")", ":", "if", "mode", "not", "in", "self", ".", "_values", ":", "self", ".", "_values", "[", "mode", "]", "=", "collections", ".", "defaultdict", "(", "list", ")...
Append (step, value) pair to history for the given mode and metric.
[ "Append", "(", "step", "value", ")", "pair", "to", "history", "for", "the", "given", "mode", "and", "metric", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/history.py#L52-L56
train
tensorflow/tensor2tensor
tensor2tensor/trax/history.py
History.get
def get(self, mode, metric): """Get the history for the given metric and mode.""" if mode not in self._values: logging.info("Metric %s not found for mode %s", metric, mode) return [] return list(self._values[mode][metric])
python
def get(self, mode, metric): """Get the history for the given metric and mode.""" if mode not in self._values: logging.info("Metric %s not found for mode %s", metric, mode) return [] return list(self._values[mode][metric])
[ "def", "get", "(", "self", ",", "mode", ",", "metric", ")", ":", "if", "mode", "not", "in", "self", ".", "_values", ":", "logging", ".", "info", "(", "\"Metric %s not found for mode %s\"", ",", "metric", ",", "mode", ")", "return", "[", "]", "return", ...
Get the history for the given metric and mode.
[ "Get", "the", "history", "for", "the", "given", "metric", "and", "mode", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/history.py#L58-L63
train
tensorflow/tensor2tensor
tensor2tensor/trax/history.py
History.metrics_for_mode
def metrics_for_mode(self, mode): """Metrics available for a given mode.""" if mode not in self._values: logging.info("Mode %s not found", mode) return [] return sorted(list(self._values[mode].keys()))
python
def metrics_for_mode(self, mode): """Metrics available for a given mode.""" if mode not in self._values: logging.info("Mode %s not found", mode) return [] return sorted(list(self._values[mode].keys()))
[ "def", "metrics_for_mode", "(", "self", ",", "mode", ")", ":", "if", "mode", "not", "in", "self", ".", "_values", ":", "logging", ".", "info", "(", "\"Mode %s not found\"", ",", "mode", ")", "return", "[", "]", "return", "sorted", "(", "list", "(", "se...
Metrics available for a given mode.
[ "Metrics", "available", "for", "a", "given", "mode", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/history.py#L70-L75
train
tensorflow/tensor2tensor
tensor2tensor/models/resnet.py
batch_norm_relu
def batch_norm_relu(inputs, is_training, relu=True, init_zero=False, data_format="channels_first"): """Performs a batch normalization followed by a ReLU. Args: inputs: `Tensor` of shape `[batch, channels, ...]`. is_training: `b...
python
def batch_norm_relu(inputs, is_training, relu=True, init_zero=False, data_format="channels_first"): """Performs a batch normalization followed by a ReLU. Args: inputs: `Tensor` of shape `[batch, channels, ...]`. is_training: `b...
[ "def", "batch_norm_relu", "(", "inputs", ",", "is_training", ",", "relu", "=", "True", ",", "init_zero", "=", "False", ",", "data_format", "=", "\"channels_first\"", ")", ":", "if", "init_zero", ":", "gamma_initializer", "=", "tf", ".", "zeros_initializer", "(...
Performs a batch normalization followed by a ReLU. Args: inputs: `Tensor` of shape `[batch, channels, ...]`. is_training: `bool` for whether the model is training. relu: `bool` if False, omits the ReLU operation. init_zero: `bool` if True, initializes scale parameter of batch normalization wi...
[ "Performs", "a", "batch", "normalization", "followed", "by", "a", "ReLU", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L41-L81
train
tensorflow/tensor2tensor
tensor2tensor/models/resnet.py
conv2d_fixed_padding
def conv2d_fixed_padding(inputs, filters, kernel_size, strides, data_format="channels_first", use_td=False, targeting_rate=None, keep_prob=None, ...
python
def conv2d_fixed_padding(inputs, filters, kernel_size, strides, data_format="channels_first", use_td=False, targeting_rate=None, keep_prob=None, ...
[ "def", "conv2d_fixed_padding", "(", "inputs", ",", "filters", ",", "kernel_size", ",", "strides", ",", "data_format", "=", "\"channels_first\"", ",", "use_td", "=", "False", ",", "targeting_rate", "=", "None", ",", "keep_prob", "=", "None", ",", "is_training", ...
Strided 2-D convolution with explicit padding. The padding is consistent and is based only on `kernel_size`, not on the dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone). Args: inputs: `Tensor` of size `[batch, channels, height_in, width_in]`. filters: `int` number of filters in the ...
[ "Strided", "2", "-", "D", "convolution", "with", "explicit", "padding", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L112-L188
train
tensorflow/tensor2tensor
tensor2tensor/models/resnet.py
residual_block
def residual_block(inputs, filters, is_training, projection_shortcut, strides, final_block, data_format="channels_first", use_td=False, targeting_rate=None, ...
python
def residual_block(inputs, filters, is_training, projection_shortcut, strides, final_block, data_format="channels_first", use_td=False, targeting_rate=None, ...
[ "def", "residual_block", "(", "inputs", ",", "filters", ",", "is_training", ",", "projection_shortcut", ",", "strides", ",", "final_block", ",", "data_format", "=", "\"channels_first\"", ",", "use_td", "=", "False", ",", "targeting_rate", "=", "None", ",", "keep...
Standard building block for residual networks with BN before convolutions. Args: inputs: `Tensor` of size `[batch, channels, height, width]`. filters: `int` number of filters for the first two convolutions. Note that the third and final convolution will use 4 times as many filters. is_training: `...
[ "Standard", "building", "block", "for", "residual", "networks", "with", "BN", "before", "convolutions", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L191-L257
train
tensorflow/tensor2tensor
tensor2tensor/models/resnet.py
bottleneck_block
def bottleneck_block(inputs, filters, is_training, projection_shortcut, strides, final_block, data_format="channels_first", use_td=False, targeting_rate...
python
def bottleneck_block(inputs, filters, is_training, projection_shortcut, strides, final_block, data_format="channels_first", use_td=False, targeting_rate...
[ "def", "bottleneck_block", "(", "inputs", ",", "filters", ",", "is_training", ",", "projection_shortcut", ",", "strides", ",", "final_block", ",", "data_format", "=", "\"channels_first\"", ",", "use_td", "=", "False", ",", "targeting_rate", "=", "None", ",", "ke...
Bottleneck block variant for residual networks with BN after convolutions. Args: inputs: `Tensor` of size `[batch, channels, height, width]`. filters: `int` number of filters for the first two convolutions. Note that the third and final convolution will use 4 times as many filters. is_training: `...
[ "Bottleneck", "block", "variant", "for", "residual", "networks", "with", "BN", "after", "convolutions", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L260-L345
train
tensorflow/tensor2tensor
tensor2tensor/models/resnet.py
block_layer
def block_layer(inputs, filters, block_fn, blocks, strides, is_training, name, data_format="channels_first", use_td=False, targeting_rate=None, keep_prob=None):...
python
def block_layer(inputs, filters, block_fn, blocks, strides, is_training, name, data_format="channels_first", use_td=False, targeting_rate=None, keep_prob=None):...
[ "def", "block_layer", "(", "inputs", ",", "filters", ",", "block_fn", ",", "blocks", ",", "strides", ",", "is_training", ",", "name", ",", "data_format", "=", "\"channels_first\"", ",", "use_td", "=", "False", ",", "targeting_rate", "=", "None", ",", "keep_p...
Creates one layer of blocks for the ResNet model. Args: inputs: `Tensor` of size `[batch, channels, height, width]`. filters: `int` number of filters for the first convolution of the layer. block_fn: `function` for the block to use within the model blocks: `int` number of blocks contained in the laye...
[ "Creates", "one", "layer", "of", "blocks", "for", "the", "ResNet", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L348-L424
train
tensorflow/tensor2tensor
tensor2tensor/models/resnet.py
resnet_v2
def resnet_v2(inputs, block_fn, layer_blocks, filters, data_format="channels_first", is_training=False, is_cifar=False, use_td=False, targeting_rate=None, keep_prob=None): """Resnet model. ...
python
def resnet_v2(inputs, block_fn, layer_blocks, filters, data_format="channels_first", is_training=False, is_cifar=False, use_td=False, targeting_rate=None, keep_prob=None): """Resnet model. ...
[ "def", "resnet_v2", "(", "inputs", ",", "block_fn", ",", "layer_blocks", ",", "filters", ",", "data_format", "=", "\"channels_first\"", ",", "is_training", "=", "False", ",", "is_cifar", "=", "False", ",", "use_td", "=", "False", ",", "targeting_rate", "=", ...
Resnet model. Args: inputs: `Tensor` images. block_fn: `function` for the block to use within the model. Either `residual_block` or `bottleneck_block`. layer_blocks: list of 3 or 4 `int`s denoting the number of blocks to include in each of the 3 or 4 block groups. Each group consists of blo...
[ "Resnet", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L427-L511
train
tensorflow/tensor2tensor
tensor2tensor/models/resnet.py
resnet_imagenet_34_td_weight_05_05
def resnet_imagenet_34_td_weight_05_05(): """Set of hyperparameters.""" hp = resnet_imagenet_34() hp.use_td = "weight" hp.targeting_rate = 0.5 hp.keep_prob = 0.5 return hp
python
def resnet_imagenet_34_td_weight_05_05(): """Set of hyperparameters.""" hp = resnet_imagenet_34() hp.use_td = "weight" hp.targeting_rate = 0.5 hp.keep_prob = 0.5 return hp
[ "def", "resnet_imagenet_34_td_weight_05_05", "(", ")", ":", "hp", "=", "resnet_imagenet_34", "(", ")", "hp", ".", "use_td", "=", "\"weight\"", "hp", ".", "targeting_rate", "=", "0.5", "hp", ".", "keep_prob", "=", "0.5", "return", "hp" ]
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L679-L686
train
tensorflow/tensor2tensor
tensor2tensor/models/resnet.py
resnet_imagenet_34_td_unit_05_05
def resnet_imagenet_34_td_unit_05_05(): """Set of hyperparameters.""" hp = resnet_imagenet_34() hp.use_td = "unit" hp.targeting_rate = 0.5 hp.keep_prob = 0.5 return hp
python
def resnet_imagenet_34_td_unit_05_05(): """Set of hyperparameters.""" hp = resnet_imagenet_34() hp.use_td = "unit" hp.targeting_rate = 0.5 hp.keep_prob = 0.5 return hp
[ "def", "resnet_imagenet_34_td_unit_05_05", "(", ")", ":", "hp", "=", "resnet_imagenet_34", "(", ")", "hp", ".", "use_td", "=", "\"unit\"", "hp", ".", "targeting_rate", "=", "0.5", "hp", ".", "keep_prob", "=", "0.5", "return", "hp" ]
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L690-L697
train
tensorflow/tensor2tensor
tensor2tensor/models/resnet.py
resnet_imagenet_34_td_unit_no_drop
def resnet_imagenet_34_td_unit_no_drop(): """Set of hyperparameters.""" hp = resnet_imagenet_34() hp.use_td = "unit" hp.targeting_rate = 0.0 hp.keep_prob = 1.0 return hp
python
def resnet_imagenet_34_td_unit_no_drop(): """Set of hyperparameters.""" hp = resnet_imagenet_34() hp.use_td = "unit" hp.targeting_rate = 0.0 hp.keep_prob = 1.0 return hp
[ "def", "resnet_imagenet_34_td_unit_no_drop", "(", ")", ":", "hp", "=", "resnet_imagenet_34", "(", ")", "hp", ".", "use_td", "=", "\"unit\"", "hp", ".", "targeting_rate", "=", "0.0", "hp", ".", "keep_prob", "=", "1.0", "return", "hp" ]
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L701-L708
train
tensorflow/tensor2tensor
tensor2tensor/models/resnet.py
resnet_cifar_15
def resnet_cifar_15(): """Set of hyperparameters.""" hp = resnet_base() hp.block_fn = "residual" hp.is_cifar = True hp.layer_sizes = [2, 2, 2] hp.filter_sizes = [16, 32, 64, 128] return hp
python
def resnet_cifar_15(): """Set of hyperparameters.""" hp = resnet_base() hp.block_fn = "residual" hp.is_cifar = True hp.layer_sizes = [2, 2, 2] hp.filter_sizes = [16, 32, 64, 128] return hp
[ "def", "resnet_cifar_15", "(", ")", ":", "hp", "=", "resnet_base", "(", ")", "hp", ".", "block_fn", "=", "\"residual\"", "hp", ".", "is_cifar", "=", "True", "hp", ".", "layer_sizes", "=", "[", "2", ",", "2", ",", "2", "]", "hp", ".", "filter_sizes", ...
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L719-L727
train
tensorflow/tensor2tensor
tensor2tensor/utils/rouge.py
_len_lcs
def _len_lcs(x, y): """Returns the length of the Longest Common Subsequence between two seqs. Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence Args: x: sequence of words y: sequence of words Returns integer: Length of LCS between x and y """ table = _lcs(x, y) n, m =...
python
def _len_lcs(x, y): """Returns the length of the Longest Common Subsequence between two seqs. Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence Args: x: sequence of words y: sequence of words Returns integer: Length of LCS between x and y """ table = _lcs(x, y) n, m =...
[ "def", "_len_lcs", "(", "x", ",", "y", ")", ":", "table", "=", "_lcs", "(", "x", ",", "y", ")", "n", ",", "m", "=", "len", "(", "x", ")", ",", "len", "(", "y", ")", "return", "table", "[", "n", ",", "m", "]" ]
Returns the length of the Longest Common Subsequence between two seqs. Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence Args: x: sequence of words y: sequence of words Returns integer: Length of LCS between x and y
[ "Returns", "the", "length", "of", "the", "Longest", "Common", "Subsequence", "between", "two", "seqs", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/rouge.py#L33-L47
train
tensorflow/tensor2tensor
tensor2tensor/utils/rouge.py
_lcs
def _lcs(x, y): """Computes the length of the LCS between two seqs. The implementation below uses a DP programming algorithm and runs in O(nm) time where n = len(x) and m = len(y). Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence Args: x: collection of words y: collection of ...
python
def _lcs(x, y): """Computes the length of the LCS between two seqs. The implementation below uses a DP programming algorithm and runs in O(nm) time where n = len(x) and m = len(y). Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence Args: x: collection of words y: collection of ...
[ "def", "_lcs", "(", "x", ",", "y", ")", ":", "n", ",", "m", "=", "len", "(", "x", ")", ",", "len", "(", "y", ")", "table", "=", "{", "}", "for", "i", "in", "range", "(", "n", "+", "1", ")", ":", "for", "j", "in", "range", "(", "m", "+...
Computes the length of the LCS between two seqs. The implementation below uses a DP programming algorithm and runs in O(nm) time where n = len(x) and m = len(y). Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence Args: x: collection of words y: collection of words Returns: ...
[ "Computes", "the", "length", "of", "the", "LCS", "between", "two", "seqs", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/rouge.py#L50-L74
train
tensorflow/tensor2tensor
tensor2tensor/utils/rouge.py
rouge_l_sentence_level
def rouge_l_sentence_level(eval_sentences, ref_sentences): """Computes ROUGE-L (sentence level) of two collections of sentences. Source: https://www.microsoft.com/en-us/research/publication/ rouge-a-package-for-automatic-evaluation-of-summaries/ Calculated according to: R_lcs = LCS(X,Y)/m P_lcs = LCS(X,Y)...
python
def rouge_l_sentence_level(eval_sentences, ref_sentences): """Computes ROUGE-L (sentence level) of two collections of sentences. Source: https://www.microsoft.com/en-us/research/publication/ rouge-a-package-for-automatic-evaluation-of-summaries/ Calculated according to: R_lcs = LCS(X,Y)/m P_lcs = LCS(X,Y)...
[ "def", "rouge_l_sentence_level", "(", "eval_sentences", ",", "ref_sentences", ")", ":", "f1_scores", "=", "[", "]", "for", "eval_sentence", ",", "ref_sentence", "in", "zip", "(", "eval_sentences", ",", "ref_sentences", ")", ":", "m", "=", "len", "(", "ref_sent...
Computes ROUGE-L (sentence level) of two collections of sentences. Source: https://www.microsoft.com/en-us/research/publication/ rouge-a-package-for-automatic-evaluation-of-summaries/ Calculated according to: R_lcs = LCS(X,Y)/m P_lcs = LCS(X,Y)/n F_lcs = ((1 + beta^2)*R_lcs*P_lcs) / (R_lcs + (beta^2) * P_...
[ "Computes", "ROUGE", "-", "L", "(", "sentence", "level", ")", "of", "two", "collections", "of", "sentences", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/rouge.py#L100-L131
train
tensorflow/tensor2tensor
tensor2tensor/utils/rouge.py
rouge_l_fscore
def rouge_l_fscore(predictions, labels, **unused_kwargs): """ROUGE scores computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: predictions: tensor, model predictions labels: tensor, gol...
python
def rouge_l_fscore(predictions, labels, **unused_kwargs): """ROUGE scores computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: predictions: tensor, model predictions labels: tensor, gol...
[ "def", "rouge_l_fscore", "(", "predictions", ",", "labels", ",", "*", "*", "unused_kwargs", ")", ":", "outputs", "=", "tf", ".", "to_int32", "(", "tf", ".", "argmax", "(", "predictions", ",", "axis", "=", "-", "1", ")", ")", "# Convert the outputs and labe...
ROUGE scores computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: predictions: tensor, model predictions labels: tensor, gold output. Returns: rouge_l_fscore: approx rouge-l f1 sco...
[ "ROUGE", "scores", "computation", "between", "labels", "and", "predictions", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/rouge.py#L134-L153
train
tensorflow/tensor2tensor
tensor2tensor/utils/rouge.py
_get_ngrams
def _get_ngrams(n, text): """Calculates n-grams. Args: n: which n-grams to calculate text: An array of tokens Returns: A set of n-grams """ ngram_set = set() text_length = len(text) max_index_ngram_start = text_length - n for i in range(max_index_ngram_start + 1): ngram_set.add(tuple(t...
python
def _get_ngrams(n, text): """Calculates n-grams. Args: n: which n-grams to calculate text: An array of tokens Returns: A set of n-grams """ ngram_set = set() text_length = len(text) max_index_ngram_start = text_length - n for i in range(max_index_ngram_start + 1): ngram_set.add(tuple(t...
[ "def", "_get_ngrams", "(", "n", ",", "text", ")", ":", "ngram_set", "=", "set", "(", ")", "text_length", "=", "len", "(", "text", ")", "max_index_ngram_start", "=", "text_length", "-", "n", "for", "i", "in", "range", "(", "max_index_ngram_start", "+", "1...
Calculates n-grams. Args: n: which n-grams to calculate text: An array of tokens Returns: A set of n-grams
[ "Calculates", "n", "-", "grams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/rouge.py#L156-L171
train
tensorflow/tensor2tensor
tensor2tensor/utils/rouge.py
rouge_2_fscore
def rouge_2_fscore(predictions, labels, **unused_kwargs): """ROUGE-2 F1 score computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: predictions: tensor, model predictions labels: tensor,...
python
def rouge_2_fscore(predictions, labels, **unused_kwargs): """ROUGE-2 F1 score computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: predictions: tensor, model predictions labels: tensor,...
[ "def", "rouge_2_fscore", "(", "predictions", ",", "labels", ",", "*", "*", "unused_kwargs", ")", ":", "outputs", "=", "tf", ".", "to_int32", "(", "tf", ".", "argmax", "(", "predictions", ",", "axis", "=", "-", "1", ")", ")", "# Convert the outputs and labe...
ROUGE-2 F1 score computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: predictions: tensor, model predictions labels: tensor, gold output. Returns: rouge2_fscore: approx rouge-2 f1 ...
[ "ROUGE", "-", "2", "F1", "score", "computation", "between", "labels", "and", "predictions", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/rouge.py#L217-L236
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem.py
normalize_example_nlp
def normalize_example_nlp(task, example, is_infer, vocab_type, vocab_offset, max_input_length, max_target_length, fixed_train_length): """Normalize the examples from different tasks so they can be merged. This function is specific to NLP tasks and normalizes them...
python
def normalize_example_nlp(task, example, is_infer, vocab_type, vocab_offset, max_input_length, max_target_length, fixed_train_length): """Normalize the examples from different tasks so they can be merged. This function is specific to NLP tasks and normalizes them...
[ "def", "normalize_example_nlp", "(", "task", ",", "example", ",", "is_infer", ",", "vocab_type", ",", "vocab_offset", ",", "max_input_length", ",", "max_target_length", ",", "fixed_train_length", ")", ":", "if", "task", ".", "has_inputs", ":", "example", "[", "\...
Normalize the examples from different tasks so they can be merged. This function is specific to NLP tasks and normalizes them so that in the end the example only has "targets" and "task_id". For tasks that originally have inputs, this is done by appending task_id to the inputs and prepending targets, so normal...
[ "Normalize", "the", "examples", "from", "different", "tasks", "so", "they", "can", "be", "merged", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem.py#L38-L108
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem.py
flatten_zip_dataset
def flatten_zip_dataset(*args): """A list of examples to a dataset containing mixed examples. Given a list of `n` dataset examples, flatten them by converting each element into a dataset and concatenating them to convert into a single dataset. Args: *args: A list containing one example each from `n` dif...
python
def flatten_zip_dataset(*args): """A list of examples to a dataset containing mixed examples. Given a list of `n` dataset examples, flatten them by converting each element into a dataset and concatenating them to convert into a single dataset. Args: *args: A list containing one example each from `n` dif...
[ "def", "flatten_zip_dataset", "(", "*", "args", ")", ":", "flattened", "=", "tf", ".", "data", ".", "Dataset", ".", "from_tensors", "(", "args", "[", "0", "]", ")", "for", "ex", "in", "args", "[", "1", ":", "]", ":", "flattened", "=", "flattened", ...
A list of examples to a dataset containing mixed examples. Given a list of `n` dataset examples, flatten them by converting each element into a dataset and concatenating them to convert into a single dataset. Args: *args: A list containing one example each from `n` different datasets. Returns: flat...
[ "A", "list", "of", "examples", "to", "a", "dataset", "containing", "mixed", "examples", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem.py#L111-L128
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem.py
aggregate_task_losses
def aggregate_task_losses(hparams, problem_hparams, logits, feature_name, feature): """Multiproblem loss function.""" # If no reweighting, we want the default loss to mimic the LM loss. if not hparams.multipro...
python
def aggregate_task_losses(hparams, problem_hparams, logits, feature_name, feature): """Multiproblem loss function.""" # If no reweighting, we want the default loss to mimic the LM loss. if not hparams.multipro...
[ "def", "aggregate_task_losses", "(", "hparams", ",", "problem_hparams", ",", "logits", ",", "feature_name", ",", "feature", ")", ":", "# If no reweighting, we want the default loss to mimic the LM loss.", "if", "not", "hparams", ".", "multiproblem_reweight_label_loss", ":", ...
Multiproblem loss function.
[ "Multiproblem", "loss", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem.py#L419-L522
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem.py
aggregate_task_lm_losses
def aggregate_task_lm_losses(hparams, problem_hparams, logits, feature_name, feature): """LM loss for multiproblems.""" summaries = [] vocab_size = problem_hparams.vocab_size[feature_name] if voca...
python
def aggregate_task_lm_losses(hparams, problem_hparams, logits, feature_name, feature): """LM loss for multiproblems.""" summaries = [] vocab_size = problem_hparams.vocab_size[feature_name] if voca...
[ "def", "aggregate_task_lm_losses", "(", "hparams", ",", "problem_hparams", ",", "logits", ",", "feature_name", ",", "feature", ")", ":", "summaries", "=", "[", "]", "vocab_size", "=", "problem_hparams", ".", "vocab_size", "[", "feature_name", "]", "if", "vocab_s...
LM loss for multiproblems.
[ "LM", "loss", "for", "multiproblems", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem.py#L525-L553
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem.py
MultiProblem.normalize_example
def normalize_example(self, task, example, encoder, hparams, is_infer): """Normalize the examples from different tasks so they can be merged.""" # Here we use the default function for NLP tasks that makes everything # a part of "targets" feature. Override in your subclasses for other uses. vocab_offset ...
python
def normalize_example(self, task, example, encoder, hparams, is_infer): """Normalize the examples from different tasks so they can be merged.""" # Here we use the default function for NLP tasks that makes everything # a part of "targets" feature. Override in your subclasses for other uses. vocab_offset ...
[ "def", "normalize_example", "(", "self", ",", "task", ",", "example", ",", "encoder", ",", "hparams", ",", "is_infer", ")", ":", "# Here we use the default function for NLP tasks that makes everything", "# a part of \"targets\" feature. Override in your subclasses for other uses.",...
Normalize the examples from different tasks so they can be merged.
[ "Normalize", "the", "examples", "from", "different", "tasks", "so", "they", "can", "be", "merged", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem.py#L145-L154
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem.py
MultiProblem.update_task_ids
def update_task_ids(self, encoder_vocab_size): """Generate task_ids for each problem. These ids correspond to the index of the task in the task_list. Args: encoder_vocab_size: the size of the vocab which is used to compute the index offset. """ for idx, task in enumerate(self.task_li...
python
def update_task_ids(self, encoder_vocab_size): """Generate task_ids for each problem. These ids correspond to the index of the task in the task_list. Args: encoder_vocab_size: the size of the vocab which is used to compute the index offset. """ for idx, task in enumerate(self.task_li...
[ "def", "update_task_ids", "(", "self", ",", "encoder_vocab_size", ")", ":", "for", "idx", ",", "task", "in", "enumerate", "(", "self", ".", "task_list", ")", ":", "task", ".", "set_task_id", "(", "idx", "+", "encoder_vocab_size", ")", "tf", ".", "logging",...
Generate task_ids for each problem. These ids correspond to the index of the task in the task_list. Args: encoder_vocab_size: the size of the vocab which is used to compute the index offset.
[ "Generate", "task_ids", "for", "each", "problem", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem.py#L385-L397
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem.py
MultiProblem.get_max_num_classes
def get_max_num_classes(self): """Compute the maximum number of classes any subtask has. This is useful for modifying the size of the softmax to include the output labels for the classification tasks. Currently, labels from different tasks are overloaded. Returns: num: Highest number of outp...
python
def get_max_num_classes(self): """Compute the maximum number of classes any subtask has. This is useful for modifying the size of the softmax to include the output labels for the classification tasks. Currently, labels from different tasks are overloaded. Returns: num: Highest number of outp...
[ "def", "get_max_num_classes", "(", "self", ")", ":", "num", "=", "0", "for", "task", "in", "self", ".", "task_list", ":", "if", "hasattr", "(", "task", ",", "\"num_classes\"", ")", ":", "if", "num", "<", "task", ".", "num_classes", ":", "num", "=", "...
Compute the maximum number of classes any subtask has. This is useful for modifying the size of the softmax to include the output labels for the classification tasks. Currently, labels from different tasks are overloaded. Returns: num: Highest number of output classes in any text classification ...
[ "Compute", "the", "maximum", "number", "of", "classes", "any", "subtask", "has", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem.py#L399-L416
train
tensorflow/tensor2tensor
tensor2tensor/layers/transformer_memory.py
RecurrentMemory.pre_attention
def pre_attention(self, segment, query_antecedent, memory_antecedent, bias): """Called prior to self-attention, to incorporate memory items. Args: segment: an integer Tensor with shape [batch] query_antecedent: a Tensor with shape [batch, length_q, channels] memory_antecedent: must be None. A...
python
def pre_attention(self, segment, query_antecedent, memory_antecedent, bias): """Called prior to self-attention, to incorporate memory items. Args: segment: an integer Tensor with shape [batch] query_antecedent: a Tensor with shape [batch, length_q, channels] memory_antecedent: must be None. A...
[ "def", "pre_attention", "(", "self", ",", "segment", ",", "query_antecedent", ",", "memory_antecedent", ",", "bias", ")", ":", "del", "segment", "return", "None", ",", "query_antecedent", ",", "memory_antecedent", ",", "bias" ]
Called prior to self-attention, to incorporate memory items. Args: segment: an integer Tensor with shape [batch] query_antecedent: a Tensor with shape [batch, length_q, channels] memory_antecedent: must be None. Attention normally allows this to be a Tensor with shape [batch, length_m, ch...
[ "Called", "prior", "to", "self", "-", "attention", "to", "incorporate", "memory", "items", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_memory.py#L31-L45
train
tensorflow/tensor2tensor
tensor2tensor/layers/transformer_memory.py
RecentTokensMemory.pre_attention
def pre_attention(self, segment, query_antecedent, memory_antecedent, bias): """Called prior to self-attention, to incorporate memory items. Args: segment: an integer Tensor with shape [batch] query_antecedent: a Tensor with shape [batch, length_q, channels] memory_antecedent: must be None. A...
python
def pre_attention(self, segment, query_antecedent, memory_antecedent, bias): """Called prior to self-attention, to incorporate memory items. Args: segment: an integer Tensor with shape [batch] query_antecedent: a Tensor with shape [batch, length_q, channels] memory_antecedent: must be None. A...
[ "def", "pre_attention", "(", "self", ",", "segment", ",", "query_antecedent", ",", "memory_antecedent", ",", "bias", ")", ":", "assert", "memory_antecedent", "is", "None", ",", "\"We only support language modeling\"", "# In eval mode, batch size may be variable", "memory_ba...
Called prior to self-attention, to incorporate memory items. Args: segment: an integer Tensor with shape [batch] query_antecedent: a Tensor with shape [batch, length_q, channels] memory_antecedent: must be None. Attention normally allows this to be a Tensor with shape [batch, length_m, ch...
[ "Called", "prior", "to", "self", "-", "attention", "to", "incorporate", "memory", "items", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_memory.py#L110-L168
train
tensorflow/tensor2tensor
tensor2tensor/layers/transformer_memory.py
RecentTokensMemory.post_attention
def post_attention(self, token, x): """Called after self-attention. The memory can be updated here. Args: token: Data returned by pre_attention, which can be used to carry over state related to the current memory operation. x: a Tensor of data after self-attention and feed-forward Retur...
python
def post_attention(self, token, x): """Called after self-attention. The memory can be updated here. Args: token: Data returned by pre_attention, which can be used to carry over state related to the current memory operation. x: a Tensor of data after self-attention and feed-forward Retur...
[ "def", "post_attention", "(", "self", ",", "token", ",", "x", ")", ":", "with", "tf", ".", "control_dependencies", "(", "[", "self", ".", "previous_segment", ".", "assign", "(", "token", "[", "0", "]", ")", ",", "self", ".", "previous_vals", ".", "assi...
Called after self-attention. The memory can be updated here. Args: token: Data returned by pre_attention, which can be used to carry over state related to the current memory operation. x: a Tensor of data after self-attention and feed-forward Returns: a (possibly modified) version of ...
[ "Called", "after", "self", "-", "attention", ".", "The", "memory", "can", "be", "updated", "here", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_memory.py#L170-L185
train
tensorflow/tensor2tensor
tensor2tensor/layers/transformer_memory.py
TransformerMemory._norm
def _norm(self, x): """Compute the safe norm.""" return tf.sqrt(tf.reduce_sum(tf.square(x), keepdims=True, axis=-1) + 1e-7)
python
def _norm(self, x): """Compute the safe norm.""" return tf.sqrt(tf.reduce_sum(tf.square(x), keepdims=True, axis=-1) + 1e-7)
[ "def", "_norm", "(", "self", ",", "x", ")", ":", "return", "tf", ".", "sqrt", "(", "tf", ".", "reduce_sum", "(", "tf", ".", "square", "(", "x", ")", ",", "keepdims", "=", "True", ",", "axis", "=", "-", "1", ")", "+", "1e-7", ")" ]
Compute the safe norm.
[ "Compute", "the", "safe", "norm", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_memory.py#L226-L228
train
tensorflow/tensor2tensor
tensor2tensor/layers/transformer_memory.py
TransformerMemory._address_content
def _address_content(self, x): """Address the memory based on content similarity. Args: x: a tensor in the shape of [batch_size, length, depth]. Returns: the logits for each memory entry [batch_size, length, memory_size]. """ mem_keys = tf.layers.dense(self.mem_vals, self.key_depth, ...
python
def _address_content(self, x): """Address the memory based on content similarity. Args: x: a tensor in the shape of [batch_size, length, depth]. Returns: the logits for each memory entry [batch_size, length, memory_size]. """ mem_keys = tf.layers.dense(self.mem_vals, self.key_depth, ...
[ "def", "_address_content", "(", "self", ",", "x", ")", ":", "mem_keys", "=", "tf", ".", "layers", ".", "dense", "(", "self", ".", "mem_vals", ",", "self", ".", "key_depth", ",", "bias_initializer", "=", "tf", ".", "constant_initializer", "(", "1.0", ")",...
Address the memory based on content similarity. Args: x: a tensor in the shape of [batch_size, length, depth]. Returns: the logits for each memory entry [batch_size, length, memory_size].
[ "Address", "the", "memory", "based", "on", "content", "similarity", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_memory.py#L230-L249
train