partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | dense_message_pass | Computes a_t from h_{t-1}, see bottom of page 3 in the paper.
Args:
node_states: [B, L, D] tensor (h_{t-1})
edge_matrices (tf.float32): [B, L*D, L*D]
Returns:
messages (tf.float32): [B, L, D] For each pair
of nodes in the graph a message is sent along both the incoming and
outgoing edge. | tensor2tensor/layers/message_passing_attention.py | def dense_message_pass(node_states, edge_matrices):
"""Computes a_t from h_{t-1}, see bottom of page 3 in the paper.
Args:
node_states: [B, L, D] tensor (h_{t-1})
edge_matrices (tf.float32): [B, L*D, L*D]
Returns:
messages (tf.float32): [B, L, D] For each pair
of nodes in the graph a message i... | def dense_message_pass(node_states, edge_matrices):
"""Computes a_t from h_{t-1}, see bottom of page 3 in the paper.
Args:
node_states: [B, L, D] tensor (h_{t-1})
edge_matrices (tf.float32): [B, L*D, L*D]
Returns:
messages (tf.float32): [B, L, D] For each pair
of nodes in the graph a message i... | [
"Computes",
"a_t",
"from",
"h_",
"{",
"t",
"-",
"1",
"}",
"see",
"bottom",
"of",
"page",
"3",
"in",
"the",
"paper",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/message_passing_attention.py#L910-L935 | [
"def",
"dense_message_pass",
"(",
"node_states",
",",
"edge_matrices",
")",
":",
"batch_size",
",",
"num_nodes",
",",
"node_dim",
"=",
"common_layers",
".",
"shape_list",
"(",
"node_states",
")",
"# Stack the nodes as a big column vector.",
"h_flat",
"=",
"tf",
".",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | to_example | Helper: build tf.Example from (string -> int/float/str list) dictionary. | tensor2tensor/data_generators/generator_utils.py | def to_example(dictionary):
"""Helper: build tf.Example from (string -> int/float/str list) dictionary."""
features = {}
for (k, v) in six.iteritems(dictionary):
if not v:
raise ValueError("Empty generated field: %s" % str((k, v)))
if isinstance(v[0], six.integer_types):
features[k] = tf.train... | def to_example(dictionary):
"""Helper: build tf.Example from (string -> int/float/str list) dictionary."""
features = {}
for (k, v) in six.iteritems(dictionary):
if not v:
raise ValueError("Empty generated field: %s" % str((k, v)))
if isinstance(v[0], six.integer_types):
features[k] = tf.train... | [
"Helper",
":",
"build",
"tf",
".",
"Example",
"from",
"(",
"string",
"-",
">",
"int",
"/",
"float",
"/",
"str",
"list",
")",
"dictionary",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L43-L62 | [
"def",
"to_example",
"(",
"dictionary",
")",
":",
"features",
"=",
"{",
"}",
"for",
"(",
"k",
",",
"v",
")",
"in",
"six",
".",
"iteritems",
"(",
"dictionary",
")",
":",
"if",
"not",
"v",
":",
"raise",
"ValueError",
"(",
"\"Empty generated field: %s\"",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | generate_files_distributed | generate_files but with a single writer writing to shard task_id. | tensor2tensor/data_generators/generator_utils.py | def generate_files_distributed(generator,
output_name,
output_dir,
num_shards=1,
max_cases=None,
task_id=0):
"""generate_files but with a single writer writing to ... | def generate_files_distributed(generator,
output_name,
output_dir,
num_shards=1,
max_cases=None,
task_id=0):
"""generate_files but with a single writer writing to ... | [
"generate_files",
"but",
"with",
"a",
"single",
"writer",
"writing",
"to",
"shard",
"task_id",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L65-L89 | [
"def",
"generate_files_distributed",
"(",
"generator",
",",
"output_name",
",",
"output_dir",
",",
"num_shards",
"=",
"1",
",",
"max_cases",
"=",
"None",
",",
"task_id",
"=",
"0",
")",
":",
"assert",
"task_id",
"<",
"num_shards",
"output_filename",
"=",
"shard... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | generate_files | Generate cases from a generator and save as TFRecord files.
Generated cases are transformed to tf.Example protos and saved as TFRecords
in sharded files named output_dir/output_name-00..N-of-00..M=num_shards.
Args:
generator: a generator yielding (string -> int/float/str list) dictionaries.
output_filen... | tensor2tensor/data_generators/generator_utils.py | def generate_files(generator, output_filenames,
max_cases=None, cycle_every_n=1):
"""Generate cases from a generator and save as TFRecord files.
Generated cases are transformed to tf.Example protos and saved as TFRecords
in sharded files named output_dir/output_name-00..N-of-00..M=num_shards.
... | def generate_files(generator, output_filenames,
max_cases=None, cycle_every_n=1):
"""Generate cases from a generator and save as TFRecord files.
Generated cases are transformed to tf.Example protos and saved as TFRecords
in sharded files named output_dir/output_name-00..N-of-00..M=num_shards.
... | [
"Generate",
"cases",
"from",
"a",
"generator",
"and",
"save",
"as",
"TFRecord",
"files",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L134-L193 | [
"def",
"generate_files",
"(",
"generator",
",",
"output_filenames",
",",
"max_cases",
"=",
"None",
",",
"cycle_every_n",
"=",
"1",
")",
":",
"if",
"outputs_exist",
"(",
"output_filenames",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Skipping generator... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | download_report_hook | Report hook for download progress.
Args:
count: current block number
block_size: block size
total_size: total size | tensor2tensor/data_generators/generator_utils.py | def download_report_hook(count, block_size, total_size):
"""Report hook for download progress.
Args:
count: current block number
block_size: block size
total_size: total size
"""
percent = int(count * block_size * 100 / total_size)
print("\r%d%%" % percent + " completed", end="\r") | def download_report_hook(count, block_size, total_size):
"""Report hook for download progress.
Args:
count: current block number
block_size: block size
total_size: total size
"""
percent = int(count * block_size * 100 / total_size)
print("\r%d%%" % percent + " completed", end="\r") | [
"Report",
"hook",
"for",
"download",
"progress",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L196-L205 | [
"def",
"download_report_hook",
"(",
"count",
",",
"block_size",
",",
"total_size",
")",
":",
"percent",
"=",
"int",
"(",
"count",
"*",
"block_size",
"*",
"100",
"/",
"total_size",
")",
"print",
"(",
"\"\\r%d%%\"",
"%",
"percent",
"+",
"\" completed\"",
",",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | maybe_download | Download filename from uri unless it's already in directory.
Copies a remote file to local if that local file does not already exist. If
the local file pre-exists this function call, it does not check that the local
file is a copy of the remote.
Remote filenames can be filepaths, any URI readable by tensorfl... | tensor2tensor/data_generators/generator_utils.py | def maybe_download(directory, filename, uri):
"""Download filename from uri unless it's already in directory.
Copies a remote file to local if that local file does not already exist. If
the local file pre-exists this function call, it does not check that the local
file is a copy of the remote.
Remote filen... | def maybe_download(directory, filename, uri):
"""Download filename from uri unless it's already in directory.
Copies a remote file to local if that local file does not already exist. If
the local file pre-exists this function call, it does not check that the local
file is a copy of the remote.
Remote filen... | [
"Download",
"filename",
"from",
"uri",
"unless",
"it",
"s",
"already",
"in",
"directory",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L208-L248 | [
"def",
"maybe_download",
"(",
"directory",
",",
"filename",
",",
"uri",
")",
":",
"tf",
".",
"gfile",
".",
"MakeDirs",
"(",
"directory",
")",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"filename",
")",
"if",
"tf",
".",
"g... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | maybe_download_from_drive | Download filename from Google drive unless it's already in directory.
Args:
directory: path to the directory that will be used.
filename: name of the file to download to (do nothing if it already exists).
url: URL to download from.
Returns:
The path to the downloaded file. | tensor2tensor/data_generators/generator_utils.py | def maybe_download_from_drive(directory, filename, url):
"""Download filename from Google drive unless it's already in directory.
Args:
directory: path to the directory that will be used.
filename: name of the file to download to (do nothing if it already exists).
url: URL to download from.
Returns:... | def maybe_download_from_drive(directory, filename, url):
"""Download filename from Google drive unless it's already in directory.
Args:
directory: path to the directory that will be used.
filename: name of the file to download to (do nothing if it already exists).
url: URL to download from.
Returns:... | [
"Download",
"filename",
"from",
"Google",
"drive",
"unless",
"it",
"s",
"already",
"in",
"directory",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L251-L298 | [
"def",
"maybe_download_from_drive",
"(",
"directory",
",",
"filename",
",",
"url",
")",
":",
"if",
"not",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"directory",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Creating directory %s\"",
"%",
"directory",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | gunzip_file | Unzips from gz_path into new_path.
Args:
gz_path: path to the zipped file.
new_path: path to where the file will be unzipped. | tensor2tensor/data_generators/generator_utils.py | def gunzip_file(gz_path, new_path):
"""Unzips from gz_path into new_path.
Args:
gz_path: path to the zipped file.
new_path: path to where the file will be unzipped.
"""
if tf.gfile.Exists(new_path):
tf.logging.info("File %s already exists, skipping unpacking" % new_path)
return
tf.logging.inf... | def gunzip_file(gz_path, new_path):
"""Unzips from gz_path into new_path.
Args:
gz_path: path to the zipped file.
new_path: path to where the file will be unzipped.
"""
if tf.gfile.Exists(new_path):
tf.logging.info("File %s already exists, skipping unpacking" % new_path)
return
tf.logging.inf... | [
"Unzips",
"from",
"gz_path",
"into",
"new_path",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L301-L318 | [
"def",
"gunzip_file",
"(",
"gz_path",
",",
"new_path",
")",
":",
"if",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"new_path",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"File %s already exists, skipping unpacking\"",
"%",
"new_path",
")",
"return",
"tf... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | get_or_generate_vocab_inner | Inner implementation for vocab generators.
Args:
data_dir: The base directory where data and vocab files are stored. If None,
then do not save the vocab even if it doesn't exist.
vocab_filename: relative filename where vocab file is stored
vocab_size: target size of the vocabulary constructed by Su... | tensor2tensor/data_generators/generator_utils.py | def get_or_generate_vocab_inner(data_dir, vocab_filename, vocab_size,
generator, max_subtoken_length=None,
reserved_tokens=None):
"""Inner implementation for vocab generators.
Args:
data_dir: The base directory where data and vocab files are store... | def get_or_generate_vocab_inner(data_dir, vocab_filename, vocab_size,
generator, max_subtoken_length=None,
reserved_tokens=None):
"""Inner implementation for vocab generators.
Args:
data_dir: The base directory where data and vocab files are store... | [
"Inner",
"implementation",
"for",
"vocab",
"generators",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L321-L358 | [
"def",
"get_or_generate_vocab_inner",
"(",
"data_dir",
",",
"vocab_filename",
",",
"vocab_size",
",",
"generator",
",",
"max_subtoken_length",
"=",
"None",
",",
"reserved_tokens",
"=",
"None",
")",
":",
"if",
"data_dir",
"and",
"vocab_filename",
":",
"vocab_filepath... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | get_or_generate_vocab | Generate a vocabulary from the datasets in sources. | tensor2tensor/data_generators/generator_utils.py | def get_or_generate_vocab(data_dir, tmp_dir, vocab_filename, vocab_size,
sources, file_byte_budget=1e6,
max_subtoken_length=None):
"""Generate a vocabulary from the datasets in sources."""
vocab_generator = generate_lines_for_vocab(tmp_dir, sources, file_byte_bud... | def get_or_generate_vocab(data_dir, tmp_dir, vocab_filename, vocab_size,
sources, file_byte_budget=1e6,
max_subtoken_length=None):
"""Generate a vocabulary from the datasets in sources."""
vocab_generator = generate_lines_for_vocab(tmp_dir, sources, file_byte_bud... | [
"Generate",
"a",
"vocabulary",
"from",
"the",
"datasets",
"in",
"sources",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L361-L368 | [
"def",
"get_or_generate_vocab",
"(",
"data_dir",
",",
"tmp_dir",
",",
"vocab_filename",
",",
"vocab_size",
",",
"sources",
",",
"file_byte_budget",
"=",
"1e6",
",",
"max_subtoken_length",
"=",
"None",
")",
":",
"vocab_generator",
"=",
"generate_lines_for_vocab",
"("... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | generate_lines_for_vocab | Generate lines for vocabulary generation. | tensor2tensor/data_generators/generator_utils.py | def generate_lines_for_vocab(tmp_dir, sources, file_byte_budget=1e6):
"""Generate lines for vocabulary generation."""
tf.logging.info("Generating vocab from: %s", str(sources))
for source in sources:
url = source[0]
filename = os.path.basename(url)
compressed_file = maybe_download(tmp_dir, filename, u... | def generate_lines_for_vocab(tmp_dir, sources, file_byte_budget=1e6):
"""Generate lines for vocabulary generation."""
tf.logging.info("Generating vocab from: %s", str(sources))
for source in sources:
url = source[0]
filename = os.path.basename(url)
compressed_file = maybe_download(tmp_dir, filename, u... | [
"Generate",
"lines",
"for",
"vocabulary",
"generation",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L371-L413 | [
"def",
"generate_lines_for_vocab",
"(",
"tmp_dir",
",",
"sources",
",",
"file_byte_budget",
"=",
"1e6",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Generating vocab from: %s\"",
",",
"str",
"(",
"sources",
")",
")",
"for",
"source",
"in",
"sources",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | get_or_generate_tabbed_vocab | r"""Generate a vocabulary from a tabbed source file.
The source is a file of source, target pairs, where each line contains
a source string and a target string, separated by a tab ('\t') character.
The index parameter specifies 0 for the source or 1 for the target.
Args:
data_dir: path to the data directo... | tensor2tensor/data_generators/generator_utils.py | def get_or_generate_tabbed_vocab(data_dir, tmp_dir, source_filename,
index, vocab_filename, vocab_size):
r"""Generate a vocabulary from a tabbed source file.
The source is a file of source, target pairs, where each line contains
a source string and a target string, separated by a... | def get_or_generate_tabbed_vocab(data_dir, tmp_dir, source_filename,
index, vocab_filename, vocab_size):
r"""Generate a vocabulary from a tabbed source file.
The source is a file of source, target pairs, where each line contains
a source string and a target string, separated by a... | [
"r",
"Generate",
"a",
"vocabulary",
"from",
"a",
"tabbed",
"source",
"file",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L416-L447 | [
"def",
"get_or_generate_tabbed_vocab",
"(",
"data_dir",
",",
"tmp_dir",
",",
"source_filename",
",",
"index",
",",
"vocab_filename",
",",
"vocab_size",
")",
":",
"def",
"generate",
"(",
")",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmp_dir... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | get_or_generate_txt_vocab | Generate a vocabulary from txt files with example-per-line. | tensor2tensor/data_generators/generator_utils.py | def get_or_generate_txt_vocab(data_dir, vocab_filename, vocab_size,
filepatterns):
"""Generate a vocabulary from txt files with example-per-line."""
if isinstance(filepatterns, str):
filepatterns = [filepatterns]
def generate():
tf.logging.info("Generating vocab from %s", fi... | def get_or_generate_txt_vocab(data_dir, vocab_filename, vocab_size,
filepatterns):
"""Generate a vocabulary from txt files with example-per-line."""
if isinstance(filepatterns, str):
filepatterns = [filepatterns]
def generate():
tf.logging.info("Generating vocab from %s", fi... | [
"Generate",
"a",
"vocabulary",
"from",
"txt",
"files",
"with",
"example",
"-",
"per",
"-",
"line",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L450-L465 | [
"def",
"get_or_generate_txt_vocab",
"(",
"data_dir",
",",
"vocab_filename",
",",
"vocab_size",
",",
"filepatterns",
")",
":",
"if",
"isinstance",
"(",
"filepatterns",
",",
"str",
")",
":",
"filepatterns",
"=",
"[",
"filepatterns",
"]",
"def",
"generate",
"(",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | _shuffle_single | Shuffle a single file of records.
Args:
fname: a string
extra_fn: an optional function from list of TFRecords to list of TFRecords
to be called after shuffling. | tensor2tensor/data_generators/generator_utils.py | def _shuffle_single(fname, extra_fn=None):
"""Shuffle a single file of records.
Args:
fname: a string
extra_fn: an optional function from list of TFRecords to list of TFRecords
to be called after shuffling.
"""
records = read_records(fname)
random.shuffle(records)
if extra_fn is not None:
... | def _shuffle_single(fname, extra_fn=None):
"""Shuffle a single file of records.
Args:
fname: a string
extra_fn: an optional function from list of TFRecords to list of TFRecords
to be called after shuffling.
"""
records = read_records(fname)
random.shuffle(records)
if extra_fn is not None:
... | [
"Shuffle",
"a",
"single",
"file",
"of",
"records",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L499-L513 | [
"def",
"_shuffle_single",
"(",
"fname",
",",
"extra_fn",
"=",
"None",
")",
":",
"records",
"=",
"read_records",
"(",
"fname",
")",
"random",
".",
"shuffle",
"(",
"records",
")",
"if",
"extra_fn",
"is",
"not",
"None",
":",
"records",
"=",
"extra_fn",
"(",... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | shuffle_dataset | Shuffles the dataset.
Args:
filenames: a list of strings
extra_fn: an optional function from list of records to list of records
to be called after shuffling a file. | tensor2tensor/data_generators/generator_utils.py | def shuffle_dataset(filenames, extra_fn=None):
"""Shuffles the dataset.
Args:
filenames: a list of strings
extra_fn: an optional function from list of records to list of records
to be called after shuffling a file.
"""
if outputs_exist(filenames):
tf.logging.info("Skipping shuffle because out... | def shuffle_dataset(filenames, extra_fn=None):
"""Shuffles the dataset.
Args:
filenames: a list of strings
extra_fn: an optional function from list of records to list of records
to be called after shuffling a file.
"""
if outputs_exist(filenames):
tf.logging.info("Skipping shuffle because out... | [
"Shuffles",
"the",
"dataset",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L516-L530 | [
"def",
"shuffle_dataset",
"(",
"filenames",
",",
"extra_fn",
"=",
"None",
")",
":",
"if",
"outputs_exist",
"(",
"filenames",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Skipping shuffle because output files exist\"",
")",
"return",
"tf",
".",
"logging",... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | pack_examples | Pack examples into longer examples.
If has_inputs=False, we are packing single-sequence examples with
targets only and no inputs.
In this case, we concatenate the targets from several examples to form
each new example. We insert a number of zeros for spacing between the
original sequences. This is to help... | tensor2tensor/data_generators/generator_utils.py | def pack_examples(examples,
has_inputs,
packed_length=256,
spacing=2,
queue_size=10,
chop_long_sequences=False):
"""Pack examples into longer examples.
If has_inputs=False, we are packing single-sequence examples with
targe... | def pack_examples(examples,
has_inputs,
packed_length=256,
spacing=2,
queue_size=10,
chop_long_sequences=False):
"""Pack examples into longer examples.
If has_inputs=False, we are packing single-sequence examples with
targe... | [
"Pack",
"examples",
"into",
"longer",
"examples",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L589-L660 | [
"def",
"pack_examples",
"(",
"examples",
",",
"has_inputs",
",",
"packed_length",
"=",
"256",
",",
"spacing",
"=",
"2",
",",
"queue_size",
"=",
"10",
",",
"chop_long_sequences",
"=",
"False",
")",
":",
"packer",
"=",
"SequencePairPacker",
"if",
"has_inputs",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | _pack_with_custom_ops | Helper-function for packing a dataset which has already been batched.
See pack_dataset()
Relies on custom ops which require a custom compiled binary.
Faster than _pack_with_tf_ops(), and denser packing.
Args:
dataset: a dataset containing padded batches of examples.
keys: a list of strings (must have... | tensor2tensor/data_generators/generator_utils.py | def _pack_with_custom_ops(dataset, keys, length):
"""Helper-function for packing a dataset which has already been batched.
See pack_dataset()
Relies on custom ops which require a custom compiled binary.
Faster than _pack_with_tf_ops(), and denser packing.
Args:
dataset: a dataset containing padded batc... | def _pack_with_custom_ops(dataset, keys, length):
"""Helper-function for packing a dataset which has already been batched.
See pack_dataset()
Relies on custom ops which require a custom compiled binary.
Faster than _pack_with_tf_ops(), and denser packing.
Args:
dataset: a dataset containing padded batc... | [
"Helper",
"-",
"function",
"for",
"packing",
"a",
"dataset",
"which",
"has",
"already",
"been",
"batched",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L736-L770 | [
"def",
"_pack_with_custom_ops",
"(",
"dataset",
",",
"keys",
",",
"length",
")",
":",
"from",
"tensor2tensor",
".",
"data_generators",
".",
"ops",
"import",
"pack_sequences_ops",
"# pylint: disable=g-import-not-at-top",
"# faster and better packing but requires custom-built bin... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | make_tmp_dir | Make a temporary directory. | tensor2tensor/data_generators/generator_utils.py | def make_tmp_dir(suffix="", prefix="tmp", dir=None): # pylint: disable=redefined-builtin
"""Make a temporary directory."""
if dir is None:
return tempfile.mkdtemp(suffix, prefix, dir)
else:
while True:
rand_term = random.randint(1, 9999)
tmp_dir = os.path.join(dir, "%s%d%s" % (prefix, rand_te... | def make_tmp_dir(suffix="", prefix="tmp", dir=None): # pylint: disable=redefined-builtin
"""Make a temporary directory."""
if dir is None:
return tempfile.mkdtemp(suffix, prefix, dir)
else:
while True:
rand_term = random.randint(1, 9999)
tmp_dir = os.path.join(dir, "%s%d%s" % (prefix, rand_te... | [
"Make",
"a",
"temporary",
"directory",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L883-L895 | [
"def",
"make_tmp_dir",
"(",
"suffix",
"=",
"\"\"",
",",
"prefix",
"=",
"\"tmp\"",
",",
"dir",
"=",
"None",
")",
":",
"# pylint: disable=redefined-builtin",
"if",
"dir",
"is",
"None",
":",
"return",
"tempfile",
".",
"mkdtemp",
"(",
"suffix",
",",
"prefix",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | tfrecord_iterator_for_problem | Iterate over the records on disk for the Problem. | tensor2tensor/data_generators/generator_utils.py | def tfrecord_iterator_for_problem(problem, data_dir,
dataset_split=tf.estimator.ModeKeys.TRAIN):
"""Iterate over the records on disk for the Problem."""
filenames = tf.gfile.Glob(problem.filepattern(data_dir, mode=dataset_split))
example_spec = problem.example_reading_spec()[0]
... | def tfrecord_iterator_for_problem(problem, data_dir,
dataset_split=tf.estimator.ModeKeys.TRAIN):
"""Iterate over the records on disk for the Problem."""
filenames = tf.gfile.Glob(problem.filepattern(data_dir, mode=dataset_split))
example_spec = problem.example_reading_spec()[0]
... | [
"Iterate",
"over",
"the",
"records",
"on",
"disk",
"for",
"the",
"Problem",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L898-L903 | [
"def",
"tfrecord_iterator_for_problem",
"(",
"problem",
",",
"data_dir",
",",
"dataset_split",
"=",
"tf",
".",
"estimator",
".",
"ModeKeys",
".",
"TRAIN",
")",
":",
"filenames",
"=",
"tf",
".",
"gfile",
".",
"Glob",
"(",
"problem",
".",
"filepattern",
"(",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | tfrecord_iterator | Yields records from TFRecord files.
Args:
filenames: list<str>, list of TFRecord filenames to read from.
gzipped: bool, whether the TFRecord files are gzip-encoded.
example_spec: dict<str feature name, tf.VarLenFeature/tf.FixedLenFeature>,
if provided, will parse each record as a tensorflow.Example... | tensor2tensor/data_generators/generator_utils.py | def tfrecord_iterator(filenames, gzipped=False, example_spec=None):
"""Yields records from TFRecord files.
Args:
filenames: list<str>, list of TFRecord filenames to read from.
gzipped: bool, whether the TFRecord files are gzip-encoded.
example_spec: dict<str feature name, tf.VarLenFeature/tf.FixedLenFe... | def tfrecord_iterator(filenames, gzipped=False, example_spec=None):
"""Yields records from TFRecord files.
Args:
filenames: list<str>, list of TFRecord filenames to read from.
gzipped: bool, whether the TFRecord files are gzip-encoded.
example_spec: dict<str feature name, tf.VarLenFeature/tf.FixedLenFe... | [
"Yields",
"records",
"from",
"TFRecord",
"files",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L906-L943 | [
"def",
"tfrecord_iterator",
"(",
"filenames",
",",
"gzipped",
"=",
"False",
",",
"example_spec",
"=",
"None",
")",
":",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
":",
"dataset",
"=",
"tf",
".",
"data",
".",
"Dataset",
".",
"f... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | random_deinterleave | Create a fill-in-the-blanks training example from text.
Split on spaces, then cut into segments at random points. Alternate segments
are assigned to the two output strings. separator_symbol separates segments
within each of the outputs.
example:
text="The quick brown fox jumps over the lazy dog."
ret... | tensor2tensor/data_generators/generator_utils.py | def random_deinterleave(text, separator_symbol="X"):
"""Create a fill-in-the-blanks training example from text.
Split on spaces, then cut into segments at random points. Alternate segments
are assigned to the two output strings. separator_symbol separates segments
within each of the outputs.
example:
t... | def random_deinterleave(text, separator_symbol="X"):
"""Create a fill-in-the-blanks training example from text.
Split on spaces, then cut into segments at random points. Alternate segments
are assigned to the two output strings. separator_symbol separates segments
within each of the outputs.
example:
t... | [
"Create",
"a",
"fill",
"-",
"in",
"-",
"the",
"-",
"blanks",
"training",
"example",
"from",
"text",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L946-L981 | [
"def",
"random_deinterleave",
"(",
"text",
",",
"separator_symbol",
"=",
"\"X\"",
")",
":",
"words",
"=",
"text",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\" \"",
")",
"n",
"=",
"len",
"(",
"words",
")",
"if",
"n",
"<=",
"1",
":",
"return",
"tex... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | neural_gpu_body | The core Neural GPU. | tensor2tensor/models/neural_gpu.py | def neural_gpu_body(inputs, hparams, name=None):
"""The core Neural GPU."""
with tf.variable_scope(name, "neural_gpu"):
def step(state, inp): # pylint: disable=missing-docstring
x = tf.nn.dropout(state, 1.0 - hparams.dropout)
for layer in range(hparams.num_hidden_layers):
x = common_layers... | def neural_gpu_body(inputs, hparams, name=None):
"""The core Neural GPU."""
with tf.variable_scope(name, "neural_gpu"):
def step(state, inp): # pylint: disable=missing-docstring
x = tf.nn.dropout(state, 1.0 - hparams.dropout)
for layer in range(hparams.num_hidden_layers):
x = common_layers... | [
"The",
"core",
"Neural",
"GPU",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/neural_gpu.py#L31-L52 | [
"def",
"neural_gpu_body",
"(",
"inputs",
",",
"hparams",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"\"neural_gpu\"",
")",
":",
"def",
"step",
"(",
"state",
",",
"inp",
")",
":",
"# pylint: disable=missing-do... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | diagonal_neural_gpu | Improved Neural GPU as in https://arxiv.org/abs/1702.08727. | tensor2tensor/models/neural_gpu.py | def diagonal_neural_gpu(inputs, hparams, name=None):
"""Improved Neural GPU as in https://arxiv.org/abs/1702.08727."""
with tf.variable_scope(name, "diagonal_neural_gpu"):
def step(state_tup, inp):
"""Single step of the improved Neural GPU."""
state, _ = state_tup
x = state
for layer in... | def diagonal_neural_gpu(inputs, hparams, name=None):
"""Improved Neural GPU as in https://arxiv.org/abs/1702.08727."""
with tf.variable_scope(name, "diagonal_neural_gpu"):
def step(state_tup, inp):
"""Single step of the improved Neural GPU."""
state, _ = state_tup
x = state
for layer in... | [
"Improved",
"Neural",
"GPU",
"as",
"in",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1702",
".",
"08727",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/neural_gpu.py#L62-L87 | [
"def",
"diagonal_neural_gpu",
"(",
"inputs",
",",
"hparams",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"\"diagonal_neural_gpu\"",
")",
":",
"def",
"step",
"(",
"state_tup",
",",
"inp",
")",
":",
"\"\"\"Singl... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | _reorder_shape | Helper to determine the shape of reorder output. | tensor2tensor/trax/layers/combinators.py | def _reorder_shape(input_shape, output=None): # pylint: disable=invalid-name
"""Helper to determine the shape of reorder output."""
if output is None:
return input_shape
return base.nested_map(output, lambda i: input_shape[i]) | def _reorder_shape(input_shape, output=None): # pylint: disable=invalid-name
"""Helper to determine the shape of reorder output."""
if output is None:
return input_shape
return base.nested_map(output, lambda i: input_shape[i]) | [
"Helper",
"to",
"determine",
"the",
"shape",
"of",
"reorder",
"output",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/combinators.py#L77-L81 | [
"def",
"_reorder_shape",
"(",
"input_shape",
",",
"output",
"=",
"None",
")",
":",
"# pylint: disable=invalid-name",
"if",
"output",
"is",
"None",
":",
"return",
"input_shape",
"return",
"base",
".",
"nested_map",
"(",
"output",
",",
"lambda",
"i",
":",
"input... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | Reorder | Reorder a tuple into another tuple.
For example, we can re-order (x, y) into (y, x) or even (y, (x, y), y).
The output argument specifies how to re-order, using integers that refer
to indices in the input tuple. For example, if
input = (x, y, z)
then
Reorder(input, output=(1, 0, 2)) = (y, x, z)
... | tensor2tensor/trax/layers/combinators.py | def Reorder(x, params, output=None, **kwargs):
"""Reorder a tuple into another tuple.
For example, we can re-order (x, y) into (y, x) or even (y, (x, y), y).
The output argument specifies how to re-order, using integers that refer
to indices in the input tuple. For example, if
input = (x, y, z)
then
... | def Reorder(x, params, output=None, **kwargs):
"""Reorder a tuple into another tuple.
For example, we can re-order (x, y) into (y, x) or even (y, (x, y), y).
The output argument specifies how to re-order, using integers that refer
to indices in the input tuple. For example, if
input = (x, y, z)
then
... | [
"Reorder",
"a",
"tuple",
"into",
"another",
"tuple",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/combinators.py#L85-L115 | [
"def",
"Reorder",
"(",
"x",
",",
"params",
",",
"output",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"del",
"params",
",",
"kwargs",
"if",
"output",
"is",
"None",
":",
"return",
"x",
"return",
"base",
".",
"nested_map",
"(",
"output",
",",
"la... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | _nested_op | Helper: sum a list of arrays or nested arrays. | tensor2tensor/trax/layers/combinators.py | def _nested_op(inputs, op): # pylint: disable=invalid-name
"""Helper: sum a list of arrays or nested arrays."""
# First the simple non-nested case.
if not isinstance(inputs[0], (list, tuple)):
return op(inputs)
# In the nested case, sum on each axis separately.
result_list = []
for i in range(len(input... | def _nested_op(inputs, op): # pylint: disable=invalid-name
"""Helper: sum a list of arrays or nested arrays."""
# First the simple non-nested case.
if not isinstance(inputs[0], (list, tuple)):
return op(inputs)
# In the nested case, sum on each axis separately.
result_list = []
for i in range(len(input... | [
"Helper",
":",
"sum",
"a",
"list",
"of",
"arrays",
"or",
"nested",
"arrays",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/combinators.py#L134-L145 | [
"def",
"_nested_op",
"(",
"inputs",
",",
"op",
")",
":",
"# pylint: disable=invalid-name",
"# First the simple non-nested case.",
"if",
"not",
"isinstance",
"(",
"inputs",
"[",
"0",
"]",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"op",
"(",
"in... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | GateBranches | Implements a gating function on a (memory, gate, candidate) tuple.
Final update is memory * gate + (1-gate) * candidate
This gating equation may also be referred to as Highway Network.
Highway Networks: https://arxiv.org/abs/1505.00387
Args:
x: A tuple of (memory, gate, candidate)
Returns:
The res... | tensor2tensor/trax/layers/combinators.py | def GateBranches(x, **unused_kwargs):
"""Implements a gating function on a (memory, gate, candidate) tuple.
Final update is memory * gate + (1-gate) * candidate
This gating equation may also be referred to as Highway Network.
Highway Networks: https://arxiv.org/abs/1505.00387
Args:
x: A tuple of (memor... | def GateBranches(x, **unused_kwargs):
"""Implements a gating function on a (memory, gate, candidate) tuple.
Final update is memory * gate + (1-gate) * candidate
This gating equation may also be referred to as Highway Network.
Highway Networks: https://arxiv.org/abs/1505.00387
Args:
x: A tuple of (memor... | [
"Implements",
"a",
"gating",
"function",
"on",
"a",
"(",
"memory",
"gate",
"candidate",
")",
"tuple",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/combinators.py#L170-L186 | [
"def",
"GateBranches",
"(",
"x",
",",
"*",
"*",
"unused_kwargs",
")",
":",
"assert",
"len",
"(",
"x",
")",
"==",
"3",
",",
"x",
"state",
",",
"gate",
",",
"candidate",
"=",
"x",
"return",
"gate",
"*",
"state",
"+",
"(",
"1.0",
"-",
"gate",
")",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | _concatenate_shape | Helper to determine the shape of Concatenate output. | tensor2tensor/trax/layers/combinators.py | def _concatenate_shape(input_shape, axis=-1): # pylint: disable=invalid-name
"""Helper to determine the shape of Concatenate output."""
ax = axis % len(input_shape[0])
concat_size = sum(shape[ax] for shape in input_shape)
out_shape = input_shape[0][:ax] + (concat_size,) + input_shape[0][ax+1:]
return out_sha... | def _concatenate_shape(input_shape, axis=-1): # pylint: disable=invalid-name
"""Helper to determine the shape of Concatenate output."""
ax = axis % len(input_shape[0])
concat_size = sum(shape[ax] for shape in input_shape)
out_shape = input_shape[0][:ax] + (concat_size,) + input_shape[0][ax+1:]
return out_sha... | [
"Helper",
"to",
"determine",
"the",
"shape",
"of",
"Concatenate",
"output",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/combinators.py#L189-L194 | [
"def",
"_concatenate_shape",
"(",
"input_shape",
",",
"axis",
"=",
"-",
"1",
")",
":",
"# pylint: disable=invalid-name",
"ax",
"=",
"axis",
"%",
"len",
"(",
"input_shape",
"[",
"0",
"]",
")",
"concat_size",
"=",
"sum",
"(",
"shape",
"[",
"ax",
"]",
"for"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | Residual | Constructs a residual version of layers, summing input to layers output. | tensor2tensor/trax/layers/combinators.py | def Residual(*layers, **kwargs):
"""Constructs a residual version of layers, summing input to layers output."""
shortcut = kwargs.get('shortcut', Identity()) # pylint: disable=no-value-for-parameter
if len(layers) > 1:
return Serial(
Branch(), # pylint: disable=no-value-for-parameter
Paralle... | def Residual(*layers, **kwargs):
"""Constructs a residual version of layers, summing input to layers output."""
shortcut = kwargs.get('shortcut', Identity()) # pylint: disable=no-value-for-parameter
if len(layers) > 1:
return Serial(
Branch(), # pylint: disable=no-value-for-parameter
Paralle... | [
"Constructs",
"a",
"residual",
"version",
"of",
"layers",
"summing",
"input",
"to",
"layers",
"output",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/combinators.py#L240-L256 | [
"def",
"Residual",
"(",
"*",
"layers",
",",
"*",
"*",
"kwargs",
")",
":",
"shortcut",
"=",
"kwargs",
".",
"get",
"(",
"'shortcut'",
",",
"Identity",
"(",
")",
")",
"# pylint: disable=no-value-for-parameter",
"if",
"len",
"(",
"layers",
")",
">",
"1",
":"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | PolicyLearner.train | Train. | tensor2tensor/rl/policy_learner.py | def train(
self,
env_fn,
hparams,
simulated,
save_continuously,
epoch,
sampling_temp=1.0,
num_env_steps=None,
env_step_multiplier=1,
eval_env_fn=None,
report_fn=None
):
"""Train."""
raise NotImplementedError() | def train(
self,
env_fn,
hparams,
simulated,
save_continuously,
epoch,
sampling_temp=1.0,
num_env_steps=None,
env_step_multiplier=1,
eval_env_fn=None,
report_fn=None
):
"""Train."""
raise NotImplementedError() | [
"Train",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/policy_learner.py#L34-L48 | [
"def",
"train",
"(",
"self",
",",
"env_fn",
",",
"hparams",
",",
"simulated",
",",
"save_continuously",
",",
"epoch",
",",
"sampling_temp",
"=",
"1.0",
",",
"num_env_steps",
"=",
"None",
",",
"env_step_multiplier",
"=",
"1",
",",
"eval_env_fn",
"=",
"None",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | update_hparams_for_universal_transformer | Adds default hparams for all of the variants of the Universal Transformer.
Args:
hparams: default hparams (usually one of the standard hparams from
transformer model (like "transformer_base")
Returns:
hparams with default values for Universal Transformers hyper-parameters | tensor2tensor/models/research/universal_transformer.py | def update_hparams_for_universal_transformer(hparams):
"""Adds default hparams for all of the variants of the Universal Transformer.
Args:
hparams: default hparams (usually one of the standard hparams from
transformer model (like "transformer_base")
Returns:
hparams with default values for Univers... | def update_hparams_for_universal_transformer(hparams):
"""Adds default hparams for all of the variants of the Universal Transformer.
Args:
hparams: default hparams (usually one of the standard hparams from
transformer model (like "transformer_base")
Returns:
hparams with default values for Univers... | [
"Adds",
"default",
"hparams",
"for",
"all",
"of",
"the",
"variants",
"of",
"the",
"Universal",
"Transformer",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer.py#L352-L436 | [
"def",
"update_hparams_for_universal_transformer",
"(",
"hparams",
")",
":",
"hparams",
".",
"daisy_chain_variables",
"=",
"False",
"# Breaks multi-gpu in while loops.",
"# If not None, mixes vanilla transformer with Universal Transformer.",
"# Options: None, \"before_ut\", and \"after_ut\... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | universal_transformer_base | Base parameters for Universal Transformer. | tensor2tensor/models/research/universal_transformer.py | def universal_transformer_base():
"""Base parameters for Universal Transformer."""
hparams = transformer.transformer_base()
# To have a similar capacity to the transformer_base with 6 layers,
# we need to increase the size of the UT's layer
# since, in fact, UT has a single layer repeating multiple times.
h... | def universal_transformer_base():
"""Base parameters for Universal Transformer."""
hparams = transformer.transformer_base()
# To have a similar capacity to the transformer_base with 6 layers,
# we need to increase the size of the UT's layer
# since, in fact, UT has a single layer repeating multiple times.
h... | [
"Base",
"parameters",
"for",
"Universal",
"Transformer",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer.py#L440-L451 | [
"def",
"universal_transformer_base",
"(",
")",
":",
"hparams",
"=",
"transformer",
".",
"transformer_base",
"(",
")",
"# To have a similar capacity to the transformer_base with 6 layers,",
"# we need to increase the size of the UT's layer",
"# since, in fact, UT has a single layer repeat... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | adaptive_universal_transformer_multilayer_tpu | Multi-layer config for adaptive Transformer on TPU. | tensor2tensor/models/research/universal_transformer.py | def adaptive_universal_transformer_multilayer_tpu():
"""Multi-layer config for adaptive Transformer on TPU."""
hparams = adaptive_universal_transformer_base_tpu()
hparams.num_inrecurrence_layers = 2
hparams.mix_with_transformer = "before_ut,after_ut"
hparams.num_mixedin_layers = 1
hparams.transformer_ffn_ty... | def adaptive_universal_transformer_multilayer_tpu():
"""Multi-layer config for adaptive Transformer on TPU."""
hparams = adaptive_universal_transformer_base_tpu()
hparams.num_inrecurrence_layers = 2
hparams.mix_with_transformer = "before_ut,after_ut"
hparams.num_mixedin_layers = 1
hparams.transformer_ffn_ty... | [
"Multi",
"-",
"layer",
"config",
"for",
"adaptive",
"Transformer",
"on",
"TPU",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer.py#L543-L555 | [
"def",
"adaptive_universal_transformer_multilayer_tpu",
"(",
")",
":",
"hparams",
"=",
"adaptive_universal_transformer_base_tpu",
"(",
")",
"hparams",
".",
"num_inrecurrence_layers",
"=",
"2",
"hparams",
".",
"mix_with_transformer",
"=",
"\"before_ut,after_ut\"",
"hparams",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | adaptive_universal_transformer_multilayer_hard | Multi-layer config for adaptive Transformer with hard attention. | tensor2tensor/models/research/universal_transformer.py | def adaptive_universal_transformer_multilayer_hard():
"""Multi-layer config for adaptive Transformer with hard attention."""
hparams = adaptive_universal_transformer_multilayer_tpu()
hparams.batch_size = 256
hparams.hard_attention_k = 8
hparams.add_step_timing_signal = True
# hparams.add_sru = True # This ... | def adaptive_universal_transformer_multilayer_hard():
"""Multi-layer config for adaptive Transformer with hard attention."""
hparams = adaptive_universal_transformer_multilayer_tpu()
hparams.batch_size = 256
hparams.hard_attention_k = 8
hparams.add_step_timing_signal = True
# hparams.add_sru = True # This ... | [
"Multi",
"-",
"layer",
"config",
"for",
"adaptive",
"Transformer",
"with",
"hard",
"attention",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer.py#L559-L568 | [
"def",
"adaptive_universal_transformer_multilayer_hard",
"(",
")",
":",
"hparams",
"=",
"adaptive_universal_transformer_multilayer_tpu",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"256",
"hparams",
".",
"hard_attention_k",
"=",
"8",
"hparams",
".",
"add_step_timing_sign... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | universal_transformer_base_range | Range of hyperparameters. | tensor2tensor/models/research/universal_transformer.py | def universal_transformer_base_range(rhp):
"""Range of hyperparameters."""
# After starting from base, set intervals for some parameters.
rhp.set_discrete("num_rec_steps", [6, 8, 10])
rhp.set_discrete("hidden_size", [1024, 2048, 4096])
rhp.set_discrete("filter_size", [2048, 4096, 8192])
rhp.set_discrete("nu... | def universal_transformer_base_range(rhp):
"""Range of hyperparameters."""
# After starting from base, set intervals for some parameters.
rhp.set_discrete("num_rec_steps", [6, 8, 10])
rhp.set_discrete("hidden_size", [1024, 2048, 4096])
rhp.set_discrete("filter_size", [2048, 4096, 8192])
rhp.set_discrete("nu... | [
"Range",
"of",
"hyperparameters",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer.py#L788-L797 | [
"def",
"universal_transformer_base_range",
"(",
"rhp",
")",
":",
"# After starting from base, set intervals for some parameters.",
"rhp",
".",
"set_discrete",
"(",
"\"num_rec_steps\"",
",",
"[",
"6",
",",
"8",
",",
"10",
"]",
")",
"rhp",
".",
"set_discrete",
"(",
"\... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | adaptive_universal_transformer_base_range | Range of hyperparameters. | tensor2tensor/models/research/universal_transformer.py | def adaptive_universal_transformer_base_range(rhp):
"""Range of hyperparameters."""
# After starting from base, set intervals for some parameters.
rhp.set_discrete("act_max_steps", [8, 16, 32])
rhp.set_float("act_loss_weight", 0.0, 0.5)
rhp.set_discrete("hidden_size", [1024, 2048, 4096])
rhp.set_discrete("f... | def adaptive_universal_transformer_base_range(rhp):
"""Range of hyperparameters."""
# After starting from base, set intervals for some parameters.
rhp.set_discrete("act_max_steps", [8, 16, 32])
rhp.set_float("act_loss_weight", 0.0, 0.5)
rhp.set_discrete("hidden_size", [1024, 2048, 4096])
rhp.set_discrete("f... | [
"Range",
"of",
"hyperparameters",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer.py#L801-L811 | [
"def",
"adaptive_universal_transformer_base_range",
"(",
"rhp",
")",
":",
"# After starting from base, set intervals for some parameters.",
"rhp",
".",
"set_discrete",
"(",
"\"act_max_steps\"",
",",
"[",
"8",
",",
"16",
",",
"32",
"]",
")",
"rhp",
".",
"set_float",
"(... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | DiagonalGate | Split channels in 3 parts. Shifts 1st and 3rd sections to left/right. | tensor2tensor/trax/models/neural_gpu.py | def DiagonalGate(x, params, **kwargs):
"""Split channels in 3 parts. Shifts 1st and 3rd sections to left/right."""
del params
del kwargs
# x : [batch, 1, length, depth]
x = np.pad(
x, [(0, 0), (0, 0), (1, 1), (0, 0)], mode='constant', constant_values=0.0)
depth = x.shape[-1] // 3
assert 3 * depth ==... | def DiagonalGate(x, params, **kwargs):
"""Split channels in 3 parts. Shifts 1st and 3rd sections to left/right."""
del params
del kwargs
# x : [batch, 1, length, depth]
x = np.pad(
x, [(0, 0), (0, 0), (1, 1), (0, 0)], mode='constant', constant_values=0.0)
depth = x.shape[-1] // 3
assert 3 * depth ==... | [
"Split",
"channels",
"in",
"3",
"parts",
".",
"Shifts",
"1st",
"and",
"3rd",
"sections",
"to",
"left",
"/",
"right",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/models/neural_gpu.py#L33-L47 | [
"def",
"DiagonalGate",
"(",
"x",
",",
"params",
",",
"*",
"*",
"kwargs",
")",
":",
"del",
"params",
"del",
"kwargs",
"# x : [batch, 1, length, depth]",
"x",
"=",
"np",
".",
"pad",
"(",
"x",
",",
"[",
"(",
"0",
",",
"0",
")",
",",
"(",
"0",
",",
"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | ConvDiagonalGRU | Build convolutional GRU with diagonal gating as in ImprovedNGPU. | tensor2tensor/trax/models/neural_gpu.py | def ConvDiagonalGRU(units, kernel_size=(3, 3)):
"""Build convolutional GRU with diagonal gating as in ImprovedNGPU."""
def BuildConv():
return layers.Conv(filters=units, kernel_size=kernel_size, padding='SAME')
return layers.GeneralGRUCell(
candidate_transform=BuildConv,
memory_transform=Diagona... | def ConvDiagonalGRU(units, kernel_size=(3, 3)):
"""Build convolutional GRU with diagonal gating as in ImprovedNGPU."""
def BuildConv():
return layers.Conv(filters=units, kernel_size=kernel_size, padding='SAME')
return layers.GeneralGRUCell(
candidate_transform=BuildConv,
memory_transform=Diagona... | [
"Build",
"convolutional",
"GRU",
"with",
"diagonal",
"gating",
"as",
"in",
"ImprovedNGPU",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/models/neural_gpu.py#L50-L60 | [
"def",
"ConvDiagonalGRU",
"(",
"units",
",",
"kernel_size",
"=",
"(",
"3",
",",
"3",
")",
")",
":",
"def",
"BuildConv",
"(",
")",
":",
"return",
"layers",
".",
"Conv",
"(",
"filters",
"=",
"units",
",",
"kernel_size",
"=",
"kernel_size",
",",
"padding"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | NeuralGPU | Implementation of Neural GPU: https://arxiv.org/abs/1702.08727.
Args:
feature_depth: Number of memory channels
steps: Number of times depthwise recurrence steps.
vocab_size: Vocabulary size.
Returns:
A NeuralGPU Stax model. | tensor2tensor/trax/models/neural_gpu.py | def NeuralGPU(feature_depth=96, steps=16, vocab_size=2):
"""Implementation of Neural GPU: https://arxiv.org/abs/1702.08727.
Args:
feature_depth: Number of memory channels
steps: Number of times depthwise recurrence steps.
vocab_size: Vocabulary size.
Returns:
A NeuralGPU Stax model.
"""
xs =... | def NeuralGPU(feature_depth=96, steps=16, vocab_size=2):
"""Implementation of Neural GPU: https://arxiv.org/abs/1702.08727.
Args:
feature_depth: Number of memory channels
steps: Number of times depthwise recurrence steps.
vocab_size: Vocabulary size.
Returns:
A NeuralGPU Stax model.
"""
xs =... | [
"Implementation",
"of",
"Neural",
"GPU",
":",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1702",
".",
"08727",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/models/neural_gpu.py#L63-L82 | [
"def",
"NeuralGPU",
"(",
"feature_depth",
"=",
"96",
",",
"steps",
"=",
"16",
",",
"vocab_size",
"=",
"2",
")",
":",
"xs",
"=",
"[",
"]",
"xs",
".",
"append",
"(",
"layers",
".",
"Embedding",
"(",
"feature_depth",
"=",
"feature_depth",
",",
"vocab_size... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | strip_ids | Strip ids_to_strip from the end ids. | tensor2tensor/data_generators/text_encoder.py | def strip_ids(ids, ids_to_strip):
"""Strip ids_to_strip from the end ids."""
ids = list(ids)
while ids and ids[-1] in ids_to_strip:
ids.pop()
return ids | def strip_ids(ids, ids_to_strip):
"""Strip ids_to_strip from the end ids."""
ids = list(ids)
while ids and ids[-1] in ids_to_strip:
ids.pop()
return ids | [
"Strip",
"ids_to_strip",
"from",
"the",
"end",
"ids",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L99-L104 | [
"def",
"strip_ids",
"(",
"ids",
",",
"ids_to_strip",
")",
":",
"ids",
"=",
"list",
"(",
"ids",
")",
"while",
"ids",
"and",
"ids",
"[",
"-",
"1",
"]",
"in",
"ids_to_strip",
":",
"ids",
".",
"pop",
"(",
")",
"return",
"ids"
] | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | _escape_token | Escape away underscores and OOV characters and append '_'.
This allows the token to be expressed as the concatenation of a list
of subtokens from the vocabulary. The underscore acts as a sentinel
which allows us to invertibly concatenate multiple such lists.
Args:
token: A unicode string to be escaped.
... | tensor2tensor/data_generators/text_encoder.py | def _escape_token(token, alphabet):
"""Escape away underscores and OOV characters and append '_'.
This allows the token to be expressed as the concatenation of a list
of subtokens from the vocabulary. The underscore acts as a sentinel
which allows us to invertibly concatenate multiple such lists.
Args:
... | def _escape_token(token, alphabet):
"""Escape away underscores and OOV characters and append '_'.
This allows the token to be expressed as the concatenation of a list
of subtokens from the vocabulary. The underscore acts as a sentinel
which allows us to invertibly concatenate multiple such lists.
Args:
... | [
"Escape",
"away",
"underscores",
"and",
"OOV",
"characters",
"and",
"append",
"_",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L400-L422 | [
"def",
"_escape_token",
"(",
"token",
",",
"alphabet",
")",
":",
"if",
"not",
"isinstance",
"(",
"token",
",",
"six",
".",
"text_type",
")",
":",
"raise",
"ValueError",
"(",
"\"Expected string type for token, got %s\"",
"%",
"type",
"(",
"token",
")",
")",
"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | TextEncoder.encode | Transform a human-readable string into a sequence of int ids.
The ids should be in the range [num_reserved_ids, vocab_size). Ids [0,
num_reserved_ids) are reserved.
EOS is not appended.
Args:
s: human-readable string to be converted.
Returns:
ids: list of integers | tensor2tensor/data_generators/text_encoder.py | def encode(self, s):
"""Transform a human-readable string into a sequence of int ids.
The ids should be in the range [num_reserved_ids, vocab_size). Ids [0,
num_reserved_ids) are reserved.
EOS is not appended.
Args:
s: human-readable string to be converted.
Returns:
ids: list of ... | def encode(self, s):
"""Transform a human-readable string into a sequence of int ids.
The ids should be in the range [num_reserved_ids, vocab_size). Ids [0,
num_reserved_ids) are reserved.
EOS is not appended.
Args:
s: human-readable string to be converted.
Returns:
ids: list of ... | [
"Transform",
"a",
"human",
"-",
"readable",
"string",
"into",
"a",
"sequence",
"of",
"int",
"ids",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L117-L131 | [
"def",
"encode",
"(",
"self",
",",
"s",
")",
":",
"return",
"[",
"int",
"(",
"w",
")",
"+",
"self",
".",
"_num_reserved_ids",
"for",
"w",
"in",
"s",
".",
"split",
"(",
")",
"]"
] | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | TextEncoder.decode | Transform a sequence of int ids into a human-readable string.
EOS is not expected in ids.
Args:
ids: list of integers to be converted.
strip_extraneous: bool, whether to strip off extraneous tokens
(EOS and PAD).
Returns:
s: human-readable string. | tensor2tensor/data_generators/text_encoder.py | def decode(self, ids, strip_extraneous=False):
"""Transform a sequence of int ids into a human-readable string.
EOS is not expected in ids.
Args:
ids: list of integers to be converted.
strip_extraneous: bool, whether to strip off extraneous tokens
(EOS and PAD).
Returns:
s: ... | def decode(self, ids, strip_extraneous=False):
"""Transform a sequence of int ids into a human-readable string.
EOS is not expected in ids.
Args:
ids: list of integers to be converted.
strip_extraneous: bool, whether to strip off extraneous tokens
(EOS and PAD).
Returns:
s: ... | [
"Transform",
"a",
"sequence",
"of",
"int",
"ids",
"into",
"a",
"human",
"-",
"readable",
"string",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L133-L148 | [
"def",
"decode",
"(",
"self",
",",
"ids",
",",
"strip_extraneous",
"=",
"False",
")",
":",
"if",
"strip_extraneous",
":",
"ids",
"=",
"strip_ids",
"(",
"ids",
",",
"list",
"(",
"range",
"(",
"self",
".",
"_num_reserved_ids",
"or",
"0",
")",
")",
")",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | TextEncoder.decode_list | Transform a sequence of int ids into a their string versions.
This method supports transforming individual input/output ids to their
string versions so that sequence to/from text conversions can be visualized
in a human readable format.
Args:
ids: list of integers to be converted.
Returns:
... | tensor2tensor/data_generators/text_encoder.py | def decode_list(self, ids):
"""Transform a sequence of int ids into a their string versions.
This method supports transforming individual input/output ids to their
string versions so that sequence to/from text conversions can be visualized
in a human readable format.
Args:
ids: list of integ... | def decode_list(self, ids):
"""Transform a sequence of int ids into a their string versions.
This method supports transforming individual input/output ids to their
string versions so that sequence to/from text conversions can be visualized
in a human readable format.
Args:
ids: list of integ... | [
"Transform",
"a",
"sequence",
"of",
"int",
"ids",
"into",
"a",
"their",
"string",
"versions",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L150-L169 | [
"def",
"decode_list",
"(",
"self",
",",
"ids",
")",
":",
"decoded_ids",
"=",
"[",
"]",
"for",
"id_",
"in",
"ids",
":",
"if",
"0",
"<=",
"id_",
"<",
"self",
".",
"_num_reserved_ids",
":",
"decoded_ids",
".",
"append",
"(",
"RESERVED_TOKENS",
"[",
"int",... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | TokenTextEncoder.encode | Converts a space-separated string of tokens to a list of ids. | tensor2tensor/data_generators/text_encoder.py | def encode(self, s):
"""Converts a space-separated string of tokens to a list of ids."""
sentence = s
tokens = sentence.strip().split()
if self._replace_oov is not None:
tokens = [t if t in self._token_to_id else self._replace_oov
for t in tokens]
ret = [self._token_to_id[tok] ... | def encode(self, s):
"""Converts a space-separated string of tokens to a list of ids."""
sentence = s
tokens = sentence.strip().split()
if self._replace_oov is not None:
tokens = [t if t in self._token_to_id else self._replace_oov
for t in tokens]
ret = [self._token_to_id[tok] ... | [
"Converts",
"a",
"space",
"-",
"separated",
"string",
"of",
"tokens",
"to",
"a",
"list",
"of",
"ids",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L314-L322 | [
"def",
"encode",
"(",
"self",
",",
"s",
")",
":",
"sentence",
"=",
"s",
"tokens",
"=",
"sentence",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"if",
"self",
".",
"_replace_oov",
"is",
"not",
"None",
":",
"tokens",
"=",
"[",
"t",
"if",
"t",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | TokenTextEncoder._init_vocab_from_file | Load vocab from a file.
Args:
filename: The file to load vocabulary from. | tensor2tensor/data_generators/text_encoder.py | def _init_vocab_from_file(self, filename):
"""Load vocab from a file.
Args:
filename: The file to load vocabulary from.
"""
with tf.gfile.Open(filename) as f:
tokens = [token.strip() for token in f.readlines()]
def token_gen():
for token in tokens:
yield token
self._... | def _init_vocab_from_file(self, filename):
"""Load vocab from a file.
Args:
filename: The file to load vocabulary from.
"""
with tf.gfile.Open(filename) as f:
tokens = [token.strip() for token in f.readlines()]
def token_gen():
for token in tokens:
yield token
self._... | [
"Load",
"vocab",
"from",
"a",
"file",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L338-L351 | [
"def",
"_init_vocab_from_file",
"(",
"self",
",",
"filename",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"filename",
")",
"as",
"f",
":",
"tokens",
"=",
"[",
"token",
".",
"strip",
"(",
")",
"for",
"token",
"in",
"f",
".",
"readlines",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | TokenTextEncoder._init_vocab_from_list | Initialize tokens from a list of tokens.
It is ok if reserved tokens appear in the vocab list. They will be
removed. The set of tokens in vocab_list should be unique.
Args:
vocab_list: A list of tokens. | tensor2tensor/data_generators/text_encoder.py | def _init_vocab_from_list(self, vocab_list):
"""Initialize tokens from a list of tokens.
It is ok if reserved tokens appear in the vocab list. They will be
removed. The set of tokens in vocab_list should be unique.
Args:
vocab_list: A list of tokens.
"""
def token_gen():
for token ... | def _init_vocab_from_list(self, vocab_list):
"""Initialize tokens from a list of tokens.
It is ok if reserved tokens appear in the vocab list. They will be
removed. The set of tokens in vocab_list should be unique.
Args:
vocab_list: A list of tokens.
"""
def token_gen():
for token ... | [
"Initialize",
"tokens",
"from",
"a",
"list",
"of",
"tokens",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L353-L367 | [
"def",
"_init_vocab_from_list",
"(",
"self",
",",
"vocab_list",
")",
":",
"def",
"token_gen",
"(",
")",
":",
"for",
"token",
"in",
"vocab_list",
":",
"if",
"token",
"not",
"in",
"RESERVED_TOKENS",
":",
"yield",
"token",
"self",
".",
"_init_vocab",
"(",
"to... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | TokenTextEncoder._init_vocab | Initialize vocabulary with tokens from token_generator. | tensor2tensor/data_generators/text_encoder.py | def _init_vocab(self, token_generator, add_reserved_tokens=True):
"""Initialize vocabulary with tokens from token_generator."""
self._id_to_token = {}
non_reserved_start_index = 0
if add_reserved_tokens:
self._id_to_token.update(enumerate(RESERVED_TOKENS))
non_reserved_start_index = len(RE... | def _init_vocab(self, token_generator, add_reserved_tokens=True):
"""Initialize vocabulary with tokens from token_generator."""
self._id_to_token = {}
non_reserved_start_index = 0
if add_reserved_tokens:
self._id_to_token.update(enumerate(RESERVED_TOKENS))
non_reserved_start_index = len(RE... | [
"Initialize",
"vocabulary",
"with",
"tokens",
"from",
"token_generator",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L369-L384 | [
"def",
"_init_vocab",
"(",
"self",
",",
"token_generator",
",",
"add_reserved_tokens",
"=",
"True",
")",
":",
"self",
".",
"_id_to_token",
"=",
"{",
"}",
"non_reserved_start_index",
"=",
"0",
"if",
"add_reserved_tokens",
":",
"self",
".",
"_id_to_token",
".",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | TokenTextEncoder.store_to_file | Write vocab file to disk.
Vocab files have one token per line. The file ends in a newline. Reserved
tokens are written to the vocab file as well.
Args:
filename: Full path of the file to store the vocab to. | tensor2tensor/data_generators/text_encoder.py | def store_to_file(self, filename):
"""Write vocab file to disk.
Vocab files have one token per line. The file ends in a newline. Reserved
tokens are written to the vocab file as well.
Args:
filename: Full path of the file to store the vocab to.
"""
with tf.gfile.Open(filename, "w") as f:... | def store_to_file(self, filename):
"""Write vocab file to disk.
Vocab files have one token per line. The file ends in a newline. Reserved
tokens are written to the vocab file as well.
Args:
filename: Full path of the file to store the vocab to.
"""
with tf.gfile.Open(filename, "w") as f:... | [
"Write",
"vocab",
"file",
"to",
"disk",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L386-L397 | [
"def",
"store_to_file",
"(",
"self",
",",
"filename",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"filename",
",",
"\"w\"",
")",
"as",
"f",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"_id_to_token",
")",
")",
":",
"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | SubwordTextEncoder.decode | Converts a sequence of subtoken ids to a native string.
Args:
ids: a list of integers in the range [0, vocab_size)
strip_extraneous: bool, whether to strip off extraneous tokens
(EOS and PAD).
Returns:
a native string | tensor2tensor/data_generators/text_encoder.py | def decode(self, ids, strip_extraneous=False):
"""Converts a sequence of subtoken ids to a native string.
Args:
ids: a list of integers in the range [0, vocab_size)
strip_extraneous: bool, whether to strip off extraneous tokens
(EOS and PAD).
Returns:
a native string
"""
... | def decode(self, ids, strip_extraneous=False):
"""Converts a sequence of subtoken ids to a native string.
Args:
ids: a list of integers in the range [0, vocab_size)
strip_extraneous: bool, whether to strip off extraneous tokens
(EOS and PAD).
Returns:
a native string
"""
... | [
"Converts",
"a",
"sequence",
"of",
"subtoken",
"ids",
"to",
"a",
"native",
"string",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L522-L536 | [
"def",
"decode",
"(",
"self",
",",
"ids",
",",
"strip_extraneous",
"=",
"False",
")",
":",
"if",
"strip_extraneous",
":",
"ids",
"=",
"strip_ids",
"(",
"ids",
",",
"list",
"(",
"range",
"(",
"self",
".",
"_num_reserved_ids",
"or",
"0",
")",
")",
")",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | SubwordTextEncoder._tokens_to_subtoken_ids | Converts a list of tokens to a list of subtoken ids.
Args:
tokens: a list of strings.
Returns:
a list of integers in the range [0, vocab_size) | tensor2tensor/data_generators/text_encoder.py | def _tokens_to_subtoken_ids(self, tokens):
"""Converts a list of tokens to a list of subtoken ids.
Args:
tokens: a list of strings.
Returns:
a list of integers in the range [0, vocab_size)
"""
ret = []
for token in tokens:
ret.extend(self._token_to_subtoken_ids(token))
ret... | def _tokens_to_subtoken_ids(self, tokens):
"""Converts a list of tokens to a list of subtoken ids.
Args:
tokens: a list of strings.
Returns:
a list of integers in the range [0, vocab_size)
"""
ret = []
for token in tokens:
ret.extend(self._token_to_subtoken_ids(token))
ret... | [
"Converts",
"a",
"list",
"of",
"tokens",
"to",
"a",
"list",
"of",
"subtoken",
"ids",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L546-L557 | [
"def",
"_tokens_to_subtoken_ids",
"(",
"self",
",",
"tokens",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"token",
"in",
"tokens",
":",
"ret",
".",
"extend",
"(",
"self",
".",
"_token_to_subtoken_ids",
"(",
"token",
")",
")",
"return",
"ret"
] | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | SubwordTextEncoder._token_to_subtoken_ids | Converts token to a list of subtoken ids.
Args:
token: a string.
Returns:
a list of integers in the range [0, vocab_size) | tensor2tensor/data_generators/text_encoder.py | def _token_to_subtoken_ids(self, token):
"""Converts token to a list of subtoken ids.
Args:
token: a string.
Returns:
a list of integers in the range [0, vocab_size)
"""
cache_location = hash(token) % self._cache_size
cache_key, cache_value = self._cache[cache_location]
if cache... | def _token_to_subtoken_ids(self, token):
"""Converts token to a list of subtoken ids.
Args:
token: a string.
Returns:
a list of integers in the range [0, vocab_size)
"""
cache_location = hash(token) % self._cache_size
cache_key, cache_value = self._cache[cache_location]
if cache... | [
"Converts",
"token",
"to",
"a",
"list",
"of",
"subtoken",
"ids",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L559-L574 | [
"def",
"_token_to_subtoken_ids",
"(",
"self",
",",
"token",
")",
":",
"cache_location",
"=",
"hash",
"(",
"token",
")",
"%",
"self",
".",
"_cache_size",
"cache_key",
",",
"cache_value",
"=",
"self",
".",
"_cache",
"[",
"cache_location",
"]",
"if",
"cache_key... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | SubwordTextEncoder._subtoken_ids_to_tokens | Converts a list of subtoken ids to a list of tokens.
Args:
subtokens: a list of integers in the range [0, vocab_size)
Returns:
a list of strings. | tensor2tensor/data_generators/text_encoder.py | def _subtoken_ids_to_tokens(self, subtokens):
"""Converts a list of subtoken ids to a list of tokens.
Args:
subtokens: a list of integers in the range [0, vocab_size)
Returns:
a list of strings.
"""
concatenated = "".join(
[self._subtoken_id_to_subtoken_string(s) for s in subtok... | def _subtoken_ids_to_tokens(self, subtokens):
"""Converts a list of subtoken ids to a list of tokens.
Args:
subtokens: a list of integers in the range [0, vocab_size)
Returns:
a list of strings.
"""
concatenated = "".join(
[self._subtoken_id_to_subtoken_string(s) for s in subtok... | [
"Converts",
"a",
"list",
"of",
"subtoken",
"ids",
"to",
"a",
"list",
"of",
"tokens",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L576-L593 | [
"def",
"_subtoken_ids_to_tokens",
"(",
"self",
",",
"subtokens",
")",
":",
"concatenated",
"=",
"\"\"",
".",
"join",
"(",
"[",
"self",
".",
"_subtoken_id_to_subtoken_string",
"(",
"s",
")",
"for",
"s",
"in",
"subtokens",
"]",
")",
"split",
"=",
"concatenated... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | SubwordTextEncoder._subtoken_id_to_subtoken_string | Converts a subtoken integer ID to a subtoken string. | tensor2tensor/data_generators/text_encoder.py | def _subtoken_id_to_subtoken_string(self, subtoken):
"""Converts a subtoken integer ID to a subtoken string."""
if 0 <= subtoken < self.vocab_size:
return self._all_subtoken_strings[subtoken]
return u"" | def _subtoken_id_to_subtoken_string(self, subtoken):
"""Converts a subtoken integer ID to a subtoken string."""
if 0 <= subtoken < self.vocab_size:
return self._all_subtoken_strings[subtoken]
return u"" | [
"Converts",
"a",
"subtoken",
"integer",
"ID",
"to",
"a",
"subtoken",
"string",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L595-L599 | [
"def",
"_subtoken_id_to_subtoken_string",
"(",
"self",
",",
"subtoken",
")",
":",
"if",
"0",
"<=",
"subtoken",
"<",
"self",
".",
"vocab_size",
":",
"return",
"self",
".",
"_all_subtoken_strings",
"[",
"subtoken",
"]",
"return",
"u\"\""
] | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | SubwordTextEncoder._escaped_token_to_subtoken_strings | Converts an escaped token string to a list of subtoken strings.
Args:
escaped_token: An escaped token as a unicode string.
Returns:
A list of subtokens as unicode strings. | tensor2tensor/data_generators/text_encoder.py | def _escaped_token_to_subtoken_strings(self, escaped_token):
"""Converts an escaped token string to a list of subtoken strings.
Args:
escaped_token: An escaped token as a unicode string.
Returns:
A list of subtokens as unicode strings.
"""
# NOTE: This algorithm is greedy; it won't nece... | def _escaped_token_to_subtoken_strings(self, escaped_token):
"""Converts an escaped token string to a list of subtoken strings.
Args:
escaped_token: An escaped token as a unicode string.
Returns:
A list of subtokens as unicode strings.
"""
# NOTE: This algorithm is greedy; it won't nece... | [
"Converts",
"an",
"escaped",
"token",
"string",
"to",
"a",
"list",
"of",
"subtoken",
"strings",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L601-L629 | [
"def",
"_escaped_token_to_subtoken_strings",
"(",
"self",
",",
"escaped_token",
")",
":",
"# NOTE: This algorithm is greedy; it won't necessarily produce the \"best\"",
"# list of subtokens.",
"ret",
"=",
"[",
"]",
"start",
"=",
"0",
"token_len",
"=",
"len",
"(",
"escaped_t... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | SubwordTextEncoder._escaped_token_to_subtoken_ids | Converts an escaped token string to a list of subtoken IDs.
Args:
escaped_token: An escaped token as a unicode string.
Returns:
A list of subtoken IDs as integers. | tensor2tensor/data_generators/text_encoder.py | def _escaped_token_to_subtoken_ids(self, escaped_token):
"""Converts an escaped token string to a list of subtoken IDs.
Args:
escaped_token: An escaped token as a unicode string.
Returns:
A list of subtoken IDs as integers.
"""
return [
self._subtoken_string_to_id[subtoken]
... | def _escaped_token_to_subtoken_ids(self, escaped_token):
"""Converts an escaped token string to a list of subtoken IDs.
Args:
escaped_token: An escaped token as a unicode string.
Returns:
A list of subtoken IDs as integers.
"""
return [
self._subtoken_string_to_id[subtoken]
... | [
"Converts",
"an",
"escaped",
"token",
"string",
"to",
"a",
"list",
"of",
"subtoken",
"IDs",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L631-L642 | [
"def",
"_escaped_token_to_subtoken_ids",
"(",
"self",
",",
"escaped_token",
")",
":",
"return",
"[",
"self",
".",
"_subtoken_string_to_id",
"[",
"subtoken",
"]",
"for",
"subtoken",
"in",
"self",
".",
"_escaped_token_to_subtoken_strings",
"(",
"escaped_token",
")",
"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | SubwordTextEncoder.build_from_generator | Builds a SubwordTextEncoder from the generated text.
Args:
generator: yields text.
target_size: int, approximate vocabulary size to create.
max_subtoken_length: Maximum length of a subtoken. If this is not set,
then the runtime and memory use of creating the vocab is quadratic in
... | tensor2tensor/data_generators/text_encoder.py | def build_from_generator(cls,
generator,
target_size,
max_subtoken_length=None,
reserved_tokens=None):
"""Builds a SubwordTextEncoder from the generated text.
Args:
generator: yields text.
ta... | def build_from_generator(cls,
generator,
target_size,
max_subtoken_length=None,
reserved_tokens=None):
"""Builds a SubwordTextEncoder from the generated text.
Args:
generator: yields text.
ta... | [
"Builds",
"a",
"SubwordTextEncoder",
"from",
"the",
"generated",
"text",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L645-L674 | [
"def",
"build_from_generator",
"(",
"cls",
",",
"generator",
",",
"target_size",
",",
"max_subtoken_length",
"=",
"None",
",",
"reserved_tokens",
"=",
"None",
")",
":",
"token_counts",
"=",
"collections",
".",
"defaultdict",
"(",
"int",
")",
"for",
"item",
"in... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | SubwordTextEncoder.build_to_target_size | Builds a SubwordTextEncoder that has `vocab_size` near `target_size`.
Uses simple recursive binary search to find a minimum token count that most
closely matches the `target_size`.
Args:
target_size: Desired vocab_size to approximate.
token_counts: A dictionary of token counts, mapping string ... | tensor2tensor/data_generators/text_encoder.py | def build_to_target_size(cls,
target_size,
token_counts,
min_val,
max_val,
max_subtoken_length=None,
reserved_tokens=None,
num_iter... | def build_to_target_size(cls,
target_size,
token_counts,
min_val,
max_val,
max_subtoken_length=None,
reserved_tokens=None,
num_iter... | [
"Builds",
"a",
"SubwordTextEncoder",
"that",
"has",
"vocab_size",
"near",
"target_size",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L677-L748 | [
"def",
"build_to_target_size",
"(",
"cls",
",",
"target_size",
",",
"token_counts",
",",
"min_val",
",",
"max_val",
",",
"max_subtoken_length",
"=",
"None",
",",
"reserved_tokens",
"=",
"None",
",",
"num_iterations",
"=",
"4",
")",
":",
"if",
"min_val",
">",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | SubwordTextEncoder.build_from_token_counts | Train a SubwordTextEncoder based on a dictionary of word counts.
Args:
token_counts: a dictionary of Unicode strings to int.
min_count: an integer - discard subtokens with lower counts.
num_iterations: an integer. how many iterations of refinement.
reserved_tokens: List of reserved tokens.... | tensor2tensor/data_generators/text_encoder.py | def build_from_token_counts(self,
token_counts,
min_count,
num_iterations=4,
reserved_tokens=None,
max_subtoken_length=None):
"""Train a SubwordTextEncoder based on a... | def build_from_token_counts(self,
token_counts,
min_count,
num_iterations=4,
reserved_tokens=None,
max_subtoken_length=None):
"""Train a SubwordTextEncoder based on a... | [
"Train",
"a",
"SubwordTextEncoder",
"based",
"on",
"a",
"dictionary",
"of",
"word",
"counts",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L750-L866 | [
"def",
"build_from_token_counts",
"(",
"self",
",",
"token_counts",
",",
"min_count",
",",
"num_iterations",
"=",
"4",
",",
"reserved_tokens",
"=",
"None",
",",
"max_subtoken_length",
"=",
"None",
")",
":",
"if",
"reserved_tokens",
"is",
"None",
":",
"reserved_t... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | SubwordTextEncoder.dump | Debugging dump of the current subtoken vocabulary. | tensor2tensor/data_generators/text_encoder.py | def dump(self):
"""Debugging dump of the current subtoken vocabulary."""
subtoken_strings = [(i, s)
for s, i in six.iteritems(self._subtoken_string_to_id)]
print(u", ".join(u"{0} : '{1}'".format(i, s)
for i, s in sorted(subtoken_strings))) | def dump(self):
"""Debugging dump of the current subtoken vocabulary."""
subtoken_strings = [(i, s)
for s, i in six.iteritems(self._subtoken_string_to_id)]
print(u", ".join(u"{0} : '{1}'".format(i, s)
for i, s in sorted(subtoken_strings))) | [
"Debugging",
"dump",
"of",
"the",
"current",
"subtoken",
"vocabulary",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L872-L877 | [
"def",
"dump",
"(",
"self",
")",
":",
"subtoken_strings",
"=",
"[",
"(",
"i",
",",
"s",
")",
"for",
"s",
",",
"i",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_subtoken_string_to_id",
")",
"]",
"print",
"(",
"u\", \"",
".",
"join",
"(",
"u\"{... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | SubwordTextEncoder._init_subtokens_from_list | Initialize token information from a list of subtoken strings.
Args:
subtoken_strings: a list of subtokens
reserved_tokens: List of reserved tokens. We must have `reserved_tokens`
as None or the empty list, or else the global variable `RESERVED_TOKENS`
must be a prefix of `reserved_token... | tensor2tensor/data_generators/text_encoder.py | def _init_subtokens_from_list(self, subtoken_strings, reserved_tokens=None):
"""Initialize token information from a list of subtoken strings.
Args:
subtoken_strings: a list of subtokens
reserved_tokens: List of reserved tokens. We must have `reserved_tokens`
as None or the empty list, or el... | def _init_subtokens_from_list(self, subtoken_strings, reserved_tokens=None):
"""Initialize token information from a list of subtoken strings.
Args:
subtoken_strings: a list of subtokens
reserved_tokens: List of reserved tokens. We must have `reserved_tokens`
as None or the empty list, or el... | [
"Initialize",
"token",
"information",
"from",
"a",
"list",
"of",
"subtoken",
"strings",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L879-L910 | [
"def",
"_init_subtokens_from_list",
"(",
"self",
",",
"subtoken_strings",
",",
"reserved_tokens",
"=",
"None",
")",
":",
"if",
"reserved_tokens",
"is",
"None",
":",
"reserved_tokens",
"=",
"[",
"]",
"if",
"reserved_tokens",
":",
"self",
".",
"_all_subtoken_strings... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | SubwordTextEncoder._load_from_file_object | Load from a file object.
Args:
f: File object to load vocabulary from | tensor2tensor/data_generators/text_encoder.py | def _load_from_file_object(self, f):
"""Load from a file object.
Args:
f: File object to load vocabulary from
"""
subtoken_strings = []
for line in f:
s = line.strip()
# Some vocab files wrap words in single quotes, but others don't
if ((s.startswith("'") and s.endswith("'")... | def _load_from_file_object(self, f):
"""Load from a file object.
Args:
f: File object to load vocabulary from
"""
subtoken_strings = []
for line in f:
s = line.strip()
# Some vocab files wrap words in single quotes, but others don't
if ((s.startswith("'") and s.endswith("'")... | [
"Load",
"from",
"a",
"file",
"object",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L919-L934 | [
"def",
"_load_from_file_object",
"(",
"self",
",",
"f",
")",
":",
"subtoken_strings",
"=",
"[",
"]",
"for",
"line",
"in",
"f",
":",
"s",
"=",
"line",
".",
"strip",
"(",
")",
"# Some vocab files wrap words in single quotes, but others don't",
"if",
"(",
"(",
"s... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | SubwordTextEncoder._load_from_file | Load from a vocab file. | tensor2tensor/data_generators/text_encoder.py | def _load_from_file(self, filename):
"""Load from a vocab file."""
if not tf.gfile.Exists(filename):
raise ValueError("File %s not found" % filename)
with tf.gfile.Open(filename) as f:
self._load_from_file_object(f) | def _load_from_file(self, filename):
"""Load from a vocab file."""
if not tf.gfile.Exists(filename):
raise ValueError("File %s not found" % filename)
with tf.gfile.Open(filename) as f:
self._load_from_file_object(f) | [
"Load",
"from",
"a",
"vocab",
"file",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L936-L941 | [
"def",
"_load_from_file",
"(",
"self",
",",
"filename",
")",
":",
"if",
"not",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"filename",
")",
":",
"raise",
"ValueError",
"(",
"\"File %s not found\"",
"%",
"filename",
")",
"with",
"tf",
".",
"gfile",
".",
"Open... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | ImageEncoder.encode | Transform a string with a filename into a list of RGB integers.
Args:
s: path to the file with an image.
Returns:
ids: list of integers | tensor2tensor/data_generators/text_encoder.py | def encode(self, s):
"""Transform a string with a filename into a list of RGB integers.
Args:
s: path to the file with an image.
Returns:
ids: list of integers
"""
try:
import matplotlib.image as im # pylint: disable=g-import-not-at-top
except ImportError as e:
tf.logg... | def encode(self, s):
"""Transform a string with a filename into a list of RGB integers.
Args:
s: path to the file with an image.
Returns:
ids: list of integers
"""
try:
import matplotlib.image as im # pylint: disable=g-import-not-at-top
except ImportError as e:
tf.logg... | [
"Transform",
"a",
"string",
"with",
"a",
"filename",
"into",
"a",
"list",
"of",
"RGB",
"integers",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L965-L980 | [
"def",
"encode",
"(",
"self",
",",
"s",
")",
":",
"try",
":",
"import",
"matplotlib",
".",
"image",
"as",
"im",
"# pylint: disable=g-import-not-at-top",
"except",
"ImportError",
"as",
"e",
":",
"tf",
".",
"logging",
".",
"warning",
"(",
"\"Reading an image req... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | ImageEncoder.decode | Transform a sequence of int ids into an image file.
Args:
ids: list of integers to be converted.
strip_extraneous: unused
Returns:
Path to the temporary file where the image was saved.
Raises:
ValueError: if the ids are not of the appropriate size. | tensor2tensor/data_generators/text_encoder.py | def decode(self, ids, strip_extraneous=False):
"""Transform a sequence of int ids into an image file.
Args:
ids: list of integers to be converted.
strip_extraneous: unused
Returns:
Path to the temporary file where the image was saved.
Raises:
ValueError: if the ids are not of ... | def decode(self, ids, strip_extraneous=False):
"""Transform a sequence of int ids into an image file.
Args:
ids: list of integers to be converted.
strip_extraneous: unused
Returns:
Path to the temporary file where the image was saved.
Raises:
ValueError: if the ids are not of ... | [
"Transform",
"a",
"sequence",
"of",
"int",
"ids",
"into",
"an",
"image",
"file",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L982-L1018 | [
"def",
"decode",
"(",
"self",
",",
"ids",
",",
"strip_extraneous",
"=",
"False",
")",
":",
"del",
"strip_extraneous",
"_",
",",
"tmp_file_path",
"=",
"tempfile",
".",
"mkstemp",
"(",
"\"_decode.png\"",
")",
"if",
"self",
".",
"_height",
"is",
"None",
"or",... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | RealEncoder.decode | Transform sequence of float values into string (float values).
Args:
ids: array of floats to be converted.
strip_extraneous: unused
Returns:
String having space separated float values.
Raises:
ValueError: if the ids are not of the appropriate size. | tensor2tensor/data_generators/text_encoder.py | def decode(self, ids, strip_extraneous=False):
"""Transform sequence of float values into string (float values).
Args:
ids: array of floats to be converted.
strip_extraneous: unused
Returns:
String having space separated float values.
Raises:
ValueError: if the ids are not of ... | def decode(self, ids, strip_extraneous=False):
"""Transform sequence of float values into string (float values).
Args:
ids: array of floats to be converted.
strip_extraneous: unused
Returns:
String having space separated float values.
Raises:
ValueError: if the ids are not of ... | [
"Transform",
"sequence",
"of",
"float",
"values",
"into",
"string",
"(",
"float",
"values",
")",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L1050-L1064 | [
"def",
"decode",
"(",
"self",
",",
"ids",
",",
"strip_extraneous",
"=",
"False",
")",
":",
"del",
"strip_extraneous",
"return",
"\" \"",
".",
"join",
"(",
"[",
"str",
"(",
"i",
")",
"for",
"i",
"in",
"ids",
"]",
")"
] | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | _pack_images | Helper utility to make a tiled field of images from numpy arrays.
Args:
images: Image tensor in shape [N, W, H, C].
rows: Number of images per row in tiled image.
cols: Number of images per column in tiled image.
Returns:
A tiled image of shape [W * rows, H * cols, C].
Truncates incomplete row... | tensor2tensor/trax/jaxboard.py | def _pack_images(images, rows, cols):
"""Helper utility to make a tiled field of images from numpy arrays.
Args:
images: Image tensor in shape [N, W, H, C].
rows: Number of images per row in tiled image.
cols: Number of images per column in tiled image.
Returns:
A tiled image of shape [W * rows,... | def _pack_images(images, rows, cols):
"""Helper utility to make a tiled field of images from numpy arrays.
Args:
images: Image tensor in shape [N, W, H, C].
rows: Number of images per row in tiled image.
cols: Number of images per column in tiled image.
Returns:
A tiled image of shape [W * rows,... | [
"Helper",
"utility",
"to",
"make",
"a",
"tiled",
"field",
"of",
"images",
"from",
"numpy",
"arrays",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/jaxboard.py#L49-L71 | [
"def",
"_pack_images",
"(",
"images",
",",
"rows",
",",
"cols",
")",
":",
"shape",
"=",
"onp",
".",
"shape",
"(",
"images",
")",
"width",
",",
"height",
",",
"depth",
"=",
"shape",
"[",
"-",
"3",
":",
"]",
"images",
"=",
"onp",
".",
"reshape",
"(... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | markdownify_operative_config_str | Convert an operative config string to markdown format. | tensor2tensor/trax/jaxboard.py | def markdownify_operative_config_str(string):
"""Convert an operative config string to markdown format."""
# TODO(b/37527917): Total hack below. Implement more principled formatting.
def process(line):
"""Convert a single line to markdown format."""
if not line.startswith('#'):
return ' ' + line... | def markdownify_operative_config_str(string):
"""Convert an operative config string to markdown format."""
# TODO(b/37527917): Total hack below. Implement more principled formatting.
def process(line):
"""Convert a single line to markdown format."""
if not line.startswith('#'):
return ' ' + line... | [
"Convert",
"an",
"operative",
"config",
"string",
"to",
"markdown",
"format",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/jaxboard.py#L326-L350 | [
"def",
"markdownify_operative_config_str",
"(",
"string",
")",
":",
"# TODO(b/37527917): Total hack below. Implement more principled formatting.",
"def",
"process",
"(",
"line",
")",
":",
"\"\"\"Convert a single line to markdown format.\"\"\"",
"if",
"not",
"line",
".",
"startswi... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | SummaryWriter.close | Close SummaryWriter. Final! | tensor2tensor/trax/jaxboard.py | def close(self):
"""Close SummaryWriter. Final!"""
if not self._closed:
self._event_writer.close()
self._closed = True
del self._event_writer | def close(self):
"""Close SummaryWriter. Final!"""
if not self._closed:
self._event_writer.close()
self._closed = True
del self._event_writer | [
"Close",
"SummaryWriter",
".",
"Final!"
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/jaxboard.py#L98-L103 | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_closed",
":",
"self",
".",
"_event_writer",
".",
"close",
"(",
")",
"self",
".",
"_closed",
"=",
"True",
"del",
"self",
".",
"_event_writer"
] | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | SummaryWriter.scalar | Saves scalar value.
Args:
tag: str: label for this data
value: int/float: number to log
step: int: training step | tensor2tensor/trax/jaxboard.py | def scalar(self, tag, value, step=None):
"""Saves scalar value.
Args:
tag: str: label for this data
value: int/float: number to log
step: int: training step
"""
value = float(onp.array(value))
if step is None:
step = self._step
else:
self._step = step
summary =... | def scalar(self, tag, value, step=None):
"""Saves scalar value.
Args:
tag: str: label for this data
value: int/float: number to log
step: int: training step
"""
value = float(onp.array(value))
if step is None:
step = self._step
else:
self._step = step
summary =... | [
"Saves",
"scalar",
"value",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/jaxboard.py#L111-L125 | [
"def",
"scalar",
"(",
"self",
",",
"tag",
",",
"value",
",",
"step",
"=",
"None",
")",
":",
"value",
"=",
"float",
"(",
"onp",
".",
"array",
"(",
"value",
")",
")",
"if",
"step",
"is",
"None",
":",
"step",
"=",
"self",
".",
"_step",
"else",
":"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | SummaryWriter.image | Saves RGB image summary from onp.ndarray [H,W], [H,W,1], or [H,W,3].
Args:
tag: str: label for this data
image: ndarray: [H,W], [H,W,1], [H,W,3] save image in greyscale or colors/
step: int: training step | tensor2tensor/trax/jaxboard.py | def image(self, tag, image, step=None):
"""Saves RGB image summary from onp.ndarray [H,W], [H,W,1], or [H,W,3].
Args:
tag: str: label for this data
image: ndarray: [H,W], [H,W,1], [H,W,3] save image in greyscale or colors/
step: int: training step
"""
image = onp.array(image)
if s... | def image(self, tag, image, step=None):
"""Saves RGB image summary from onp.ndarray [H,W], [H,W,1], or [H,W,3].
Args:
tag: str: label for this data
image: ndarray: [H,W], [H,W,1], [H,W,3] save image in greyscale or colors/
step: int: training step
"""
image = onp.array(image)
if s... | [
"Saves",
"RGB",
"image",
"summary",
"from",
"onp",
".",
"ndarray",
"[",
"H",
"W",
"]",
"[",
"H",
"W",
"1",
"]",
"or",
"[",
"H",
"W",
"3",
"]",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/jaxboard.py#L127-L152 | [
"def",
"image",
"(",
"self",
",",
"tag",
",",
"image",
",",
"step",
"=",
"None",
")",
":",
"image",
"=",
"onp",
".",
"array",
"(",
"image",
")",
"if",
"step",
"is",
"None",
":",
"step",
"=",
"self",
".",
"_step",
"else",
":",
"self",
".",
"_ste... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | SummaryWriter.images | Saves (rows, cols) tiled images from onp.ndarray.
If either rows or cols aren't given, they are determined automatically
from the size of the image batch, if neither are given a long column
of images is produced. This truncates the image batch rather than padding
if it doesn't fill the final row.
... | tensor2tensor/trax/jaxboard.py | def images(self, tag, images, step=None, rows=None, cols=None):
"""Saves (rows, cols) tiled images from onp.ndarray.
If either rows or cols aren't given, they are determined automatically
from the size of the image batch, if neither are given a long column
of images is produced. This truncates the imag... | def images(self, tag, images, step=None, rows=None, cols=None):
"""Saves (rows, cols) tiled images from onp.ndarray.
If either rows or cols aren't given, they are determined automatically
from the size of the image batch, if neither are given a long column
of images is produced. This truncates the imag... | [
"Saves",
"(",
"rows",
"cols",
")",
"tiled",
"images",
"from",
"onp",
".",
"ndarray",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/jaxboard.py#L154-L183 | [
"def",
"images",
"(",
"self",
",",
"tag",
",",
"images",
",",
"step",
"=",
"None",
",",
"rows",
"=",
"None",
",",
"cols",
"=",
"None",
")",
":",
"images",
"=",
"onp",
".",
"array",
"(",
"images",
")",
"if",
"step",
"is",
"None",
":",
"step",
"=... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | SummaryWriter.plot | Saves matplotlib plot output to summary image.
Args:
tag: str: label for this data
mpl_plt: matplotlib stateful pyplot object with prepared plotting state
step: int: training step
close_plot: bool: automatically closes plot | tensor2tensor/trax/jaxboard.py | def plot(self, tag, mpl_plt, step=None, close_plot=True):
"""Saves matplotlib plot output to summary image.
Args:
tag: str: label for this data
mpl_plt: matplotlib stateful pyplot object with prepared plotting state
step: int: training step
close_plot: bool: automatically closes plot
... | def plot(self, tag, mpl_plt, step=None, close_plot=True):
"""Saves matplotlib plot output to summary image.
Args:
tag: str: label for this data
mpl_plt: matplotlib stateful pyplot object with prepared plotting state
step: int: training step
close_plot: bool: automatically closes plot
... | [
"Saves",
"matplotlib",
"plot",
"output",
"to",
"summary",
"image",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/jaxboard.py#L185-L210 | [
"def",
"plot",
"(",
"self",
",",
"tag",
",",
"mpl_plt",
",",
"step",
"=",
"None",
",",
"close_plot",
"=",
"True",
")",
":",
"if",
"step",
"is",
"None",
":",
"step",
"=",
"self",
".",
"_step",
"else",
":",
"self",
".",
"_step",
"=",
"step",
"fig",... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | SummaryWriter.audio | Saves audio.
NB: single channel only right now.
Args:
tag: str: label for this data
audiodata: ndarray [Nsamples,]: data between (-1.0,1.0) to save as wave
step: int: training step
sample_rate: sample rate of passed in audio buffer | tensor2tensor/trax/jaxboard.py | def audio(self, tag, audiodata, step=None, sample_rate=44100):
"""Saves audio.
NB: single channel only right now.
Args:
tag: str: label for this data
audiodata: ndarray [Nsamples,]: data between (-1.0,1.0) to save as wave
step: int: training step
sample_rate: sample rate of passed ... | def audio(self, tag, audiodata, step=None, sample_rate=44100):
"""Saves audio.
NB: single channel only right now.
Args:
tag: str: label for this data
audiodata: ndarray [Nsamples,]: data between (-1.0,1.0) to save as wave
step: int: training step
sample_rate: sample rate of passed ... | [
"Saves",
"audio",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/jaxboard.py#L212-L249 | [
"def",
"audio",
"(",
"self",
",",
"tag",
",",
"audiodata",
",",
"step",
"=",
"None",
",",
"sample_rate",
"=",
"44100",
")",
":",
"audiodata",
"=",
"onp",
".",
"array",
"(",
"audiodata",
")",
"if",
"step",
"is",
"None",
":",
"step",
"=",
"self",
"."... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | SummaryWriter.histogram | Saves histogram of values.
Args:
tag: str: label for this data
values: ndarray: will be flattened by this routine
bins: number of bins in histogram, or array of bins for onp.histogram
step: int: training step | tensor2tensor/trax/jaxboard.py | def histogram(self, tag, values, bins, step=None):
"""Saves histogram of values.
Args:
tag: str: label for this data
values: ndarray: will be flattened by this routine
bins: number of bins in histogram, or array of bins for onp.histogram
step: int: training step
"""
if step is N... | def histogram(self, tag, values, bins, step=None):
"""Saves histogram of values.
Args:
tag: str: label for this data
values: ndarray: will be flattened by this routine
bins: number of bins in histogram, or array of bins for onp.histogram
step: int: training step
"""
if step is N... | [
"Saves",
"histogram",
"of",
"values",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/jaxboard.py#L251-L287 | [
"def",
"histogram",
"(",
"self",
",",
"tag",
",",
"values",
",",
"bins",
",",
"step",
"=",
"None",
")",
":",
"if",
"step",
"is",
"None",
":",
"step",
"=",
"self",
".",
"_step",
"else",
":",
"self",
".",
"_step",
"=",
"step",
"values",
"=",
"onp",... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | SummaryWriter.text | Saves a text summary.
Args:
tag: str: label for this data
textdata: string, or 1D/2D list/numpy array of strings
step: int: training step
Note: markdown formatting is rendered by tensorboard. | tensor2tensor/trax/jaxboard.py | def text(self, tag, textdata, step=None):
"""Saves a text summary.
Args:
tag: str: label for this data
textdata: string, or 1D/2D list/numpy array of strings
step: int: training step
Note: markdown formatting is rendered by tensorboard.
"""
if step is None:
step = self._step... | def text(self, tag, textdata, step=None):
"""Saves a text summary.
Args:
tag: str: label for this data
textdata: string, or 1D/2D list/numpy array of strings
step: int: training step
Note: markdown formatting is rendered by tensorboard.
"""
if step is None:
step = self._step... | [
"Saves",
"a",
"text",
"summary",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/jaxboard.py#L289-L322 | [
"def",
"text",
"(",
"self",
",",
"tag",
",",
"textdata",
",",
"step",
"=",
"None",
")",
":",
"if",
"step",
"is",
"None",
":",
"step",
"=",
"self",
".",
"_step",
"else",
":",
"self",
".",
"_step",
"=",
"step",
"smd",
"=",
"SummaryMetadata",
"(",
"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | import_usr_dir | Import module at usr_dir, if provided. | tensor2tensor/utils/usr_dir.py | def import_usr_dir(usr_dir):
"""Import module at usr_dir, if provided."""
if not usr_dir:
return
if usr_dir == INTERNAL_USR_DIR_PACKAGE:
# The package has been installed with pip under this name for Cloud ML
# Engine so just import it.
importlib.import_module(INTERNAL_USR_DIR_PACKAGE)
return
... | def import_usr_dir(usr_dir):
"""Import module at usr_dir, if provided."""
if not usr_dir:
return
if usr_dir == INTERNAL_USR_DIR_PACKAGE:
# The package has been installed with pip under this name for Cloud ML
# Engine so just import it.
importlib.import_module(INTERNAL_USR_DIR_PACKAGE)
return
... | [
"Import",
"module",
"at",
"usr_dir",
"if",
"provided",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/usr_dir.py#L30-L46 | [
"def",
"import_usr_dir",
"(",
"usr_dir",
")",
":",
"if",
"not",
"usr_dir",
":",
"return",
"if",
"usr_dir",
"==",
"INTERNAL_USR_DIR_PACKAGE",
":",
"# The package has been installed with pip under this name for Cloud ML",
"# Engine so just import it.",
"importlib",
".",
"import... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | basic_params1 | A set of basic hyperparameters. | tensor2tensor/layers/common_hparams.py | def basic_params1():
"""A set of basic hyperparameters."""
return hparam.HParams(
# If the problem consists of variable-length sequences
# (see problem.batch_size_means_tokens()), then this is the number
# of tokens per batch per GPU or per TPU core. Otherwise, this is
# the number of examp... | def basic_params1():
"""A set of basic hyperparameters."""
return hparam.HParams(
# If the problem consists of variable-length sequences
# (see problem.batch_size_means_tokens()), then this is the number
# of tokens per batch per GPU or per TPU core. Otherwise, this is
# the number of examp... | [
"A",
"set",
"of",
"basic",
"hyperparameters",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_hparams.py#L29-L351 | [
"def",
"basic_params1",
"(",
")",
":",
"return",
"hparam",
".",
"HParams",
"(",
"# If the problem consists of variable-length sequences",
"# (see problem.batch_size_means_tokens()), then this is the number",
"# of tokens per batch per GPU or per TPU core. Otherwise, this is",
"# the numbe... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | basic_range1 | A basic range of hyperparameters. | tensor2tensor/layers/common_hparams.py | def basic_range1(ranged_hparams):
"""A basic range of hyperparameters."""
rhp = ranged_hparams
rhp.set_discrete("batch_size", [1024, 2048, 4096])
rhp.set_discrete("num_hidden_layers", [1, 2, 3, 4, 5, 6])
rhp.set_discrete("hidden_size", [32, 64, 128, 256, 512], scale=rhp.LOG_SCALE)
rhp.set_discrete("kernel_h... | def basic_range1(ranged_hparams):
"""A basic range of hyperparameters."""
rhp = ranged_hparams
rhp.set_discrete("batch_size", [1024, 2048, 4096])
rhp.set_discrete("num_hidden_layers", [1, 2, 3, 4, 5, 6])
rhp.set_discrete("hidden_size", [32, 64, 128, 256, 512], scale=rhp.LOG_SCALE)
rhp.set_discrete("kernel_h... | [
"A",
"basic",
"range",
"of",
"hyperparameters",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_hparams.py#L473-L497 | [
"def",
"basic_range1",
"(",
"ranged_hparams",
")",
":",
"rhp",
"=",
"ranged_hparams",
"rhp",
".",
"set_discrete",
"(",
"\"batch_size\"",
",",
"[",
"1024",
",",
"2048",
",",
"4096",
"]",
")",
"rhp",
".",
"set_discrete",
"(",
"\"num_hidden_layers\"",
",",
"[",... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | RangedHParams._check_reset_and_type_change | Check if name is in orig_ctr or in one of the other type containers. | tensor2tensor/layers/common_hparams.py | def _check_reset_and_type_change(self, name, orig_ctr):
"""Check if name is in orig_ctr or in one of the other type containers."""
# Resetting a hyperparameter
if name in orig_ctr:
tf.logging.warning("Overwriting hparam %s", name)
ctr_names = [
(self._categorical_params, "categorical"),
... | def _check_reset_and_type_change(self, name, orig_ctr):
"""Check if name is in orig_ctr or in one of the other type containers."""
# Resetting a hyperparameter
if name in orig_ctr:
tf.logging.warning("Overwriting hparam %s", name)
ctr_names = [
(self._categorical_params, "categorical"),
... | [
"Check",
"if",
"name",
"is",
"in",
"orig_ctr",
"or",
"in",
"one",
"of",
"the",
"other",
"type",
"containers",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_hparams.py#L374-L397 | [
"def",
"_check_reset_and_type_change",
"(",
"self",
",",
"name",
",",
"orig_ctr",
")",
":",
"# Resetting a hyperparameter",
"if",
"name",
"in",
"orig_ctr",
":",
"tf",
".",
"logging",
".",
"warning",
"(",
"\"Overwriting hparam %s\"",
",",
"name",
")",
"ctr_names",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | RangedHParams.to_parameter_specs | To list of dicts suitable for Cloud ML Engine hyperparameter tuning. | tensor2tensor/layers/common_hparams.py | def to_parameter_specs(self, name_prefix=""):
"""To list of dicts suitable for Cloud ML Engine hyperparameter tuning."""
specs = []
for name, categories, _ in self._categorical_params.values():
spec = {
"parameterName": name_prefix + name,
"type": "CATEGORICAL",
"categori... | def to_parameter_specs(self, name_prefix=""):
"""To list of dicts suitable for Cloud ML Engine hyperparameter tuning."""
specs = []
for name, categories, _ in self._categorical_params.values():
spec = {
"parameterName": name_prefix + name,
"type": "CATEGORICAL",
"categori... | [
"To",
"list",
"of",
"dicts",
"suitable",
"for",
"Cloud",
"ML",
"Engine",
"hyperparameter",
"tuning",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_hparams.py#L426-L469 | [
"def",
"to_parameter_specs",
"(",
"self",
",",
"name_prefix",
"=",
"\"\"",
")",
":",
"specs",
"=",
"[",
"]",
"for",
"name",
",",
"categories",
",",
"_",
"in",
"self",
".",
"_categorical_params",
".",
"values",
"(",
")",
":",
"spec",
"=",
"{",
"\"parame... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | register_game | Create and register problems for the game.
Args:
game_name: str, one of the games in ATARI_GAMES, e.g. "bank_heist".
game_mode: the frame skip and sticky keys config.
Raises:
ValueError: if game_name or game_mode are wrong. | tensor2tensor/data_generators/gym_env.py | def register_game(game_name, game_mode="NoFrameskip-v4"):
"""Create and register problems for the game.
Args:
game_name: str, one of the games in ATARI_GAMES, e.g. "bank_heist".
game_mode: the frame skip and sticky keys config.
Raises:
ValueError: if game_name or game_mode are wrong.
"""
if game... | def register_game(game_name, game_mode="NoFrameskip-v4"):
"""Create and register problems for the game.
Args:
game_name: str, one of the games in ATARI_GAMES, e.g. "bank_heist".
game_mode: the frame skip and sticky keys config.
Raises:
ValueError: if game_name or game_mode are wrong.
"""
if game... | [
"Create",
"and",
"register",
"problems",
"for",
"the",
"game",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/gym_env.py#L884-L902 | [
"def",
"register_game",
"(",
"game_name",
",",
"game_mode",
"=",
"\"NoFrameskip-v4\"",
")",
":",
"if",
"game_name",
"not",
"in",
"ATARI_GAMES",
":",
"raise",
"ValueError",
"(",
"\"Game %s not in ATARI_GAMES\"",
"%",
"game_name",
")",
"if",
"game_mode",
"not",
"in"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | T2TEnv._decode_png | Decodes a single observation from PNG. | tensor2tensor/data_generators/gym_env.py | def _decode_png(self, encoded_observation):
"""Decodes a single observation from PNG."""
return self._session.obj.run(
self._decoded_image_t.obj,
feed_dict={self._encoded_image_p.obj: encoded_observation}
) | def _decode_png(self, encoded_observation):
"""Decodes a single observation from PNG."""
return self._session.obj.run(
self._decoded_image_t.obj,
feed_dict={self._encoded_image_p.obj: encoded_observation}
) | [
"Decodes",
"a",
"single",
"observation",
"from",
"PNG",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/gym_env.py#L227-L232 | [
"def",
"_decode_png",
"(",
"self",
",",
"encoded_observation",
")",
":",
"return",
"self",
".",
"_session",
".",
"obj",
".",
"run",
"(",
"self",
".",
"_decoded_image_t",
".",
"obj",
",",
"feed_dict",
"=",
"{",
"self",
".",
"_encoded_image_p",
".",
"obj",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | T2TEnv._encode_observations | Encodes observations as PNG. | tensor2tensor/data_generators/gym_env.py | def _encode_observations(self, observations):
"""Encodes observations as PNG."""
return [
Observation(
self._session.obj.run(
self._encoded_image_t.obj,
feed_dict={self._decoded_image_p.obj: observation}
),
self._decode_png
)
... | def _encode_observations(self, observations):
"""Encodes observations as PNG."""
return [
Observation(
self._session.obj.run(
self._encoded_image_t.obj,
feed_dict={self._decoded_image_p.obj: observation}
),
self._decode_png
)
... | [
"Encodes",
"observations",
"as",
"PNG",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/gym_env.py#L234-L245 | [
"def",
"_encode_observations",
"(",
"self",
",",
"observations",
")",
":",
"return",
"[",
"Observation",
"(",
"self",
".",
"_session",
".",
"obj",
".",
"run",
"(",
"self",
".",
"_encoded_image_t",
".",
"obj",
",",
"feed_dict",
"=",
"{",
"self",
".",
"_de... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | T2TEnv.step | Makes a step in all environments.
Does any preprocessing and records frames.
Args:
actions: Batch of actions.
Returns:
(obs, rewards, dones) - batches of observations, rewards and done flags
respectively.
Raises:
ValueError: when the data for current epoch has already been lo... | tensor2tensor/data_generators/gym_env.py | def step(self, actions):
"""Makes a step in all environments.
Does any preprocessing and records frames.
Args:
actions: Batch of actions.
Returns:
(obs, rewards, dones) - batches of observations, rewards and done flags
respectively.
Raises:
ValueError: when the data for c... | def step(self, actions):
"""Makes a step in all environments.
Does any preprocessing and records frames.
Args:
actions: Batch of actions.
Returns:
(obs, rewards, dones) - batches of observations, rewards and done flags
respectively.
Raises:
ValueError: when the data for c... | [
"Makes",
"a",
"step",
"in",
"all",
"environments",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/gym_env.py#L264-L301 | [
"def",
"step",
"(",
"self",
",",
"actions",
")",
":",
"if",
"self",
".",
"_store_rollouts",
"and",
"self",
".",
"_rollouts_by_epoch_and_split",
"[",
"self",
".",
"current_epoch",
"]",
":",
"raise",
"ValueError",
"(",
"\"Data for current epoch has already been loaded... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | T2TEnv.reset | Resets environments at given indices.
Does any preprocessing and adds rollouts to history.
Args:
indices: Indices of environments to reset.
Returns:
Batch of initial observations of reset environments.
Raises:
ValueError: when there's no current epoch. | tensor2tensor/data_generators/gym_env.py | def reset(self, indices=None):
"""Resets environments at given indices.
Does any preprocessing and adds rollouts to history.
Args:
indices: Indices of environments to reset.
Returns:
Batch of initial observations of reset environments.
Raises:
ValueError: when there's no curren... | def reset(self, indices=None):
"""Resets environments at given indices.
Does any preprocessing and adds rollouts to history.
Args:
indices: Indices of environments to reset.
Returns:
Batch of initial observations of reset environments.
Raises:
ValueError: when there's no curren... | [
"Resets",
"environments",
"at",
"given",
"indices",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/gym_env.py#L314-L351 | [
"def",
"reset",
"(",
"self",
",",
"indices",
"=",
"None",
")",
":",
"if",
"self",
".",
"_store_rollouts",
"and",
"self",
".",
"current_epoch",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"No current epoch. start_new_epoch() should first be called.\"",
")",
"i... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | T2TEnv.extra_reading_spec | Additional data fields to store on disk and their decoders. | tensor2tensor/data_generators/gym_env.py | def extra_reading_spec(self):
"""Additional data fields to store on disk and their decoders."""
field_names = ("frame_number", "action", "reward", "done")
data_fields = {
name: tf.FixedLenFeature([1], tf.int64) for name in field_names
}
decoders = {
name: tf.contrib.slim.tfexample_de... | def extra_reading_spec(self):
"""Additional data fields to store on disk and their decoders."""
field_names = ("frame_number", "action", "reward", "done")
data_fields = {
name: tf.FixedLenFeature([1], tf.int64) for name in field_names
}
decoders = {
name: tf.contrib.slim.tfexample_de... | [
"Additional",
"data",
"fields",
"to",
"store",
"on",
"disk",
"and",
"their",
"decoders",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/gym_env.py#L373-L383 | [
"def",
"extra_reading_spec",
"(",
"self",
")",
":",
"field_names",
"=",
"(",
"\"frame_number\"",
",",
"\"action\"",
",",
"\"reward\"",
",",
"\"done\"",
")",
"data_fields",
"=",
"{",
"name",
":",
"tf",
".",
"FixedLenFeature",
"(",
"[",
"1",
"]",
",",
"tf",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | T2TEnv._split_current_epoch | Splits frames in the current epoch according to self.dataset_splits.
Rollouts can be broken on shard boundary. This is desirable when we have
few long rollouts and we want to make sure we have data in the dev set. | tensor2tensor/data_generators/gym_env.py | def _split_current_epoch(self):
"""Splits frames in the current epoch according to self.dataset_splits.
Rollouts can be broken on shard boundary. This is desirable when we have
few long rollouts and we want to make sure we have data in the dev set.
"""
num_frames = self._calc_num_frames(self._curre... | def _split_current_epoch(self):
"""Splits frames in the current epoch according to self.dataset_splits.
Rollouts can be broken on shard boundary. This is desirable when we have
few long rollouts and we want to make sure we have data in the dev set.
"""
num_frames = self._calc_num_frames(self._curre... | [
"Splits",
"frames",
"in",
"the",
"current",
"epoch",
"according",
"to",
"self",
".",
"dataset_splits",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/gym_env.py#L417-L462 | [
"def",
"_split_current_epoch",
"(",
"self",
")",
":",
"num_frames",
"=",
"self",
".",
"_calc_num_frames",
"(",
"self",
".",
"_current_epoch_rollouts",
")",
"num_shards",
"=",
"sum",
"(",
"split",
"[",
"\"shards\"",
"]",
"for",
"split",
"in",
"self",
".",
"da... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | T2TEnv.splits_and_paths | List of pairs (split, paths) for the current epoch. | tensor2tensor/data_generators/gym_env.py | def splits_and_paths(self, data_dir):
"""List of pairs (split, paths) for the current epoch."""
filepath_fns = {
problem.DatasetSplit.TRAIN: self.training_filepaths,
problem.DatasetSplit.EVAL: self.dev_filepaths,
problem.DatasetSplit.TEST: self.test_filepaths,
}
def append_epoch... | def splits_and_paths(self, data_dir):
"""List of pairs (split, paths) for the current epoch."""
filepath_fns = {
problem.DatasetSplit.TRAIN: self.training_filepaths,
problem.DatasetSplit.EVAL: self.dev_filepaths,
problem.DatasetSplit.TEST: self.test_filepaths,
}
def append_epoch... | [
"List",
"of",
"pairs",
"(",
"split",
"paths",
")",
"for",
"the",
"current",
"epoch",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/gym_env.py#L464-L484 | [
"def",
"splits_and_paths",
"(",
"self",
",",
"data_dir",
")",
":",
"filepath_fns",
"=",
"{",
"problem",
".",
"DatasetSplit",
".",
"TRAIN",
":",
"self",
".",
"training_filepaths",
",",
"problem",
".",
"DatasetSplit",
".",
"EVAL",
":",
"self",
".",
"dev_filepa... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | T2TEnv.generate_data | Saves the current epoch rollouts to disk, split into train/dev sets. | tensor2tensor/data_generators/gym_env.py | def generate_data(self, data_dir, tmp_dir=None, task_id=-1):
"""Saves the current epoch rollouts to disk, split into train/dev sets."""
if not self._rollouts_by_epoch_and_split[self.current_epoch]:
# Data not loaded from disk.
self._split_current_epoch()
rollouts_by_split = self._rollouts_by_ep... | def generate_data(self, data_dir, tmp_dir=None, task_id=-1):
"""Saves the current epoch rollouts to disk, split into train/dev sets."""
if not self._rollouts_by_epoch_and_split[self.current_epoch]:
# Data not loaded from disk.
self._split_current_epoch()
rollouts_by_split = self._rollouts_by_ep... | [
"Saves",
"the",
"current",
"epoch",
"rollouts",
"to",
"disk",
"split",
"into",
"train",
"/",
"dev",
"sets",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/gym_env.py#L494-L517 | [
"def",
"generate_data",
"(",
"self",
",",
"data_dir",
",",
"tmp_dir",
"=",
"None",
",",
"task_id",
"=",
"-",
"1",
")",
":",
"if",
"not",
"self",
".",
"_rollouts_by_epoch_and_split",
"[",
"self",
".",
"current_epoch",
"]",
":",
"# Data not loaded from disk.",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | T2TGymEnv.set_initial_state | Sets the state that will be used on next reset. | tensor2tensor/data_generators/gym_env.py | def set_initial_state(self, initial_state, initial_frames):
"""Sets the state that will be used on next reset."""
self._initial_state = initial_state
self._initial_frames = initial_frames[:, -1, ...]
self._should_preprocess_on_reset = False | def set_initial_state(self, initial_state, initial_frames):
"""Sets the state that will be used on next reset."""
self._initial_state = initial_state
self._initial_frames = initial_frames[:, -1, ...]
self._should_preprocess_on_reset = False | [
"Sets",
"the",
"state",
"that",
"will",
"be",
"used",
"on",
"next",
"reset",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/gym_env.py#L723-L727 | [
"def",
"set_initial_state",
"(",
"self",
",",
"initial_state",
",",
"initial_frames",
")",
":",
"self",
".",
"_initial_state",
"=",
"initial_state",
"self",
".",
"_initial_frames",
"=",
"initial_frames",
"[",
":",
",",
"-",
"1",
",",
"...",
"]",
"self",
".",... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | image_to_tf_summary_value | Converts a NumPy image to a tf.Summary.Value object.
Args:
image: 3-D NumPy array.
tag: name for tf.Summary.Value for display in tensorboard.
Returns:
image_summary: A tf.Summary.Value object. | tensor2tensor/data_generators/image_utils.py | def image_to_tf_summary_value(image, tag):
"""Converts a NumPy image to a tf.Summary.Value object.
Args:
image: 3-D NumPy array.
tag: name for tf.Summary.Value for display in tensorboard.
Returns:
image_summary: A tf.Summary.Value object.
"""
curr_image = np.asarray(image, dtype=np.uint8)
heigh... | def image_to_tf_summary_value(image, tag):
"""Converts a NumPy image to a tf.Summary.Value object.
Args:
image: 3-D NumPy array.
tag: name for tf.Summary.Value for display in tensorboard.
Returns:
image_summary: A tf.Summary.Value object.
"""
curr_image = np.asarray(image, dtype=np.uint8)
heigh... | [
"Converts",
"a",
"NumPy",
"image",
"to",
"a",
"tf",
".",
"Summary",
".",
"Value",
"object",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/image_utils.py#L43-L62 | [
"def",
"image_to_tf_summary_value",
"(",
"image",
",",
"tag",
")",
":",
"curr_image",
"=",
"np",
".",
"asarray",
"(",
"image",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"height",
",",
"width",
",",
"n_channels",
"=",
"curr_image",
".",
"shape",
"# If m... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | convert_predictions_to_image_summaries | Optionally converts images from hooks_args to image summaries.
Args:
hook_args: DecodeHookArgs namedtuple
Returns:
summaries: list of tf.Summary values if hook_args.decode_hpara | tensor2tensor/data_generators/image_utils.py | def convert_predictions_to_image_summaries(hook_args):
"""Optionally converts images from hooks_args to image summaries.
Args:
hook_args: DecodeHookArgs namedtuple
Returns:
summaries: list of tf.Summary values if hook_args.decode_hpara
"""
decode_hparams = hook_args.decode_hparams
if not decode_hpa... | def convert_predictions_to_image_summaries(hook_args):
"""Optionally converts images from hooks_args to image summaries.
Args:
hook_args: DecodeHookArgs namedtuple
Returns:
summaries: list of tf.Summary values if hook_args.decode_hpara
"""
decode_hparams = hook_args.decode_hparams
if not decode_hpa... | [
"Optionally",
"converts",
"images",
"from",
"hooks_args",
"to",
"image",
"summaries",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/image_utils.py#L65-L88 | [
"def",
"convert_predictions_to_image_summaries",
"(",
"hook_args",
")",
":",
"decode_hparams",
"=",
"hook_args",
".",
"decode_hparams",
"if",
"not",
"decode_hparams",
".",
"display_decoded_images",
":",
"return",
"[",
"]",
"predictions",
"=",
"hook_args",
".",
"predic... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | resize_by_area | image resize function used by quite a few image problems. | tensor2tensor/data_generators/image_utils.py | def resize_by_area(img, size):
"""image resize function used by quite a few image problems."""
return tf.to_int64(
tf.image.resize_images(img, [size, size], tf.image.ResizeMethod.AREA)) | def resize_by_area(img, size):
"""image resize function used by quite a few image problems."""
return tf.to_int64(
tf.image.resize_images(img, [size, size], tf.image.ResizeMethod.AREA)) | [
"image",
"resize",
"function",
"used",
"by",
"quite",
"a",
"few",
"image",
"problems",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/image_utils.py#L91-L94 | [
"def",
"resize_by_area",
"(",
"img",
",",
"size",
")",
":",
"return",
"tf",
".",
"to_int64",
"(",
"tf",
".",
"image",
".",
"resize_images",
"(",
"img",
",",
"[",
"size",
",",
"size",
"]",
",",
"tf",
".",
"image",
".",
"ResizeMethod",
".",
"AREA",
"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | make_multiscale | Returns list of scaled images, one for each resolution.
Args:
image: Tensor of shape [height, height, num_channels].
resolutions: List of heights that image's height is resized to.
resize_method: tf.image.ResizeMethod.
num_channels: Number of channels in image.
Returns:
List of Tensors, one fo... | tensor2tensor/data_generators/image_utils.py | def make_multiscale(image, resolutions,
resize_method=tf.image.ResizeMethod.BICUBIC,
num_channels=3):
"""Returns list of scaled images, one for each resolution.
Args:
image: Tensor of shape [height, height, num_channels].
resolutions: List of heights that image's hei... | def make_multiscale(image, resolutions,
resize_method=tf.image.ResizeMethod.BICUBIC,
num_channels=3):
"""Returns list of scaled images, one for each resolution.
Args:
image: Tensor of shape [height, height, num_channels].
resolutions: List of heights that image's hei... | [
"Returns",
"list",
"of",
"scaled",
"images",
"one",
"for",
"each",
"resolution",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/image_utils.py#L97-L122 | [
"def",
"make_multiscale",
"(",
"image",
",",
"resolutions",
",",
"resize_method",
"=",
"tf",
".",
"image",
".",
"ResizeMethod",
".",
"BICUBIC",
",",
"num_channels",
"=",
"3",
")",
":",
"scaled_images",
"=",
"[",
"]",
"for",
"height",
"in",
"resolutions",
"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | make_multiscale_dilated | Returns list of scaled images, one for each resolution.
Resizes by skipping every nth pixel.
Args:
image: Tensor of shape [height, height, num_channels].
resolutions: List of heights that image's height is resized to. The function
assumes VALID padding, so the original image's height must be divisib... | tensor2tensor/data_generators/image_utils.py | def make_multiscale_dilated(image, resolutions, num_channels=3):
"""Returns list of scaled images, one for each resolution.
Resizes by skipping every nth pixel.
Args:
image: Tensor of shape [height, height, num_channels].
resolutions: List of heights that image's height is resized to. The function
... | def make_multiscale_dilated(image, resolutions, num_channels=3):
"""Returns list of scaled images, one for each resolution.
Resizes by skipping every nth pixel.
Args:
image: Tensor of shape [height, height, num_channels].
resolutions: List of heights that image's height is resized to. The function
... | [
"Returns",
"list",
"of",
"scaled",
"images",
"one",
"for",
"each",
"resolution",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/image_utils.py#L125-L151 | [
"def",
"make_multiscale_dilated",
"(",
"image",
",",
"resolutions",
",",
"num_channels",
"=",
"3",
")",
":",
"image_height",
"=",
"common_layers",
".",
"shape_list",
"(",
"image",
")",
"[",
"0",
"]",
"scaled_images",
"=",
"[",
"]",
"for",
"height",
"in",
"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | encode_images_as_png | Yield images encoded as pngs. | tensor2tensor/data_generators/image_utils.py | def encode_images_as_png(images):
"""Yield images encoded as pngs."""
if tf.executing_eagerly():
for image in images:
yield tf.image.encode_png(image).numpy()
else:
(height, width, channels) = images[0].shape
with tf.Graph().as_default():
image_t = tf.placeholder(dtype=tf.uint8, shape=(hei... | def encode_images_as_png(images):
"""Yield images encoded as pngs."""
if tf.executing_eagerly():
for image in images:
yield tf.image.encode_png(image).numpy()
else:
(height, width, channels) = images[0].shape
with tf.Graph().as_default():
image_t = tf.placeholder(dtype=tf.uint8, shape=(hei... | [
"Yield",
"images",
"encoded",
"as",
"pngs",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/image_utils.py#L266-L279 | [
"def",
"encode_images_as_png",
"(",
"images",
")",
":",
"if",
"tf",
".",
"executing_eagerly",
"(",
")",
":",
"for",
"image",
"in",
"images",
":",
"yield",
"tf",
".",
"image",
".",
"encode_png",
"(",
"image",
")",
".",
"numpy",
"(",
")",
"else",
":",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | image_generator | Generator for images that takes image and labels lists and creates pngs.
Args:
images: list of images given as [width x height x channels] numpy arrays.
labels: list of ints, same length as images.
Yields:
A dictionary representing the images with the following fields:
* image/encoded: the string ... | tensor2tensor/data_generators/image_utils.py | def image_generator(images, labels):
"""Generator for images that takes image and labels lists and creates pngs.
Args:
images: list of images given as [width x height x channels] numpy arrays.
labels: list of ints, same length as images.
Yields:
A dictionary representing the images with the followin... | def image_generator(images, labels):
"""Generator for images that takes image and labels lists and creates pngs.
Args:
images: list of images given as [width x height x channels] numpy arrays.
labels: list of ints, same length as images.
Yields:
A dictionary representing the images with the followin... | [
"Generator",
"for",
"images",
"that",
"takes",
"image",
"and",
"labels",
"lists",
"and",
"creates",
"pngs",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/image_utils.py#L282-L311 | [
"def",
"image_generator",
"(",
"images",
",",
"labels",
")",
":",
"if",
"not",
"images",
":",
"raise",
"ValueError",
"(",
"\"Must provide some images for the generator.\"",
")",
"width",
",",
"height",
",",
"_",
"=",
"images",
"[",
"0",
"]",
".",
"shape",
"f... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | image_augmentation | Image augmentation: cropping, flipping, and color transforms. | tensor2tensor/data_generators/image_utils.py | def image_augmentation(images, do_colors=False, crop_size=None):
"""Image augmentation: cropping, flipping, and color transforms."""
if crop_size is None:
crop_size = [299, 299]
images = tf.random_crop(images, crop_size + [3])
images = tf.image.random_flip_left_right(images)
if do_colors: # More augmenta... | def image_augmentation(images, do_colors=False, crop_size=None):
"""Image augmentation: cropping, flipping, and color transforms."""
if crop_size is None:
crop_size = [299, 299]
images = tf.random_crop(images, crop_size + [3])
images = tf.image.random_flip_left_right(images)
if do_colors: # More augmenta... | [
"Image",
"augmentation",
":",
"cropping",
"flipping",
"and",
"color",
"transforms",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/image_utils.py#L378-L389 | [
"def",
"image_augmentation",
"(",
"images",
",",
"do_colors",
"=",
"False",
",",
"crop_size",
"=",
"None",
")",
":",
"if",
"crop_size",
"is",
"None",
":",
"crop_size",
"=",
"[",
"299",
",",
"299",
"]",
"images",
"=",
"tf",
".",
"random_crop",
"(",
"ima... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | cifar_image_augmentation | Image augmentation suitable for CIFAR-10/100.
As described in https://arxiv.org/pdf/1608.06993v3.pdf (page 5).
Args:
images: a Tensor.
Returns:
Tensor of the same shape as images. | tensor2tensor/data_generators/image_utils.py | def cifar_image_augmentation(images):
"""Image augmentation suitable for CIFAR-10/100.
As described in https://arxiv.org/pdf/1608.06993v3.pdf (page 5).
Args:
images: a Tensor.
Returns:
Tensor of the same shape as images.
"""
images = tf.image.resize_image_with_crop_or_pad(images, 40, 40)
images ... | def cifar_image_augmentation(images):
"""Image augmentation suitable for CIFAR-10/100.
As described in https://arxiv.org/pdf/1608.06993v3.pdf (page 5).
Args:
images: a Tensor.
Returns:
Tensor of the same shape as images.
"""
images = tf.image.resize_image_with_crop_or_pad(images, 40, 40)
images ... | [
"Image",
"augmentation",
"suitable",
"for",
"CIFAR",
"-",
"10",
"/",
"100",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/image_utils.py#L392-L405 | [
"def",
"cifar_image_augmentation",
"(",
"images",
")",
":",
"images",
"=",
"tf",
".",
"image",
".",
"resize_image_with_crop_or_pad",
"(",
"images",
",",
"40",
",",
"40",
")",
"images",
"=",
"tf",
".",
"random_crop",
"(",
"images",
",",
"[",
"32",
",",
"3... | 272500b6efe353aeb638d2745ed56e519462ca31 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.