partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
_remove_double_brackets
Remove double brackets, but leave the viewable text. Args: text: a string Returns: a string
tensor2tensor/data_generators/wiki_revision_utils.py
def _remove_double_brackets(text): """Remove double brackets, but leave the viewable text. Args: text: a string Returns: a string """ def replacement_fn(s): if ":" in s: # this is probably a category or something like that. return "" # keep the part after the bar. bar_pos = s...
def _remove_double_brackets(text): """Remove double brackets, but leave the viewable text. Args: text: a string Returns: a string """ def replacement_fn(s): if ":" in s: # this is probably a category or something like that. return "" # keep the part after the bar. bar_pos = s...
[ "Remove", "double", "brackets", "but", "leave", "the", "viewable", "text", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L343-L362
[ "def", "_remove_double_brackets", "(", "text", ")", ":", "def", "replacement_fn", "(", "s", ")", ":", "if", "\":\"", "in", "s", ":", "# this is probably a category or something like that.", "return", "\"\"", "# keep the part after the bar.", "bar_pos", "=", "s", ".", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
_remove_boring_lines
Remove lines that do not start with a letter or a quote. From inspecting the data, this seems to leave in most prose and remove most weird stuff. Args: text: a string Returns: a string
tensor2tensor/data_generators/wiki_revision_utils.py
def _remove_boring_lines(text): """Remove lines that do not start with a letter or a quote. From inspecting the data, this seems to leave in most prose and remove most weird stuff. Args: text: a string Returns: a string """ lines = text.split("\n") filtered = [line for line in lines if re.matc...
def _remove_boring_lines(text): """Remove lines that do not start with a letter or a quote. From inspecting the data, this seems to leave in most prose and remove most weird stuff. Args: text: a string Returns: a string """ lines = text.split("\n") filtered = [line for line in lines if re.matc...
[ "Remove", "lines", "that", "do", "not", "start", "with", "a", "letter", "or", "a", "quote", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L365-L378
[ "def", "_remove_boring_lines", "(", "text", ")", ":", "lines", "=", "text", ".", "split", "(", "\"\\n\"", ")", "filtered", "=", "[", "line", "for", "line", "in", "lines", "if", "re", ".", "match", "(", "\"[a-zA-z\\\"\\']\"", ",", "line", ")", "]", "ret...
272500b6efe353aeb638d2745ed56e519462ca31
train
get_or_generate_vocabulary
Get or generate the vocabulary. Args: data_dir: a string tmp_dir: a string data_prefix: a string max_page_size_exp: an integer approx_vocab_size: an integer strip: a boolean Returns: a TextEncoder
tensor2tensor/data_generators/wiki_revision_utils.py
def get_or_generate_vocabulary(data_dir, tmp_dir, data_prefix, max_page_size_exp, approx_vocab_size=32768, strip=True): """Get or generate the vocabulary. Args:...
def get_or_generate_vocabulary(data_dir, tmp_dir, data_prefix, max_page_size_exp, approx_vocab_size=32768, strip=True): """Get or generate the vocabulary. Args:...
[ "Get", "or", "generate", "the", "vocabulary", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L401-L440
[ "def", "get_or_generate_vocabulary", "(", "data_dir", ",", "tmp_dir", ",", "data_prefix", ",", "max_page_size_exp", ",", "approx_vocab_size", "=", "32768", ",", "strip", "=", "True", ")", ":", "num_pages_for_vocab_generation", "=", "approx_vocab_size", "//", "3", "v...
272500b6efe353aeb638d2745ed56e519462ca31
train
get_encoder_from_vocab
Get encoder from vocab file. If vocab is not found in output dir, it will be copied there by copy_vocab_to_output_dir to clarify the vocab used to generate the data. Args: vocab_filepath: path to vocab, either local or cns Returns: A SubwordTextEncoder vocabulary object. None if the output_parallel_t...
tensor2tensor/data_generators/wiki_revision_utils.py
def get_encoder_from_vocab(vocab_filepath): """Get encoder from vocab file. If vocab is not found in output dir, it will be copied there by copy_vocab_to_output_dir to clarify the vocab used to generate the data. Args: vocab_filepath: path to vocab, either local or cns Returns: A SubwordTextEncoder...
def get_encoder_from_vocab(vocab_filepath): """Get encoder from vocab file. If vocab is not found in output dir, it will be copied there by copy_vocab_to_output_dir to clarify the vocab used to generate the data. Args: vocab_filepath: path to vocab, either local or cns Returns: A SubwordTextEncoder...
[ "Get", "encoder", "from", "vocab", "file", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L443-L461
[ "def", "get_encoder_from_vocab", "(", "vocab_filepath", ")", ":", "if", "not", "tf", ".", "gfile", ".", "Exists", "(", "vocab_filepath", ")", ":", "raise", "ValueError", "(", "\"Vocab file does not exist: {}.\"", ".", "format", "(", "vocab_filepath", ")", ")", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
edit_distance_filter
Filter out examples that exceed max_edit_ratio between source and target. Args: source_target_input: a list of [source, target] pairs max_equal_to_diff_ratio: cutoff for ratio of equal chars / diff chars between source and target Returns: source_target_output: filtered subset of [source, ...
tensor2tensor/data_generators/wiki_revision_utils.py
def edit_distance_filter(source_target_input, max_equal_to_diff_ratio=0): """Filter out examples that exceed max_edit_ratio between source and target. Args: source_target_input: a list of [source, target] pairs max_equal_to_diff_ratio: cutoff for ratio of equal chars / diff chars between source a...
def edit_distance_filter(source_target_input, max_equal_to_diff_ratio=0): """Filter out examples that exceed max_edit_ratio between source and target. Args: source_target_input: a list of [source, target] pairs max_equal_to_diff_ratio: cutoff for ratio of equal chars / diff chars between source a...
[ "Filter", "out", "examples", "that", "exceed", "max_edit_ratio", "between", "source", "and", "target", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L476-L508
[ "def", "edit_distance_filter", "(", "source_target_input", ",", "max_equal_to_diff_ratio", "=", "0", ")", ":", "thrown_out_count", "=", "0", "source_target_output", "=", "[", "]", "if", "not", "max_equal_to_diff_ratio", ":", "return", "source_target_input", ",", "thro...
272500b6efe353aeb638d2745ed56e519462ca31
train
introduce_errors
Artificially add spelling errors and infill markers. This function should be applied to the inputs of a correction model. The artificial errors are particularly useful to train a network to correct spelling when the training data does not contain many natural errors. Also replaces some substrings with an "...
tensor2tensor/data_generators/wiki_revision_utils.py
def introduce_errors(s, corruption_rate=3e-3, infill_marker="|?|", max_infill_len=8): """Artificially add spelling errors and infill markers. This function should be applied to the inputs of a correction model. The artificial errors are particularly...
def introduce_errors(s, corruption_rate=3e-3, infill_marker="|?|", max_infill_len=8): """Artificially add spelling errors and infill markers. This function should be applied to the inputs of a correction model. The artificial errors are particularly...
[ "Artificially", "add", "spelling", "errors", "and", "infill", "markers", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L511-L574
[ "def", "introduce_errors", "(", "s", ",", "corruption_rate", "=", "3e-3", ",", "infill_marker", "=", "\"|?|\"", ",", "max_infill_len", "=", "8", ")", ":", "num_errors", "=", "0", "ret", "=", "[", "]", "operations", "=", "[", "\"delete\"", ",", "# delete a ...
272500b6efe353aeb638d2745ed56e519462ca31
train
fast_match_sequences
Compute diffs between two sequences. This function is similar in functionality and spirit to difflib.SequenceMatcher.get_opcodes, but it seems to run faster. if a_start, a_end, b_start, b_end are specified, then we compute diffs of the segments a[a_start:a_end] and b[b_start:b_end]. Returned indices are re...
tensor2tensor/data_generators/wiki_revision_utils.py
def fast_match_sequences(a, b, a_start=0, a_end=None, b_start=0, b_end=None, min_match_length=3, max_recursion_depth=128): """Compute diffs bet...
def fast_match_sequences(a, b, a_start=0, a_end=None, b_start=0, b_end=None, min_match_length=3, max_recursion_depth=128): """Compute diffs bet...
[ "Compute", "diffs", "between", "two", "sequences", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L577-L675
[ "def", "fast_match_sequences", "(", "a", ",", "b", ",", "a_start", "=", "0", ",", "a_end", "=", "None", ",", "b_start", "=", "0", ",", "b_end", "=", "None", ",", "min_match_length", "=", "3", ",", "max_recursion_depth", "=", "128", ")", ":", "if", "a...
272500b6efe353aeb638d2745ed56e519462ca31
train
RestoreHook.begin
Load variables from checkpoint. New model variables have the following name foramt: new_model_scope/old_model_scope/xxx/xxx:0 To find the map of name to variable, need to strip the new_model_scope and then match the old_model_scope and remove the suffix :0.
tensor2tensor/utils/restore_hook.py
def begin(self): """Load variables from checkpoint. New model variables have the following name foramt: new_model_scope/old_model_scope/xxx/xxx:0 To find the map of name to variable, need to strip the new_model_scope and then match the old_model_scope and remove the suffix :0. """ variable...
def begin(self): """Load variables from checkpoint. New model variables have the following name foramt: new_model_scope/old_model_scope/xxx/xxx:0 To find the map of name to variable, need to strip the new_model_scope and then match the old_model_scope and remove the suffix :0. """ variable...
[ "Load", "variables", "from", "checkpoint", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/restore_hook.py#L38-L61
[ "def", "begin", "(", "self", ")", ":", "variables_to_restore", "=", "tf", ".", "contrib", ".", "framework", ".", "get_variables_to_restore", "(", "include", "=", "self", ".", "_include", ",", "exclude", "=", "self", ".", "_exclude", ")", "# remove new_model_sc...
272500b6efe353aeb638d2745ed56e519462ca31
train
TimeStep.create_time_step
Creates a TimeStep with both rewards and actions as optional.
tensor2tensor/envs/time_step.py
def create_time_step(cls, observation=None, done=False, raw_reward=None, processed_reward=None, action=None): """Creates a TimeStep with both rewards and actions as optional.""" return cls(observa...
def create_time_step(cls, observation=None, done=False, raw_reward=None, processed_reward=None, action=None): """Creates a TimeStep with both rewards and actions as optional.""" return cls(observa...
[ "Creates", "a", "TimeStep", "with", "both", "rewards", "and", "actions", "as", "optional", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/time_step.py#L59-L67
[ "def", "create_time_step", "(", "cls", ",", "observation", "=", "None", ",", "done", "=", "False", ",", "raw_reward", "=", "None", ",", "processed_reward", "=", "None", ",", "action", "=", "None", ")", ":", "return", "cls", "(", "observation", ",", "done...
272500b6efe353aeb638d2745ed56e519462ca31
train
attention
Complete attention layer with preprocessing.
tensor2tensor/models/slicenet.py
def attention(targets_shifted, inputs_encoded, norm_fn, hparams, bias=None): """Complete attention layer with preprocessing.""" separabilities = [hparams.separability, hparams.separability] if hparams.separability < 0: separabilities = [hparams.separability - 1, hparams.separability] targets_timed = common_...
def attention(targets_shifted, inputs_encoded, norm_fn, hparams, bias=None): """Complete attention layer with preprocessing.""" separabilities = [hparams.separability, hparams.separability] if hparams.separability < 0: separabilities = [hparams.separability - 1, hparams.separability] targets_timed = common_...
[ "Complete", "attention", "layer", "with", "preprocessing", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L33-L81
[ "def", "attention", "(", "targets_shifted", ",", "inputs_encoded", ",", "norm_fn", ",", "hparams", ",", "bias", "=", "None", ")", ":", "separabilities", "=", "[", "hparams", ".", "separability", ",", "hparams", ".", "separability", "]", "if", "hparams", ".",...
272500b6efe353aeb638d2745ed56e519462ca31
train
multi_conv_res
A stack of separable convolution blocks with residual connections.
tensor2tensor/models/slicenet.py
def multi_conv_res(x, padding, name, layers, hparams, mask=None, source=None): """A stack of separable convolution blocks with residual connections.""" with tf.variable_scope(name): padding_bias = None if mask is not None: padding_bias = (1.0 - mask) * -1e9 # Bias to not attend to padding. if p...
def multi_conv_res(x, padding, name, layers, hparams, mask=None, source=None): """A stack of separable convolution blocks with residual connections.""" with tf.variable_scope(name): padding_bias = None if mask is not None: padding_bias = (1.0 - mask) * -1e9 # Bias to not attend to padding. if p...
[ "A", "stack", "of", "separable", "convolution", "blocks", "with", "residual", "connections", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L84-L142
[ "def", "multi_conv_res", "(", "x", ",", "padding", ",", "name", ",", "layers", ",", "hparams", ",", "mask", "=", "None", ",", "source", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "padding_bias", "=", "None", "i...
272500b6efe353aeb638d2745ed56e519462ca31
train
rank_loss
Experimental rank loss, thanks to kkurach@ for the code.
tensor2tensor/models/slicenet.py
def rank_loss(sentence_emb, image_emb, margin=0.2): """Experimental rank loss, thanks to kkurach@ for the code.""" with tf.name_scope("rank_loss"): # Normalize first as this is assumed in cosine similarity later. sentence_emb = tf.nn.l2_normalize(sentence_emb, 1) image_emb = tf.nn.l2_normalize(image_emb...
def rank_loss(sentence_emb, image_emb, margin=0.2): """Experimental rank loss, thanks to kkurach@ for the code.""" with tf.name_scope("rank_loss"): # Normalize first as this is assumed in cosine similarity later. sentence_emb = tf.nn.l2_normalize(sentence_emb, 1) image_emb = tf.nn.l2_normalize(image_emb...
[ "Experimental", "rank", "loss", "thanks", "to", "kkurach" ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L145-L162
[ "def", "rank_loss", "(", "sentence_emb", ",", "image_emb", ",", "margin", "=", "0.2", ")", ":", "with", "tf", ".", "name_scope", "(", "\"rank_loss\"", ")", ":", "# Normalize first as this is assumed in cosine similarity later.", "sentence_emb", "=", "tf", ".", "nn",...
272500b6efe353aeb638d2745ed56e519462ca31
train
similarity_cost
Loss telling to be more similar to your own targets than to others.
tensor2tensor/models/slicenet.py
def similarity_cost(inputs_encoded, targets_encoded): """Loss telling to be more similar to your own targets than to others.""" # This is a first very simple version: handle variable-length by padding # to same length and putting everything into batch. In need of a better way. x, y = common_layers.pad_to_same_l...
def similarity_cost(inputs_encoded, targets_encoded): """Loss telling to be more similar to your own targets than to others.""" # This is a first very simple version: handle variable-length by padding # to same length and putting everything into batch. In need of a better way. x, y = common_layers.pad_to_same_l...
[ "Loss", "telling", "to", "be", "more", "similar", "to", "your", "own", "targets", "than", "to", "others", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L165-L172
[ "def", "similarity_cost", "(", "inputs_encoded", ",", "targets_encoded", ")", ":", "# This is a first very simple version: handle variable-length by padding", "# to same length and putting everything into batch. In need of a better way.", "x", ",", "y", "=", "common_layers", ".", "pa...
272500b6efe353aeb638d2745ed56e519462ca31
train
slicenet_middle
Middle part of slicenet, connecting encoder and decoder.
tensor2tensor/models/slicenet.py
def slicenet_middle(inputs_encoded, targets, target_space_emb, mask, hparams): """Middle part of slicenet, connecting encoder and decoder.""" def norm_fn(x, name): with tf.variable_scope(name, default_name="norm"): return common_layers.apply_norm(x, hparams.norm_type, hparams.hidden_size, ...
def slicenet_middle(inputs_encoded, targets, target_space_emb, mask, hparams): """Middle part of slicenet, connecting encoder and decoder.""" def norm_fn(x, name): with tf.variable_scope(name, default_name="norm"): return common_layers.apply_norm(x, hparams.norm_type, hparams.hidden_size, ...
[ "Middle", "part", "of", "slicenet", "connecting", "encoder", "and", "decoder", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L175-L212
[ "def", "slicenet_middle", "(", "inputs_encoded", ",", "targets", ",", "target_space_emb", ",", "mask", ",", "hparams", ")", ":", "def", "norm_fn", "(", "x", ",", "name", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
embedding_to_padding
Input embeddings -> is_padding.
tensor2tensor/models/slicenet.py
def embedding_to_padding(emb): """Input embeddings -> is_padding.""" emb_sum = tf.reduce_sum(tf.abs(emb), axis=-1, keep_dims=True) return tf.to_float(tf.equal(emb_sum, 0.0))
def embedding_to_padding(emb): """Input embeddings -> is_padding.""" emb_sum = tf.reduce_sum(tf.abs(emb), axis=-1, keep_dims=True) return tf.to_float(tf.equal(emb_sum, 0.0))
[ "Input", "embeddings", "-", ">", "is_padding", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L221-L224
[ "def", "embedding_to_padding", "(", "emb", ")", ":", "emb_sum", "=", "tf", ".", "reduce_sum", "(", "tf", ".", "abs", "(", "emb", ")", ",", "axis", "=", "-", "1", ",", "keep_dims", "=", "True", ")", "return", "tf", ".", "to_float", "(", "tf", ".", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
slicenet_internal
The slicenet model, main step used for training.
tensor2tensor/models/slicenet.py
def slicenet_internal(inputs, targets, target_space, hparams, run_decoder=True): """The slicenet model, main step used for training.""" with tf.variable_scope("slicenet"): # Project to hidden size if necessary if inputs.get_shape().as_list()[-1] != hparams.hidden_size: inputs = common_layers.conv_bloc...
def slicenet_internal(inputs, targets, target_space, hparams, run_decoder=True): """The slicenet model, main step used for training.""" with tf.variable_scope("slicenet"): # Project to hidden size if necessary if inputs.get_shape().as_list()[-1] != hparams.hidden_size: inputs = common_layers.conv_bloc...
[ "The", "slicenet", "model", "main", "step", "used", "for", "training", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L227-L261
[ "def", "slicenet_internal", "(", "inputs", ",", "targets", ",", "target_space", ",", "hparams", ",", "run_decoder", "=", "True", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"slicenet\"", ")", ":", "# Project to hidden size if necessary", "if", "inputs", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
slicenet_params1
Set of hyperparameters.
tensor2tensor/models/slicenet.py
def slicenet_params1(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.batch_size = 1024 hparams.hidden_size = 768 hparams.dropout = 0.5 hparams.symbol_dropout = 0.2 hparams.label_smoothing = 0.1 hparams.clip_grad_norm = 2.0 hparams.num_hidden_layers = 4 hparams.kerne...
def slicenet_params1(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.batch_size = 1024 hparams.hidden_size = 768 hparams.dropout = 0.5 hparams.symbol_dropout = 0.2 hparams.label_smoothing = 0.1 hparams.clip_grad_norm = 2.0 hparams.num_hidden_layers = 4 hparams.kerne...
[ "Set", "of", "hyperparameters", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L296-L334
[ "def", "slicenet_params1", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "batch_size", "=", "1024", "hparams", ".", "hidden_size", "=", "768", "hparams", ".", "dropout", "=", "0.5", "hparams", ".", "symbol_d...
272500b6efe353aeb638d2745ed56e519462ca31
train
slicenet_params1_noam
Version with Noam's decay scheme.
tensor2tensor/models/slicenet.py
def slicenet_params1_noam(): """Version with Noam's decay scheme.""" hparams = slicenet_params1() hparams.learning_rate_decay_scheme = "noam" hparams.learning_rate = 1.0 hparams.learning_rate_warmup_steps = 4000 hparams.initializer = "uniform_unit_scaling" hparams.optimizer_adam_epsilon = 1e-9 hparams.o...
def slicenet_params1_noam(): """Version with Noam's decay scheme.""" hparams = slicenet_params1() hparams.learning_rate_decay_scheme = "noam" hparams.learning_rate = 1.0 hparams.learning_rate_warmup_steps = 4000 hparams.initializer = "uniform_unit_scaling" hparams.optimizer_adam_epsilon = 1e-9 hparams.o...
[ "Version", "with", "Noam", "s", "decay", "scheme", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L338-L348
[ "def", "slicenet_params1_noam", "(", ")", ":", "hparams", "=", "slicenet_params1", "(", ")", "hparams", ".", "learning_rate_decay_scheme", "=", "\"noam\"", "hparams", ".", "learning_rate", "=", "1.0", "hparams", ".", "learning_rate_warmup_steps", "=", "4000", "hpara...
272500b6efe353aeb638d2745ed56e519462ca31
train
slicenet_params1_tiny
Version for fast local runs.
tensor2tensor/models/slicenet.py
def slicenet_params1_tiny(): """Version for fast local runs.""" hparams = slicenet_params1() hparams.attention_type = "simple" hparams.separability = 0 hparams.hidden_size = 128 hparams.num_hidden_layers = 2 hparams.batch_size = 512 hparams.learning_rate_warmup_steps = 200 return hparams
def slicenet_params1_tiny(): """Version for fast local runs.""" hparams = slicenet_params1() hparams.attention_type = "simple" hparams.separability = 0 hparams.hidden_size = 128 hparams.num_hidden_layers = 2 hparams.batch_size = 512 hparams.learning_rate_warmup_steps = 200 return hparams
[ "Version", "for", "fast", "local", "runs", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L352-L361
[ "def", "slicenet_params1_tiny", "(", ")", ":", "hparams", "=", "slicenet_params1", "(", ")", "hparams", ".", "attention_type", "=", "\"simple\"", "hparams", ".", "separability", "=", "0", "hparams", ".", "hidden_size", "=", "128", "hparams", ".", "num_hidden_lay...
272500b6efe353aeb638d2745ed56e519462ca31
train
slicenet_range1
Small range of hyperparameters.
tensor2tensor/models/slicenet.py
def slicenet_range1(ranged_hparams): """Small range of hyperparameters.""" rhp = ranged_hparams rhp.set_float("clip_grad_norm", 1.0, 10.0, scale=rhp.LOG_SCALE) rhp.set_float("learning_rate", 0.02, 1.0, scale=rhp.LOG_SCALE) rhp.set_float("optimizer_adam_beta2", 0.995, 0.998) rhp.set_float("weight_decay", 1.0...
def slicenet_range1(ranged_hparams): """Small range of hyperparameters.""" rhp = ranged_hparams rhp.set_float("clip_grad_norm", 1.0, 10.0, scale=rhp.LOG_SCALE) rhp.set_float("learning_rate", 0.02, 1.0, scale=rhp.LOG_SCALE) rhp.set_float("optimizer_adam_beta2", 0.995, 0.998) rhp.set_float("weight_decay", 1.0...
[ "Small", "range", "of", "hyperparameters", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L365-L371
[ "def", "slicenet_range1", "(", "ranged_hparams", ")", ":", "rhp", "=", "ranged_hparams", "rhp", ".", "set_float", "(", "\"clip_grad_norm\"", ",", "1.0", ",", "10.0", ",", "scale", "=", "rhp", ".", "LOG_SCALE", ")", "rhp", ".", "set_float", "(", "\"learning_r...
272500b6efe353aeb638d2745ed56e519462ca31
train
TokenTextEncoderOov.encode
Converts a space-separated string of tokens to lists of ids. Also store temporary vocabulary IDs for source OOV tokens. OOVs are represented by their temporary OOV number. E.g., if the vocabulary size is 50k and the source has 3 OOVs, then these temporary OOV numbers will be 50000, 50001, 50002. A...
tensor2tensor/data_generators/pointer_generator_word.py
def encode(self, s): """Converts a space-separated string of tokens to lists of ids. Also store temporary vocabulary IDs for source OOV tokens. OOVs are represented by their temporary OOV number. E.g., if the vocabulary size is 50k and the source has 3 OOVs, then these temporary OOV numbers will be...
def encode(self, s): """Converts a space-separated string of tokens to lists of ids. Also store temporary vocabulary IDs for source OOV tokens. OOVs are represented by their temporary OOV number. E.g., if the vocabulary size is 50k and the source has 3 OOVs, then these temporary OOV numbers will be...
[ "Converts", "a", "space", "-", "separated", "string", "of", "tokens", "to", "lists", "of", "ids", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/pointer_generator_word.py#L93-L136
[ "def", "encode", "(", "self", ",", "s", ")", ":", "sentence", "=", "s", "tokens", "=", "sentence", ".", "strip", "(", ")", ".", "split", "(", ")", "ids", "=", "[", "]", "ids_extend", "=", "[", "]", "oovs", "=", "{", "}", "for", "t", "in", "to...
272500b6efe353aeb638d2745ed56e519462ca31
train
TokenTextEncoderOov.encode_target
Converts a space-separated string of tokens to lists of ids. Also store a version of extened vocabulary IDs. For target OOVs that are in the source, encode them using the temporary vocab IDs. For target OOVs not in the source, encode them as <UNK> Args: target: target string source_oov...
tensor2tensor/data_generators/pointer_generator_word.py
def encode_target(self, target, source_oovs): """Converts a space-separated string of tokens to lists of ids. Also store a version of extened vocabulary IDs. For target OOVs that are in the source, encode them using the temporary vocab IDs. For target OOVs not in the source, encode them as <UNK> ...
def encode_target(self, target, source_oovs): """Converts a space-separated string of tokens to lists of ids. Also store a version of extened vocabulary IDs. For target OOVs that are in the source, encode them using the temporary vocab IDs. For target OOVs not in the source, encode them as <UNK> ...
[ "Converts", "a", "space", "-", "separated", "string", "of", "tokens", "to", "lists", "of", "ids", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/pointer_generator_word.py#L138-L173
[ "def", "encode_target", "(", "self", ",", "target", ",", "source_oovs", ")", ":", "tokens", "=", "target", ".", "strip", "(", ")", ".", "split", "(", ")", "ids", "=", "[", "]", "ids_extend", "=", "[", "]", "for", "t", "in", "tokens", ":", "if", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
TokenTextEncoderOov.decode_list_oov
decode ids back to tokens, considering OOVs temporary IDs. Args: ids: vocab ids. Could possibly include source temporary OOV ID starting from vocab_size. source_oov_id_to_token: a list of source OOV tokens, with the order the same as they appear in the source. Returns: decoded to...
tensor2tensor/data_generators/pointer_generator_word.py
def decode_list_oov(self, ids, source_oov_id_to_token): """decode ids back to tokens, considering OOVs temporary IDs. Args: ids: vocab ids. Could possibly include source temporary OOV ID starting from vocab_size. source_oov_id_to_token: a list of source OOV tokens, with the order the sa...
def decode_list_oov(self, ids, source_oov_id_to_token): """decode ids back to tokens, considering OOVs temporary IDs. Args: ids: vocab ids. Could possibly include source temporary OOV ID starting from vocab_size. source_oov_id_to_token: a list of source OOV tokens, with the order the sa...
[ "decode", "ids", "back", "to", "tokens", "considering", "OOVs", "temporary", "IDs", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/pointer_generator_word.py#L178-L198
[ "def", "decode_list_oov", "(", "self", ",", "ids", ",", "source_oov_id_to_token", ")", ":", "seq", "=", "reversed", "(", "ids", ")", "if", "self", ".", "_reverse", "else", "ids", "tokens", "=", "[", "]", "for", "cur_id", "in", "seq", ":", "if", "cur_id...
272500b6efe353aeb638d2745ed56e519462ca31
train
_smallest_size_at_least
Computes new shape with the smallest side equal to `smallest_side`. Computes new shape with the smallest side equal to `smallest_side` while preserving the original aspect ratio. Args: height: an int32 scalar tensor indicating the current height. width: an int32 scalar tensor indicating the current ...
tensor2tensor/data_generators/vqa_utils.py
def _smallest_size_at_least(height, width, smallest_side): """Computes new shape with the smallest side equal to `smallest_side`. Computes new shape with the smallest side equal to `smallest_side` while preserving the original aspect ratio. Args: height: an int32 scalar tensor indicating the current h...
def _smallest_size_at_least(height, width, smallest_side): """Computes new shape with the smallest side equal to `smallest_side`. Computes new shape with the smallest side equal to `smallest_side` while preserving the original aspect ratio. Args: height: an int32 scalar tensor indicating the current h...
[ "Computes", "new", "shape", "with", "the", "smallest", "side", "equal", "to", "smallest_side", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa_utils.py#L36-L63
[ "def", "_smallest_size_at_least", "(", "height", ",", "width", ",", "smallest_side", ")", ":", "smallest_side", "=", "tf", ".", "convert_to_tensor", "(", "smallest_side", ",", "dtype", "=", "tf", ".", "int32", ")", "height", "=", "tf", ".", "to_float", "(", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
_aspect_preserving_resize
Resize images preserving the original aspect ratio. Args: image: A 3-D image `Tensor`. smallest_side: A python integer or scalar `Tensor` indicating the size of the smallest side after resize. Returns: resized_image: A 3-D tensor containing the resized image.
tensor2tensor/data_generators/vqa_utils.py
def _aspect_preserving_resize(image, smallest_side): """Resize images preserving the original aspect ratio. Args: image: A 3-D image `Tensor`. smallest_side: A python integer or scalar `Tensor` indicating the size of the smallest side after resize. Returns: resized_image: A 3-D tensor containing...
def _aspect_preserving_resize(image, smallest_side): """Resize images preserving the original aspect ratio. Args: image: A 3-D image `Tensor`. smallest_side: A python integer or scalar `Tensor` indicating the size of the smallest side after resize. Returns: resized_image: A 3-D tensor containing...
[ "Resize", "images", "preserving", "the", "original", "aspect", "ratio", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa_utils.py#L66-L89
[ "def", "_aspect_preserving_resize", "(", "image", ",", "smallest_side", ")", ":", "smallest_side", "=", "tf", ".", "convert_to_tensor", "(", "smallest_side", ",", "dtype", "=", "tf", ".", "int32", ")", "shape", "=", "tf", ".", "shape", "(", "image", ")", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
_distort_color
Distort the color of a Tensor image. Each color distortion is non-commutative and thus ordering of the color ops matters. Ideally we would randomly permute the ordering of the color ops. Rather then adding that level of complication, we select a distinct ordering of color ops for each preprocessing thread. ...
tensor2tensor/data_generators/vqa_utils.py
def _distort_color(image, color_ordering=0, scope=None): """Distort the color of a Tensor image. Each color distortion is non-commutative and thus ordering of the color ops matters. Ideally we would randomly permute the ordering of the color ops. Rather then adding that level of complication, we select a disti...
def _distort_color(image, color_ordering=0, scope=None): """Distort the color of a Tensor image. Each color distortion is non-commutative and thus ordering of the color ops matters. Ideally we would randomly permute the ordering of the color ops. Rather then adding that level of complication, we select a disti...
[ "Distort", "the", "color", "of", "a", "Tensor", "image", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa_utils.py#L98-L140
[ "def", "_distort_color", "(", "image", ",", "color_ordering", "=", "0", ",", "scope", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "scope", ",", "\"distort_color\"", ",", "[", "image", "]", ")", ":", "if", "color_ordering", "==", "0", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
_apply_with_random_selector
Computes func(x, sel), with sel sampled from [0...num_cases-1]. Args: x: input Tensor. func: Python function to apply. num_cases: Python int32, number of cases to sample sel from. Returns: The result of func(x, sel), where func receives the value of the selector as a python integer, but sel is...
tensor2tensor/data_generators/vqa_utils.py
def _apply_with_random_selector(x, func, num_cases): """Computes func(x, sel), with sel sampled from [0...num_cases-1]. Args: x: input Tensor. func: Python function to apply. num_cases: Python int32, number of cases to sample sel from. Returns: The result of func(x, sel), where func receives the...
def _apply_with_random_selector(x, func, num_cases): """Computes func(x, sel), with sel sampled from [0...num_cases-1]. Args: x: input Tensor. func: Python function to apply. num_cases: Python int32, number of cases to sample sel from. Returns: The result of func(x, sel), where func receives the...
[ "Computes", "func", "(", "x", "sel", ")", "with", "sel", "sampled", "from", "[", "0", "...", "num_cases", "-", "1", "]", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa_utils.py#L143-L160
[ "def", "_apply_with_random_selector", "(", "x", ",", "func", ",", "num_cases", ")", ":", "sel", "=", "tf", ".", "random_uniform", "(", "[", "]", ",", "maxval", "=", "num_cases", ",", "dtype", "=", "tf", ".", "int32", ")", "# Pass the real x only to one of th...
272500b6efe353aeb638d2745ed56e519462ca31
train
_mean_image_subtraction
Subtracts the given means from each image channel. For example: means = [123.68, 116.779, 103.939] image = _mean_image_subtraction(image, means) Note that the rank of `image` must be known. Args: image: a tensor of size [height, width, C]. means: a C-vector of values to subtract from each chann...
tensor2tensor/data_generators/vqa_utils.py
def _mean_image_subtraction(image, means): """Subtracts the given means from each image channel. For example: means = [123.68, 116.779, 103.939] image = _mean_image_subtraction(image, means) Note that the rank of `image` must be known. Args: image: a tensor of size [height, width, C]. means: ...
def _mean_image_subtraction(image, means): """Subtracts the given means from each image channel. For example: means = [123.68, 116.779, 103.939] image = _mean_image_subtraction(image, means) Note that the rank of `image` must be known. Args: image: a tensor of size [height, width, C]. means: ...
[ "Subtracts", "the", "given", "means", "from", "each", "image", "channel", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa_utils.py#L163-L193
[ "def", "_mean_image_subtraction", "(", "image", ",", "means", ")", ":", "if", "image", ".", "get_shape", "(", ")", ".", "ndims", "!=", "3", ":", "raise", "ValueError", "(", "\"Input must be of size [height, width, C>0]\"", ")", "num_channels", "=", "image", ".",...
272500b6efe353aeb638d2745ed56e519462ca31
train
vqa_v2_preprocess_image
vqa v2 preprocess image.
tensor2tensor/data_generators/vqa_utils.py
def vqa_v2_preprocess_image( image, height, width, mode, resize_side=512, distort=True, image_model_fn="resnet_v1_152", ): """vqa v2 preprocess image.""" image = tf.image.convert_image_dtype(image, dtype=tf.float32) assert resize_side > 0 if resize_side: image = _aspect_preservi...
def vqa_v2_preprocess_image( image, height, width, mode, resize_side=512, distort=True, image_model_fn="resnet_v1_152", ): """vqa v2 preprocess image.""" image = tf.image.convert_image_dtype(image, dtype=tf.float32) assert resize_side > 0 if resize_side: image = _aspect_preservi...
[ "vqa", "v2", "preprocess", "image", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa_utils.py#L196-L236
[ "def", "vqa_v2_preprocess_image", "(", "image", ",", "height", ",", "width", ",", "mode", ",", "resize_side", "=", "512", ",", "distort", "=", "True", ",", "image_model_fn", "=", "\"resnet_v1_152\"", ",", ")", ":", "image", "=", "tf", ".", "image", ".", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
transformer_prepare_encoder
Prepare one shard of the model for the encoder. Args: inputs: a Tensor. target_space: a Tensor. hparams: run hyperparameters features: optionally pass the entire features dictionary as well. This is needed now for "packed" datasets. Returns: encoder_input: a Tensor, bottom of encoder sta...
tensor2tensor/layers/transformer_layers.py
def transformer_prepare_encoder(inputs, target_space, hparams, features=None): """Prepare one shard of the model for the encoder. Args: inputs: a Tensor. target_space: a Tensor. hparams: run hyperparameters features: optionally pass the entire features dictionary as well. This is needed now f...
def transformer_prepare_encoder(inputs, target_space, hparams, features=None): """Prepare one shard of the model for the encoder. Args: inputs: a Tensor. target_space: a Tensor. hparams: run hyperparameters features: optionally pass the entire features dictionary as well. This is needed now f...
[ "Prepare", "one", "shard", "of", "the", "model", "for", "the", "encoder", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_layers.py#L35-L116
[ "def", "transformer_prepare_encoder", "(", "inputs", ",", "target_space", ",", "hparams", ",", "features", "=", "None", ")", ":", "ishape_static", "=", "inputs", ".", "shape", ".", "as_list", "(", ")", "encoder_input", "=", "inputs", "if", "features", "and", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
transformer_encoder
A stack of transformer layers. Args: encoder_input: a Tensor encoder_self_attention_bias: bias Tensor for self-attention (see common_attention.attention_bias()) hparams: hyperparameters for model name: a string nonpadding: optional Tensor with shape [batch_size, encoder_length] indic...
tensor2tensor/layers/transformer_layers.py
def transformer_encoder(encoder_input, encoder_self_attention_bias, hparams, name="encoder", nonpadding=None, save_weights_to=None, make_image_summary=True, ...
def transformer_encoder(encoder_input, encoder_self_attention_bias, hparams, name="encoder", nonpadding=None, save_weights_to=None, make_image_summary=True, ...
[ "A", "stack", "of", "transformer", "layers", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_layers.py#L119-L239
[ "def", "transformer_encoder", "(", "encoder_input", ",", "encoder_self_attention_bias", ",", "hparams", ",", "name", "=", "\"encoder\"", ",", "nonpadding", "=", "None", ",", "save_weights_to", "=", "None", ",", "make_image_summary", "=", "True", ",", "losses", "="...
272500b6efe353aeb638d2745ed56e519462ca31
train
transformer_ffn_layer
Feed-forward layer in the transformer. Args: x: a Tensor of shape [batch_size, length, hparams.hidden_size] hparams: hyperparameters for model pad_remover: an expert_utils.PadRemover object tracking the padding positions. If provided, when using convolutional settings, the padding is removed ...
tensor2tensor/layers/transformer_layers.py
def transformer_ffn_layer(x, hparams, pad_remover=None, conv_padding="LEFT", nonpadding_mask=None, losses=None, cache=None, decode_loop_st...
def transformer_ffn_layer(x, hparams, pad_remover=None, conv_padding="LEFT", nonpadding_mask=None, losses=None, cache=None, decode_loop_st...
[ "Feed", "-", "forward", "layer", "in", "the", "transformer", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_layers.py#L242-L380
[ "def", "transformer_ffn_layer", "(", "x", ",", "hparams", ",", "pad_remover", "=", "None", ",", "conv_padding", "=", "\"LEFT\"", ",", "nonpadding_mask", "=", "None", ",", "losses", "=", "None", ",", "cache", "=", "None", ",", "decode_loop_step", "=", "None",...
272500b6efe353aeb638d2745ed56e519462ca31
train
lmx_base
Transformer on languagemodel_lm1b32k_packed. 50M Params.
tensor2tensor/models/research/lm_experiments.py
def lmx_base(): """Transformer on languagemodel_lm1b32k_packed. 50M Params.""" hparams = transformer.transformer_tpu() # sharing is counterproductive when underparameterized hparams.shared_embedding_and_softmax_weights = False # we judge by log-ppl, so label smoothing hurts. hparams.label_smoothing = 0.0 ...
def lmx_base(): """Transformer on languagemodel_lm1b32k_packed. 50M Params.""" hparams = transformer.transformer_tpu() # sharing is counterproductive when underparameterized hparams.shared_embedding_and_softmax_weights = False # we judge by log-ppl, so label smoothing hurts. hparams.label_smoothing = 0.0 ...
[ "Transformer", "on", "languagemodel_lm1b32k_packed", ".", "50M", "Params", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/lm_experiments.py#L45-L60
[ "def", "lmx_base", "(", ")", ":", "hparams", "=", "transformer", ".", "transformer_tpu", "(", ")", "# sharing is counterproductive when underparameterized", "hparams", ".", "shared_embedding_and_softmax_weights", "=", "False", "# we judge by log-ppl, so label smoothing hurts.", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
lmx_h3k_f12k
HParams for training languagemodel_lm1b32k_packed. 880M Params.
tensor2tensor/models/research/lm_experiments.py
def lmx_h3k_f12k(): """HParams for training languagemodel_lm1b32k_packed. 880M Params.""" hparams = lmx_base() hparams.hidden_size = 3072 hparams.filter_size = 12288 hparams.batch_size = 2048 hparams.weight_dtype = "bfloat16" return hparams
def lmx_h3k_f12k(): """HParams for training languagemodel_lm1b32k_packed. 880M Params.""" hparams = lmx_base() hparams.hidden_size = 3072 hparams.filter_size = 12288 hparams.batch_size = 2048 hparams.weight_dtype = "bfloat16" return hparams
[ "HParams", "for", "training", "languagemodel_lm1b32k_packed", ".", "880M", "Params", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/lm_experiments.py#L82-L89
[ "def", "lmx_h3k_f12k", "(", ")", ":", "hparams", "=", "lmx_base", "(", ")", "hparams", ".", "hidden_size", "=", "3072", "hparams", ".", "filter_size", "=", "12288", "hparams", ".", "batch_size", "=", "2048", "hparams", ".", "weight_dtype", "=", "\"bfloat16\"...
272500b6efe353aeb638d2745ed56e519462ca31
train
lmx_h4k_f16k
HParams for training languagemodel_lm1b32k_packed. 1470M Params.
tensor2tensor/models/research/lm_experiments.py
def lmx_h4k_f16k(): """HParams for training languagemodel_lm1b32k_packed. 1470M Params.""" hparams = lmx_base() hparams.hidden_size = 4096 hparams.filter_size = 16384 hparams.batch_size = 1024 hparams.weight_dtype = "bfloat16" return hparams
def lmx_h4k_f16k(): """HParams for training languagemodel_lm1b32k_packed. 1470M Params.""" hparams = lmx_base() hparams.hidden_size = 4096 hparams.filter_size = 16384 hparams.batch_size = 1024 hparams.weight_dtype = "bfloat16" return hparams
[ "HParams", "for", "training", "languagemodel_lm1b32k_packed", ".", "1470M", "Params", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/lm_experiments.py#L93-L100
[ "def", "lmx_h4k_f16k", "(", ")", ":", "hparams", "=", "lmx_base", "(", ")", "hparams", ".", "hidden_size", "=", "4096", "hparams", ".", "filter_size", "=", "16384", "hparams", ".", "batch_size", "=", "1024", "hparams", ".", "weight_dtype", "=", "\"bfloat16\"...
272500b6efe353aeb638d2745ed56e519462ca31
train
lmx_relative
Language model using relative attention.
tensor2tensor/models/research/lm_experiments.py
def lmx_relative(): """Language model using relative attention.""" hparams = lmx_base() hparams.self_attention_type = "dot_product_relative_v2" hparams.activation_dtype = "float32" hparams.weight_dtype = "float32" return hparams
def lmx_relative(): """Language model using relative attention.""" hparams = lmx_base() hparams.self_attention_type = "dot_product_relative_v2" hparams.activation_dtype = "float32" hparams.weight_dtype = "float32" return hparams
[ "Language", "model", "using", "relative", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/lm_experiments.py#L104-L110
[ "def", "lmx_relative", "(", ")", ":", "hparams", "=", "lmx_base", "(", ")", "hparams", ".", "self_attention_type", "=", "\"dot_product_relative_v2\"", "hparams", ".", "activation_dtype", "=", "\"float32\"", "hparams", ".", "weight_dtype", "=", "\"float32\"", "return...
272500b6efe353aeb638d2745ed56e519462ca31
train
lmx_moe_h1k_f4k_x32
Transformer with mixture of experts. 890M Params.
tensor2tensor/models/research/lm_experiments.py
def lmx_moe_h1k_f4k_x32(): """Transformer with mixture of experts. 890M Params.""" hparams = lmx_h1k_f4k() hparams.ffn_layer = "local_moe_tpu" hparams.moe_num_experts = 32 hparams.weight_dtype = "bfloat16" hparams.batch_size = 8192 return hparams
def lmx_moe_h1k_f4k_x32(): """Transformer with mixture of experts. 890M Params.""" hparams = lmx_h1k_f4k() hparams.ffn_layer = "local_moe_tpu" hparams.moe_num_experts = 32 hparams.weight_dtype = "bfloat16" hparams.batch_size = 8192 return hparams
[ "Transformer", "with", "mixture", "of", "experts", ".", "890M", "Params", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/lm_experiments.py#L130-L137
[ "def", "lmx_moe_h1k_f4k_x32", "(", ")", ":", "hparams", "=", "lmx_h1k_f4k", "(", ")", "hparams", ".", "ffn_layer", "=", "\"local_moe_tpu\"", "hparams", ".", "moe_num_experts", "=", "32", "hparams", ".", "weight_dtype", "=", "\"bfloat16\"", "hparams", ".", "batch...
272500b6efe353aeb638d2745ed56e519462ca31
train
lmx_moe_h1k_f8k_x16
Transformer with mixture of experts. 890M Params.
tensor2tensor/models/research/lm_experiments.py
def lmx_moe_h1k_f8k_x16(): """Transformer with mixture of experts. 890M Params.""" hparams = lmx_h1k_f4k() hparams.filter_size = 8192 hparams.ffn_layer = "local_moe_tpu" hparams.moe_num_experts = 16 hparams.weight_dtype = "bfloat16" hparams.batch_size = 8192 return hparams
def lmx_moe_h1k_f8k_x16(): """Transformer with mixture of experts. 890M Params.""" hparams = lmx_h1k_f4k() hparams.filter_size = 8192 hparams.ffn_layer = "local_moe_tpu" hparams.moe_num_experts = 16 hparams.weight_dtype = "bfloat16" hparams.batch_size = 8192 return hparams
[ "Transformer", "with", "mixture", "of", "experts", ".", "890M", "Params", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/lm_experiments.py#L141-L149
[ "def", "lmx_moe_h1k_f8k_x16", "(", ")", ":", "hparams", "=", "lmx_h1k_f4k", "(", ")", "hparams", ".", "filter_size", "=", "8192", "hparams", ".", "ffn_layer", "=", "\"local_moe_tpu\"", "hparams", ".", "moe_num_experts", "=", "16", "hparams", ".", "weight_dtype",...
272500b6efe353aeb638d2745ed56e519462ca31
train
lmx_h1k_f64k
HParams for training languagemodel_lm1b32k_packed. 880M Params.
tensor2tensor/models/research/lm_experiments.py
def lmx_h1k_f64k(): """HParams for training languagemodel_lm1b32k_packed. 880M Params.""" hparams = lmx_base() hparams.hidden_size = 1024 hparams.filter_size = 65536 hparams.batch_size = 2048 return hparams
def lmx_h1k_f64k(): """HParams for training languagemodel_lm1b32k_packed. 880M Params.""" hparams = lmx_base() hparams.hidden_size = 1024 hparams.filter_size = 65536 hparams.batch_size = 2048 return hparams
[ "HParams", "for", "training", "languagemodel_lm1b32k_packed", ".", "880M", "Params", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/lm_experiments.py#L153-L159
[ "def", "lmx_h1k_f64k", "(", ")", ":", "hparams", "=", "lmx_base", "(", ")", "hparams", ".", "hidden_size", "=", "1024", "hparams", ".", "filter_size", "=", "65536", "hparams", ".", "batch_size", "=", "2048", "return", "hparams" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
compute_uncertainty_reward
Uncertainty reward based on logits.
tensor2tensor/rl/envs/simulated_batch_env.py
def compute_uncertainty_reward(logits, predictions): """Uncertainty reward based on logits.""" # TODO(rsepassi): Add support for L1/L2 loss models. Current code only # works for softmax models. vocab_size = logits.shape[-1] assert vocab_size > 1 log_probs = common_layers.log_prob_from_logits(logits) max_l...
def compute_uncertainty_reward(logits, predictions): """Uncertainty reward based on logits.""" # TODO(rsepassi): Add support for L1/L2 loss models. Current code only # works for softmax models. vocab_size = logits.shape[-1] assert vocab_size > 1 log_probs = common_layers.log_prob_from_logits(logits) max_l...
[ "Uncertainty", "reward", "based", "on", "logits", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/envs/simulated_batch_env.py#L85-L99
[ "def", "compute_uncertainty_reward", "(", "logits", ",", "predictions", ")", ":", "# TODO(rsepassi): Add support for L1/L2 loss models. Current code only", "# works for softmax models.", "vocab_size", "=", "logits", ".", "shape", "[", "-", "1", "]", "assert", "vocab_size", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
SimulatedBatchEnv._reset_non_empty
Reset the batch of environments. Args: indices: The batch indices of the environments to reset; defaults to all. Returns: Batch tensor of the new observations.
tensor2tensor/rl/envs/simulated_batch_env.py
def _reset_non_empty(self, indices): """Reset the batch of environments. Args: indices: The batch indices of the environments to reset; defaults to all. Returns: Batch tensor of the new observations. """ reset_video_op = tf.cond( self._video_condition, lambda: tf.py_fun...
def _reset_non_empty(self, indices): """Reset the batch of environments. Args: indices: The batch indices of the environments to reset; defaults to all. Returns: Batch tensor of the new observations. """ reset_video_op = tf.cond( self._video_condition, lambda: tf.py_fun...
[ "Reset", "the", "batch", "of", "environments", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/envs/simulated_batch_env.py#L232-L259
[ "def", "_reset_non_empty", "(", "self", ",", "indices", ")", ":", "reset_video_op", "=", "tf", ".", "cond", "(", "self", ".", "_video_condition", ",", "lambda", ":", "tf", ".", "py_func", "(", "self", ".", "_video_reset_writer", ",", "[", "]", ",", "[", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
set_random_seed
Set the random seed from flag everywhere.
tensor2tensor/bin/t2t_datagen.py
def set_random_seed(): """Set the random seed from flag everywhere.""" tf.set_random_seed(FLAGS.random_seed) random.seed(FLAGS.random_seed) np.random.seed(FLAGS.random_seed)
def set_random_seed(): """Set the random seed from flag everywhere.""" tf.set_random_seed(FLAGS.random_seed) random.seed(FLAGS.random_seed) np.random.seed(FLAGS.random_seed)
[ "Set", "the", "random", "seed", "from", "flag", "everywhere", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_datagen.py#L154-L158
[ "def", "set_random_seed", "(", ")", ":", "tf", ".", "set_random_seed", "(", "FLAGS", ".", "random_seed", ")", "random", ".", "seed", "(", "FLAGS", ".", "random_seed", ")", "np", ".", "random", ".", "seed", "(", "FLAGS", ".", "random_seed", ")" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
generate_data_for_problem
Generate data for a problem in _SUPPORTED_PROBLEM_GENERATORS.
tensor2tensor/bin/t2t_datagen.py
def generate_data_for_problem(problem): """Generate data for a problem in _SUPPORTED_PROBLEM_GENERATORS.""" training_gen, dev_gen, test_gen = _SUPPORTED_PROBLEM_GENERATORS[problem] num_train_shards = FLAGS.num_shards or 10 tf.logging.info("Generating training data for %s.", problem) train_output_files = gene...
def generate_data_for_problem(problem): """Generate data for a problem in _SUPPORTED_PROBLEM_GENERATORS.""" training_gen, dev_gen, test_gen = _SUPPORTED_PROBLEM_GENERATORS[problem] num_train_shards = FLAGS.num_shards or 10 tf.logging.info("Generating training data for %s.", problem) train_output_files = gene...
[ "Generate", "data", "for", "a", "problem", "in", "_SUPPORTED_PROBLEM_GENERATORS", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_datagen.py#L224-L251
[ "def", "generate_data_for_problem", "(", "problem", ")", ":", "training_gen", ",", "dev_gen", ",", "test_gen", "=", "_SUPPORTED_PROBLEM_GENERATORS", "[", "problem", "]", "num_train_shards", "=", "FLAGS", ".", "num_shards", "or", "10", "tf", ".", "logging", ".", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
generate_data_for_env_problem
Generate data for `EnvProblem`s.
tensor2tensor/bin/t2t_datagen.py
def generate_data_for_env_problem(problem_name): """Generate data for `EnvProblem`s.""" assert FLAGS.env_problem_max_env_steps > 0, ("--env_problem_max_env_steps " "should be greater than zero") assert FLAGS.env_problem_batch_size > 0, ("--env_problem_batch_size shou...
def generate_data_for_env_problem(problem_name): """Generate data for `EnvProblem`s.""" assert FLAGS.env_problem_max_env_steps > 0, ("--env_problem_max_env_steps " "should be greater than zero") assert FLAGS.env_problem_batch_size > 0, ("--env_problem_batch_size shou...
[ "Generate", "data", "for", "EnvProblem", "s", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_datagen.py#L260-L275
[ "def", "generate_data_for_env_problem", "(", "problem_name", ")", ":", "assert", "FLAGS", ".", "env_problem_max_env_steps", ">", "0", ",", "(", "\"--env_problem_max_env_steps \"", "\"should be greater than zero\"", ")", "assert", "FLAGS", ".", "env_problem_batch_size", ">",...
272500b6efe353aeb638d2745ed56e519462ca31
train
generate_data_for_registered_problem
Generate data for a registered problem.
tensor2tensor/bin/t2t_datagen.py
def generate_data_for_registered_problem(problem_name): """Generate data for a registered problem.""" tf.logging.info("Generating data for %s.", problem_name) if FLAGS.num_shards: raise ValueError("--num_shards should not be set for registered Problem.") problem = registry.problem(problem_name) task_id = ...
def generate_data_for_registered_problem(problem_name): """Generate data for a registered problem.""" tf.logging.info("Generating data for %s.", problem_name) if FLAGS.num_shards: raise ValueError("--num_shards should not be set for registered Problem.") problem = registry.problem(problem_name) task_id = ...
[ "Generate", "data", "for", "a", "registered", "problem", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_datagen.py#L278-L301
[ "def", "generate_data_for_registered_problem", "(", "problem_name", ")", ":", "tf", ".", "logging", ".", "info", "(", "\"Generating data for %s.\"", ",", "problem_name", ")", "if", "FLAGS", ".", "num_shards", ":", "raise", "ValueError", "(", "\"--num_shards should not...
272500b6efe353aeb638d2745ed56e519462ca31
train
_collect_data
Traverses directory collecting input and target files. Args: directory: base path to extracted audio and transcripts. Returns: list of (media_base, media_filepath, label) tuples
tensor2tensor/data_generators/common_voice.py
def _collect_data(directory): """Traverses directory collecting input and target files. Args: directory: base path to extracted audio and transcripts. Returns: list of (media_base, media_filepath, label) tuples """ # Returns: data_files = [] transcripts = [ filename for filename in os.listdir...
def _collect_data(directory): """Traverses directory collecting input and target files. Args: directory: base path to extracted audio and transcripts. Returns: list of (media_base, media_filepath, label) tuples """ # Returns: data_files = [] transcripts = [ filename for filename in os.listdir...
[ "Traverses", "directory", "collecting", "input", "and", "target", "files", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/common_voice.py#L42-L66
[ "def", "_collect_data", "(", "directory", ")", ":", "# Returns:", "data_files", "=", "[", "]", "transcripts", "=", "[", "filename", "for", "filename", "in", "os", ".", "listdir", "(", "directory", ")", "if", "filename", ".", "endswith", "(", "\".csv\"", ")...
272500b6efe353aeb638d2745ed56e519462ca31
train
_file_exists
Checks if the filename exists under the path.
tensor2tensor/data_generators/common_voice.py
def _file_exists(path, filename): """Checks if the filename exists under the path.""" return os.path.isfile(os.path.join(path, filename))
def _file_exists(path, filename): """Checks if the filename exists under the path.""" return os.path.isfile(os.path.join(path, filename))
[ "Checks", "if", "the", "filename", "exists", "under", "the", "path", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/common_voice.py#L69-L71
[ "def", "_file_exists", "(", "path", ",", "filename", ")", ":", "return", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")", ")" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
_is_relative
Checks if the filename is relative, not absolute.
tensor2tensor/data_generators/common_voice.py
def _is_relative(path, filename): """Checks if the filename is relative, not absolute.""" return os.path.abspath(os.path.join(path, filename)).startswith(path)
def _is_relative(path, filename): """Checks if the filename is relative, not absolute.""" return os.path.abspath(os.path.join(path, filename)).startswith(path)
[ "Checks", "if", "the", "filename", "is", "relative", "not", "absolute", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/common_voice.py#L74-L76
[ "def", "_is_relative", "(", "path", ",", "filename", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")", ")", ".", "startswith", "(", "path", ")" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
define_ppo_step
Define ppo step.
tensor2tensor/rl/ppo.py
def define_ppo_step(data_points, hparams, action_space, lr): """Define ppo step.""" observation, action, discounted_reward, norm_advantage, old_pdf = data_points obs_shape = common_layers.shape_list(observation) observation = tf.reshape( observation, [obs_shape[0] * obs_shape[1]] + obs_shape[2:] ) (l...
def define_ppo_step(data_points, hparams, action_space, lr): """Define ppo step.""" observation, action, discounted_reward, norm_advantage, old_pdf = data_points obs_shape = common_layers.shape_list(observation) observation = tf.reshape( observation, [obs_shape[0] * obs_shape[1]] + obs_shape[2:] ) (l...
[ "Define", "ppo", "step", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/ppo.py#L33-L68
[ "def", "define_ppo_step", "(", "data_points", ",", "hparams", ",", "action_space", ",", "lr", ")", ":", "observation", ",", "action", ",", "discounted_reward", ",", "norm_advantage", ",", "old_pdf", "=", "data_points", "obs_shape", "=", "common_layers", ".", "sh...
272500b6efe353aeb638d2745ed56e519462ca31
train
define_ppo_epoch
PPO epoch.
tensor2tensor/rl/ppo.py
def define_ppo_epoch(memory, hparams, action_space, batch_size): """PPO epoch.""" observation, reward, done, action, old_pdf, value = memory # This is to avoid propagating gradients through simulated environment. observation = tf.stop_gradient(observation) action = tf.stop_gradient(action) reward = tf.stop...
def define_ppo_epoch(memory, hparams, action_space, batch_size): """PPO epoch.""" observation, reward, done, action, old_pdf, value = memory # This is to avoid propagating gradients through simulated environment. observation = tf.stop_gradient(observation) action = tf.stop_gradient(action) reward = tf.stop...
[ "PPO", "epoch", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/ppo.py#L71-L142
[ "def", "define_ppo_epoch", "(", "memory", ",", "hparams", ",", "action_space", ",", "batch_size", ")", ":", "observation", ",", "reward", ",", "done", ",", "action", ",", "old_pdf", ",", "value", "=", "memory", "# This is to avoid propagating gradients through simul...
272500b6efe353aeb638d2745ed56e519462ca31
train
calculate_generalized_advantage_estimator
Generalized advantage estimator. Returns: GAE estimator. It will be one element shorter than the input; this is because to compute GAE for [0, ..., N-1] one needs V for [1, ..., N].
tensor2tensor/rl/ppo.py
def calculate_generalized_advantage_estimator( reward, value, done, gae_gamma, gae_lambda): # pylint: disable=g-doc-args """Generalized advantage estimator. Returns: GAE estimator. It will be one element shorter than the input; this is because to compute GAE for [0, ..., N-1] one needs V for [1, ...,...
def calculate_generalized_advantage_estimator( reward, value, done, gae_gamma, gae_lambda): # pylint: disable=g-doc-args """Generalized advantage estimator. Returns: GAE estimator. It will be one element shorter than the input; this is because to compute GAE for [0, ..., N-1] one needs V for [1, ...,...
[ "Generalized", "advantage", "estimator", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/ppo.py#L145-L166
[ "def", "calculate_generalized_advantage_estimator", "(", "reward", ",", "value", ",", "done", ",", "gae_gamma", ",", "gae_lambda", ")", ":", "# pylint: disable=g-doc-args", "# pylint: enable=g-doc-args", "next_value", "=", "value", "[", "1", ":", ",", ":", "]", "nex...
272500b6efe353aeb638d2745ed56e519462ca31
train
gym_space_spec
Returns a reading spec of a gym space. NOTE: Only implemented currently for Box and Discrete. Args: gym_space: instance of gym.spaces whose spec we want. Returns: Reading spec for that space. Raises: NotImplementedError: For spaces whose reading spec we haven't implemented.
tensor2tensor/envs/gym_spaces_utils.py
def gym_space_spec(gym_space): """Returns a reading spec of a gym space. NOTE: Only implemented currently for Box and Discrete. Args: gym_space: instance of gym.spaces whose spec we want. Returns: Reading spec for that space. Raises: NotImplementedError: For spaces whose reading spec we haven'...
def gym_space_spec(gym_space): """Returns a reading spec of a gym space. NOTE: Only implemented currently for Box and Discrete. Args: gym_space: instance of gym.spaces whose spec we want. Returns: Reading spec for that space. Raises: NotImplementedError: For spaces whose reading spec we haven'...
[ "Returns", "a", "reading", "spec", "of", "a", "gym", "space", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/gym_spaces_utils.py#L41-L69
[ "def", "gym_space_spec", "(", "gym_space", ")", ":", "# First try to determine the type.", "try", ":", "tf_dtype", "=", "tf", ".", "as_dtype", "(", "gym_space", ".", "dtype", ")", "except", "TypeError", "as", "e", ":", "tf", ".", "logging", ".", "error", "("...
272500b6efe353aeb638d2745ed56e519462ca31
train
cardinality
Number of elements that can be represented by the space. Makes the most sense for Discrete or Box type with integral dtype, ex: number of actions in an action space. Args: gym_space: The gym space. Returns: np.int64 number of observations that can be represented by this space, or returns None whe...
tensor2tensor/envs/gym_spaces_utils.py
def cardinality(gym_space): """Number of elements that can be represented by the space. Makes the most sense for Discrete or Box type with integral dtype, ex: number of actions in an action space. Args: gym_space: The gym space. Returns: np.int64 number of observations that can be represented by th...
def cardinality(gym_space): """Number of elements that can be represented by the space. Makes the most sense for Discrete or Box type with integral dtype, ex: number of actions in an action space. Args: gym_space: The gym space. Returns: np.int64 number of observations that can be represented by th...
[ "Number", "of", "elements", "that", "can", "be", "represented", "by", "the", "space", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/gym_spaces_utils.py#L83-L113
[ "def", "cardinality", "(", "gym_space", ")", ":", "if", "(", "gym_space", ".", "dtype", "==", "np", ".", "float32", ")", "or", "(", "gym_space", ".", "dtype", "==", "np", ".", "float64", ")", ":", "tf", ".", "logging", ".", "error", "(", "\"Returning...
272500b6efe353aeb638d2745ed56e519462ca31
train
image_rmse
RMSE but will argmax if last dim is not 1.
tensor2tensor/utils/metrics.py
def image_rmse(predictions, labels, weights_fn=common_layers.weights_all): """RMSE but will argmax if last dim is not 1.""" if common_layers.shape_list(predictions)[-1] == 1: predictions = tf.squeeze(predictions, axis=[-1]) else: predictions = tf.argmax(predictions, axis=-1) return padded_rmse(predictio...
def image_rmse(predictions, labels, weights_fn=common_layers.weights_all): """RMSE but will argmax if last dim is not 1.""" if common_layers.shape_list(predictions)[-1] == 1: predictions = tf.squeeze(predictions, axis=[-1]) else: predictions = tf.argmax(predictions, axis=-1) return padded_rmse(predictio...
[ "RMSE", "but", "will", "argmax", "if", "last", "dim", "is", "not", "1", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L69-L75
[ "def", "image_rmse", "(", "predictions", ",", "labels", ",", "weights_fn", "=", "common_layers", ".", "weights_all", ")", ":", "if", "common_layers", ".", "shape_list", "(", "predictions", ")", "[", "-", "1", "]", "==", "1", ":", "predictions", "=", "tf", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
abs_error
Computes mean(abs(preds-target)).
tensor2tensor/utils/metrics.py
def abs_error(predictions, labels, weights_fn=None): """Computes mean(abs(preds-target)).""" del weights_fn # Unused targets = tf.squeeze(labels, axis=[2, 3]) batch_abs_error = tf.abs(predictions - targets) den = tf.ones(tf.shape(batch_abs_error), dtype=tf.float32) return (batch_abs_error, den)
def abs_error(predictions, labels, weights_fn=None): """Computes mean(abs(preds-target)).""" del weights_fn # Unused targets = tf.squeeze(labels, axis=[2, 3]) batch_abs_error = tf.abs(predictions - targets) den = tf.ones(tf.shape(batch_abs_error), dtype=tf.float32) return (batch_abs_error, den)
[ "Computes", "mean", "(", "abs", "(", "preds", "-", "target", "))", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L88-L94
[ "def", "abs_error", "(", "predictions", ",", "labels", ",", "weights_fn", "=", "None", ")", ":", "del", "weights_fn", "# Unused", "targets", "=", "tf", ".", "squeeze", "(", "labels", ",", "axis", "=", "[", "2", ",", "3", "]", ")", "batch_abs_error", "=...
272500b6efe353aeb638d2745ed56e519462ca31
train
padded_variance_explained
Explained variance, also known as R^2.
tensor2tensor/utils/metrics.py
def padded_variance_explained(predictions, labels, weights_fn=common_layers.weights_all): """Explained variance, also known as R^2.""" predictions, labels = common_layers.pad_with_zeros(predictions, labels) targets = labels weights = weights_fn(targets...
def padded_variance_explained(predictions, labels, weights_fn=common_layers.weights_all): """Explained variance, also known as R^2.""" predictions, labels = common_layers.pad_with_zeros(predictions, labels) targets = labels weights = weights_fn(targets...
[ "Explained", "variance", "also", "known", "as", "R^2", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L109-L121
[ "def", "padded_variance_explained", "(", "predictions", ",", "labels", ",", "weights_fn", "=", "common_layers", ".", "weights_all", ")", ":", "predictions", ",", "labels", "=", "common_layers", ".", "pad_with_zeros", "(", "predictions", ",", "labels", ")", "target...
272500b6efe353aeb638d2745ed56e519462ca31
train
padded_accuracy_topk
Percentage of times that top-k predictions matches labels on non-0s.
tensor2tensor/utils/metrics.py
def padded_accuracy_topk(predictions, labels, k, weights_fn=common_layers.weights_nonzero): """Percentage of times that top-k predictions matches labels on non-0s.""" with tf.variable_scope("padded_accuracy_topk", values=[predictions, labels...
def padded_accuracy_topk(predictions, labels, k, weights_fn=common_layers.weights_nonzero): """Percentage of times that top-k predictions matches labels on non-0s.""" with tf.variable_scope("padded_accuracy_topk", values=[predictions, labels...
[ "Percentage", "of", "times", "that", "top", "-", "k", "predictions", "matches", "labels", "on", "non", "-", "0s", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L124-L142
[ "def", "padded_accuracy_topk", "(", "predictions", ",", "labels", ",", "k", ",", "weights_fn", "=", "common_layers", ".", "weights_nonzero", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"padded_accuracy_topk\"", ",", "values", "=", "[", "predictions", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
rounding_sequence_accuracy
Sequence accuracy for L1/L2 losses: round down the predictions to ints.
tensor2tensor/utils/metrics.py
def rounding_sequence_accuracy(predictions, labels, weights_fn=common_layers.weights_nonzero): """Sequence accuracy for L1/L2 losses: round down the predictions to ints.""" outputs = tf.squeeze(tf.to_int32(predictions), axis=-1) weights = weights_fn(la...
def rounding_sequence_accuracy(predictions, labels, weights_fn=common_layers.weights_nonzero): """Sequence accuracy for L1/L2 losses: round down the predictions to ints.""" outputs = tf.squeeze(tf.to_int32(predictions), axis=-1) weights = weights_fn(la...
[ "Sequence", "accuracy", "for", "L1", "/", "L2", "losses", ":", "round", "down", "the", "predictions", "to", "ints", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L151-L161
[ "def", "rounding_sequence_accuracy", "(", "predictions", ",", "labels", ",", "weights_fn", "=", "common_layers", ".", "weights_nonzero", ")", ":", "outputs", "=", "tf", ".", "squeeze", "(", "tf", ".", "to_int32", "(", "predictions", ")", ",", "axis", "=", "-...
272500b6efe353aeb638d2745ed56e519462ca31
train
padded_sequence_accuracy
Percentage of times that predictions matches labels everywhere (non-0).
tensor2tensor/utils/metrics.py
def padded_sequence_accuracy(predictions, labels, weights_fn=common_layers.weights_nonzero): """Percentage of times that predictions matches labels everywhere (non-0).""" # If the last dimension is 1 then we're using L1/L2 loss. if common_layers.shape_list...
def padded_sequence_accuracy(predictions, labels, weights_fn=common_layers.weights_nonzero): """Percentage of times that predictions matches labels everywhere (non-0).""" # If the last dimension is 1 then we're using L1/L2 loss. if common_layers.shape_list...
[ "Percentage", "of", "times", "that", "predictions", "matches", "labels", "everywhere", "(", "non", "-", "0", ")", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L164-L197
[ "def", "padded_sequence_accuracy", "(", "predictions", ",", "labels", ",", "weights_fn", "=", "common_layers", ".", "weights_nonzero", ")", ":", "# If the last dimension is 1 then we're using L1/L2 loss.", "if", "common_layers", ".", "shape_list", "(", "predictions", ")", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
sequence_edit_distance
Average edit distance, ignoring padding 0s. The score returned is the edit distance divided by the total length of reference truth and the weight returned is the total length of the truth. Args: predictions: Tensor of shape [`batch_size`, `length`, 1, `num_classes`] and type tf.float32 representing ...
tensor2tensor/utils/metrics.py
def sequence_edit_distance(predictions, labels, weights_fn=common_layers.weights_nonzero): """Average edit distance, ignoring padding 0s. The score returned is the edit distance divided by the total length of reference truth and the weight returned is the tot...
def sequence_edit_distance(predictions, labels, weights_fn=common_layers.weights_nonzero): """Average edit distance, ignoring padding 0s. The score returned is the edit distance divided by the total length of reference truth and the weight returned is the tot...
[ "Average", "edit", "distance", "ignoring", "padding", "0s", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L200-L241
[ "def", "sequence_edit_distance", "(", "predictions", ",", "labels", ",", "weights_fn", "=", "common_layers", ".", "weights_nonzero", ")", ":", "if", "weights_fn", "is", "not", "common_layers", ".", "weights_nonzero", ":", "raise", "ValueError", "(", "\"Only weights_...
272500b6efe353aeb638d2745ed56e519462ca31
train
padded_neg_log_perplexity
Average log-perplexity exluding padding 0s. No smoothing.
tensor2tensor/utils/metrics.py
def padded_neg_log_perplexity(predictions, labels, weights_fn=common_layers.weights_nonzero): """Average log-perplexity exluding padding 0s. No smoothing.""" num, den = common_layers.padded_cross_entropy( predictions, labels, 0.0, weights_fn=weights_...
def padded_neg_log_perplexity(predictions, labels, weights_fn=common_layers.weights_nonzero): """Average log-perplexity exluding padding 0s. No smoothing.""" num, den = common_layers.padded_cross_entropy( predictions, labels, 0.0, weights_fn=weights_...
[ "Average", "log", "-", "perplexity", "exluding", "padding", "0s", ".", "No", "smoothing", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L244-L250
[ "def", "padded_neg_log_perplexity", "(", "predictions", ",", "labels", ",", "weights_fn", "=", "common_layers", ".", "weights_nonzero", ")", ":", "num", ",", "den", "=", "common_layers", ".", "padded_cross_entropy", "(", "predictions", ",", "labels", ",", "0.0", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
padded_neg_log_perplexity_with_masking
Average log-perplexity with custom targets_mask.
tensor2tensor/utils/metrics.py
def padded_neg_log_perplexity_with_masking( predictions, labels, features, weights_fn=None): """Average log-perplexity with custom targets_mask.""" del weights_fn if "targets_mask" not in features: raise ValueError("masked_neg_log_perplexity requires targets_mask feature") # Features are 4 ...
def padded_neg_log_perplexity_with_masking( predictions, labels, features, weights_fn=None): """Average log-perplexity with custom targets_mask.""" del weights_fn if "targets_mask" not in features: raise ValueError("masked_neg_log_perplexity requires targets_mask feature") # Features are 4 ...
[ "Average", "log", "-", "perplexity", "with", "custom", "targets_mask", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L253-L273
[ "def", "padded_neg_log_perplexity_with_masking", "(", "predictions", ",", "labels", ",", "features", ",", "weights_fn", "=", "None", ")", ":", "del", "weights_fn", "if", "\"targets_mask\"", "not", "in", "features", ":", "raise", "ValueError", "(", "\"masked_neg_log_...
272500b6efe353aeb638d2745ed56e519462ca31
train
dmol_neg_log_perplexity
Average log-perplexity excluding padding 0s. No smoothing.
tensor2tensor/utils/metrics.py
def dmol_neg_log_perplexity(predictions, labels, weights_fn=None): """Average log-perplexity excluding padding 0s. No smoothing.""" del weights_fn # Unused num, den = common_layers.dml_loss( predictions, labels, reduce_sum=False) return (-num, den)
def dmol_neg_log_perplexity(predictions, labels, weights_fn=None): """Average log-perplexity excluding padding 0s. No smoothing.""" del weights_fn # Unused num, den = common_layers.dml_loss( predictions, labels, reduce_sum=False) return (-num, den)
[ "Average", "log", "-", "perplexity", "excluding", "padding", "0s", ".", "No", "smoothing", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L276-L283
[ "def", "dmol_neg_log_perplexity", "(", "predictions", ",", "labels", ",", "weights_fn", "=", "None", ")", ":", "del", "weights_fn", "# Unused", "num", ",", "den", "=", "common_layers", ".", "dml_loss", "(", "predictions", ",", "labels", ",", "reduce_sum", "=",...
272500b6efe353aeb638d2745ed56e519462ca31
train
rounding_accuracy
Rounding accuracy for L1/L2 losses: round down the predictions to ints.
tensor2tensor/utils/metrics.py
def rounding_accuracy(predictions, labels, weights_fn=common_layers.weights_nonzero): """Rounding accuracy for L1/L2 losses: round down the predictions to ints.""" outputs = tf.squeeze(tf.to_int32(predictions)) labels = tf.squeeze(labels) weights = weights_fn(labels) ...
def rounding_accuracy(predictions, labels, weights_fn=common_layers.weights_nonzero): """Rounding accuracy for L1/L2 losses: round down the predictions to ints.""" outputs = tf.squeeze(tf.to_int32(predictions)) labels = tf.squeeze(labels) weights = weights_fn(labels) ...
[ "Rounding", "accuracy", "for", "L1", "/", "L2", "losses", ":", "round", "down", "the", "predictions", "to", "ints", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L286-L294
[ "def", "rounding_accuracy", "(", "predictions", ",", "labels", ",", "weights_fn", "=", "common_layers", ".", "weights_nonzero", ")", ":", "outputs", "=", "tf", ".", "squeeze", "(", "tf", ".", "to_int32", "(", "predictions", ")", ")", "labels", "=", "tf", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
padded_accuracy
Percentage of times that predictions matches labels on non-0s.
tensor2tensor/utils/metrics.py
def padded_accuracy(predictions, labels, weights_fn=common_layers.weights_nonzero): """Percentage of times that predictions matches labels on non-0s.""" # If the last dimension is 1 then we're using L1/L2 loss. if common_layers.shape_list(predictions)[-1] == 1: return r...
def padded_accuracy(predictions, labels, weights_fn=common_layers.weights_nonzero): """Percentage of times that predictions matches labels on non-0s.""" # If the last dimension is 1 then we're using L1/L2 loss. if common_layers.shape_list(predictions)[-1] == 1: return r...
[ "Percentage", "of", "times", "that", "predictions", "matches", "labels", "on", "non", "-", "0s", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L297-L310
[ "def", "padded_accuracy", "(", "predictions", ",", "labels", ",", "weights_fn", "=", "common_layers", ".", "weights_nonzero", ")", ":", "# If the last dimension is 1 then we're using L1/L2 loss.", "if", "common_layers", ".", "shape_list", "(", "predictions", ")", "[", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
multilabel_accuracy_matchk
Used to evaluate the VQA accuracy. Let n be the times that predictions appear in labels, then final score is min(n/k, 1). Refer to https://arxiv.org/pdf/1505.00468.pdf. Args: predictions: A tensor with shape [batch_size, 1, 1, 1, vocab_size]. labels: A tensor with shape [batch_size, length, 1, 1]. ...
tensor2tensor/utils/metrics.py
def multilabel_accuracy_matchk(predictions, labels, k, weights_fn=common_layers.weights_nonzero): """Used to evaluate the VQA accuracy. Let n be the times that predictions appear in labels, then final score is min(n/k, 1...
def multilabel_accuracy_matchk(predictions, labels, k, weights_fn=common_layers.weights_nonzero): """Used to evaluate the VQA accuracy. Let n be the times that predictions appear in labels, then final score is min(n/k, 1...
[ "Used", "to", "evaluate", "the", "VQA", "accuracy", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L313-L343
[ "def", "multilabel_accuracy_matchk", "(", "predictions", ",", "labels", ",", "k", ",", "weights_fn", "=", "common_layers", ".", "weights_nonzero", ")", ":", "predictions", "=", "tf", ".", "to_int32", "(", "tf", ".", "argmax", "(", "predictions", ",", "axis", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
set_precision
Precision of set predictions. Args: predictions : A Tensor of scores of shape [batch, nlabels]. labels: A Tensor of int32s giving true set elements, of shape [batch, seq_length]. weights_fn: A function to weight the elements. Returns: hits: A Tensor of shape [batch, nlabels]. weights: A ...
tensor2tensor/utils/metrics.py
def set_precision(predictions, labels, weights_fn=common_layers.weights_nonzero): """Precision of set predictions. Args: predictions : A Tensor of scores of shape [batch, nlabels]. labels: A Tensor of int32s giving true set elements, of shape [batch, seq_length]. weights_fn: A f...
def set_precision(predictions, labels, weights_fn=common_layers.weights_nonzero): """Precision of set predictions. Args: predictions : A Tensor of scores of shape [batch, nlabels]. labels: A Tensor of int32s giving true set elements, of shape [batch, seq_length]. weights_fn: A f...
[ "Precision", "of", "set", "predictions", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L351-L371
[ "def", "set_precision", "(", "predictions", ",", "labels", ",", "weights_fn", "=", "common_layers", ".", "weights_nonzero", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"set_precision\"", ",", "values", "=", "[", "predictions", ",", "labels", "]", ")"...
272500b6efe353aeb638d2745ed56e519462ca31
train
image_summary
Reshapes predictions and passes it to tensorboard. Args: predictions : The predicted image (logits). targets : The ground truth. hparams: model hparams. Returns: summary_proto: containing the summary images. weights: A Tensor of zeros of the same shape as predictions.
tensor2tensor/utils/metrics.py
def image_summary(predictions, targets, hparams): """Reshapes predictions and passes it to tensorboard. Args: predictions : The predicted image (logits). targets : The ground truth. hparams: model hparams. Returns: summary_proto: containing the summary images. weights: A Tensor of zeros of t...
def image_summary(predictions, targets, hparams): """Reshapes predictions and passes it to tensorboard. Args: predictions : The predicted image (logits). targets : The ground truth. hparams: model hparams. Returns: summary_proto: containing the summary images. weights: A Tensor of zeros of t...
[ "Reshapes", "predictions", "and", "passes", "it", "to", "tensorboard", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L396-L414
[ "def", "image_summary", "(", "predictions", ",", "targets", ",", "hparams", ")", ":", "del", "hparams", "results", "=", "tf", ".", "cast", "(", "tf", ".", "argmax", "(", "predictions", ",", "axis", "=", "-", "1", ")", ",", "tf", ".", "uint8", ")", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
softmax_cross_entropy_one_hot
Calculate softmax cross entropy given one-hot labels and logits. Args: logits: Tensor of size [batch-size, o=1, p=1, num-classes] labels: Tensor of size [batch-size, o=1, p=1, num-classes] weights_fn: Function that takes in labels and weighs examples (unused) Returns: cross-entropy (scalar), weight...
tensor2tensor/utils/metrics.py
def softmax_cross_entropy_one_hot(logits, labels, weights_fn=None): """Calculate softmax cross entropy given one-hot labels and logits. Args: logits: Tensor of size [batch-size, o=1, p=1, num-classes] labels: Tensor of size [batch-size, o=1, p=1, num-classes] weights_fn: Function that takes in labels a...
def softmax_cross_entropy_one_hot(logits, labels, weights_fn=None): """Calculate softmax cross entropy given one-hot labels and logits. Args: logits: Tensor of size [batch-size, o=1, p=1, num-classes] labels: Tensor of size [batch-size, o=1, p=1, num-classes] weights_fn: Function that takes in labels a...
[ "Calculate", "softmax", "cross", "entropy", "given", "one", "-", "hot", "labels", "and", "logits", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L417-L432
[ "def", "softmax_cross_entropy_one_hot", "(", "logits", ",", "labels", ",", "weights_fn", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"softmax_cross_entropy_one_hot\"", ",", "values", "=", "[", "logits", ",", "labels", "]", ")", ":", "del...
272500b6efe353aeb638d2745ed56e519462ca31
train
sigmoid_accuracy_one_hot
Calculate accuracy for a set, given one-hot labels and logits. Args: logits: Tensor of size [batch-size, o=1, p=1, num-classes] labels: Tensor of size [batch-size, o=1, p=1, num-classes] weights_fn: Function that takes in labels and weighs examples (unused) Returns: accuracy (scalar), weights
tensor2tensor/utils/metrics.py
def sigmoid_accuracy_one_hot(logits, labels, weights_fn=None): """Calculate accuracy for a set, given one-hot labels and logits. Args: logits: Tensor of size [batch-size, o=1, p=1, num-classes] labels: Tensor of size [batch-size, o=1, p=1, num-classes] weights_fn: Function that takes in labels and weig...
def sigmoid_accuracy_one_hot(logits, labels, weights_fn=None): """Calculate accuracy for a set, given one-hot labels and logits. Args: logits: Tensor of size [batch-size, o=1, p=1, num-classes] labels: Tensor of size [batch-size, o=1, p=1, num-classes] weights_fn: Function that takes in labels and weig...
[ "Calculate", "accuracy", "for", "a", "set", "given", "one", "-", "hot", "labels", "and", "logits", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L435-L451
[ "def", "sigmoid_accuracy_one_hot", "(", "logits", ",", "labels", ",", "weights_fn", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"sigmoid_accuracy_one_hot\"", ",", "values", "=", "[", "logits", ",", "labels", "]", ")", ":", "del", "weig...
272500b6efe353aeb638d2745ed56e519462ca31
train
sigmoid_recall_one_hot
Calculate recall for a set, given one-hot labels and logits. Predictions are converted to one-hot, as predictions[example][arg-max(example)] = 1 Args: logits: Tensor of size [batch-size, o=1, p=1, num-classes] labels: Tensor of size [batch-size, o=1, p=1, num-classes] weights_fn: Function that takes...
tensor2tensor/utils/metrics.py
def sigmoid_recall_one_hot(logits, labels, weights_fn=None): """Calculate recall for a set, given one-hot labels and logits. Predictions are converted to one-hot, as predictions[example][arg-max(example)] = 1 Args: logits: Tensor of size [batch-size, o=1, p=1, num-classes] labels: Tensor of size [batc...
def sigmoid_recall_one_hot(logits, labels, weights_fn=None): """Calculate recall for a set, given one-hot labels and logits. Predictions are converted to one-hot, as predictions[example][arg-max(example)] = 1 Args: logits: Tensor of size [batch-size, o=1, p=1, num-classes] labels: Tensor of size [batc...
[ "Calculate", "recall", "for", "a", "set", "given", "one", "-", "hot", "labels", "and", "logits", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L477-L497
[ "def", "sigmoid_recall_one_hot", "(", "logits", ",", "labels", ",", "weights_fn", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"sigmoid_recall_one_hot\"", ",", "values", "=", "[", "logits", ",", "labels", "]", ")", ":", "del", "weights_...
272500b6efe353aeb638d2745ed56e519462ca31
train
sigmoid_cross_entropy_one_hot
Calculate sigmoid cross entropy for one-hot lanels and logits. Args: logits: Tensor of size [batch-size, o=1, p=1, num-classes] labels: Tensor of size [batch-size, o=1, p=1, num-classes] weights_fn: Function that takes in labels and weighs examples (unused) Returns: cross_entropy (scalar), weights
tensor2tensor/utils/metrics.py
def sigmoid_cross_entropy_one_hot(logits, labels, weights_fn=None): """Calculate sigmoid cross entropy for one-hot lanels and logits. Args: logits: Tensor of size [batch-size, o=1, p=1, num-classes] labels: Tensor of size [batch-size, o=1, p=1, num-classes] weights_fn: Function that takes in labels and...
def sigmoid_cross_entropy_one_hot(logits, labels, weights_fn=None): """Calculate sigmoid cross entropy for one-hot lanels and logits. Args: logits: Tensor of size [batch-size, o=1, p=1, num-classes] labels: Tensor of size [batch-size, o=1, p=1, num-classes] weights_fn: Function that takes in labels and...
[ "Calculate", "sigmoid", "cross", "entropy", "for", "one", "-", "hot", "lanels", "and", "logits", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L500-L515
[ "def", "sigmoid_cross_entropy_one_hot", "(", "logits", ",", "labels", ",", "weights_fn", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"sigmoid_cross_entropy_one_hot\"", ",", "values", "=", "[", "logits", ",", "labels", "]", ")", ":", "del...
272500b6efe353aeb638d2745ed56e519462ca31
train
roc_auc
Calculate ROC AUC. Requires binary classes. Args: logits: Tensor of size [batch_size, 1, 1, num_classes] labels: Tensor of size [batch_size, 1, 1, num_classes] weights_fn: Function that takes in labels and weighs examples (unused) Returns: ROC AUC (scalar), weights
tensor2tensor/utils/metrics.py
def roc_auc(logits, labels, weights_fn=None): """Calculate ROC AUC. Requires binary classes. Args: logits: Tensor of size [batch_size, 1, 1, num_classes] labels: Tensor of size [batch_size, 1, 1, num_classes] weights_fn: Function that takes in labels and weighs examples (unused) Returns: ROC A...
def roc_auc(logits, labels, weights_fn=None): """Calculate ROC AUC. Requires binary classes. Args: logits: Tensor of size [batch_size, 1, 1, num_classes] labels: Tensor of size [batch_size, 1, 1, num_classes] weights_fn: Function that takes in labels and weighs examples (unused) Returns: ROC A...
[ "Calculate", "ROC", "AUC", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L518-L534
[ "def", "roc_auc", "(", "logits", ",", "labels", ",", "weights_fn", "=", "None", ")", ":", "del", "weights_fn", "with", "tf", ".", "variable_scope", "(", "\"roc_auc\"", ",", "values", "=", "[", "logits", ",", "labels", "]", ")", ":", "predictions", "=", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
create_evaluation_metrics
Creates the evaluation metrics for the model. Args: problems: List of Problem instances. model_hparams: a set of hparams. Returns: dict<metric name, metric function>. The metric functions have signature (Tensor predictions, features) -> (metric Tensor, update op), where features is a dict with...
tensor2tensor/utils/metrics.py
def create_evaluation_metrics(problems, model_hparams): """Creates the evaluation metrics for the model. Args: problems: List of Problem instances. model_hparams: a set of hparams. Returns: dict<metric name, metric function>. The metric functions have signature (Tensor predictions, features) -> ...
def create_evaluation_metrics(problems, model_hparams): """Creates the evaluation metrics for the model. Args: problems: List of Problem instances. model_hparams: a set of hparams. Returns: dict<metric name, metric function>. The metric functions have signature (Tensor predictions, features) -> ...
[ "Creates", "the", "evaluation", "metrics", "for", "the", "model", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L537-L638
[ "def", "create_evaluation_metrics", "(", "problems", ",", "model_hparams", ")", ":", "def", "reduce_dimensions", "(", "predictions", ",", "labels", ")", ":", "\"\"\"Reduce dimensions for high-dimensional predictions and labels.\"\"\"", "# We will treat first dimensions as batch. On...
272500b6efe353aeb638d2745ed56e519462ca31
train
create_eager_metrics_for_problem
See create_eager_metrics.
tensor2tensor/utils/metrics.py
def create_eager_metrics_for_problem(problem, model_hparams): """See create_eager_metrics.""" metric_fns = problem.eval_metric_fns(model_hparams) problem_hparams = problem.get_hparams(model_hparams) target_modality = problem_hparams.modality["targets"] weights_fn = model_hparams.weights_fn.get( "targets...
def create_eager_metrics_for_problem(problem, model_hparams): """See create_eager_metrics.""" metric_fns = problem.eval_metric_fns(model_hparams) problem_hparams = problem.get_hparams(model_hparams) target_modality = problem_hparams.modality["targets"] weights_fn = model_hparams.weights_fn.get( "targets...
[ "See", "create_eager_metrics", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L641-L649
[ "def", "create_eager_metrics_for_problem", "(", "problem", ",", "model_hparams", ")", ":", "metric_fns", "=", "problem", ".", "eval_metric_fns", "(", "model_hparams", ")", "problem_hparams", "=", "problem", ".", "get_hparams", "(", "model_hparams", ")", "target_modali...
272500b6efe353aeb638d2745ed56e519462ca31
train
create_eager_metrics
Create metrics accumulators and averager for Eager mode. Args: metric_names: list<str> from Metrics enum 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. ...
tensor2tensor/utils/metrics.py
def create_eager_metrics(metric_names, weights_fn=common_layers.weights_all): """Create metrics accumulators and averager for Eager mode. Args: metric_names: list<str> from Metrics enum weights_fn: function that takes labels and returns a weights mask. Defaults to weights of all 1, i.e. common_layers...
def create_eager_metrics(metric_names, weights_fn=common_layers.weights_all): """Create metrics accumulators and averager for Eager mode. Args: metric_names: list<str> from Metrics enum weights_fn: function that takes labels and returns a weights mask. Defaults to weights of all 1, i.e. common_layers...
[ "Create", "metrics", "accumulators", "and", "averager", "for", "Eager", "mode", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L652-L667
[ "def", "create_eager_metrics", "(", "metric_names", ",", "weights_fn", "=", "common_layers", ".", "weights_all", ")", ":", "metric_fns", "=", "dict", "(", "[", "(", "name", ",", "METRICS_FNS", "[", "name", "]", ")", "for", "name", "in", "metric_names", "]", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
create_eager_metrics_internal
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...
tensor2tensor/utils/metrics.py
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): """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...
[ "Create", "metrics", "accumulators", "and", "averager", "for", "Eager", "mode", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L670-L701
[ "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",...
272500b6efe353aeb638d2745ed56e519462ca31
train
word_error_rate
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.
tensor2tensor/utils/metrics.py
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): """Calculate word error rate. Args: raw_predictions: The raw predictions. labels: The actual labels. lookup: A tf.constant mapping indices to ...
[ "Calculate", "word", "error", "rate", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L704-L761
[ "def", "word_error_rate", "(", "raw_predictions", ",", "labels", ",", "lookup", "=", "None", ",", "weights_fn", "=", "common_layers", ".", "weights_nonzero", ")", ":", "def", "from_tokens", "(", "raw", ",", "lookup_", ")", ":", "gathered", "=", "tf", ".", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
pearson_correlation_coefficient
Calculate pearson correlation coefficient. Args: predictions: The raw predictions. labels: The actual labels. weights_fn: Weighting function. Returns: The pearson correlation coefficient.
tensor2tensor/utils/metrics.py
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): """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...
[ "Calculate", "pearson", "correlation", "coefficient", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L764-L778
[ "def", "pearson_correlation_coefficient", "(", "predictions", ",", "labels", ",", "weights_fn", "=", "None", ")", ":", "del", "weights_fn", "_", ",", "pearson", "=", "tf", ".", "contrib", ".", "metrics", ".", "streaming_pearson_correlation", "(", "predictions", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
attention_lm_prepare_decoder
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...
tensor2tensor/models/research/attention_lm.py
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): """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...
[ "Prepare", "one", "shard", "of", "the", "model", "for", "the", "decoder", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm.py#L66-L89
[ "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...
272500b6efe353aeb638d2745ed56e519462ca31
train
attention_lm_decoder
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
tensor2tensor/models/research/attention_lm.py
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"): """A stack of attention_lm layers. Args: decoder_input: a Tensor decoder_self_attention_bias: bias Tensor for self-attention (see c...
[ "A", "stack", "of", "attention_lm", "layers", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm.py#L92-L127
[ "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...
272500b6efe353aeb638d2745ed56e519462ca31
train
attention_lm_base
Set of hyperparameters.
tensor2tensor/models/research/attention_lm.py
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(): """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...
[ "Set", "of", "hyperparameters", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm.py#L131-L163
[ "def", "attention_lm_base", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "hidden_size", "=", "1024", "hparams", ".", "batch_size", "=", "8192", "hparams", ".", "max_length", "=", "256", "hparams", ".", "dro...
272500b6efe353aeb638d2745ed56e519462ca31
train
attention_lm_small
Cheap model. on lm1b_32k: 45M params 2 steps/sec on [GeForce GTX TITAN X] Returns: an hparams object.
tensor2tensor/models/research/attention_lm.py
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(): """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 ...
[ "Cheap", "model", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm.py#L167-L182
[ "def", "attention_lm_small", "(", ")", ":", "hparams", "=", "attention_lm_base", "(", ")", "hparams", ".", "num_hidden_layers", "=", "4", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", "filter_size", "=", "2048", "hparams", ".", "layer_prepostprocess...
272500b6efe353aeb638d2745ed56e519462ca31
train
attention_lm_translation
Version to use for seq2seq.
tensor2tensor/models/research/attention_lm.py
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(): """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...
[ "Version", "to", "use", "for", "seq2seq", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm.py#L186-L196
[ "def", "attention_lm_translation", "(", ")", ":", "hparams", "=", "attention_lm_base", "(", ")", "hparams", ".", "layer_preprocess_sequence", "=", "\"n\"", "hparams", ".", "layer_postprocess_sequence", "=", "\"da\"", "hparams", ".", "learning_rate", "=", "0.4", "hpa...
272500b6efe353aeb638d2745ed56e519462ca31
train
_get_ngrams
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...
tensor2tensor/utils/bleu_hook.py
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): """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...
[ "Extracts", "all", "n", "-", "grams", "up", "to", "a", "given", "maximum", "order", "from", "an", "input", "segment", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L40-L57
[ "def", "_get_ngrams", "(", "segment", ",", "max_order", ")", ":", "ngram_counts", "=", "collections", ".", "Counter", "(", ")", "for", "order", "in", "range", "(", "1", ",", "max_order", "+", "1", ")", ":", "for", "i", "in", "range", "(", "0", ",", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
bleu_score
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...
tensor2tensor/utils/bleu_hook.py
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): """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...
[ "BLEU", "score", "computation", "between", "labels", "and", "predictions", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L132-L152
[ "def", "bleu_score", "(", "predictions", ",", "labels", ",", "*", "*", "unused_kwargs", ")", ":", "outputs", "=", "tf", ".", "to_int32", "(", "tf", ".", "argmax", "(", "predictions", ",", "axis", "=", "-", "1", ")", ")", "# Convert the outputs and labels t...
272500b6efe353aeb638d2745ed56e519462ca31
train
bleu_tokenize
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...
tensor2tensor/utils/bleu_hook.py
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): 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. ...
[ "r", "Tokenize", "a", "string", "following", "the", "official", "BLEU", "implementation", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L172-L199
[ "def", "bleu_tokenize", "(", "string", ")", ":", "string", "=", "uregex", ".", "nondigit_punct_re", ".", "sub", "(", "r\"\\1 \\2 \"", ",", "string", ")", "string", "=", "uregex", ".", "punct_nondigit_re", ".", "sub", "(", "r\" \\1 \\2\"", ",", "string", ")",...
272500b6efe353aeb638d2745ed56e519462ca31
train
bleu_wrapper
Compute BLEU for two files (reference and hypothesis translation).
tensor2tensor/utils/bleu_hook.py
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): """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...
[ "Compute", "BLEU", "for", "two", "files", "(", "reference", "and", "hypothesis", "translation", ")", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L202-L215
[ "def", "bleu_wrapper", "(", "ref_filename", ",", "hyp_filename", ",", "case_sensitive", "=", "False", ")", ":", "ref_lines", "=", "text_encoder", ".", "native_to_unicode", "(", "tf", ".", "gfile", ".", "Open", "(", "ref_filename", ",", "\"r\"", ")", ".", "re...
272500b6efe353aeb638d2745ed56e519462ca31
train
_try_twice_tf_glob
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...
tensor2tensor/utils/bleu_hook.py
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): """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 ...
[ "Glob", "twice", "first", "time", "possibly", "catching", "NotFoundError", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L221-L245
[ "def", "_try_twice_tf_glob", "(", "pattern", ")", ":", "try", ":", "return", "tf", ".", "gfile", ".", "Glob", "(", "pattern", ")", "except", "tf", ".", "errors", ".", "NotFoundError", ":", "return", "tf", ".", "gfile", ".", "Glob", "(", "pattern", ")" ...
272500b6efe353aeb638d2745ed56e519462ca31
train
_read_stepfiles_list
Return list of StepFiles sorted by step from files at path_prefix.
tensor2tensor/utils/bleu_hook.py
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): """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 ...
[ "Return", "list", "of", "StepFiles", "sorted", "by", "step", "from", "files", "at", "path_prefix", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L248-L264
[ "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"...
272500b6efe353aeb638d2745ed56e519462ca31
train
stepfiles_iterator
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...
tensor2tensor/utils/bleu_hook.py
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): """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 ...
[ "Continuously", "yield", "new", "files", "with", "steps", "in", "filename", "as", "they", "appear", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L267-L317
[ "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...
272500b6efe353aeb638d2745ed56e519462ca31
train
_get_vqa_v2_annotations
Extract the VQA V2 annotation files to directory unless it's there.
tensor2tensor/data_generators/vqa.py
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"): """Extract the VQA V2 annotation files to directory unless it's there.""" annotation_file = generator_utils.maybe_download_from_drive( directory, annotation_file...
[ "Extract", "the", "VQA", "V2", "annotation", "files", "to", "directory", "unless", "it", "s", "there", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa.py#L44-L51
[ "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...
272500b6efe353aeb638d2745ed56e519462ca31
train
_get_vqa_v2_image_raw_dataset
Extract the VQA V2 image data set to directory unless it's there.
tensor2tensor/data_generators/vqa.py
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): """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...
[ "Extract", "the", "VQA", "V2", "image", "data", "set", "to", "directory", "unless", "it", "s", "there", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa.py#L54-L62
[ "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",...
272500b6efe353aeb638d2745ed56e519462ca31
train
_get_vqa_v2_image_feature_dataset
Extract the VQA V2 feature data set to directory unless it's there.
tensor2tensor/data_generators/vqa.py
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"): """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...
[ "Extract", "the", "VQA", "V2", "feature", "data", "set", "to", "directory", "unless", "it", "s", "there", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa.py#L65-L71
[ "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...
272500b6efe353aeb638d2745ed56e519462ca31
train
_parse_fail
Helper function for raising a value error for bad assignment.
tensor2tensor/utils/hparam.py
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): """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))
[ "Helper", "function", "for", "raising", "a", "value", "error", "for", "bad", "assignment", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L42-L46
[ "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", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
_process_scalar_value
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...
tensor2tensor/utils/hparam.py
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): """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...
[ "Update", "results_dictionary", "with", "a", "scalar", "value", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L55-L101
[ "def", "_process_scalar_value", "(", "name", ",", "parse_fn", ",", "var_type", ",", "m_dict", ",", "values", ",", "results_dictionary", ")", ":", "try", ":", "parsed_value", "=", "parse_fn", "(", "m_dict", "[", "'val'", "]", ")", "except", "ValueError", ":",...
272500b6efe353aeb638d2745ed56e519462ca31
train
_process_list_value
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...
tensor2tensor/utils/hparam.py
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): """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_...
[ "Update", "results_dictionary", "from", "a", "list", "of", "values", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L104-L135
[ "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...
272500b6efe353aeb638d2745ed56e519462ca31
train
_cast_to_type_if_compatible
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...
tensor2tensor/utils/hparam.py
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): """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...
[ "Cast", "hparam", "to", "the", "provided", "type", "if", "compatible", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L138-L183
[ "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...
272500b6efe353aeb638d2745ed56e519462ca31
train
parse_values
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'...
tensor2tensor/utils/hparam.py
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): """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...
[ "Parses", "hyperparameter", "values", "from", "a", "string", "into", "a", "python", "map", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L186-L298
[ "def", "parse_values", "(", "values", ",", "type_map", ",", "ignore_unknown", "=", "False", ")", ":", "results_dictionary", "=", "{", "}", "pos", "=", "0", "while", "pos", "<", "len", "(", "values", ")", ":", "m", "=", "PARAM_RE", ".", "match", "(", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
HParams.add_hparam
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.
tensor2tensor/utils/hparam.py
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): """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...
[ "Adds", "{", "name", "value", "}", "pair", "to", "hyperparameters", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L418-L441
[ "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...
272500b6efe353aeb638d2745ed56e519462ca31