repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
tensorflow/tensor2tensor | tensor2tensor/layers/common_image_attention.py | local_global_attention | def local_global_attention(x,
self_attention_bias,
hparams,
q_padding="LEFT",
kv_padding="LEFT"):
"""Local and global 1d self attention."""
with tf.variable_scope("self_local_global_att"):
[x_global, x_lo... | python | def local_global_attention(x,
self_attention_bias,
hparams,
q_padding="LEFT",
kv_padding="LEFT"):
"""Local and global 1d self attention."""
with tf.variable_scope("self_local_global_att"):
[x_global, x_lo... | [
"def",
"local_global_attention",
"(",
"x",
",",
"self_attention_bias",
",",
"hparams",
",",
"q_padding",
"=",
"\"LEFT\"",
",",
"kv_padding",
"=",
"\"LEFT\"",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"self_local_global_att\"",
")",
":",
"[",
"x_globa... | Local and global 1d self attention. | [
"Local",
"and",
"global",
"1d",
"self",
"attention",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_image_attention.py#L225-L269 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_image_attention.py | full_self_attention | def full_self_attention(x,
self_attention_bias,
hparams,
q_padding="LEFT",
kv_padding="LEFT"):
"""Full self-attention layer."""
x, x_shape, is_4d = maybe_reshape_4d_to_3d(x)
if self_attention_bias is not None:
self... | python | def full_self_attention(x,
self_attention_bias,
hparams,
q_padding="LEFT",
kv_padding="LEFT"):
"""Full self-attention layer."""
x, x_shape, is_4d = maybe_reshape_4d_to_3d(x)
if self_attention_bias is not None:
self... | [
"def",
"full_self_attention",
"(",
"x",
",",
"self_attention_bias",
",",
"hparams",
",",
"q_padding",
"=",
"\"LEFT\"",
",",
"kv_padding",
"=",
"\"LEFT\"",
")",
":",
"x",
",",
"x_shape",
",",
"is_4d",
"=",
"maybe_reshape_4d_to_3d",
"(",
"x",
")",
"if",
"self_... | Full self-attention layer. | [
"Full",
"self",
"-",
"attention",
"layer",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_image_attention.py#L272-L299 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_image_attention.py | encdec_attention_1d | def encdec_attention_1d(x,
encoder_output,
encoder_decoder_attention_bias,
hparams):
"""Local 1d self attention."""
x, x_shape, is_4d = maybe_reshape_4d_to_3d(x)
encoder_output, _, _ = maybe_reshape_4d_to_3d(encoder_output)
with tf.variable... | python | def encdec_attention_1d(x,
encoder_output,
encoder_decoder_attention_bias,
hparams):
"""Local 1d self attention."""
x, x_shape, is_4d = maybe_reshape_4d_to_3d(x)
encoder_output, _, _ = maybe_reshape_4d_to_3d(encoder_output)
with tf.variable... | [
"def",
"encdec_attention_1d",
"(",
"x",
",",
"encoder_output",
",",
"encoder_decoder_attention_bias",
",",
"hparams",
")",
":",
"x",
",",
"x_shape",
",",
"is_4d",
"=",
"maybe_reshape_4d_to_3d",
"(",
"x",
")",
"encoder_output",
",",
"_",
",",
"_",
"=",
"maybe_r... | Local 1d self attention. | [
"Local",
"1d",
"self",
"attention",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_image_attention.py#L302-L324 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_image_attention.py | transformer_decoder_layers | def transformer_decoder_layers(inputs,
encoder_output,
num_layers,
hparams,
self_attention_bias=None,
encoder_decoder_attention_bias=None,
... | python | def transformer_decoder_layers(inputs,
encoder_output,
num_layers,
hparams,
self_attention_bias=None,
encoder_decoder_attention_bias=None,
... | [
"def",
"transformer_decoder_layers",
"(",
"inputs",
",",
"encoder_output",
",",
"num_layers",
",",
"hparams",
",",
"self_attention_bias",
"=",
"None",
",",
"encoder_decoder_attention_bias",
"=",
"None",
",",
"attention_type",
"=",
"AttentionType",
".",
"LOCAL_2D",
","... | Multi layer transformer. | [
"Multi",
"layer",
"transformer",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_image_attention.py#L327-L396 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_image_attention.py | transformer_encoder_layers | def transformer_encoder_layers(inputs,
num_layers,
hparams,
attention_type=AttentionType.GLOBAL,
self_attention_bias=None,
q_padding="VALID",
... | python | def transformer_encoder_layers(inputs,
num_layers,
hparams,
attention_type=AttentionType.GLOBAL,
self_attention_bias=None,
q_padding="VALID",
... | [
"def",
"transformer_encoder_layers",
"(",
"inputs",
",",
"num_layers",
",",
"hparams",
",",
"attention_type",
"=",
"AttentionType",
".",
"GLOBAL",
",",
"self_attention_bias",
"=",
"None",
",",
"q_padding",
"=",
"\"VALID\"",
",",
"kv_padding",
"=",
"\"VALID\"",
","... | Multi layer transformer encoder. | [
"Multi",
"layer",
"transformer",
"encoder",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_image_attention.py#L399-L431 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_image_attention.py | ffn_layer | def ffn_layer(x, hparams, losses=None):
"""ffn layer transformer."""
with tf.variable_scope("ffn"):
if hparams.ffn_layer == "none":
return x
if hparams.ffn_layer == "conv_hidden_relu":
y = common_layers.dense_relu_dense(
x,
hparams.filter_size,
hparams.hidden_size,
... | python | def ffn_layer(x, hparams, losses=None):
"""ffn layer transformer."""
with tf.variable_scope("ffn"):
if hparams.ffn_layer == "none":
return x
if hparams.ffn_layer == "conv_hidden_relu":
y = common_layers.dense_relu_dense(
x,
hparams.filter_size,
hparams.hidden_size,
... | [
"def",
"ffn_layer",
"(",
"x",
",",
"hparams",
",",
"losses",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"ffn\"",
")",
":",
"if",
"hparams",
".",
"ffn_layer",
"==",
"\"none\"",
":",
"return",
"x",
"if",
"hparams",
".",
"ffn_layer... | ffn layer transformer. | [
"ffn",
"layer",
"transformer",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_image_attention.py#L434-L481 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_image_attention.py | get_self_attention_bias | def get_self_attention_bias(x):
"""Creates masked self attention bias.
Args:
x: A tensor of shape [batch, length, depth]
Returns:
self_attention_bias: A tensor of shape [length, length, 1]
"""
x_shape = common_layers.shape_list(x)
self_attention_bias = common_attention.attention_bias_lower_triang... | python | def get_self_attention_bias(x):
"""Creates masked self attention bias.
Args:
x: A tensor of shape [batch, length, depth]
Returns:
self_attention_bias: A tensor of shape [length, length, 1]
"""
x_shape = common_layers.shape_list(x)
self_attention_bias = common_attention.attention_bias_lower_triang... | [
"def",
"get_self_attention_bias",
"(",
"x",
")",
":",
"x_shape",
"=",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"self_attention_bias",
"=",
"common_attention",
".",
"attention_bias_lower_triangle",
"(",
"x_shape",
"[",
"1",
"]",
")",
"return",
"self_atten... | Creates masked self attention bias.
Args:
x: A tensor of shape [batch, length, depth]
Returns:
self_attention_bias: A tensor of shape [length, length, 1] | [
"Creates",
"masked",
"self",
"attention",
"bias",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_image_attention.py#L484-L497 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_image_attention.py | postprocess_image | def postprocess_image(x, rows, cols, hparams):
"""Postprocessing after decoding.
Args:
x: Tensor of shape [batch, ...], where ... can be any rank such that the
number of elements in x is batch * rows * cols * hparams.hidden_size.
rows: Integer representing number of rows in a 2-D data point.
cols... | python | def postprocess_image(x, rows, cols, hparams):
"""Postprocessing after decoding.
Args:
x: Tensor of shape [batch, ...], where ... can be any rank such that the
number of elements in x is batch * rows * cols * hparams.hidden_size.
rows: Integer representing number of rows in a 2-D data point.
cols... | [
"def",
"postprocess_image",
"(",
"x",
",",
"rows",
",",
"cols",
",",
"hparams",
")",
":",
"batch",
"=",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"[",
"0",
"]",
"x",
"=",
"tf",
".",
"reshape",
"(",
"x",
",",
"[",
"batch",
",",
"rows",
",... | Postprocessing after decoding.
Args:
x: Tensor of shape [batch, ...], where ... can be any rank such that the
number of elements in x is batch * rows * cols * hparams.hidden_size.
rows: Integer representing number of rows in a 2-D data point.
cols: Integer representing number of columns in a 2-D da... | [
"Postprocessing",
"after",
"decoding",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_image_attention.py#L500-L555 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_image_attention.py | prepare_encoder | def prepare_encoder(inputs, hparams, attention_type="local_1d"):
"""Prepare encoder for images."""
x = prepare_image(inputs, hparams, name="enc_channels")
# Add position signals.
x = add_pos_signals(x, hparams, "enc_pos")
x_shape = common_layers.shape_list(x)
if attention_type == "local_1d":
x = tf.resh... | python | def prepare_encoder(inputs, hparams, attention_type="local_1d"):
"""Prepare encoder for images."""
x = prepare_image(inputs, hparams, name="enc_channels")
# Add position signals.
x = add_pos_signals(x, hparams, "enc_pos")
x_shape = common_layers.shape_list(x)
if attention_type == "local_1d":
x = tf.resh... | [
"def",
"prepare_encoder",
"(",
"inputs",
",",
"hparams",
",",
"attention_type",
"=",
"\"local_1d\"",
")",
":",
"x",
"=",
"prepare_image",
"(",
"inputs",
",",
"hparams",
",",
"name",
"=",
"\"enc_channels\"",
")",
"# Add position signals.",
"x",
"=",
"add_pos_sign... | Prepare encoder for images. | [
"Prepare",
"encoder",
"for",
"images",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_image_attention.py#L558-L569 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_image_attention.py | prepare_decoder | def prepare_decoder(targets, hparams):
"""Prepare decoder for images."""
targets_shape = common_layers.shape_list(targets)
channels = hparams.num_channels
curr_infer_length = None
# during training, images are [batch, IMG_LEN, IMG_LEN, 3].
# At inference, they are [batch, curr_infer_length, 1, 1]
if hpar... | python | def prepare_decoder(targets, hparams):
"""Prepare decoder for images."""
targets_shape = common_layers.shape_list(targets)
channels = hparams.num_channels
curr_infer_length = None
# during training, images are [batch, IMG_LEN, IMG_LEN, 3].
# At inference, they are [batch, curr_infer_length, 1, 1]
if hpar... | [
"def",
"prepare_decoder",
"(",
"targets",
",",
"hparams",
")",
":",
"targets_shape",
"=",
"common_layers",
".",
"shape_list",
"(",
"targets",
")",
"channels",
"=",
"hparams",
".",
"num_channels",
"curr_infer_length",
"=",
"None",
"# during training, images are [batch,... | Prepare decoder for images. | [
"Prepare",
"decoder",
"for",
"images",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_image_attention.py#L572-L629 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_image_attention.py | create_output | def create_output(decoder_output, rows, cols, targets, hparams):
"""Creates output from decoder output and vars.
Args:
decoder_output: Tensor of shape [batch, ...], where ... can be any rank such
that the number of elements is batch * rows * cols * hparams.hidden_size.
rows: Integer representing numb... | python | def create_output(decoder_output, rows, cols, targets, hparams):
"""Creates output from decoder output and vars.
Args:
decoder_output: Tensor of shape [batch, ...], where ... can be any rank such
that the number of elements is batch * rows * cols * hparams.hidden_size.
rows: Integer representing numb... | [
"def",
"create_output",
"(",
"decoder_output",
",",
"rows",
",",
"cols",
",",
"targets",
",",
"hparams",
")",
":",
"del",
"targets",
"# unused arg",
"decoded_image",
"=",
"postprocess_image",
"(",
"decoder_output",
",",
"rows",
",",
"cols",
",",
"hparams",
")"... | Creates output from decoder output and vars.
Args:
decoder_output: Tensor of shape [batch, ...], where ... can be any rank such
that the number of elements is batch * rows * cols * hparams.hidden_size.
rows: Integer representing number of rows in a 2-D data point.
cols: Integer representing number ... | [
"Creates",
"output",
"from",
"decoder",
"output",
"and",
"vars",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_image_attention.py#L639-L672 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_image_attention.py | get_channel_embeddings | def get_channel_embeddings(io_depth, targets, hidden_size, name="channel"):
"""Get separate embedding for each of the channels."""
targets_split = tf.split(targets, io_depth, axis=3)
rgb_embedding_var = tf.get_variable("rgb_target_emb_%s" % name,
[256 * io_depth, hidden_size]... | python | def get_channel_embeddings(io_depth, targets, hidden_size, name="channel"):
"""Get separate embedding for each of the channels."""
targets_split = tf.split(targets, io_depth, axis=3)
rgb_embedding_var = tf.get_variable("rgb_target_emb_%s" % name,
[256 * io_depth, hidden_size]... | [
"def",
"get_channel_embeddings",
"(",
"io_depth",
",",
"targets",
",",
"hidden_size",
",",
"name",
"=",
"\"channel\"",
")",
":",
"targets_split",
"=",
"tf",
".",
"split",
"(",
"targets",
",",
"io_depth",
",",
"axis",
"=",
"3",
")",
"rgb_embedding_var",
"=",
... | Get separate embedding for each of the channels. | [
"Get",
"separate",
"embedding",
"for",
"each",
"of",
"the",
"channels",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_image_attention.py#L675-L690 | train |
tensorflow/tensor2tensor | tensor2tensor/rl/envs/py_func_batch_env.py | PyFuncBatchEnv.simulate | def simulate(self, action):
"""Step the batch of environments.
The results of the step can be accessed from the variables defined below.
Args:
action: Tensor holding the batch of actions to apply.
Returns:
Operation.
"""
with tf.name_scope("environment/simulate"):
if action.... | python | def simulate(self, action):
"""Step the batch of environments.
The results of the step can be accessed from the variables defined below.
Args:
action: Tensor holding the batch of actions to apply.
Returns:
Operation.
"""
with tf.name_scope("environment/simulate"):
if action.... | [
"def",
"simulate",
"(",
"self",
",",
"action",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"\"environment/simulate\"",
")",
":",
"if",
"action",
".",
"dtype",
"in",
"(",
"tf",
".",
"float16",
",",
"tf",
".",
"float32",
",",
"tf",
".",
"float64",
... | Step the batch of environments.
The results of the step can be accessed from the variables defined below.
Args:
action: Tensor holding the batch of actions to apply.
Returns:
Operation. | [
"Step",
"the",
"batch",
"of",
"environments",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/envs/py_func_batch_env.py#L79-L110 | train |
tensorflow/tensor2tensor | tensor2tensor/rl/envs/py_func_batch_env.py | PyFuncBatchEnv._reset_non_empty | 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.
"""
observ = tf.py_func(
self._batch_env.reset, [indices], self.observ_dtype, ... | python | 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.
"""
observ = tf.py_func(
self._batch_env.reset, [indices], self.observ_dtype, ... | [
"def",
"_reset_non_empty",
"(",
"self",
",",
"indices",
")",
":",
"observ",
"=",
"tf",
".",
"py_func",
"(",
"self",
".",
"_batch_env",
".",
"reset",
",",
"[",
"indices",
"]",
",",
"self",
".",
"observ_dtype",
",",
"name",
"=",
"\"reset\"",
")",
"observ... | 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",
"the",
"batch",
"of",
"environments",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/envs/py_func_batch_env.py#L112-L126 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wiki_revision_utils.py | include_revision | def include_revision(revision_num, skip_factor=1.1):
"""Decide whether to include a revision.
If the number of revisions is large, we exclude some revisions to avoid
a quadratic blowup in runtime, since the article is likely also large.
We make the ratio between consecutive included revision numbers
appprox... | python | def include_revision(revision_num, skip_factor=1.1):
"""Decide whether to include a revision.
If the number of revisions is large, we exclude some revisions to avoid
a quadratic blowup in runtime, since the article is likely also large.
We make the ratio between consecutive included revision numbers
appprox... | [
"def",
"include_revision",
"(",
"revision_num",
",",
"skip_factor",
"=",
"1.1",
")",
":",
"if",
"skip_factor",
"<=",
"1.0",
":",
"return",
"True",
"return",
"(",
"int",
"(",
"math",
".",
"log1p",
"(",
"revision_num",
")",
"/",
"math",
".",
"log",
"(",
... | Decide whether to include a revision.
If the number of revisions is large, we exclude some revisions to avoid
a quadratic blowup in runtime, since the article is likely also large.
We make the ratio between consecutive included revision numbers
appproximately equal to "factor".
Args:
revision_num: an i... | [
"Decide",
"whether",
"to",
"include",
"a",
"revision",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L36-L55 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wiki_revision_utils.py | file_page_generator | def file_page_generator(my_file, max_page_size=2**28):
"""Read wikipedia pages from a history dump.
Since some pages can be terabytes in size (with all the revisions),
we limit page size to max_page_size bytes.
Args:
my_file: an open file object.
max_page_size: an integer
Yields:
strings
"""
... | python | def file_page_generator(my_file, max_page_size=2**28):
"""Read wikipedia pages from a history dump.
Since some pages can be terabytes in size (with all the revisions),
we limit page size to max_page_size bytes.
Args:
my_file: an open file object.
max_page_size: an integer
Yields:
strings
"""
... | [
"def",
"file_page_generator",
"(",
"my_file",
",",
"max_page_size",
"=",
"2",
"**",
"28",
")",
":",
"page_start",
"=",
"\" <page>\\n\"",
"page_end",
"=",
"\" </page>\\n\"",
"chunk_size",
"=",
"max_page_size",
"page_start",
"=",
"\" <page>\\n\"",
"page_end",
"=",
... | Read wikipedia pages from a history dump.
Since some pages can be terabytes in size (with all the revisions),
we limit page size to max_page_size bytes.
Args:
my_file: an open file object.
max_page_size: an integer
Yields:
strings | [
"Read",
"wikipedia",
"pages",
"from",
"a",
"history",
"dump",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L58-L99 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wiki_revision_utils.py | get_title | def get_title(page):
"""Extract the title from a page.
Args:
page: a string
Returns:
a string
"""
start_pos = page.find("<title>")
end_pos = page.find("</title>")
assert start_pos != -1
assert end_pos != -1
start_pos += len("<title>")
return text_encoder.to_unicode_utf8(page[start_pos:end_p... | python | def get_title(page):
"""Extract the title from a page.
Args:
page: a string
Returns:
a string
"""
start_pos = page.find("<title>")
end_pos = page.find("</title>")
assert start_pos != -1
assert end_pos != -1
start_pos += len("<title>")
return text_encoder.to_unicode_utf8(page[start_pos:end_p... | [
"def",
"get_title",
"(",
"page",
")",
":",
"start_pos",
"=",
"page",
".",
"find",
"(",
"\"<title>\"",
")",
"end_pos",
"=",
"page",
".",
"find",
"(",
"\"</title>\"",
")",
"assert",
"start_pos",
"!=",
"-",
"1",
"assert",
"end_pos",
"!=",
"-",
"1",
"start... | Extract the title from a page.
Args:
page: a string
Returns:
a string | [
"Extract",
"the",
"title",
"from",
"a",
"page",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L102-L115 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wiki_revision_utils.py | get_id | def get_id(page):
"""Extract the id from a page.
Args:
page: a string
Returns:
an integer
"""
start_pos = page.find("<id>")
end_pos = page.find("</id>")
assert start_pos != -1
assert end_pos != -1
start_pos += len("<id>")
return int(page[start_pos:end_pos]) | python | def get_id(page):
"""Extract the id from a page.
Args:
page: a string
Returns:
an integer
"""
start_pos = page.find("<id>")
end_pos = page.find("</id>")
assert start_pos != -1
assert end_pos != -1
start_pos += len("<id>")
return int(page[start_pos:end_pos]) | [
"def",
"get_id",
"(",
"page",
")",
":",
"start_pos",
"=",
"page",
".",
"find",
"(",
"\"<id>\"",
")",
"end_pos",
"=",
"page",
".",
"find",
"(",
"\"</id>\"",
")",
"assert",
"start_pos",
"!=",
"-",
"1",
"assert",
"end_pos",
"!=",
"-",
"1",
"start_pos",
... | Extract the id from a page.
Args:
page: a string
Returns:
an integer | [
"Extract",
"the",
"id",
"from",
"a",
"page",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L118-L131 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wiki_revision_utils.py | get_revisions | def get_revisions(page):
"""Extract the revisions of a page.
Args:
page: a string
Returns:
a list of strings
"""
start_string = " <revision>\n"
end_string = " </revision>\n"
ret = []
current_pos = 0
while True:
start_pos = page.find(start_string, current_pos)
if start_pos == -1:... | python | def get_revisions(page):
"""Extract the revisions of a page.
Args:
page: a string
Returns:
a list of strings
"""
start_string = " <revision>\n"
end_string = " </revision>\n"
ret = []
current_pos = 0
while True:
start_pos = page.find(start_string, current_pos)
if start_pos == -1:... | [
"def",
"get_revisions",
"(",
"page",
")",
":",
"start_string",
"=",
"\" <revision>\\n\"",
"end_string",
"=",
"\" </revision>\\n\"",
"ret",
"=",
"[",
"]",
"current_pos",
"=",
"0",
"while",
"True",
":",
"start_pos",
"=",
"page",
".",
"find",
"(",
"start_st... | Extract the revisions of a page.
Args:
page: a string
Returns:
a list of strings | [
"Extract",
"the",
"revisions",
"of",
"a",
"page",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L134-L154 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wiki_revision_utils.py | parse_page | def parse_page(raw_page):
"""Create a dictionary with title, id, and list of revisions.
The dictionary contains:
"title": a string
"id": an integer
"revisions": a list of strings
Args:
raw_page: a string
Returns:
a dictionary, or None in the case of an error.
"""
ret = {"title": get_title(r... | python | def parse_page(raw_page):
"""Create a dictionary with title, id, and list of revisions.
The dictionary contains:
"title": a string
"id": an integer
"revisions": a list of strings
Args:
raw_page: a string
Returns:
a dictionary, or None in the case of an error.
"""
ret = {"title": get_title(r... | [
"def",
"parse_page",
"(",
"raw_page",
")",
":",
"ret",
"=",
"{",
"\"title\"",
":",
"get_title",
"(",
"raw_page",
")",
",",
"\"id\"",
":",
"get_id",
"(",
"raw_page",
")",
"}",
"if",
"\":\"",
"in",
"ret",
"[",
"\"title\"",
"]",
":",
"return",
"None",
"... | Create a dictionary with title, id, and list of revisions.
The dictionary contains:
"title": a string
"id": an integer
"revisions": a list of strings
Args:
raw_page: a string
Returns:
a dictionary, or None in the case of an error. | [
"Create",
"a",
"dictionary",
"with",
"title",
"id",
"and",
"list",
"of",
"revisions",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L157-L175 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wiki_revision_utils.py | maybe_copy_file_to_directory | def maybe_copy_file_to_directory(source_filepath, target_directory):
"""Copy a file to a directory if it is not already there.
Returns the target filepath.
Args:
source_filepath: a string
target_directory: a string
Returns:
a string
"""
if not tf.gfile.Exists(target_directory):
tf.logging... | python | def maybe_copy_file_to_directory(source_filepath, target_directory):
"""Copy a file to a directory if it is not already there.
Returns the target filepath.
Args:
source_filepath: a string
target_directory: a string
Returns:
a string
"""
if not tf.gfile.Exists(target_directory):
tf.logging... | [
"def",
"maybe_copy_file_to_directory",
"(",
"source_filepath",
",",
"target_directory",
")",
":",
"if",
"not",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"target_directory",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Creating directory %s\"",
"%",
"target... | Copy a file to a directory if it is not already there.
Returns the target filepath.
Args:
source_filepath: a string
target_directory: a string
Returns:
a string | [
"Copy",
"a",
"file",
"to",
"a",
"directory",
"if",
"it",
"is",
"not",
"already",
"there",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L178-L203 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wiki_revision_utils.py | corpus_page_generator | def corpus_page_generator(corpus_files, tmp_dir, max_page_size_exp):
"""Generate pages from a list of .7z encoded history dumps.
Args:
corpus_files: a list of strings
tmp_dir: a string
max_page_size_exp: an integer
Yields:
strings
"""
for remote_filepath in corpus_files:
filepath = mayb... | python | def corpus_page_generator(corpus_files, tmp_dir, max_page_size_exp):
"""Generate pages from a list of .7z encoded history dumps.
Args:
corpus_files: a list of strings
tmp_dir: a string
max_page_size_exp: an integer
Yields:
strings
"""
for remote_filepath in corpus_files:
filepath = mayb... | [
"def",
"corpus_page_generator",
"(",
"corpus_files",
",",
"tmp_dir",
",",
"max_page_size_exp",
")",
":",
"for",
"remote_filepath",
"in",
"corpus_files",
":",
"filepath",
"=",
"maybe_copy_file_to_directory",
"(",
"remote_filepath",
",",
"tmp_dir",
")",
"tf",
".",
"lo... | Generate pages from a list of .7z encoded history dumps.
Args:
corpus_files: a list of strings
tmp_dir: a string
max_page_size_exp: an integer
Yields:
strings | [
"Generate",
"pages",
"from",
"a",
"list",
"of",
".",
"7z",
"encoded",
"history",
"dumps",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L206-L228 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wiki_revision_utils.py | get_text | def get_text(revision, strip=True):
"""Extract the text from a revision.
Args:
revision: a string
strip: a boolean
Returns:
a string
"""
# text start tag looks like "<text ..otherstuff>"
start_pos = revision.find("<text")
assert start_pos != -1
end_tag_pos = revision.find(">", start_pos)
... | python | def get_text(revision, strip=True):
"""Extract the text from a revision.
Args:
revision: a string
strip: a boolean
Returns:
a string
"""
# text start tag looks like "<text ..otherstuff>"
start_pos = revision.find("<text")
assert start_pos != -1
end_tag_pos = revision.find(">", start_pos)
... | [
"def",
"get_text",
"(",
"revision",
",",
"strip",
"=",
"True",
")",
":",
"# text start tag looks like \"<text ..otherstuff>\"",
"start_pos",
"=",
"revision",
".",
"find",
"(",
"\"<text\"",
")",
"assert",
"start_pos",
"!=",
"-",
"1",
"end_tag_pos",
"=",
"revision",... | Extract the text from a revision.
Args:
revision: a string
strip: a boolean
Returns:
a string | [
"Extract",
"the",
"text",
"from",
"a",
"revision",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L231-L255 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wiki_revision_utils.py | _remove_curly_braces | def _remove_curly_braces(text):
"""Remove everything in curly braces.
Curly braces may be nested, so we keep track of depth.
Args:
text: a string
Returns:
a string
"""
current_pos = 0
depth = 0
ret = ""
for match in re.finditer("[{}]", text):
if depth == 0:
ret += text[current_pos:... | python | def _remove_curly_braces(text):
"""Remove everything in curly braces.
Curly braces may be nested, so we keep track of depth.
Args:
text: a string
Returns:
a string
"""
current_pos = 0
depth = 0
ret = ""
for match in re.finditer("[{}]", text):
if depth == 0:
ret += text[current_pos:... | [
"def",
"_remove_curly_braces",
"(",
"text",
")",
":",
"current_pos",
"=",
"0",
"depth",
"=",
"0",
"ret",
"=",
"\"\"",
"for",
"match",
"in",
"re",
".",
"finditer",
"(",
"\"[{}]\"",
",",
"text",
")",
":",
"if",
"depth",
"==",
"0",
":",
"ret",
"+=",
"... | Remove everything in curly braces.
Curly braces may be nested, so we keep track of depth.
Args:
text: a string
Returns:
a string | [
"Remove",
"everything",
"in",
"curly",
"braces",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L316-L340 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wiki_revision_utils.py | _remove_double_brackets | 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... | python | 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",
")",
":",
"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.
Args:
text: a string
Returns:
a string | [
"Remove",
"double",
"brackets",
"but",
"leave",
"the",
"viewable",
"text",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L343-L362 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wiki_revision_utils.py | _remove_boring_lines | 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... | python | 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",
")",
":",
"lines",
"=",
"text",
".",
"split",
"(",
"\"\\n\"",
")",
"filtered",
"=",
"[",
"line",
"for",
"line",
"in",
"lines",
"if",
"re",
".",
"match",
"(",
"\"[a-zA-z\\\"\\']\"",
",",
"line",
")",
"]",
"ret... | 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 | [
"Remove",
"lines",
"that",
"do",
"not",
"start",
"with",
"a",
"letter",
"or",
"a",
"quote",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L365-L378 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wiki_revision_utils.py | get_or_generate_vocabulary | 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:... | python | 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",
")",
":",
"num_pages_for_vocab_generation",
"=",
"approx_vocab_size",
"//",
"3",
"v... | 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 | [
"Get",
"or",
"generate",
"the",
"vocabulary",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L401-L440 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wiki_revision_utils.py | get_encoder_from_vocab | 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... | python | 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",
")",
":",
"if",
"not",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"vocab_filepath",
")",
":",
"raise",
"ValueError",
"(",
"\"Vocab file does not exist: {}.\"",
".",
"format",
"(",
"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 vocabulary object. None if the output_parallel_t... | [
"Get",
"encoder",
"from",
"vocab",
"file",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L443-L461 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wiki_revision_utils.py | edit_distance_filter | 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... | python | 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",
")",
":",
"thrown_out_count",
"=",
"0",
"source_target_output",
"=",
"[",
"]",
"if",
"not",
"max_equal_to_diff_ratio",
":",
"return",
"source_target_input",
",",
"thro... | 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, ... | [
"Filter",
"out",
"examples",
"that",
"exceed",
"max_edit_ratio",
"between",
"source",
"and",
"target",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L476-L508 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wiki_revision_utils.py | introduce_errors | 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... | python | 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",
")",
":",
"num_errors",
"=",
"0",
"ret",
"=",
"[",
"]",
"operations",
"=",
"[",
"\"delete\"",
",",
"# delete a ... | 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 "... | [
"Artificially",
"add",
"spelling",
"errors",
"and",
"infill",
"markers",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L511-L574 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wiki_revision_utils.py | fast_match_sequences | 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... | python | 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",
")",
":",
"if",
"a... | 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... | [
"Compute",
"diffs",
"between",
"two",
"sequences",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki_revision_utils.py#L577-L675 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/restore_hook.py | RestoreHook.begin | 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... | python | 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",
")",
":",
"variables_to_restore",
"=",
"tf",
".",
"contrib",
".",
"framework",
".",
"get_variables_to_restore",
"(",
"include",
"=",
"self",
".",
"_include",
",",
"exclude",
"=",
"self",
".",
"_exclude",
")",
"# remove new_model_sc... | 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. | [
"Load",
"variables",
"from",
"checkpoint",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/restore_hook.py#L38-L61 | train |
tensorflow/tensor2tensor | tensor2tensor/envs/time_step.py | TimeStep.create_time_step | 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... | python | 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",
")",
":",
"return",
"cls",
"(",
"observation",
",",
"done... | Creates a TimeStep with both rewards and actions as optional. | [
"Creates",
"a",
"TimeStep",
"with",
"both",
"rewards",
"and",
"actions",
"as",
"optional",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/time_step.py#L59-L67 | train |
tensorflow/tensor2tensor | tensor2tensor/models/slicenet.py | attention | 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_... | python | 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",
")",
":",
"separabilities",
"=",
"[",
"hparams",
".",
"separability",
",",
"hparams",
".",
"separability",
"]",
"if",
"hparams",
".",... | Complete attention layer with preprocessing. | [
"Complete",
"attention",
"layer",
"with",
"preprocessing",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L33-L81 | train |
tensorflow/tensor2tensor | tensor2tensor/models/slicenet.py | multi_conv_res | 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... | python | 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",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
")",
":",
"padding_bias",
"=",
"None",
"i... | A stack of separable convolution blocks with residual connections. | [
"A",
"stack",
"of",
"separable",
"convolution",
"blocks",
"with",
"residual",
"connections",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L84-L142 | train |
tensorflow/tensor2tensor | tensor2tensor/models/slicenet.py | rank_loss | 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... | python | 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",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"\"rank_loss\"",
")",
":",
"# Normalize first as this is assumed in cosine similarity later.",
"sentence_emb",
"=",
"tf",
".",
"nn",... | Experimental rank loss, thanks to kkurach@ for the code. | [
"Experimental",
"rank",
"loss",
"thanks",
"to",
"kkurach"
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L145-L162 | train |
tensorflow/tensor2tensor | tensor2tensor/models/slicenet.py | similarity_cost | 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... | python | 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",
")",
":",
"# 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... | Loss telling to be more similar to your own targets than to others. | [
"Loss",
"telling",
"to",
"be",
"more",
"similar",
"to",
"your",
"own",
"targets",
"than",
"to",
"others",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L165-L172 | train |
tensorflow/tensor2tensor | tensor2tensor/models/slicenet.py | slicenet_middle | 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,
... | python | 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",
")",
":",
"def",
"norm_fn",
"(",
"x",
",",
"name",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
... | Middle part of slicenet, connecting encoder and decoder. | [
"Middle",
"part",
"of",
"slicenet",
"connecting",
"encoder",
"and",
"decoder",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L175-L212 | train |
tensorflow/tensor2tensor | tensor2tensor/models/slicenet.py | embedding_to_padding | 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)) | python | 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",
")",
":",
"emb_sum",
"=",
"tf",
".",
"reduce_sum",
"(",
"tf",
".",
"abs",
"(",
"emb",
")",
",",
"axis",
"=",
"-",
"1",
",",
"keep_dims",
"=",
"True",
")",
"return",
"tf",
".",
"to_float",
"(",
"tf",
".",
... | Input embeddings -> is_padding. | [
"Input",
"embeddings",
"-",
">",
"is_padding",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L221-L224 | train |
tensorflow/tensor2tensor | tensor2tensor/models/slicenet.py | slicenet_internal | 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... | python | 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",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"slicenet\"",
")",
":",
"# Project to hidden size if necessary",
"if",
"inputs",
... | The slicenet model, main step used for training. | [
"The",
"slicenet",
"model",
"main",
"step",
"used",
"for",
"training",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L227-L261 | train |
tensorflow/tensor2tensor | tensor2tensor/models/slicenet.py | slicenet_params1 | 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... | python | 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",
"(",
")",
":",
"hparams",
"=",
"common_hparams",
".",
"basic_params1",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"1024",
"hparams",
".",
"hidden_size",
"=",
"768",
"hparams",
".",
"dropout",
"=",
"0.5",
"hparams",
".",
"symbol_d... | Set of hyperparameters. | [
"Set",
"of",
"hyperparameters",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L296-L334 | train |
tensorflow/tensor2tensor | tensor2tensor/models/slicenet.py | slicenet_params1_noam | 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... | python | 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",
"(",
")",
":",
"hparams",
"=",
"slicenet_params1",
"(",
")",
"hparams",
".",
"learning_rate_decay_scheme",
"=",
"\"noam\"",
"hparams",
".",
"learning_rate",
"=",
"1.0",
"hparams",
".",
"learning_rate_warmup_steps",
"=",
"4000",
"hpara... | Version with Noam's decay scheme. | [
"Version",
"with",
"Noam",
"s",
"decay",
"scheme",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L338-L348 | train |
tensorflow/tensor2tensor | tensor2tensor/models/slicenet.py | slicenet_params1_tiny | 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 | python | 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",
"(",
")",
":",
"hparams",
"=",
"slicenet_params1",
"(",
")",
"hparams",
".",
"attention_type",
"=",
"\"simple\"",
"hparams",
".",
"separability",
"=",
"0",
"hparams",
".",
"hidden_size",
"=",
"128",
"hparams",
".",
"num_hidden_lay... | Version for fast local runs. | [
"Version",
"for",
"fast",
"local",
"runs",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L352-L361 | train |
tensorflow/tensor2tensor | tensor2tensor/models/slicenet.py | slicenet_range1 | 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... | python | 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",
")",
":",
"rhp",
"=",
"ranged_hparams",
"rhp",
".",
"set_float",
"(",
"\"clip_grad_norm\"",
",",
"1.0",
",",
"10.0",
",",
"scale",
"=",
"rhp",
".",
"LOG_SCALE",
")",
"rhp",
".",
"set_float",
"(",
"\"learning_r... | Small range of hyperparameters. | [
"Small",
"range",
"of",
"hyperparameters",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L365-L371 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/pointer_generator_word.py | TokenTextEncoderOov.encode | 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... | python | 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",
")",
":",
"sentence",
"=",
"s",
"tokens",
"=",
"sentence",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"ids",
"=",
"[",
"]",
"ids_extend",
"=",
"[",
"]",
"oovs",
"=",
"{",
"}",
"for",
"t",
"in",
"to... | 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... | [
"Converts",
"a",
"space",
"-",
"separated",
"string",
"of",
"tokens",
"to",
"lists",
"of",
"ids",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/pointer_generator_word.py#L93-L136 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/pointer_generator_word.py | TokenTextEncoderOov.encode_target | 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>
... | python | 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",
")",
":",
"tokens",
"=",
"target",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"ids",
"=",
"[",
"]",
"ids_extend",
"=",
"[",
"]",
"for",
"t",
"in",
"tokens",
":",
"if",
"... | 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... | [
"Converts",
"a",
"space",
"-",
"separated",
"string",
"of",
"tokens",
"to",
"lists",
"of",
"ids",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/pointer_generator_word.py#L138-L173 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/pointer_generator_word.py | TokenTextEncoderOov.decode_list_oov | 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... | python | 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",
")",
":",
"seq",
"=",
"reversed",
"(",
"ids",
")",
"if",
"self",
".",
"_reverse",
"else",
"ids",
"tokens",
"=",
"[",
"]",
"for",
"cur_id",
"in",
"seq",
":",
"if",
"cur_id... | 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... | [
"decode",
"ids",
"back",
"to",
"tokens",
"considering",
"OOVs",
"temporary",
"IDs",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/pointer_generator_word.py#L178-L198 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/vqa_utils.py | _smallest_size_at_least | 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... | python | 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",
")",
":",
"smallest_side",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"smallest_side",
",",
"dtype",
"=",
"tf",
".",
"int32",
")",
"height",
"=",
"tf",
".",
"to_float",
"(",
... | 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 ... | [
"Computes",
"new",
"shape",
"with",
"the",
"smallest",
"side",
"equal",
"to",
"smallest_side",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa_utils.py#L36-L63 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/vqa_utils.py | _aspect_preserving_resize | 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... | python | 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",
")",
":",
"smallest_side",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"smallest_side",
",",
"dtype",
"=",
"tf",
".",
"int32",
")",
"shape",
"=",
"tf",
".",
"shape",
"(",
"image",
")",
"... | 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. | [
"Resize",
"images",
"preserving",
"the",
"original",
"aspect",
"ratio",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa_utils.py#L66-L89 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/vqa_utils.py | _distort_color | 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... | python | 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",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"scope",
",",
"\"distort_color\"",
",",
"[",
"image",
"]",
")",
":",
"if",
"color_ordering",
"==",
"0",
"... | 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.
... | [
"Distort",
"the",
"color",
"of",
"a",
"Tensor",
"image",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa_utils.py#L98-L140 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/vqa_utils.py | _apply_with_random_selector | 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... | python | 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",
")",
":",
"sel",
"=",
"tf",
".",
"random_uniform",
"(",
"[",
"]",
",",
"maxval",
"=",
"num_cases",
",",
"dtype",
"=",
"tf",
".",
"int32",
")",
"# Pass the real x only to one of th... | 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... | [
"Computes",
"func",
"(",
"x",
"sel",
")",
"with",
"sel",
"sampled",
"from",
"[",
"0",
"...",
"num_cases",
"-",
"1",
"]",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa_utils.py#L143-L160 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/vqa_utils.py | _mean_image_subtraction | 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: ... | python | 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",
")",
":",
"if",
"image",
".",
"get_shape",
"(",
")",
".",
"ndims",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"\"Input must be of size [height, width, C>0]\"",
")",
"num_channels",
"=",
"image",
".",... | 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... | [
"Subtracts",
"the",
"given",
"means",
"from",
"each",
"image",
"channel",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa_utils.py#L163-L193 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/vqa_utils.py | vqa_v2_preprocess_image | 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... | python | 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\"",
",",
")",
":",
"image",
"=",
"tf",
".",
"image",
".",
... | vqa v2 preprocess image. | [
"vqa",
"v2",
"preprocess",
"image",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa_utils.py#L196-L236 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/transformer_layers.py | transformer_prepare_encoder | 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... | python | 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",
")",
":",
"ishape_static",
"=",
"inputs",
".",
"shape",
".",
"as_list",
"(",
")",
"encoder_input",
"=",
"inputs",
"if",
"features",
"and",
... | 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... | [
"Prepare",
"one",
"shard",
"of",
"the",
"model",
"for",
"the",
"encoder",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_layers.py#L35-L116 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/transformer_layers.py | transformer_encoder | def transformer_encoder(encoder_input,
encoder_self_attention_bias,
hparams,
name="encoder",
nonpadding=None,
save_weights_to=None,
make_image_summary=True,
... | python | 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",
",",
"losses",
"="... | 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... | [
"A",
"stack",
"of",
"transformer",
"layers",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_layers.py#L119-L239 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/transformer_layers.py | transformer_ffn_layer | def transformer_ffn_layer(x,
hparams,
pad_remover=None,
conv_padding="LEFT",
nonpadding_mask=None,
losses=None,
cache=None,
decode_loop_st... | python | 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_step",
"=",
"None",... | 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 ... | [
"Feed",
"-",
"forward",
"layer",
"in",
"the",
"transformer",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_layers.py#L242-L380 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/lm_experiments.py | lmx_base | 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
... | python | 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",
"(",
")",
":",
"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.",
... | Transformer on languagemodel_lm1b32k_packed. 50M Params. | [
"Transformer",
"on",
"languagemodel_lm1b32k_packed",
".",
"50M",
"Params",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/lm_experiments.py#L45-L60 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/lm_experiments.py | lmx_h3k_f12k | 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 | python | 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",
"=",
"lmx_base",
"(",
")",
"hparams",
".",
"hidden_size",
"=",
"3072",
"hparams",
".",
"filter_size",
"=",
"12288",
"hparams",
".",
"batch_size",
"=",
"2048",
"hparams",
".",
"weight_dtype",
"=",
"\"bfloat16\"... | HParams for training languagemodel_lm1b32k_packed. 880M Params. | [
"HParams",
"for",
"training",
"languagemodel_lm1b32k_packed",
".",
"880M",
"Params",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/lm_experiments.py#L82-L89 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/lm_experiments.py | lmx_h4k_f16k | 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 | python | 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",
"=",
"lmx_base",
"(",
")",
"hparams",
".",
"hidden_size",
"=",
"4096",
"hparams",
".",
"filter_size",
"=",
"16384",
"hparams",
".",
"batch_size",
"=",
"1024",
"hparams",
".",
"weight_dtype",
"=",
"\"bfloat16\"... | HParams for training languagemodel_lm1b32k_packed. 1470M Params. | [
"HParams",
"for",
"training",
"languagemodel_lm1b32k_packed",
".",
"1470M",
"Params",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/lm_experiments.py#L93-L100 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/lm_experiments.py | lmx_relative | 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 | python | 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",
"(",
")",
":",
"hparams",
"=",
"lmx_base",
"(",
")",
"hparams",
".",
"self_attention_type",
"=",
"\"dot_product_relative_v2\"",
"hparams",
".",
"activation_dtype",
"=",
"\"float32\"",
"hparams",
".",
"weight_dtype",
"=",
"\"float32\"",
"return... | Language model using relative attention. | [
"Language",
"model",
"using",
"relative",
"attention",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/lm_experiments.py#L104-L110 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/lm_experiments.py | lmx_moe_h1k_f4k_x32 | 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 | python | 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",
"(",
")",
":",
"hparams",
"=",
"lmx_h1k_f4k",
"(",
")",
"hparams",
".",
"ffn_layer",
"=",
"\"local_moe_tpu\"",
"hparams",
".",
"moe_num_experts",
"=",
"32",
"hparams",
".",
"weight_dtype",
"=",
"\"bfloat16\"",
"hparams",
".",
"batch... | Transformer with mixture of experts. 890M Params. | [
"Transformer",
"with",
"mixture",
"of",
"experts",
".",
"890M",
"Params",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/lm_experiments.py#L130-L137 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/lm_experiments.py | lmx_moe_h1k_f8k_x16 | 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 | python | 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",
"(",
")",
":",
"hparams",
"=",
"lmx_h1k_f4k",
"(",
")",
"hparams",
".",
"filter_size",
"=",
"8192",
"hparams",
".",
"ffn_layer",
"=",
"\"local_moe_tpu\"",
"hparams",
".",
"moe_num_experts",
"=",
"16",
"hparams",
".",
"weight_dtype",... | Transformer with mixture of experts. 890M Params. | [
"Transformer",
"with",
"mixture",
"of",
"experts",
".",
"890M",
"Params",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/lm_experiments.py#L141-L149 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/lm_experiments.py | lmx_h1k_f64k | 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 | python | 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",
"=",
"lmx_base",
"(",
")",
"hparams",
".",
"hidden_size",
"=",
"1024",
"hparams",
".",
"filter_size",
"=",
"65536",
"hparams",
".",
"batch_size",
"=",
"2048",
"return",
"hparams"
] | HParams for training languagemodel_lm1b32k_packed. 880M Params. | [
"HParams",
"for",
"training",
"languagemodel_lm1b32k_packed",
".",
"880M",
"Params",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/lm_experiments.py#L153-L159 | train |
tensorflow/tensor2tensor | tensor2tensor/rl/envs/simulated_batch_env.py | compute_uncertainty_reward | 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... | python | 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",
")",
":",
"# TODO(rsepassi): Add support for L1/L2 loss models. Current code only",
"# works for softmax models.",
"vocab_size",
"=",
"logits",
".",
"shape",
"[",
"-",
"1",
"]",
"assert",
"vocab_size",
... | Uncertainty reward based on logits. | [
"Uncertainty",
"reward",
"based",
"on",
"logits",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/envs/simulated_batch_env.py#L85-L99 | train |
tensorflow/tensor2tensor | tensor2tensor/rl/envs/simulated_batch_env.py | SimulatedBatchEnv._reset_non_empty | 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... | python | 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_video_op",
"=",
"tf",
".",
"cond",
"(",
"self",
".",
"_video_condition",
",",
"lambda",
":",
"tf",
".",
"py_func",
"(",
"self",
".",
"_video_reset_writer",
",",
"[",
"]",
",",
"[",
... | 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",
"the",
"batch",
"of",
"environments",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/envs/simulated_batch_env.py#L232-L259 | train |
tensorflow/tensor2tensor | tensor2tensor/bin/t2t_datagen.py | set_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) | python | 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",
"(",
")",
":",
"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. | [
"Set",
"the",
"random",
"seed",
"from",
"flag",
"everywhere",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_datagen.py#L154-L158 | train |
tensorflow/tensor2tensor | tensor2tensor/bin/t2t_datagen.py | generate_data_for_problem | 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... | python | 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",
")",
":",
"training_gen",
",",
"dev_gen",
",",
"test_gen",
"=",
"_SUPPORTED_PROBLEM_GENERATORS",
"[",
"problem",
"]",
"num_train_shards",
"=",
"FLAGS",
".",
"num_shards",
"or",
"10",
"tf",
".",
"logging",
".",
... | Generate data for a problem in _SUPPORTED_PROBLEM_GENERATORS. | [
"Generate",
"data",
"for",
"a",
"problem",
"in",
"_SUPPORTED_PROBLEM_GENERATORS",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_datagen.py#L224-L251 | train |
tensorflow/tensor2tensor | tensor2tensor/bin/t2t_datagen.py | generate_data_for_env_problem | 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... | python | 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",
")",
":",
"assert",
"FLAGS",
".",
"env_problem_max_env_steps",
">",
"0",
",",
"(",
"\"--env_problem_max_env_steps \"",
"\"should be greater than zero\"",
")",
"assert",
"FLAGS",
".",
"env_problem_batch_size",
">",... | Generate data for `EnvProblem`s. | [
"Generate",
"data",
"for",
"EnvProblem",
"s",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_datagen.py#L260-L275 | train |
tensorflow/tensor2tensor | tensor2tensor/bin/t2t_datagen.py | generate_data_for_registered_problem | 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 = ... | python | 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",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Generating data for %s.\"",
",",
"problem_name",
")",
"if",
"FLAGS",
".",
"num_shards",
":",
"raise",
"ValueError",
"(",
"\"--num_shards should not... | Generate data for a registered problem. | [
"Generate",
"data",
"for",
"a",
"registered",
"problem",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_datagen.py#L278-L301 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/common_voice.py | _collect_data | 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... | python | 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",
")",
":",
"# Returns:",
"data_files",
"=",
"[",
"]",
"transcripts",
"=",
"[",
"filename",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
"if",
"filename",
".",
"endswith",
"(",
"\".csv\"",
")... | 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 | [
"Traverses",
"directory",
"collecting",
"input",
"and",
"target",
"files",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/common_voice.py#L42-L66 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/common_voice.py | _file_exists | def _file_exists(path, filename):
"""Checks if the filename exists under the path."""
return os.path.isfile(os.path.join(path, filename)) | python | 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",
")",
":",
"return",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
")"
] | Checks if the filename exists under the path. | [
"Checks",
"if",
"the",
"filename",
"exists",
"under",
"the",
"path",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/common_voice.py#L69-L71 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/common_voice.py | _is_relative | def _is_relative(path, filename):
"""Checks if the filename is relative, not absolute."""
return os.path.abspath(os.path.join(path, filename)).startswith(path) | python | 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",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
")",
".",
"startswith",
"(",
"path",
")"
] | Checks if the filename is relative, not absolute. | [
"Checks",
"if",
"the",
"filename",
"is",
"relative",
"not",
"absolute",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/common_voice.py#L74-L76 | train |
tensorflow/tensor2tensor | tensor2tensor/rl/ppo.py | define_ppo_step | 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... | python | 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",
")",
":",
"observation",
",",
"action",
",",
"discounted_reward",
",",
"norm_advantage",
",",
"old_pdf",
"=",
"data_points",
"obs_shape",
"=",
"common_layers",
".",
"sh... | Define ppo step. | [
"Define",
"ppo",
"step",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/ppo.py#L33-L68 | train |
tensorflow/tensor2tensor | tensor2tensor/rl/ppo.py | define_ppo_epoch | 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... | python | 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",
")",
":",
"observation",
",",
"reward",
",",
"done",
",",
"action",
",",
"old_pdf",
",",
"value",
"=",
"memory",
"# This is to avoid propagating gradients through simul... | PPO epoch. | [
"PPO",
"epoch",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/ppo.py#L71-L142 | train |
tensorflow/tensor2tensor | tensor2tensor/rl/ppo.py | calculate_generalized_advantage_estimator | 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, ...,... | python | 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",
"# pylint: enable=g-doc-args",
"next_value",
"=",
"value",
"[",
"1",
":",
",",
":",
"]",
"nex... | 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]. | [
"Generalized",
"advantage",
"estimator",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/ppo.py#L145-L166 | train |
tensorflow/tensor2tensor | tensor2tensor/envs/gym_spaces_utils.py | gym_space_spec | 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'... | python | 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",
")",
":",
"# First try to determine the type.",
"try",
":",
"tf_dtype",
"=",
"tf",
".",
"as_dtype",
"(",
"gym_space",
".",
"dtype",
")",
"except",
"TypeError",
"as",
"e",
":",
"tf",
".",
"logging",
".",
"error",
"("... | 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. | [
"Returns",
"a",
"reading",
"spec",
"of",
"a",
"gym",
"space",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/gym_spaces_utils.py#L41-L69 | train |
tensorflow/tensor2tensor | tensor2tensor/envs/gym_spaces_utils.py | cardinality | 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... | python | 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",
")",
":",
"if",
"(",
"gym_space",
".",
"dtype",
"==",
"np",
".",
"float32",
")",
"or",
"(",
"gym_space",
".",
"dtype",
"==",
"np",
".",
"float64",
")",
":",
"tf",
".",
"logging",
".",
"error",
"(",
"\"Returning... | 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... | [
"Number",
"of",
"elements",
"that",
"can",
"be",
"represented",
"by",
"the",
"space",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/gym_spaces_utils.py#L83-L113 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | image_rmse | 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... | python | 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",
")",
":",
"if",
"common_layers",
".",
"shape_list",
"(",
"predictions",
")",
"[",
"-",
"1",
"]",
"==",
"1",
":",
"predictions",
"=",
"tf",
... | RMSE but will argmax if last dim is not 1. | [
"RMSE",
"but",
"will",
"argmax",
"if",
"last",
"dim",
"is",
"not",
"1",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L69-L75 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | abs_error | 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) | python | 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",
")",
":",
"del",
"weights_fn",
"# Unused",
"targets",
"=",
"tf",
".",
"squeeze",
"(",
"labels",
",",
"axis",
"=",
"[",
"2",
",",
"3",
"]",
")",
"batch_abs_error",
"=... | Computes mean(abs(preds-target)). | [
"Computes",
"mean",
"(",
"abs",
"(",
"preds",
"-",
"target",
"))",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L88-L94 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | padded_variance_explained | 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... | python | 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",
")",
":",
"predictions",
",",
"labels",
"=",
"common_layers",
".",
"pad_with_zeros",
"(",
"predictions",
",",
"labels",
")",
"target... | Explained variance, also known as R^2. | [
"Explained",
"variance",
"also",
"known",
"as",
"R^2",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L109-L121 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | padded_accuracy_topk | 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... | python | 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",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"padded_accuracy_topk\"",
",",
"values",
"=",
"[",
"predictions",
"... | Percentage of times that top-k predictions matches labels on non-0s. | [
"Percentage",
"of",
"times",
"that",
"top",
"-",
"k",
"predictions",
"matches",
"labels",
"on",
"non",
"-",
"0s",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L124-L142 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | rounding_sequence_accuracy | 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... | python | 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",
")",
":",
"outputs",
"=",
"tf",
".",
"squeeze",
"(",
"tf",
".",
"to_int32",
"(",
"predictions",
")",
",",
"axis",
"=",
"-... | Sequence accuracy for L1/L2 losses: round down the predictions to ints. | [
"Sequence",
"accuracy",
"for",
"L1",
"/",
"L2",
"losses",
":",
"round",
"down",
"the",
"predictions",
"to",
"ints",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L151-L161 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | padded_sequence_accuracy | 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... | python | 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",
")",
":",
"# If the last dimension is 1 then we're using L1/L2 loss.",
"if",
"common_layers",
".",
"shape_list",
"(",
"predictions",
")",
... | Percentage of times that predictions matches labels everywhere (non-0). | [
"Percentage",
"of",
"times",
"that",
"predictions",
"matches",
"labels",
"everywhere",
"(",
"non",
"-",
"0",
")",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L164-L197 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | sequence_edit_distance | 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... | python | 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",
")",
":",
"if",
"weights_fn",
"is",
"not",
"common_layers",
".",
"weights_nonzero",
":",
"raise",
"ValueError",
"(",
"\"Only weights_... | 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 ... | [
"Average",
"edit",
"distance",
"ignoring",
"padding",
"0s",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L200-L241 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | padded_neg_log_perplexity | 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_... | python | 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",
")",
":",
"num",
",",
"den",
"=",
"common_layers",
".",
"padded_cross_entropy",
"(",
"predictions",
",",
"labels",
",",
"0.0",
... | Average log-perplexity exluding padding 0s. No smoothing. | [
"Average",
"log",
"-",
"perplexity",
"exluding",
"padding",
"0s",
".",
"No",
"smoothing",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L244-L250 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | padded_neg_log_perplexity_with_masking | 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 ... | python | 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",
")",
":",
"del",
"weights_fn",
"if",
"\"targets_mask\"",
"not",
"in",
"features",
":",
"raise",
"ValueError",
"(",
"\"masked_neg_log_... | Average log-perplexity with custom targets_mask. | [
"Average",
"log",
"-",
"perplexity",
"with",
"custom",
"targets_mask",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L253-L273 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | dmol_neg_log_perplexity | 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) | python | 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",
")",
":",
"del",
"weights_fn",
"# Unused",
"num",
",",
"den",
"=",
"common_layers",
".",
"dml_loss",
"(",
"predictions",
",",
"labels",
",",
"reduce_sum",
"=",... | Average log-perplexity excluding padding 0s. No smoothing. | [
"Average",
"log",
"-",
"perplexity",
"excluding",
"padding",
"0s",
".",
"No",
"smoothing",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L276-L283 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | rounding_accuracy | 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)
... | python | 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",
")",
":",
"outputs",
"=",
"tf",
".",
"squeeze",
"(",
"tf",
".",
"to_int32",
"(",
"predictions",
")",
")",
"labels",
"=",
"tf",
"... | Rounding accuracy for L1/L2 losses: round down the predictions to ints. | [
"Rounding",
"accuracy",
"for",
"L1",
"/",
"L2",
"losses",
":",
"round",
"down",
"the",
"predictions",
"to",
"ints",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L286-L294 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | padded_accuracy | 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... | python | 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",
")",
":",
"# If the last dimension is 1 then we're using L1/L2 loss.",
"if",
"common_layers",
".",
"shape_list",
"(",
"predictions",
")",
"[",
"... | Percentage of times that predictions matches labels on non-0s. | [
"Percentage",
"of",
"times",
"that",
"predictions",
"matches",
"labels",
"on",
"non",
"-",
"0s",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L297-L310 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | multilabel_accuracy_matchk | 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... | python | 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",
")",
":",
"predictions",
"=",
"tf",
".",
"to_int32",
"(",
"tf",
".",
"argmax",
"(",
"predictions",
",",
"axis",
... | 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].
... | [
"Used",
"to",
"evaluate",
"the",
"VQA",
"accuracy",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L313-L343 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | set_precision | 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... | python | 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",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"set_precision\"",
",",
"values",
"=",
"[",
"predictions",
",",
"labels",
"]",
")"... | 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 ... | [
"Precision",
"of",
"set",
"predictions",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L351-L371 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | image_summary | 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... | python | 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",
")",
":",
"del",
"hparams",
"results",
"=",
"tf",
".",
"cast",
"(",
"tf",
".",
"argmax",
"(",
"predictions",
",",
"axis",
"=",
"-",
"1",
")",
",",
"tf",
".",
"uint8",
")",
... | 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. | [
"Reshapes",
"predictions",
"and",
"passes",
"it",
"to",
"tensorboard",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L396-L414 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | softmax_cross_entropy_one_hot | 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... | python | 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",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"softmax_cross_entropy_one_hot\"",
",",
"values",
"=",
"[",
"logits",
",",
"labels",
"]",
")",
":",
"del... | 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... | [
"Calculate",
"softmax",
"cross",
"entropy",
"given",
"one",
"-",
"hot",
"labels",
"and",
"logits",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L417-L432 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | sigmoid_accuracy_one_hot | 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... | python | 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",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"sigmoid_accuracy_one_hot\"",
",",
"values",
"=",
"[",
"logits",
",",
"labels",
"]",
")",
":",
"del",
"weig... | 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 | [
"Calculate",
"accuracy",
"for",
"a",
"set",
"given",
"one",
"-",
"hot",
"labels",
"and",
"logits",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L435-L451 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | sigmoid_recall_one_hot | 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... | python | 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",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"sigmoid_recall_one_hot\"",
",",
"values",
"=",
"[",
"logits",
",",
"labels",
"]",
")",
":",
"del",
"weights_... | 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... | [
"Calculate",
"recall",
"for",
"a",
"set",
"given",
"one",
"-",
"hot",
"labels",
"and",
"logits",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L477-L497 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | sigmoid_cross_entropy_one_hot | 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... | python | 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",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"sigmoid_cross_entropy_one_hot\"",
",",
"values",
"=",
"[",
"logits",
",",
"labels",
"]",
")",
":",
"del... | 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 | [
"Calculate",
"sigmoid",
"cross",
"entropy",
"for",
"one",
"-",
"hot",
"lanels",
"and",
"logits",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L500-L515 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | roc_auc | 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... | python | 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",
")",
":",
"del",
"weights_fn",
"with",
"tf",
".",
"variable_scope",
"(",
"\"roc_auc\"",
",",
"values",
"=",
"[",
"logits",
",",
"labels",
"]",
")",
":",
"predictions",
"=",
... | 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 | [
"Calculate",
"ROC",
"AUC",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L518-L534 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | create_evaluation_metrics | 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) -> ... | python | 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",
")",
":",
"def",
"reduce_dimensions",
"(",
"predictions",
",",
"labels",
")",
":",
"\"\"\"Reduce dimensions for high-dimensional predictions and labels.\"\"\"",
"# We will treat first dimensions as batch. On... | 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... | [
"Creates",
"the",
"evaluation",
"metrics",
"for",
"the",
"model",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L537-L638 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | create_eager_metrics_for_problem | 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... | python | 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",
")",
":",
"metric_fns",
"=",
"problem",
".",
"eval_metric_fns",
"(",
"model_hparams",
")",
"problem_hparams",
"=",
"problem",
".",
"get_hparams",
"(",
"model_hparams",
")",
"target_modali... | See create_eager_metrics. | [
"See",
"create_eager_metrics",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L641-L649 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | create_eager_metrics | 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... | python | 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",
")",
":",
"metric_fns",
"=",
"dict",
"(",
"[",
"(",
"name",
",",
"METRICS_FNS",
"[",
"name",
"]",
")",
"for",
"name",
"in",
"metric_names",
"]",
... | 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.
... | [
"Create",
"metrics",
"accumulators",
"and",
"averager",
"for",
"Eager",
"mode",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L652-L667 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.