id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
22,600 | tensorflow/tensor2tensor | tensor2tensor/data_generators/common_voice.py | _is_relative | def _is_relative(path, filename):
"""Checks if the filename is relative, not absolute."""
return os.path.abspath(os.path.join(path, filename)).startswith(path) | python | def _is_relative(path, filename):
"""Checks if the filename is relative, not absolute."""
return os.path.abspath(os.path.join(path, filename)).startswith(path) | [
"def",
"_is_relative",
"(",
"path",
",",
"filename",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
")",
".",
"startswith",
"(",
"path",
")"
] | Checks if the filename is relative, not absolute. | [
"Checks",
"if",
"the",
"filename",
"is",
"relative",
"not",
"absolute",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/common_voice.py#L74-L76 |
22,601 | tensorflow/tensor2tensor | tensor2tensor/rl/ppo.py | define_ppo_step | def define_ppo_step(data_points, hparams, action_space, lr):
"""Define ppo step."""
observation, action, discounted_reward, norm_advantage, old_pdf = data_points
obs_shape = common_layers.shape_list(observation)
observation = tf.reshape(
observation, [obs_shape[0] * obs_shape[1]] + obs_shape[2:]
)
(l... | python | def define_ppo_step(data_points, hparams, action_space, lr):
"""Define ppo step."""
observation, action, discounted_reward, norm_advantage, old_pdf = data_points
obs_shape = common_layers.shape_list(observation)
observation = tf.reshape(
observation, [obs_shape[0] * obs_shape[1]] + obs_shape[2:]
)
(l... | [
"def",
"define_ppo_step",
"(",
"data_points",
",",
"hparams",
",",
"action_space",
",",
"lr",
")",
":",
"observation",
",",
"action",
",",
"discounted_reward",
",",
"norm_advantage",
",",
"old_pdf",
"=",
"data_points",
"obs_shape",
"=",
"common_layers",
".",
"sh... | Define ppo step. | [
"Define",
"ppo",
"step",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/ppo.py#L33-L68 |
22,602 | tensorflow/tensor2tensor | tensor2tensor/rl/ppo.py | define_ppo_epoch | def define_ppo_epoch(memory, hparams, action_space, batch_size):
"""PPO epoch."""
observation, reward, done, action, old_pdf, value = memory
# This is to avoid propagating gradients through simulated environment.
observation = tf.stop_gradient(observation)
action = tf.stop_gradient(action)
reward = tf.stop... | python | def define_ppo_epoch(memory, hparams, action_space, batch_size):
"""PPO epoch."""
observation, reward, done, action, old_pdf, value = memory
# This is to avoid propagating gradients through simulated environment.
observation = tf.stop_gradient(observation)
action = tf.stop_gradient(action)
reward = tf.stop... | [
"def",
"define_ppo_epoch",
"(",
"memory",
",",
"hparams",
",",
"action_space",
",",
"batch_size",
")",
":",
"observation",
",",
"reward",
",",
"done",
",",
"action",
",",
"old_pdf",
",",
"value",
"=",
"memory",
"# This is to avoid propagating gradients through simul... | PPO epoch. | [
"PPO",
"epoch",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/ppo.py#L71-L142 |
22,603 | tensorflow/tensor2tensor | tensor2tensor/rl/ppo.py | calculate_generalized_advantage_estimator | def calculate_generalized_advantage_estimator(
reward, value, done, gae_gamma, gae_lambda):
# pylint: disable=g-doc-args
"""Generalized advantage estimator.
Returns:
GAE estimator. It will be one element shorter than the input; this is
because to compute GAE for [0, ..., N-1] one needs V for [1, ...,... | python | def calculate_generalized_advantage_estimator(
reward, value, done, gae_gamma, gae_lambda):
# pylint: disable=g-doc-args
"""Generalized advantage estimator.
Returns:
GAE estimator. It will be one element shorter than the input; this is
because to compute GAE for [0, ..., N-1] one needs V for [1, ...,... | [
"def",
"calculate_generalized_advantage_estimator",
"(",
"reward",
",",
"value",
",",
"done",
",",
"gae_gamma",
",",
"gae_lambda",
")",
":",
"# pylint: disable=g-doc-args",
"# pylint: enable=g-doc-args",
"next_value",
"=",
"value",
"[",
"1",
":",
",",
":",
"]",
"nex... | Generalized advantage estimator.
Returns:
GAE estimator. It will be one element shorter than the input; this is
because to compute GAE for [0, ..., N-1] one needs V for [1, ..., N]. | [
"Generalized",
"advantage",
"estimator",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/ppo.py#L145-L166 |
22,604 | tensorflow/tensor2tensor | tensor2tensor/envs/gym_spaces_utils.py | gym_space_spec | def gym_space_spec(gym_space):
"""Returns a reading spec of a gym space.
NOTE: Only implemented currently for Box and Discrete.
Args:
gym_space: instance of gym.spaces whose spec we want.
Returns:
Reading spec for that space.
Raises:
NotImplementedError: For spaces whose reading spec we haven'... | python | def gym_space_spec(gym_space):
"""Returns a reading spec of a gym space.
NOTE: Only implemented currently for Box and Discrete.
Args:
gym_space: instance of gym.spaces whose spec we want.
Returns:
Reading spec for that space.
Raises:
NotImplementedError: For spaces whose reading spec we haven'... | [
"def",
"gym_space_spec",
"(",
"gym_space",
")",
":",
"# First try to determine the type.",
"try",
":",
"tf_dtype",
"=",
"tf",
".",
"as_dtype",
"(",
"gym_space",
".",
"dtype",
")",
"except",
"TypeError",
"as",
"e",
":",
"tf",
".",
"logging",
".",
"error",
"("... | Returns a reading spec of a gym space.
NOTE: Only implemented currently for Box and Discrete.
Args:
gym_space: instance of gym.spaces whose spec we want.
Returns:
Reading spec for that space.
Raises:
NotImplementedError: For spaces whose reading spec we haven't implemented. | [
"Returns",
"a",
"reading",
"spec",
"of",
"a",
"gym",
"space",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/gym_spaces_utils.py#L41-L69 |
22,605 | tensorflow/tensor2tensor | tensor2tensor/envs/gym_spaces_utils.py | cardinality | def cardinality(gym_space):
"""Number of elements that can be represented by the space.
Makes the most sense for Discrete or Box type with integral dtype, ex: number
of actions in an action space.
Args:
gym_space: The gym space.
Returns:
np.int64 number of observations that can be represented by th... | python | def cardinality(gym_space):
"""Number of elements that can be represented by the space.
Makes the most sense for Discrete or Box type with integral dtype, ex: number
of actions in an action space.
Args:
gym_space: The gym space.
Returns:
np.int64 number of observations that can be represented by th... | [
"def",
"cardinality",
"(",
"gym_space",
")",
":",
"if",
"(",
"gym_space",
".",
"dtype",
"==",
"np",
".",
"float32",
")",
"or",
"(",
"gym_space",
".",
"dtype",
"==",
"np",
".",
"float64",
")",
":",
"tf",
".",
"logging",
".",
"error",
"(",
"\"Returning... | Number of elements that can be represented by the space.
Makes the most sense for Discrete or Box type with integral dtype, ex: number
of actions in an action space.
Args:
gym_space: The gym space.
Returns:
np.int64 number of observations that can be represented by this space, or
returns None whe... | [
"Number",
"of",
"elements",
"that",
"can",
"be",
"represented",
"by",
"the",
"space",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/gym_spaces_utils.py#L83-L113 |
22,606 | tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | image_rmse | def image_rmse(predictions, labels, weights_fn=common_layers.weights_all):
"""RMSE but will argmax if last dim is not 1."""
if common_layers.shape_list(predictions)[-1] == 1:
predictions = tf.squeeze(predictions, axis=[-1])
else:
predictions = tf.argmax(predictions, axis=-1)
return padded_rmse(predictio... | python | def image_rmse(predictions, labels, weights_fn=common_layers.weights_all):
"""RMSE but will argmax if last dim is not 1."""
if common_layers.shape_list(predictions)[-1] == 1:
predictions = tf.squeeze(predictions, axis=[-1])
else:
predictions = tf.argmax(predictions, axis=-1)
return padded_rmse(predictio... | [
"def",
"image_rmse",
"(",
"predictions",
",",
"labels",
",",
"weights_fn",
"=",
"common_layers",
".",
"weights_all",
")",
":",
"if",
"common_layers",
".",
"shape_list",
"(",
"predictions",
")",
"[",
"-",
"1",
"]",
"==",
"1",
":",
"predictions",
"=",
"tf",
... | RMSE but will argmax if last dim is not 1. | [
"RMSE",
"but",
"will",
"argmax",
"if",
"last",
"dim",
"is",
"not",
"1",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L69-L75 |
22,607 | tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | padded_variance_explained | def padded_variance_explained(predictions,
labels,
weights_fn=common_layers.weights_all):
"""Explained variance, also known as R^2."""
predictions, labels = common_layers.pad_with_zeros(predictions, labels)
targets = labels
weights = weights_fn(targets... | python | def padded_variance_explained(predictions,
labels,
weights_fn=common_layers.weights_all):
"""Explained variance, also known as R^2."""
predictions, labels = common_layers.pad_with_zeros(predictions, labels)
targets = labels
weights = weights_fn(targets... | [
"def",
"padded_variance_explained",
"(",
"predictions",
",",
"labels",
",",
"weights_fn",
"=",
"common_layers",
".",
"weights_all",
")",
":",
"predictions",
",",
"labels",
"=",
"common_layers",
".",
"pad_with_zeros",
"(",
"predictions",
",",
"labels",
")",
"target... | Explained variance, also known as R^2. | [
"Explained",
"variance",
"also",
"known",
"as",
"R^2",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L109-L121 |
22,608 | tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | sequence_edit_distance | def sequence_edit_distance(predictions,
labels,
weights_fn=common_layers.weights_nonzero):
"""Average edit distance, ignoring padding 0s.
The score returned is the edit distance divided by the total length of
reference truth and the weight returned is the tot... | python | def sequence_edit_distance(predictions,
labels,
weights_fn=common_layers.weights_nonzero):
"""Average edit distance, ignoring padding 0s.
The score returned is the edit distance divided by the total length of
reference truth and the weight returned is the tot... | [
"def",
"sequence_edit_distance",
"(",
"predictions",
",",
"labels",
",",
"weights_fn",
"=",
"common_layers",
".",
"weights_nonzero",
")",
":",
"if",
"weights_fn",
"is",
"not",
"common_layers",
".",
"weights_nonzero",
":",
"raise",
"ValueError",
"(",
"\"Only weights_... | Average edit distance, ignoring padding 0s.
The score returned is the edit distance divided by the total length of
reference truth and the weight returned is the total length of the truth.
Args:
predictions: Tensor of shape [`batch_size`, `length`, 1, `num_classes`] and
type tf.float32 representing ... | [
"Average",
"edit",
"distance",
"ignoring",
"padding",
"0s",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L200-L241 |
22,609 | tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | padded_neg_log_perplexity | def padded_neg_log_perplexity(predictions,
labels,
weights_fn=common_layers.weights_nonzero):
"""Average log-perplexity exluding padding 0s. No smoothing."""
num, den = common_layers.padded_cross_entropy(
predictions, labels, 0.0, weights_fn=weights_... | python | def padded_neg_log_perplexity(predictions,
labels,
weights_fn=common_layers.weights_nonzero):
"""Average log-perplexity exluding padding 0s. No smoothing."""
num, den = common_layers.padded_cross_entropy(
predictions, labels, 0.0, weights_fn=weights_... | [
"def",
"padded_neg_log_perplexity",
"(",
"predictions",
",",
"labels",
",",
"weights_fn",
"=",
"common_layers",
".",
"weights_nonzero",
")",
":",
"num",
",",
"den",
"=",
"common_layers",
".",
"padded_cross_entropy",
"(",
"predictions",
",",
"labels",
",",
"0.0",
... | Average log-perplexity exluding padding 0s. No smoothing. | [
"Average",
"log",
"-",
"perplexity",
"exluding",
"padding",
"0s",
".",
"No",
"smoothing",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L244-L250 |
22,610 | tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | padded_neg_log_perplexity_with_masking | def padded_neg_log_perplexity_with_masking(
predictions,
labels,
features,
weights_fn=None):
"""Average log-perplexity with custom targets_mask."""
del weights_fn
if "targets_mask" not in features:
raise ValueError("masked_neg_log_perplexity requires targets_mask feature")
# Features are 4 ... | python | def padded_neg_log_perplexity_with_masking(
predictions,
labels,
features,
weights_fn=None):
"""Average log-perplexity with custom targets_mask."""
del weights_fn
if "targets_mask" not in features:
raise ValueError("masked_neg_log_perplexity requires targets_mask feature")
# Features are 4 ... | [
"def",
"padded_neg_log_perplexity_with_masking",
"(",
"predictions",
",",
"labels",
",",
"features",
",",
"weights_fn",
"=",
"None",
")",
":",
"del",
"weights_fn",
"if",
"\"targets_mask\"",
"not",
"in",
"features",
":",
"raise",
"ValueError",
"(",
"\"masked_neg_log_... | Average log-perplexity with custom targets_mask. | [
"Average",
"log",
"-",
"perplexity",
"with",
"custom",
"targets_mask",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L253-L273 |
22,611 | tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | multilabel_accuracy_matchk | def multilabel_accuracy_matchk(predictions,
labels,
k,
weights_fn=common_layers.weights_nonzero):
"""Used to evaluate the VQA accuracy.
Let n be the times that predictions appear in labels, then final score
is min(n/k, 1... | python | def multilabel_accuracy_matchk(predictions,
labels,
k,
weights_fn=common_layers.weights_nonzero):
"""Used to evaluate the VQA accuracy.
Let n be the times that predictions appear in labels, then final score
is min(n/k, 1... | [
"def",
"multilabel_accuracy_matchk",
"(",
"predictions",
",",
"labels",
",",
"k",
",",
"weights_fn",
"=",
"common_layers",
".",
"weights_nonzero",
")",
":",
"predictions",
"=",
"tf",
".",
"to_int32",
"(",
"tf",
".",
"argmax",
"(",
"predictions",
",",
"axis",
... | Used to evaluate the VQA accuracy.
Let n be the times that predictions appear in labels, then final score
is min(n/k, 1).
Refer to https://arxiv.org/pdf/1505.00468.pdf.
Args:
predictions: A tensor with shape [batch_size, 1, 1, 1, vocab_size].
labels: A tensor with shape [batch_size, length, 1, 1].
... | [
"Used",
"to",
"evaluate",
"the",
"VQA",
"accuracy",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L313-L343 |
22,612 | tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | set_precision | def set_precision(predictions, labels,
weights_fn=common_layers.weights_nonzero):
"""Precision of set predictions.
Args:
predictions : A Tensor of scores of shape [batch, nlabels].
labels: A Tensor of int32s giving true set elements,
of shape [batch, seq_length].
weights_fn: A f... | python | def set_precision(predictions, labels,
weights_fn=common_layers.weights_nonzero):
"""Precision of set predictions.
Args:
predictions : A Tensor of scores of shape [batch, nlabels].
labels: A Tensor of int32s giving true set elements,
of shape [batch, seq_length].
weights_fn: A f... | [
"def",
"set_precision",
"(",
"predictions",
",",
"labels",
",",
"weights_fn",
"=",
"common_layers",
".",
"weights_nonzero",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"set_precision\"",
",",
"values",
"=",
"[",
"predictions",
",",
"labels",
"]",
")"... | Precision of set predictions.
Args:
predictions : A Tensor of scores of shape [batch, nlabels].
labels: A Tensor of int32s giving true set elements,
of shape [batch, seq_length].
weights_fn: A function to weight the elements.
Returns:
hits: A Tensor of shape [batch, nlabels].
weights: A ... | [
"Precision",
"of",
"set",
"predictions",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L351-L371 |
22,613 | tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | image_summary | def image_summary(predictions, targets, hparams):
"""Reshapes predictions and passes it to tensorboard.
Args:
predictions : The predicted image (logits).
targets : The ground truth.
hparams: model hparams.
Returns:
summary_proto: containing the summary images.
weights: A Tensor of zeros of t... | python | def image_summary(predictions, targets, hparams):
"""Reshapes predictions and passes it to tensorboard.
Args:
predictions : The predicted image (logits).
targets : The ground truth.
hparams: model hparams.
Returns:
summary_proto: containing the summary images.
weights: A Tensor of zeros of t... | [
"def",
"image_summary",
"(",
"predictions",
",",
"targets",
",",
"hparams",
")",
":",
"del",
"hparams",
"results",
"=",
"tf",
".",
"cast",
"(",
"tf",
".",
"argmax",
"(",
"predictions",
",",
"axis",
"=",
"-",
"1",
")",
",",
"tf",
".",
"uint8",
")",
... | Reshapes predictions and passes it to tensorboard.
Args:
predictions : The predicted image (logits).
targets : The ground truth.
hparams: model hparams.
Returns:
summary_proto: containing the summary images.
weights: A Tensor of zeros of the same shape as predictions. | [
"Reshapes",
"predictions",
"and",
"passes",
"it",
"to",
"tensorboard",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L396-L414 |
22,614 | tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | softmax_cross_entropy_one_hot | def softmax_cross_entropy_one_hot(logits, labels, weights_fn=None):
"""Calculate softmax cross entropy given one-hot labels and logits.
Args:
logits: Tensor of size [batch-size, o=1, p=1, num-classes]
labels: Tensor of size [batch-size, o=1, p=1, num-classes]
weights_fn: Function that takes in labels a... | python | def softmax_cross_entropy_one_hot(logits, labels, weights_fn=None):
"""Calculate softmax cross entropy given one-hot labels and logits.
Args:
logits: Tensor of size [batch-size, o=1, p=1, num-classes]
labels: Tensor of size [batch-size, o=1, p=1, num-classes]
weights_fn: Function that takes in labels a... | [
"def",
"softmax_cross_entropy_one_hot",
"(",
"logits",
",",
"labels",
",",
"weights_fn",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"softmax_cross_entropy_one_hot\"",
",",
"values",
"=",
"[",
"logits",
",",
"labels",
"]",
")",
":",
"del... | Calculate softmax cross entropy given one-hot labels and logits.
Args:
logits: Tensor of size [batch-size, o=1, p=1, num-classes]
labels: Tensor of size [batch-size, o=1, p=1, num-classes]
weights_fn: Function that takes in labels and weighs examples (unused)
Returns:
cross-entropy (scalar), weight... | [
"Calculate",
"softmax",
"cross",
"entropy",
"given",
"one",
"-",
"hot",
"labels",
"and",
"logits",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L417-L432 |
22,615 | tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | sigmoid_accuracy_one_hot | def sigmoid_accuracy_one_hot(logits, labels, weights_fn=None):
"""Calculate accuracy for a set, given one-hot labels and logits.
Args:
logits: Tensor of size [batch-size, o=1, p=1, num-classes]
labels: Tensor of size [batch-size, o=1, p=1, num-classes]
weights_fn: Function that takes in labels and weig... | python | def sigmoid_accuracy_one_hot(logits, labels, weights_fn=None):
"""Calculate accuracy for a set, given one-hot labels and logits.
Args:
logits: Tensor of size [batch-size, o=1, p=1, num-classes]
labels: Tensor of size [batch-size, o=1, p=1, num-classes]
weights_fn: Function that takes in labels and weig... | [
"def",
"sigmoid_accuracy_one_hot",
"(",
"logits",
",",
"labels",
",",
"weights_fn",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"sigmoid_accuracy_one_hot\"",
",",
"values",
"=",
"[",
"logits",
",",
"labels",
"]",
")",
":",
"del",
"weig... | Calculate accuracy for a set, given one-hot labels and logits.
Args:
logits: Tensor of size [batch-size, o=1, p=1, num-classes]
labels: Tensor of size [batch-size, o=1, p=1, num-classes]
weights_fn: Function that takes in labels and weighs examples (unused)
Returns:
accuracy (scalar), weights | [
"Calculate",
"accuracy",
"for",
"a",
"set",
"given",
"one",
"-",
"hot",
"labels",
"and",
"logits",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L435-L451 |
22,616 | tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | sigmoid_recall_one_hot | def sigmoid_recall_one_hot(logits, labels, weights_fn=None):
"""Calculate recall for a set, given one-hot labels and logits.
Predictions are converted to one-hot,
as predictions[example][arg-max(example)] = 1
Args:
logits: Tensor of size [batch-size, o=1, p=1, num-classes]
labels: Tensor of size [batc... | python | def sigmoid_recall_one_hot(logits, labels, weights_fn=None):
"""Calculate recall for a set, given one-hot labels and logits.
Predictions are converted to one-hot,
as predictions[example][arg-max(example)] = 1
Args:
logits: Tensor of size [batch-size, o=1, p=1, num-classes]
labels: Tensor of size [batc... | [
"def",
"sigmoid_recall_one_hot",
"(",
"logits",
",",
"labels",
",",
"weights_fn",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"sigmoid_recall_one_hot\"",
",",
"values",
"=",
"[",
"logits",
",",
"labels",
"]",
")",
":",
"del",
"weights_... | Calculate recall for a set, given one-hot labels and logits.
Predictions are converted to one-hot,
as predictions[example][arg-max(example)] = 1
Args:
logits: Tensor of size [batch-size, o=1, p=1, num-classes]
labels: Tensor of size [batch-size, o=1, p=1, num-classes]
weights_fn: Function that takes... | [
"Calculate",
"recall",
"for",
"a",
"set",
"given",
"one",
"-",
"hot",
"labels",
"and",
"logits",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L477-L497 |
22,617 | tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | sigmoid_cross_entropy_one_hot | def sigmoid_cross_entropy_one_hot(logits, labels, weights_fn=None):
"""Calculate sigmoid cross entropy for one-hot lanels and logits.
Args:
logits: Tensor of size [batch-size, o=1, p=1, num-classes]
labels: Tensor of size [batch-size, o=1, p=1, num-classes]
weights_fn: Function that takes in labels and... | python | def sigmoid_cross_entropy_one_hot(logits, labels, weights_fn=None):
"""Calculate sigmoid cross entropy for one-hot lanels and logits.
Args:
logits: Tensor of size [batch-size, o=1, p=1, num-classes]
labels: Tensor of size [batch-size, o=1, p=1, num-classes]
weights_fn: Function that takes in labels and... | [
"def",
"sigmoid_cross_entropy_one_hot",
"(",
"logits",
",",
"labels",
",",
"weights_fn",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"sigmoid_cross_entropy_one_hot\"",
",",
"values",
"=",
"[",
"logits",
",",
"labels",
"]",
")",
":",
"del... | Calculate sigmoid cross entropy for one-hot lanels and logits.
Args:
logits: Tensor of size [batch-size, o=1, p=1, num-classes]
labels: Tensor of size [batch-size, o=1, p=1, num-classes]
weights_fn: Function that takes in labels and weighs examples (unused)
Returns:
cross_entropy (scalar), weights | [
"Calculate",
"sigmoid",
"cross",
"entropy",
"for",
"one",
"-",
"hot",
"lanels",
"and",
"logits",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L500-L515 |
22,618 | tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | roc_auc | def roc_auc(logits, labels, weights_fn=None):
"""Calculate ROC AUC.
Requires binary classes.
Args:
logits: Tensor of size [batch_size, 1, 1, num_classes]
labels: Tensor of size [batch_size, 1, 1, num_classes]
weights_fn: Function that takes in labels and weighs examples (unused)
Returns:
ROC A... | python | def roc_auc(logits, labels, weights_fn=None):
"""Calculate ROC AUC.
Requires binary classes.
Args:
logits: Tensor of size [batch_size, 1, 1, num_classes]
labels: Tensor of size [batch_size, 1, 1, num_classes]
weights_fn: Function that takes in labels and weighs examples (unused)
Returns:
ROC A... | [
"def",
"roc_auc",
"(",
"logits",
",",
"labels",
",",
"weights_fn",
"=",
"None",
")",
":",
"del",
"weights_fn",
"with",
"tf",
".",
"variable_scope",
"(",
"\"roc_auc\"",
",",
"values",
"=",
"[",
"logits",
",",
"labels",
"]",
")",
":",
"predictions",
"=",
... | Calculate ROC AUC.
Requires binary classes.
Args:
logits: Tensor of size [batch_size, 1, 1, num_classes]
labels: Tensor of size [batch_size, 1, 1, num_classes]
weights_fn: Function that takes in labels and weighs examples (unused)
Returns:
ROC AUC (scalar), weights | [
"Calculate",
"ROC",
"AUC",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L518-L534 |
22,619 | tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | create_evaluation_metrics | def create_evaluation_metrics(problems, model_hparams):
"""Creates the evaluation metrics for the model.
Args:
problems: List of Problem instances.
model_hparams: a set of hparams.
Returns:
dict<metric name, metric function>. The metric functions have signature
(Tensor predictions, features) -> ... | python | def create_evaluation_metrics(problems, model_hparams):
"""Creates the evaluation metrics for the model.
Args:
problems: List of Problem instances.
model_hparams: a set of hparams.
Returns:
dict<metric name, metric function>. The metric functions have signature
(Tensor predictions, features) -> ... | [
"def",
"create_evaluation_metrics",
"(",
"problems",
",",
"model_hparams",
")",
":",
"def",
"reduce_dimensions",
"(",
"predictions",
",",
"labels",
")",
":",
"\"\"\"Reduce dimensions for high-dimensional predictions and labels.\"\"\"",
"# We will treat first dimensions as batch. On... | Creates the evaluation metrics for the model.
Args:
problems: List of Problem instances.
model_hparams: a set of hparams.
Returns:
dict<metric name, metric function>. The metric functions have signature
(Tensor predictions, features) -> (metric Tensor, update op), where features
is a dict with... | [
"Creates",
"the",
"evaluation",
"metrics",
"for",
"the",
"model",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L537-L638 |
22,620 | tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | create_eager_metrics_for_problem | def create_eager_metrics_for_problem(problem, model_hparams):
"""See create_eager_metrics."""
metric_fns = problem.eval_metric_fns(model_hparams)
problem_hparams = problem.get_hparams(model_hparams)
target_modality = problem_hparams.modality["targets"]
weights_fn = model_hparams.weights_fn.get(
"targets... | python | def create_eager_metrics_for_problem(problem, model_hparams):
"""See create_eager_metrics."""
metric_fns = problem.eval_metric_fns(model_hparams)
problem_hparams = problem.get_hparams(model_hparams)
target_modality = problem_hparams.modality["targets"]
weights_fn = model_hparams.weights_fn.get(
"targets... | [
"def",
"create_eager_metrics_for_problem",
"(",
"problem",
",",
"model_hparams",
")",
":",
"metric_fns",
"=",
"problem",
".",
"eval_metric_fns",
"(",
"model_hparams",
")",
"problem_hparams",
"=",
"problem",
".",
"get_hparams",
"(",
"model_hparams",
")",
"target_modali... | See create_eager_metrics. | [
"See",
"create_eager_metrics",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L641-L649 |
22,621 | tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | word_error_rate | def word_error_rate(raw_predictions,
labels,
lookup=None,
weights_fn=common_layers.weights_nonzero):
"""Calculate word error rate.
Args:
raw_predictions: The raw predictions.
labels: The actual labels.
lookup: A tf.constant mapping indices to ... | python | def word_error_rate(raw_predictions,
labels,
lookup=None,
weights_fn=common_layers.weights_nonzero):
"""Calculate word error rate.
Args:
raw_predictions: The raw predictions.
labels: The actual labels.
lookup: A tf.constant mapping indices to ... | [
"def",
"word_error_rate",
"(",
"raw_predictions",
",",
"labels",
",",
"lookup",
"=",
"None",
",",
"weights_fn",
"=",
"common_layers",
".",
"weights_nonzero",
")",
":",
"def",
"from_tokens",
"(",
"raw",
",",
"lookup_",
")",
":",
"gathered",
"=",
"tf",
".",
... | Calculate word error rate.
Args:
raw_predictions: The raw predictions.
labels: The actual labels.
lookup: A tf.constant mapping indices to output tokens.
weights_fn: Weighting function.
Returns:
The word error rate. | [
"Calculate",
"word",
"error",
"rate",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L704-L761 |
22,622 | tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | pearson_correlation_coefficient | def pearson_correlation_coefficient(predictions, labels, weights_fn=None):
"""Calculate pearson correlation coefficient.
Args:
predictions: The raw predictions.
labels: The actual labels.
weights_fn: Weighting function.
Returns:
The pearson correlation coefficient.
"""
del weights_fn
_, pe... | python | def pearson_correlation_coefficient(predictions, labels, weights_fn=None):
"""Calculate pearson correlation coefficient.
Args:
predictions: The raw predictions.
labels: The actual labels.
weights_fn: Weighting function.
Returns:
The pearson correlation coefficient.
"""
del weights_fn
_, pe... | [
"def",
"pearson_correlation_coefficient",
"(",
"predictions",
",",
"labels",
",",
"weights_fn",
"=",
"None",
")",
":",
"del",
"weights_fn",
"_",
",",
"pearson",
"=",
"tf",
".",
"contrib",
".",
"metrics",
".",
"streaming_pearson_correlation",
"(",
"predictions",
... | Calculate pearson correlation coefficient.
Args:
predictions: The raw predictions.
labels: The actual labels.
weights_fn: Weighting function.
Returns:
The pearson correlation coefficient. | [
"Calculate",
"pearson",
"correlation",
"coefficient",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L764-L778 |
22,623 | tensorflow/tensor2tensor | tensor2tensor/models/research/attention_lm.py | attention_lm_decoder | def attention_lm_decoder(decoder_input,
decoder_self_attention_bias,
hparams,
name="decoder"):
"""A stack of attention_lm layers.
Args:
decoder_input: a Tensor
decoder_self_attention_bias: bias Tensor for self-attention
(see c... | python | def attention_lm_decoder(decoder_input,
decoder_self_attention_bias,
hparams,
name="decoder"):
"""A stack of attention_lm layers.
Args:
decoder_input: a Tensor
decoder_self_attention_bias: bias Tensor for self-attention
(see c... | [
"def",
"attention_lm_decoder",
"(",
"decoder_input",
",",
"decoder_self_attention_bias",
",",
"hparams",
",",
"name",
"=",
"\"decoder\"",
")",
":",
"x",
"=",
"decoder_input",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
")",
":",
"for",
"layer",
"in",
"ra... | A stack of attention_lm layers.
Args:
decoder_input: a Tensor
decoder_self_attention_bias: bias Tensor for self-attention
(see common_attention.attention_bias())
hparams: hyperparameters for model
name: a string
Returns:
y: a Tensors | [
"A",
"stack",
"of",
"attention_lm",
"layers",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm.py#L92-L127 |
22,624 | tensorflow/tensor2tensor | tensor2tensor/models/research/attention_lm.py | attention_lm_small | def attention_lm_small():
"""Cheap model.
on lm1b_32k:
45M params
2 steps/sec on [GeForce GTX TITAN X]
Returns:
an hparams object.
"""
hparams = attention_lm_base()
hparams.num_hidden_layers = 4
hparams.hidden_size = 512
hparams.filter_size = 2048
hparams.layer_prepostprocess_dropout ... | python | def attention_lm_small():
"""Cheap model.
on lm1b_32k:
45M params
2 steps/sec on [GeForce GTX TITAN X]
Returns:
an hparams object.
"""
hparams = attention_lm_base()
hparams.num_hidden_layers = 4
hparams.hidden_size = 512
hparams.filter_size = 2048
hparams.layer_prepostprocess_dropout ... | [
"def",
"attention_lm_small",
"(",
")",
":",
"hparams",
"=",
"attention_lm_base",
"(",
")",
"hparams",
".",
"num_hidden_layers",
"=",
"4",
"hparams",
".",
"hidden_size",
"=",
"512",
"hparams",
".",
"filter_size",
"=",
"2048",
"hparams",
".",
"layer_prepostprocess... | Cheap model.
on lm1b_32k:
45M params
2 steps/sec on [GeForce GTX TITAN X]
Returns:
an hparams object. | [
"Cheap",
"model",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm.py#L167-L182 |
22,625 | tensorflow/tensor2tensor | tensor2tensor/utils/bleu_hook.py | bleu_score | def bleu_score(predictions, labels, **unused_kwargs):
"""BLEU score computation between labels and predictions.
An approximate BLEU scoring method since we do not glue word pieces or
decode the ids and tokenize the output. By default, we use ngram order of 4
and use brevity penalty. Also, this does not have be... | python | def bleu_score(predictions, labels, **unused_kwargs):
"""BLEU score computation between labels and predictions.
An approximate BLEU scoring method since we do not glue word pieces or
decode the ids and tokenize the output. By default, we use ngram order of 4
and use brevity penalty. Also, this does not have be... | [
"def",
"bleu_score",
"(",
"predictions",
",",
"labels",
",",
"*",
"*",
"unused_kwargs",
")",
":",
"outputs",
"=",
"tf",
".",
"to_int32",
"(",
"tf",
".",
"argmax",
"(",
"predictions",
",",
"axis",
"=",
"-",
"1",
")",
")",
"# Convert the outputs and labels t... | BLEU score computation between labels and predictions.
An approximate BLEU scoring method since we do not glue word pieces or
decode the ids and tokenize the output. By default, we use ngram order of 4
and use brevity penalty. Also, this does not have beam search.
Args:
predictions: tensor, model predicti... | [
"BLEU",
"score",
"computation",
"between",
"labels",
"and",
"predictions",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L132-L152 |
22,626 | tensorflow/tensor2tensor | tensor2tensor/utils/bleu_hook.py | bleu_tokenize | def bleu_tokenize(string):
r"""Tokenize a string following the official BLEU implementation.
See https://github.com/moses-smt/mosesdecoder/"
"blob/master/scripts/generic/mteval-v14.pl#L954-L983
In our case, the input string is expected to be just one line
and no HTML entities de-escaping is needed.
... | python | def bleu_tokenize(string):
r"""Tokenize a string following the official BLEU implementation.
See https://github.com/moses-smt/mosesdecoder/"
"blob/master/scripts/generic/mteval-v14.pl#L954-L983
In our case, the input string is expected to be just one line
and no HTML entities de-escaping is needed.
... | [
"def",
"bleu_tokenize",
"(",
"string",
")",
":",
"string",
"=",
"uregex",
".",
"nondigit_punct_re",
".",
"sub",
"(",
"r\"\\1 \\2 \"",
",",
"string",
")",
"string",
"=",
"uregex",
".",
"punct_nondigit_re",
".",
"sub",
"(",
"r\" \\1 \\2\"",
",",
"string",
")",... | r"""Tokenize a string following the official BLEU implementation.
See https://github.com/moses-smt/mosesdecoder/"
"blob/master/scripts/generic/mteval-v14.pl#L954-L983
In our case, the input string is expected to be just one line
and no HTML entities de-escaping is needed.
So we just tokenize on punc... | [
"r",
"Tokenize",
"a",
"string",
"following",
"the",
"official",
"BLEU",
"implementation",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L172-L199 |
22,627 | tensorflow/tensor2tensor | tensor2tensor/utils/bleu_hook.py | _try_twice_tf_glob | def _try_twice_tf_glob(pattern):
"""Glob twice, first time possibly catching `NotFoundError`.
tf.gfile.Glob may crash with
```
tensorflow.python.framework.errors_impl.NotFoundError:
xy/model.ckpt-1130761_temp_9cb4cb0b0f5f4382b5ea947aadfb7a40;
No such file or directory
```
Standard glob.glob does not ... | python | def _try_twice_tf_glob(pattern):
"""Glob twice, first time possibly catching `NotFoundError`.
tf.gfile.Glob may crash with
```
tensorflow.python.framework.errors_impl.NotFoundError:
xy/model.ckpt-1130761_temp_9cb4cb0b0f5f4382b5ea947aadfb7a40;
No such file or directory
```
Standard glob.glob does not ... | [
"def",
"_try_twice_tf_glob",
"(",
"pattern",
")",
":",
"try",
":",
"return",
"tf",
".",
"gfile",
".",
"Glob",
"(",
"pattern",
")",
"except",
"tf",
".",
"errors",
".",
"NotFoundError",
":",
"return",
"tf",
".",
"gfile",
".",
"Glob",
"(",
"pattern",
")"
... | Glob twice, first time possibly catching `NotFoundError`.
tf.gfile.Glob may crash with
```
tensorflow.python.framework.errors_impl.NotFoundError:
xy/model.ckpt-1130761_temp_9cb4cb0b0f5f4382b5ea947aadfb7a40;
No such file or directory
```
Standard glob.glob does not have this bug, but does not handle mul... | [
"Glob",
"twice",
"first",
"time",
"possibly",
"catching",
"NotFoundError",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L221-L245 |
22,628 | tensorflow/tensor2tensor | tensor2tensor/utils/bleu_hook.py | _read_stepfiles_list | def _read_stepfiles_list(path_prefix, path_suffix=".index", min_steps=0):
"""Return list of StepFiles sorted by step from files at path_prefix."""
stepfiles = []
for filename in _try_twice_tf_glob(path_prefix + "*-[0-9]*" + path_suffix):
basename = filename[:-len(path_suffix)] if path_suffix else filename
... | python | def _read_stepfiles_list(path_prefix, path_suffix=".index", min_steps=0):
"""Return list of StepFiles sorted by step from files at path_prefix."""
stepfiles = []
for filename in _try_twice_tf_glob(path_prefix + "*-[0-9]*" + path_suffix):
basename = filename[:-len(path_suffix)] if path_suffix else filename
... | [
"def",
"_read_stepfiles_list",
"(",
"path_prefix",
",",
"path_suffix",
"=",
"\".index\"",
",",
"min_steps",
"=",
"0",
")",
":",
"stepfiles",
"=",
"[",
"]",
"for",
"filename",
"in",
"_try_twice_tf_glob",
"(",
"path_prefix",
"+",
"\"*-[0-9]*\"",
"+",
"path_suffix"... | Return list of StepFiles sorted by step from files at path_prefix. | [
"Return",
"list",
"of",
"StepFiles",
"sorted",
"by",
"step",
"from",
"files",
"at",
"path_prefix",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L248-L264 |
22,629 | tensorflow/tensor2tensor | tensor2tensor/utils/bleu_hook.py | stepfiles_iterator | def stepfiles_iterator(path_prefix, wait_minutes=0, min_steps=0,
path_suffix=".index", sleep_sec=10):
"""Continuously yield new files with steps in filename as they appear.
This is useful for checkpoint files or other files whose names differ just in
an integer marking the number of steps ... | python | def stepfiles_iterator(path_prefix, wait_minutes=0, min_steps=0,
path_suffix=".index", sleep_sec=10):
"""Continuously yield new files with steps in filename as they appear.
This is useful for checkpoint files or other files whose names differ just in
an integer marking the number of steps ... | [
"def",
"stepfiles_iterator",
"(",
"path_prefix",
",",
"wait_minutes",
"=",
"0",
",",
"min_steps",
"=",
"0",
",",
"path_suffix",
"=",
"\".index\"",
",",
"sleep_sec",
"=",
"10",
")",
":",
"# Wildcard D*-[0-9]* does not match D/x-1, so if D is a directory let",
"# path_pre... | Continuously yield new files with steps in filename as they appear.
This is useful for checkpoint files or other files whose names differ just in
an integer marking the number of steps and match the wildcard path_prefix +
"*-[0-9]*" + path_suffix.
Unlike `tf.contrib.training.checkpoints_iterator`, this implem... | [
"Continuously",
"yield",
"new",
"files",
"with",
"steps",
"in",
"filename",
"as",
"they",
"appear",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/bleu_hook.py#L267-L317 |
22,630 | tensorflow/tensor2tensor | tensor2tensor/data_generators/vqa.py | _get_vqa_v2_annotations | def _get_vqa_v2_annotations(directory,
annotation_url,
annotation_filename="vqa_v2.tar.gz"):
"""Extract the VQA V2 annotation files to directory unless it's there."""
annotation_file = generator_utils.maybe_download_from_drive(
directory, annotation_file... | python | def _get_vqa_v2_annotations(directory,
annotation_url,
annotation_filename="vqa_v2.tar.gz"):
"""Extract the VQA V2 annotation files to directory unless it's there."""
annotation_file = generator_utils.maybe_download_from_drive(
directory, annotation_file... | [
"def",
"_get_vqa_v2_annotations",
"(",
"directory",
",",
"annotation_url",
",",
"annotation_filename",
"=",
"\"vqa_v2.tar.gz\"",
")",
":",
"annotation_file",
"=",
"generator_utils",
".",
"maybe_download_from_drive",
"(",
"directory",
",",
"annotation_filename",
",",
"anno... | Extract the VQA V2 annotation files to directory unless it's there. | [
"Extract",
"the",
"VQA",
"V2",
"annotation",
"files",
"to",
"directory",
"unless",
"it",
"s",
"there",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa.py#L44-L51 |
22,631 | tensorflow/tensor2tensor | tensor2tensor/data_generators/vqa.py | _get_vqa_v2_image_raw_dataset | def _get_vqa_v2_image_raw_dataset(directory, image_root_url, image_urls):
"""Extract the VQA V2 image data set to directory unless it's there."""
for url in image_urls:
filename = os.path.basename(url)
download_url = os.path.join(image_root_url, url)
path = generator_utils.maybe_download(directory, file... | python | def _get_vqa_v2_image_raw_dataset(directory, image_root_url, image_urls):
"""Extract the VQA V2 image data set to directory unless it's there."""
for url in image_urls:
filename = os.path.basename(url)
download_url = os.path.join(image_root_url, url)
path = generator_utils.maybe_download(directory, file... | [
"def",
"_get_vqa_v2_image_raw_dataset",
"(",
"directory",
",",
"image_root_url",
",",
"image_urls",
")",
":",
"for",
"url",
"in",
"image_urls",
":",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"url",
")",
"download_url",
"=",
"os",
".",
"path",... | Extract the VQA V2 image data set to directory unless it's there. | [
"Extract",
"the",
"VQA",
"V2",
"image",
"data",
"set",
"to",
"directory",
"unless",
"it",
"s",
"there",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa.py#L54-L62 |
22,632 | tensorflow/tensor2tensor | tensor2tensor/data_generators/vqa.py | _get_vqa_v2_image_feature_dataset | def _get_vqa_v2_image_feature_dataset(
directory, feature_url, feature_filename="mscoco_feat.tar.gz"):
"""Extract the VQA V2 feature data set to directory unless it's there."""
feature_file = generator_utils.maybe_download_from_drive(
directory, feature_filename, feature_url)
with tarfile.open(feature_f... | python | def _get_vqa_v2_image_feature_dataset(
directory, feature_url, feature_filename="mscoco_feat.tar.gz"):
"""Extract the VQA V2 feature data set to directory unless it's there."""
feature_file = generator_utils.maybe_download_from_drive(
directory, feature_filename, feature_url)
with tarfile.open(feature_f... | [
"def",
"_get_vqa_v2_image_feature_dataset",
"(",
"directory",
",",
"feature_url",
",",
"feature_filename",
"=",
"\"mscoco_feat.tar.gz\"",
")",
":",
"feature_file",
"=",
"generator_utils",
".",
"maybe_download_from_drive",
"(",
"directory",
",",
"feature_filename",
",",
"f... | Extract the VQA V2 feature data set to directory unless it's there. | [
"Extract",
"the",
"VQA",
"V2",
"feature",
"data",
"set",
"to",
"directory",
"unless",
"it",
"s",
"there",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa.py#L65-L71 |
22,633 | tensorflow/tensor2tensor | tensor2tensor/utils/hparam.py | _parse_fail | def _parse_fail(name, var_type, value, values):
"""Helper function for raising a value error for bad assignment."""
raise ValueError(
'Could not parse hparam \'%s\' of type \'%s\' with value \'%s\' in %s' %
(name, var_type.__name__, value, values)) | python | def _parse_fail(name, var_type, value, values):
"""Helper function for raising a value error for bad assignment."""
raise ValueError(
'Could not parse hparam \'%s\' of type \'%s\' with value \'%s\' in %s' %
(name, var_type.__name__, value, values)) | [
"def",
"_parse_fail",
"(",
"name",
",",
"var_type",
",",
"value",
",",
"values",
")",
":",
"raise",
"ValueError",
"(",
"'Could not parse hparam \\'%s\\' of type \\'%s\\' with value \\'%s\\' in %s'",
"%",
"(",
"name",
",",
"var_type",
".",
"__name__",
",",
"value",
"... | Helper function for raising a value error for bad assignment. | [
"Helper",
"function",
"for",
"raising",
"a",
"value",
"error",
"for",
"bad",
"assignment",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L42-L46 |
22,634 | tensorflow/tensor2tensor | tensor2tensor/utils/hparam.py | _process_scalar_value | def _process_scalar_value(name, parse_fn, var_type, m_dict, values,
results_dictionary):
"""Update results_dictionary with a scalar value.
Used to update the results_dictionary to be returned by parse_values when
encountering a clause with a scalar RHS (e.g. "s=5" or "arr[0]=5".)
Mu... | python | def _process_scalar_value(name, parse_fn, var_type, m_dict, values,
results_dictionary):
"""Update results_dictionary with a scalar value.
Used to update the results_dictionary to be returned by parse_values when
encountering a clause with a scalar RHS (e.g. "s=5" or "arr[0]=5".)
Mu... | [
"def",
"_process_scalar_value",
"(",
"name",
",",
"parse_fn",
",",
"var_type",
",",
"m_dict",
",",
"values",
",",
"results_dictionary",
")",
":",
"try",
":",
"parsed_value",
"=",
"parse_fn",
"(",
"m_dict",
"[",
"'val'",
"]",
")",
"except",
"ValueError",
":",... | Update results_dictionary with a scalar value.
Used to update the results_dictionary to be returned by parse_values when
encountering a clause with a scalar RHS (e.g. "s=5" or "arr[0]=5".)
Mutates results_dictionary.
Args:
name: Name of variable in assignment ("s" or "arr").
parse_fn: Function for p... | [
"Update",
"results_dictionary",
"with",
"a",
"scalar",
"value",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L55-L101 |
22,635 | tensorflow/tensor2tensor | tensor2tensor/utils/hparam.py | _process_list_value | def _process_list_value(name, parse_fn, var_type, m_dict, values,
results_dictionary):
"""Update results_dictionary from a list of values.
Used to update results_dictionary to be returned by parse_values when
encountering a clause with a list RHS (e.g. "arr=[1,2,3]".)
Mutates results_... | python | def _process_list_value(name, parse_fn, var_type, m_dict, values,
results_dictionary):
"""Update results_dictionary from a list of values.
Used to update results_dictionary to be returned by parse_values when
encountering a clause with a list RHS (e.g. "arr=[1,2,3]".)
Mutates results_... | [
"def",
"_process_list_value",
"(",
"name",
",",
"parse_fn",
",",
"var_type",
",",
"m_dict",
",",
"values",
",",
"results_dictionary",
")",
":",
"if",
"m_dict",
"[",
"'index'",
"]",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"'Assignment of a list to... | Update results_dictionary from a list of values.
Used to update results_dictionary to be returned by parse_values when
encountering a clause with a list RHS (e.g. "arr=[1,2,3]".)
Mutates results_dictionary.
Args:
name: Name of variable in assignment ("arr").
parse_fn: Function for parsing individual... | [
"Update",
"results_dictionary",
"from",
"a",
"list",
"of",
"values",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L104-L135 |
22,636 | tensorflow/tensor2tensor | tensor2tensor/utils/hparam.py | _cast_to_type_if_compatible | def _cast_to_type_if_compatible(name, param_type, value):
"""Cast hparam to the provided type, if compatible.
Args:
name: Name of the hparam to be cast.
param_type: The type of the hparam.
value: The value to be cast, if compatible.
Returns:
The result of casting `value` to `param_type`.
Rais... | python | def _cast_to_type_if_compatible(name, param_type, value):
"""Cast hparam to the provided type, if compatible.
Args:
name: Name of the hparam to be cast.
param_type: The type of the hparam.
value: The value to be cast, if compatible.
Returns:
The result of casting `value` to `param_type`.
Rais... | [
"def",
"_cast_to_type_if_compatible",
"(",
"name",
",",
"param_type",
",",
"value",
")",
":",
"fail_msg",
"=",
"(",
"\"Could not cast hparam '%s' of type '%s' from value %r\"",
"%",
"(",
"name",
",",
"param_type",
",",
"value",
")",
")",
"# Some callers use None, for wh... | Cast hparam to the provided type, if compatible.
Args:
name: Name of the hparam to be cast.
param_type: The type of the hparam.
value: The value to be cast, if compatible.
Returns:
The result of casting `value` to `param_type`.
Raises:
ValueError: If the type of `value` is not compatible wi... | [
"Cast",
"hparam",
"to",
"the",
"provided",
"type",
"if",
"compatible",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L138-L183 |
22,637 | tensorflow/tensor2tensor | tensor2tensor/utils/hparam.py | parse_values | def parse_values(values, type_map, ignore_unknown=False):
"""Parses hyperparameter values from a string into a python map.
`values` is a string containing comma-separated `name=value` pairs.
For each pair, the value of the hyperparameter named `name` is set to
`value`.
If a hyperparameter name appears multi... | python | def parse_values(values, type_map, ignore_unknown=False):
"""Parses hyperparameter values from a string into a python map.
`values` is a string containing comma-separated `name=value` pairs.
For each pair, the value of the hyperparameter named `name` is set to
`value`.
If a hyperparameter name appears multi... | [
"def",
"parse_values",
"(",
"values",
",",
"type_map",
",",
"ignore_unknown",
"=",
"False",
")",
":",
"results_dictionary",
"=",
"{",
"}",
"pos",
"=",
"0",
"while",
"pos",
"<",
"len",
"(",
"values",
")",
":",
"m",
"=",
"PARAM_RE",
".",
"match",
"(",
... | Parses hyperparameter values from a string into a python map.
`values` is a string containing comma-separated `name=value` pairs.
For each pair, the value of the hyperparameter named `name` is set to
`value`.
If a hyperparameter name appears multiple times in `values`, a ValueError
is raised (e.g. 'a=1,a=2'... | [
"Parses",
"hyperparameter",
"values",
"from",
"a",
"string",
"into",
"a",
"python",
"map",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L186-L298 |
22,638 | tensorflow/tensor2tensor | tensor2tensor/utils/hparam.py | HParams.set_hparam | def set_hparam(self, name, value):
"""Set the value of an existing hyperparameter.
This function verifies that the type of the value matches the type of the
existing hyperparameter.
Args:
name: Name of the hyperparameter.
value: New value of the hyperparameter.
Raises:
KeyError:... | python | def set_hparam(self, name, value):
"""Set the value of an existing hyperparameter.
This function verifies that the type of the value matches the type of the
existing hyperparameter.
Args:
name: Name of the hyperparameter.
value: New value of the hyperparameter.
Raises:
KeyError:... | [
"def",
"set_hparam",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"param_type",
",",
"is_list",
"=",
"self",
".",
"_hparam_types",
"[",
"name",
"]",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"if",
"not",
"is_list",
":",
"raise",
"... | Set the value of an existing hyperparameter.
This function verifies that the type of the value matches the type of the
existing hyperparameter.
Args:
name: Name of the hyperparameter.
value: New value of the hyperparameter.
Raises:
KeyError: If the hyperparameter doesn't exist.
... | [
"Set",
"the",
"value",
"of",
"an",
"existing",
"hyperparameter",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L443-L468 |
22,639 | tensorflow/tensor2tensor | tensor2tensor/utils/hparam.py | HParams.del_hparam | def del_hparam(self, name):
"""Removes the hyperparameter with key 'name'.
Does nothing if it isn't present.
Args:
name: Name of the hyperparameter.
"""
if hasattr(self, name):
delattr(self, name)
del self._hparam_types[name] | python | def del_hparam(self, name):
"""Removes the hyperparameter with key 'name'.
Does nothing if it isn't present.
Args:
name: Name of the hyperparameter.
"""
if hasattr(self, name):
delattr(self, name)
del self._hparam_types[name] | [
"def",
"del_hparam",
"(",
"self",
",",
"name",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"name",
")",
":",
"delattr",
"(",
"self",
",",
"name",
")",
"del",
"self",
".",
"_hparam_types",
"[",
"name",
"]"
] | Removes the hyperparameter with key 'name'.
Does nothing if it isn't present.
Args:
name: Name of the hyperparameter. | [
"Removes",
"the",
"hyperparameter",
"with",
"key",
"name",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L470-L480 |
22,640 | tensorflow/tensor2tensor | tensor2tensor/utils/hparam.py | HParams.parse | def parse(self, values):
"""Override existing hyperparameter values, parsing new values from a string.
See parse_values for more detail on the allowed format for values.
Args:
values: String. Comma separated list of `name=value` pairs where 'value'
must follow the syntax described above.
... | python | def parse(self, values):
"""Override existing hyperparameter values, parsing new values from a string.
See parse_values for more detail on the allowed format for values.
Args:
values: String. Comma separated list of `name=value` pairs where 'value'
must follow the syntax described above.
... | [
"def",
"parse",
"(",
"self",
",",
"values",
")",
":",
"type_map",
"=",
"{",
"}",
"for",
"name",
",",
"t",
"in",
"self",
".",
"_hparam_types",
".",
"items",
"(",
")",
":",
"param_type",
",",
"_",
"=",
"t",
"type_map",
"[",
"name",
"]",
"=",
"param... | Override existing hyperparameter values, parsing new values from a string.
See parse_values for more detail on the allowed format for values.
Args:
values: String. Comma separated list of `name=value` pairs where 'value'
must follow the syntax described above.
Returns:
The `HParams` ... | [
"Override",
"existing",
"hyperparameter",
"values",
"parsing",
"new",
"values",
"from",
"a",
"string",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L482-L504 |
22,641 | tensorflow/tensor2tensor | tensor2tensor/utils/hparam.py | HParams.override_from_dict | def override_from_dict(self, values_dict):
"""Override existing hyperparameter values, parsing new values from a dictionary.
Args:
values_dict: Dictionary of name:value pairs.
Returns:
The `HParams` instance.
Raises:
KeyError: If a hyperparameter in `values_dict` doesn't exist.
... | python | def override_from_dict(self, values_dict):
"""Override existing hyperparameter values, parsing new values from a dictionary.
Args:
values_dict: Dictionary of name:value pairs.
Returns:
The `HParams` instance.
Raises:
KeyError: If a hyperparameter in `values_dict` doesn't exist.
... | [
"def",
"override_from_dict",
"(",
"self",
",",
"values_dict",
")",
":",
"for",
"name",
",",
"value",
"in",
"values_dict",
".",
"items",
"(",
")",
":",
"self",
".",
"set_hparam",
"(",
"name",
",",
"value",
")",
"return",
"self"
] | Override existing hyperparameter values, parsing new values from a dictionary.
Args:
values_dict: Dictionary of name:value pairs.
Returns:
The `HParams` instance.
Raises:
KeyError: If a hyperparameter in `values_dict` doesn't exist.
ValueError: If `values_dict` cannot be parsed. | [
"Override",
"existing",
"hyperparameter",
"values",
"parsing",
"new",
"values",
"from",
"a",
"dictionary",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L506-L521 |
22,642 | tensorflow/tensor2tensor | tensor2tensor/utils/hparam.py | HParams.to_json | def to_json(self, indent=None, separators=None, sort_keys=False):
"""Serializes the hyperparameters into JSON.
Args:
indent: If a non-negative integer, JSON array elements and object members
will be pretty-printed with that indent level. An indent level of 0, or
negative, will only insert... | python | def to_json(self, indent=None, separators=None, sort_keys=False):
"""Serializes the hyperparameters into JSON.
Args:
indent: If a non-negative integer, JSON array elements and object members
will be pretty-printed with that indent level. An indent level of 0, or
negative, will only insert... | [
"def",
"to_json",
"(",
"self",
",",
"indent",
"=",
"None",
",",
"separators",
"=",
"None",
",",
"sort_keys",
"=",
"False",
")",
":",
"def",
"remove_callables",
"(",
"x",
")",
":",
"\"\"\"Omit callable elements from input with arbitrary nesting.\"\"\"",
"if",
"isin... | Serializes the hyperparameters into JSON.
Args:
indent: If a non-negative integer, JSON array elements and object members
will be pretty-printed with that indent level. An indent level of 0, or
negative, will only insert newlines. `None` (the default) selects the
most compact represen... | [
"Serializes",
"the",
"hyperparameters",
"into",
"JSON",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L529-L556 |
22,643 | tensorflow/tensor2tensor | tensor2tensor/utils/hparam.py | HParams.parse_json | def parse_json(self, values_json):
"""Override existing hyperparameter values, parsing new values from a json object.
Args:
values_json: String containing a json object of name:value pairs.
Returns:
The `HParams` instance.
Raises:
KeyError: If a hyperparameter in `values_json` doesn... | python | def parse_json(self, values_json):
"""Override existing hyperparameter values, parsing new values from a json object.
Args:
values_json: String containing a json object of name:value pairs.
Returns:
The `HParams` instance.
Raises:
KeyError: If a hyperparameter in `values_json` doesn... | [
"def",
"parse_json",
"(",
"self",
",",
"values_json",
")",
":",
"values_map",
"=",
"json",
".",
"loads",
"(",
"values_json",
")",
"return",
"self",
".",
"override_from_dict",
"(",
"values_map",
")"
] | Override existing hyperparameter values, parsing new values from a json object.
Args:
values_json: String containing a json object of name:value pairs.
Returns:
The `HParams` instance.
Raises:
KeyError: If a hyperparameter in `values_json` doesn't exist.
ValueError: If `values_jso... | [
"Override",
"existing",
"hyperparameter",
"values",
"parsing",
"new",
"values",
"from",
"a",
"json",
"object",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L558-L572 |
22,644 | tensorflow/tensor2tensor | tensor2tensor/utils/hparam.py | HParams.values | def values(self):
"""Return the hyperparameter values as a Python dictionary.
Returns:
A dictionary with hyperparameter names as keys. The values are the
hyperparameter values.
"""
return {n: getattr(self, n) for n in self._hparam_types.keys()} | python | def values(self):
"""Return the hyperparameter values as a Python dictionary.
Returns:
A dictionary with hyperparameter names as keys. The values are the
hyperparameter values.
"""
return {n: getattr(self, n) for n in self._hparam_types.keys()} | [
"def",
"values",
"(",
"self",
")",
":",
"return",
"{",
"n",
":",
"getattr",
"(",
"self",
",",
"n",
")",
"for",
"n",
"in",
"self",
".",
"_hparam_types",
".",
"keys",
"(",
")",
"}"
] | Return the hyperparameter values as a Python dictionary.
Returns:
A dictionary with hyperparameter names as keys. The values are the
hyperparameter values. | [
"Return",
"the",
"hyperparameter",
"values",
"as",
"a",
"Python",
"dictionary",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L574-L581 |
22,645 | tensorflow/tensor2tensor | tensor2tensor/utils/hparam.py | HParams.get | def get(self, key, default=None):
"""Returns the value of `key` if it exists, else `default`."""
if key in self._hparam_types:
# Ensure that default is compatible with the parameter type.
if default is not None:
param_type, is_param_list = self._hparam_types[key]
type_str = 'list<%s>... | python | def get(self, key, default=None):
"""Returns the value of `key` if it exists, else `default`."""
if key in self._hparam_types:
# Ensure that default is compatible with the parameter type.
if default is not None:
param_type, is_param_list = self._hparam_types[key]
type_str = 'list<%s>... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"if",
"key",
"in",
"self",
".",
"_hparam_types",
":",
"# Ensure that default is compatible with the parameter type.",
"if",
"default",
"is",
"not",
"None",
":",
"param_type",
",",
"i... | Returns the value of `key` if it exists, else `default`. | [
"Returns",
"the",
"value",
"of",
"key",
"if",
"it",
"exists",
"else",
"default",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L583-L608 |
22,646 | tensorflow/tensor2tensor | tensor2tensor/utils/hparam.py | HParams._get_kind_name | def _get_kind_name(param_type, is_list):
"""Returns the field name given parameter type and is_list.
Args:
param_type: Data type of the hparam.
is_list: Whether this is a list.
Returns:
A string representation of the field name.
Raises:
ValueError: If parameter type is not rec... | python | def _get_kind_name(param_type, is_list):
"""Returns the field name given parameter type and is_list.
Args:
param_type: Data type of the hparam.
is_list: Whether this is a list.
Returns:
A string representation of the field name.
Raises:
ValueError: If parameter type is not rec... | [
"def",
"_get_kind_name",
"(",
"param_type",
",",
"is_list",
")",
":",
"if",
"issubclass",
"(",
"param_type",
",",
"bool",
")",
":",
"# This check must happen before issubclass(param_type, six.integer_types),",
"# since Python considers bool to be a subclass of int.",
"typename",
... | Returns the field name given parameter type and is_list.
Args:
param_type: Data type of the hparam.
is_list: Whether this is a list.
Returns:
A string representation of the field name.
Raises:
ValueError: If parameter type is not recognized. | [
"Returns",
"the",
"field",
"name",
"given",
"parameter",
"type",
"and",
"is_list",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparam.py#L620-L651 |
22,647 | tensorflow/tensor2tensor | tensor2tensor/trax/trainer.py | _default_output_dir | def _default_output_dir():
"""Default output directory."""
try:
dataset_name = gin.query_parameter("inputs.dataset_name")
except ValueError:
dataset_name = "random"
dir_name = "{model_name}_{dataset_name}_{timestamp}".format(
model_name=gin.query_parameter("train.model").configurable.name,
d... | python | def _default_output_dir():
"""Default output directory."""
try:
dataset_name = gin.query_parameter("inputs.dataset_name")
except ValueError:
dataset_name = "random"
dir_name = "{model_name}_{dataset_name}_{timestamp}".format(
model_name=gin.query_parameter("train.model").configurable.name,
d... | [
"def",
"_default_output_dir",
"(",
")",
":",
"try",
":",
"dataset_name",
"=",
"gin",
".",
"query_parameter",
"(",
"\"inputs.dataset_name\"",
")",
"except",
"ValueError",
":",
"dataset_name",
"=",
"\"random\"",
"dir_name",
"=",
"\"{model_name}_{dataset_name}_{timestamp}\... | Default output directory. | [
"Default",
"output",
"directory",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trainer.py#L48-L62 |
22,648 | tensorflow/tensor2tensor | tensor2tensor/trax/trainer.py | _setup_gin | def _setup_gin():
"""Setup gin configuration."""
# Imports for configurables
# pylint: disable=g-import-not-at-top,unused-import,g-bad-import-order,reimported,unused-variable
from tensor2tensor.trax import models as _trax_models
from tensor2tensor.trax import optimizers as _trax_opt
# pylint: disable=g-impo... | python | def _setup_gin():
"""Setup gin configuration."""
# Imports for configurables
# pylint: disable=g-import-not-at-top,unused-import,g-bad-import-order,reimported,unused-variable
from tensor2tensor.trax import models as _trax_models
from tensor2tensor.trax import optimizers as _trax_opt
# pylint: disable=g-impo... | [
"def",
"_setup_gin",
"(",
")",
":",
"# Imports for configurables",
"# pylint: disable=g-import-not-at-top,unused-import,g-bad-import-order,reimported,unused-variable",
"from",
"tensor2tensor",
".",
"trax",
"import",
"models",
"as",
"_trax_models",
"from",
"tensor2tensor",
".",
"t... | Setup gin configuration. | [
"Setup",
"gin",
"configuration",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trainer.py#L65-L81 |
22,649 | tensorflow/tensor2tensor | tensor2tensor/v2/t2t.py | _make_info | def _make_info(shape_list, num_classes):
"""Create an info-like tuple for feature given some shapes and vocab size."""
feature_info = collections.namedtuple("FeatureInfo", ["shape", "num_classes"])
cur_shape = list(shape_list[0])
# We need to merge the provided shapes, put None where they disagree.
for shape ... | python | def _make_info(shape_list, num_classes):
"""Create an info-like tuple for feature given some shapes and vocab size."""
feature_info = collections.namedtuple("FeatureInfo", ["shape", "num_classes"])
cur_shape = list(shape_list[0])
# We need to merge the provided shapes, put None where they disagree.
for shape ... | [
"def",
"_make_info",
"(",
"shape_list",
",",
"num_classes",
")",
":",
"feature_info",
"=",
"collections",
".",
"namedtuple",
"(",
"\"FeatureInfo\"",
",",
"[",
"\"shape\"",
",",
"\"num_classes\"",
"]",
")",
"cur_shape",
"=",
"list",
"(",
"shape_list",
"[",
"0",... | Create an info-like tuple for feature given some shapes and vocab size. | [
"Create",
"an",
"info",
"-",
"like",
"tuple",
"for",
"feature",
"given",
"some",
"shapes",
"and",
"vocab",
"size",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L86-L98 |
22,650 | tensorflow/tensor2tensor | tensor2tensor/v2/t2t.py | _select_features | def _select_features(example, feature_list=None):
"""Select a subset of features from the example dict."""
feature_list = feature_list or ["inputs", "targets"]
return {f: example[f] for f in feature_list} | python | def _select_features(example, feature_list=None):
"""Select a subset of features from the example dict."""
feature_list = feature_list or ["inputs", "targets"]
return {f: example[f] for f in feature_list} | [
"def",
"_select_features",
"(",
"example",
",",
"feature_list",
"=",
"None",
")",
":",
"feature_list",
"=",
"feature_list",
"or",
"[",
"\"inputs\"",
",",
"\"targets\"",
"]",
"return",
"{",
"f",
":",
"example",
"[",
"f",
"]",
"for",
"f",
"in",
"feature_list... | Select a subset of features from the example dict. | [
"Select",
"a",
"subset",
"of",
"features",
"from",
"the",
"example",
"dict",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L101-L104 |
22,651 | tensorflow/tensor2tensor | tensor2tensor/v2/t2t.py | optimize_fn | def optimize_fn(model,
optimizer=None,
learning_rate_schedule=None,
loss=None,
metrics=None):
"""Compile the model in Keras."""
learning_rate_schedule = learning_rate_schedule or T2TLearningRateSchedule()
if optimizer:
optimizer = optimizer(learn... | python | def optimize_fn(model,
optimizer=None,
learning_rate_schedule=None,
loss=None,
metrics=None):
"""Compile the model in Keras."""
learning_rate_schedule = learning_rate_schedule or T2TLearningRateSchedule()
if optimizer:
optimizer = optimizer(learn... | [
"def",
"optimize_fn",
"(",
"model",
",",
"optimizer",
"=",
"None",
",",
"learning_rate_schedule",
"=",
"None",
",",
"loss",
"=",
"None",
",",
"metrics",
"=",
"None",
")",
":",
"learning_rate_schedule",
"=",
"learning_rate_schedule",
"or",
"T2TLearningRateSchedule"... | Compile the model in Keras. | [
"Compile",
"the",
"model",
"in",
"Keras",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L233-L253 |
22,652 | tensorflow/tensor2tensor | tensor2tensor/v2/t2t.py | train_fn | def train_fn(data_dir=None, output_dir=None,
model_class=gin.REQUIRED, dataset=gin.REQUIRED,
input_names=None, target_names=None,
train_steps=1000, eval_steps=1, eval_frequency=100):
"""Train the given model on the given dataset.
Args:
data_dir: Directory where the data i... | python | def train_fn(data_dir=None, output_dir=None,
model_class=gin.REQUIRED, dataset=gin.REQUIRED,
input_names=None, target_names=None,
train_steps=1000, eval_steps=1, eval_frequency=100):
"""Train the given model on the given dataset.
Args:
data_dir: Directory where the data i... | [
"def",
"train_fn",
"(",
"data_dir",
"=",
"None",
",",
"output_dir",
"=",
"None",
",",
"model_class",
"=",
"gin",
".",
"REQUIRED",
",",
"dataset",
"=",
"gin",
".",
"REQUIRED",
",",
"input_names",
"=",
"None",
",",
"target_names",
"=",
"None",
",",
"train_... | Train the given model on the given dataset.
Args:
data_dir: Directory where the data is located.
output_dir: Directory where to put the logs and checkpoints.
model_class: The model class to train.
dataset: The name of the dataset to train on.
input_names: List of strings with the names of the fea... | [
"Train",
"the",
"given",
"model",
"on",
"the",
"given",
"dataset",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L259-L324 |
22,653 | tensorflow/tensor2tensor | tensor2tensor/v2/t2t.py | t2t_train | def t2t_train(model_name, dataset_name,
data_dir=None, output_dir=None, config_file=None, config=None):
"""Main function to train the given model on the given dataset.
Args:
model_name: The name of the model to train.
dataset_name: The name of the dataset to train on.
data_dir: Directory ... | python | def t2t_train(model_name, dataset_name,
data_dir=None, output_dir=None, config_file=None, config=None):
"""Main function to train the given model on the given dataset.
Args:
model_name: The name of the model to train.
dataset_name: The name of the dataset to train on.
data_dir: Directory ... | [
"def",
"t2t_train",
"(",
"model_name",
",",
"dataset_name",
",",
"data_dir",
"=",
"None",
",",
"output_dir",
"=",
"None",
",",
"config_file",
"=",
"None",
",",
"config",
"=",
"None",
")",
":",
"if",
"model_name",
"not",
"in",
"_MODEL_REGISTRY",
":",
"raise... | Main function to train the given model on the given dataset.
Args:
model_name: The name of the model to train.
dataset_name: The name of the dataset to train on.
data_dir: Directory where the data is located.
output_dir: Directory where to put the logs and checkpoints.
config_file: the gin config... | [
"Main",
"function",
"to",
"train",
"the",
"given",
"model",
"on",
"the",
"given",
"dataset",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/v2/t2t.py#L327-L347 |
22,654 | tensorflow/tensor2tensor | tensor2tensor/bin/t2t_decoder.py | decode | def decode(estimator, hparams, decode_hp):
"""Decode from estimator. Interactive, from file, or from dataset."""
if FLAGS.decode_interactive:
if estimator.config.use_tpu:
raise ValueError("TPU can only decode from dataset.")
decoding.decode_interactively(estimator, hparams, decode_hp,
... | python | def decode(estimator, hparams, decode_hp):
"""Decode from estimator. Interactive, from file, or from dataset."""
if FLAGS.decode_interactive:
if estimator.config.use_tpu:
raise ValueError("TPU can only decode from dataset.")
decoding.decode_interactively(estimator, hparams, decode_hp,
... | [
"def",
"decode",
"(",
"estimator",
",",
"hparams",
",",
"decode_hp",
")",
":",
"if",
"FLAGS",
".",
"decode_interactive",
":",
"if",
"estimator",
".",
"config",
".",
"use_tpu",
":",
"raise",
"ValueError",
"(",
"\"TPU can only decode from dataset.\"",
")",
"decodi... | Decode from estimator. Interactive, from file, or from dataset. | [
"Decode",
"from",
"estimator",
".",
"Interactive",
"from",
"file",
"or",
"from",
"dataset",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_decoder.py#L82-L104 |
22,655 | tensorflow/tensor2tensor | tensor2tensor/bin/t2t_decoder.py | score_file | def score_file(filename):
"""Score each line in a file and return the scores."""
# Prepare model.
hparams = create_hparams()
encoders = registry.problem(FLAGS.problem).feature_encoders(FLAGS.data_dir)
has_inputs = "inputs" in encoders
# Prepare features for feeding into the model.
if has_inputs:
inpu... | python | def score_file(filename):
"""Score each line in a file and return the scores."""
# Prepare model.
hparams = create_hparams()
encoders = registry.problem(FLAGS.problem).feature_encoders(FLAGS.data_dir)
has_inputs = "inputs" in encoders
# Prepare features for feeding into the model.
if has_inputs:
inpu... | [
"def",
"score_file",
"(",
"filename",
")",
":",
"# Prepare model.",
"hparams",
"=",
"create_hparams",
"(",
")",
"encoders",
"=",
"registry",
".",
"problem",
"(",
"FLAGS",
".",
"problem",
")",
".",
"feature_encoders",
"(",
"FLAGS",
".",
"data_dir",
")",
"has_... | Score each line in a file and return the scores. | [
"Score",
"each",
"line",
"in",
"a",
"file",
"and",
"return",
"the",
"scores",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_decoder.py#L107-L164 |
22,656 | tensorflow/tensor2tensor | tensor2tensor/models/research/autoencoders.py | time_to_channels | def time_to_channels(embedded_video):
"""Put time dimension on channels in an embedded video."""
video_shape = common_layers.shape_list(embedded_video)
if len(video_shape) != 5:
raise ValueError("Assuming videos given as tensors in the format "
"[batch, time, height, width, channels] but ... | python | def time_to_channels(embedded_video):
"""Put time dimension on channels in an embedded video."""
video_shape = common_layers.shape_list(embedded_video)
if len(video_shape) != 5:
raise ValueError("Assuming videos given as tensors in the format "
"[batch, time, height, width, channels] but ... | [
"def",
"time_to_channels",
"(",
"embedded_video",
")",
":",
"video_shape",
"=",
"common_layers",
".",
"shape_list",
"(",
"embedded_video",
")",
"if",
"len",
"(",
"video_shape",
")",
"!=",
"5",
":",
"raise",
"ValueError",
"(",
"\"Assuming videos given as tensors in t... | Put time dimension on channels in an embedded video. | [
"Put",
"time",
"dimension",
"on",
"channels",
"in",
"an",
"embedded",
"video",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L38-L49 |
22,657 | tensorflow/tensor2tensor | tensor2tensor/models/research/autoencoders.py | autoencoder_autoregressive | def autoencoder_autoregressive():
"""Autoregressive autoencoder model."""
hparams = autoencoder_basic()
hparams.add_hparam("autoregressive_forget_base", False)
hparams.add_hparam("autoregressive_mode", "none")
hparams.add_hparam("autoregressive_decode_steps", 0)
hparams.add_hparam("autoregressive_eval_pure_... | python | def autoencoder_autoregressive():
"""Autoregressive autoencoder model."""
hparams = autoencoder_basic()
hparams.add_hparam("autoregressive_forget_base", False)
hparams.add_hparam("autoregressive_mode", "none")
hparams.add_hparam("autoregressive_decode_steps", 0)
hparams.add_hparam("autoregressive_eval_pure_... | [
"def",
"autoencoder_autoregressive",
"(",
")",
":",
"hparams",
"=",
"autoencoder_basic",
"(",
")",
"hparams",
".",
"add_hparam",
"(",
"\"autoregressive_forget_base\"",
",",
"False",
")",
"hparams",
".",
"add_hparam",
"(",
"\"autoregressive_mode\"",
",",
"\"none\"",
... | Autoregressive autoencoder model. | [
"Autoregressive",
"autoencoder",
"model",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1073-L1081 |
22,658 | tensorflow/tensor2tensor | tensor2tensor/models/research/autoencoders.py | autoencoder_residual | def autoencoder_residual():
"""Residual autoencoder model."""
hparams = autoencoder_autoregressive()
hparams.optimizer = "Adafactor"
hparams.clip_grad_norm = 1.0
hparams.learning_rate_constant = 0.5
hparams.learning_rate_warmup_steps = 500
hparams.learning_rate_schedule = "constant * linear_warmup * rsqrt... | python | def autoencoder_residual():
"""Residual autoencoder model."""
hparams = autoencoder_autoregressive()
hparams.optimizer = "Adafactor"
hparams.clip_grad_norm = 1.0
hparams.learning_rate_constant = 0.5
hparams.learning_rate_warmup_steps = 500
hparams.learning_rate_schedule = "constant * linear_warmup * rsqrt... | [
"def",
"autoencoder_residual",
"(",
")",
":",
"hparams",
"=",
"autoencoder_autoregressive",
"(",
")",
"hparams",
".",
"optimizer",
"=",
"\"Adafactor\"",
"hparams",
".",
"clip_grad_norm",
"=",
"1.0",
"hparams",
".",
"learning_rate_constant",
"=",
"0.5",
"hparams",
... | Residual autoencoder model. | [
"Residual",
"autoencoder",
"model",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1085-L1103 |
22,659 | tensorflow/tensor2tensor | tensor2tensor/models/research/autoencoders.py | autoencoder_residual_text | def autoencoder_residual_text():
"""Residual autoencoder model for text."""
hparams = autoencoder_residual()
hparams.bottleneck_bits = 32
hparams.batch_size = 1024
hparams.hidden_size = 64
hparams.max_hidden_size = 512
hparams.bottleneck_noise = 0.0
hparams.bottom = {
"inputs": modalities.identity... | python | def autoencoder_residual_text():
"""Residual autoencoder model for text."""
hparams = autoencoder_residual()
hparams.bottleneck_bits = 32
hparams.batch_size = 1024
hparams.hidden_size = 64
hparams.max_hidden_size = 512
hparams.bottleneck_noise = 0.0
hparams.bottom = {
"inputs": modalities.identity... | [
"def",
"autoencoder_residual_text",
"(",
")",
":",
"hparams",
"=",
"autoencoder_residual",
"(",
")",
"hparams",
".",
"bottleneck_bits",
"=",
"32",
"hparams",
".",
"batch_size",
"=",
"1024",
"hparams",
".",
"hidden_size",
"=",
"64",
"hparams",
".",
"max_hidden_si... | Residual autoencoder model for text. | [
"Residual",
"autoencoder",
"model",
"for",
"text",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1107-L1124 |
22,660 | tensorflow/tensor2tensor | tensor2tensor/models/research/autoencoders.py | autoencoder_residual_discrete | def autoencoder_residual_discrete():
"""Residual discrete autoencoder model."""
hparams = autoencoder_residual()
hparams.bottleneck_bits = 1024
hparams.bottleneck_noise = 0.05
hparams.add_hparam("discretize_warmup_steps", 16000)
hparams.add_hparam("bottleneck_kind", "tanh_discrete")
hparams.add_hparam("is... | python | def autoencoder_residual_discrete():
"""Residual discrete autoencoder model."""
hparams = autoencoder_residual()
hparams.bottleneck_bits = 1024
hparams.bottleneck_noise = 0.05
hparams.add_hparam("discretize_warmup_steps", 16000)
hparams.add_hparam("bottleneck_kind", "tanh_discrete")
hparams.add_hparam("is... | [
"def",
"autoencoder_residual_discrete",
"(",
")",
":",
"hparams",
"=",
"autoencoder_residual",
"(",
")",
"hparams",
".",
"bottleneck_bits",
"=",
"1024",
"hparams",
".",
"bottleneck_noise",
"=",
"0.05",
"hparams",
".",
"add_hparam",
"(",
"\"discretize_warmup_steps\"",
... | Residual discrete autoencoder model. | [
"Residual",
"discrete",
"autoencoder",
"model",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1140-L1153 |
22,661 | tensorflow/tensor2tensor | tensor2tensor/models/research/autoencoders.py | autoencoder_residual_discrete_big | def autoencoder_residual_discrete_big():
"""Residual discrete autoencoder model, big version."""
hparams = autoencoder_residual_discrete()
hparams.hidden_size = 128
hparams.max_hidden_size = 4096
hparams.bottleneck_noise = 0.1
hparams.residual_dropout = 0.4
return hparams | python | def autoencoder_residual_discrete_big():
"""Residual discrete autoencoder model, big version."""
hparams = autoencoder_residual_discrete()
hparams.hidden_size = 128
hparams.max_hidden_size = 4096
hparams.bottleneck_noise = 0.1
hparams.residual_dropout = 0.4
return hparams | [
"def",
"autoencoder_residual_discrete_big",
"(",
")",
":",
"hparams",
"=",
"autoencoder_residual_discrete",
"(",
")",
"hparams",
".",
"hidden_size",
"=",
"128",
"hparams",
".",
"max_hidden_size",
"=",
"4096",
"hparams",
".",
"bottleneck_noise",
"=",
"0.1",
"hparams"... | Residual discrete autoencoder model, big version. | [
"Residual",
"discrete",
"autoencoder",
"model",
"big",
"version",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1157-L1164 |
22,662 | tensorflow/tensor2tensor | tensor2tensor/models/research/autoencoders.py | autoencoder_ordered_text | def autoencoder_ordered_text():
"""Ordered discrete autoencoder model for text."""
hparams = autoencoder_ordered_discrete()
hparams.bottleneck_bits = 1024
hparams.bottleneck_shared_bits = 1024-64
hparams.bottleneck_shared_bits_start_warmup = 75000
hparams.bottleneck_shared_bits_stop_warmup = 275000
hparam... | python | def autoencoder_ordered_text():
"""Ordered discrete autoencoder model for text."""
hparams = autoencoder_ordered_discrete()
hparams.bottleneck_bits = 1024
hparams.bottleneck_shared_bits = 1024-64
hparams.bottleneck_shared_bits_start_warmup = 75000
hparams.bottleneck_shared_bits_stop_warmup = 275000
hparam... | [
"def",
"autoencoder_ordered_text",
"(",
")",
":",
"hparams",
"=",
"autoencoder_ordered_discrete",
"(",
")",
"hparams",
".",
"bottleneck_bits",
"=",
"1024",
"hparams",
".",
"bottleneck_shared_bits",
"=",
"1024",
"-",
"64",
"hparams",
".",
"bottleneck_shared_bits_start_... | Ordered discrete autoencoder model for text. | [
"Ordered",
"discrete",
"autoencoder",
"model",
"for",
"text",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1214-L1234 |
22,663 | tensorflow/tensor2tensor | tensor2tensor/models/research/autoencoders.py | autoencoder_ordered_text_small | def autoencoder_ordered_text_small():
"""Ordered discrete autoencoder model for text, small version."""
hparams = autoencoder_ordered_text()
hparams.bottleneck_bits = 32
hparams.num_hidden_layers = 3
hparams.hidden_size = 64
hparams.max_hidden_size = 512
hparams.bottleneck_noise = 0.0
hparams.autoregres... | python | def autoencoder_ordered_text_small():
"""Ordered discrete autoencoder model for text, small version."""
hparams = autoencoder_ordered_text()
hparams.bottleneck_bits = 32
hparams.num_hidden_layers = 3
hparams.hidden_size = 64
hparams.max_hidden_size = 512
hparams.bottleneck_noise = 0.0
hparams.autoregres... | [
"def",
"autoencoder_ordered_text_small",
"(",
")",
":",
"hparams",
"=",
"autoencoder_ordered_text",
"(",
")",
"hparams",
".",
"bottleneck_bits",
"=",
"32",
"hparams",
".",
"num_hidden_layers",
"=",
"3",
"hparams",
".",
"hidden_size",
"=",
"64",
"hparams",
".",
"... | Ordered discrete autoencoder model for text, small version. | [
"Ordered",
"discrete",
"autoencoder",
"model",
"for",
"text",
"small",
"version",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1238-L1248 |
22,664 | tensorflow/tensor2tensor | tensor2tensor/models/research/autoencoders.py | autoencoder_discrete_pong | def autoencoder_discrete_pong():
"""Discrete autoencoder model for compressing pong frames."""
hparams = autoencoder_ordered_discrete()
hparams.num_hidden_layers = 3
hparams.bottleneck_bits = 24
hparams.batch_size = 2
hparams.gan_loss_factor = 0.01
hparams.bottleneck_l2_factor = 0.001
hparams.add_hparam... | python | def autoencoder_discrete_pong():
"""Discrete autoencoder model for compressing pong frames."""
hparams = autoencoder_ordered_discrete()
hparams.num_hidden_layers = 3
hparams.bottleneck_bits = 24
hparams.batch_size = 2
hparams.gan_loss_factor = 0.01
hparams.bottleneck_l2_factor = 0.001
hparams.add_hparam... | [
"def",
"autoencoder_discrete_pong",
"(",
")",
":",
"hparams",
"=",
"autoencoder_ordered_discrete",
"(",
")",
"hparams",
".",
"num_hidden_layers",
"=",
"3",
"hparams",
".",
"bottleneck_bits",
"=",
"24",
"hparams",
".",
"batch_size",
"=",
"2",
"hparams",
".",
"gan... | Discrete autoencoder model for compressing pong frames. | [
"Discrete",
"autoencoder",
"model",
"for",
"compressing",
"pong",
"frames",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1261-L1270 |
22,665 | tensorflow/tensor2tensor | tensor2tensor/models/research/autoencoders.py | autoencoder_discrete_tiny | def autoencoder_discrete_tiny():
"""Discrete autoencoder model for compressing pong frames for testing."""
hparams = autoencoder_ordered_discrete()
hparams.num_hidden_layers = 2
hparams.bottleneck_bits = 24
hparams.batch_size = 2
hparams.gan_loss_factor = 0.
hparams.bottleneck_l2_factor = 0.001
hparams.... | python | def autoencoder_discrete_tiny():
"""Discrete autoencoder model for compressing pong frames for testing."""
hparams = autoencoder_ordered_discrete()
hparams.num_hidden_layers = 2
hparams.bottleneck_bits = 24
hparams.batch_size = 2
hparams.gan_loss_factor = 0.
hparams.bottleneck_l2_factor = 0.001
hparams.... | [
"def",
"autoencoder_discrete_tiny",
"(",
")",
":",
"hparams",
"=",
"autoencoder_ordered_discrete",
"(",
")",
"hparams",
".",
"num_hidden_layers",
"=",
"2",
"hparams",
".",
"bottleneck_bits",
"=",
"24",
"hparams",
".",
"batch_size",
"=",
"2",
"hparams",
".",
"gan... | Discrete autoencoder model for compressing pong frames for testing. | [
"Discrete",
"autoencoder",
"model",
"for",
"compressing",
"pong",
"frames",
"for",
"testing",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1274-L1286 |
22,666 | tensorflow/tensor2tensor | tensor2tensor/models/research/autoencoders.py | autoencoder_discrete_cifar | def autoencoder_discrete_cifar():
"""Discrete autoencoder model for compressing cifar."""
hparams = autoencoder_ordered_discrete()
hparams.bottleneck_noise = 0.0
hparams.bottleneck_bits = 90
hparams.num_hidden_layers = 2
hparams.hidden_size = 256
hparams.num_residual_layers = 4
hparams.batch_size = 32
... | python | def autoencoder_discrete_cifar():
"""Discrete autoencoder model for compressing cifar."""
hparams = autoencoder_ordered_discrete()
hparams.bottleneck_noise = 0.0
hparams.bottleneck_bits = 90
hparams.num_hidden_layers = 2
hparams.hidden_size = 256
hparams.num_residual_layers = 4
hparams.batch_size = 32
... | [
"def",
"autoencoder_discrete_cifar",
"(",
")",
":",
"hparams",
"=",
"autoencoder_ordered_discrete",
"(",
")",
"hparams",
".",
"bottleneck_noise",
"=",
"0.0",
"hparams",
".",
"bottleneck_bits",
"=",
"90",
"hparams",
".",
"num_hidden_layers",
"=",
"2",
"hparams",
".... | Discrete autoencoder model for compressing cifar. | [
"Discrete",
"autoencoder",
"model",
"for",
"compressing",
"cifar",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1290-L1300 |
22,667 | tensorflow/tensor2tensor | tensor2tensor/models/research/autoencoders.py | autoencoder_range | def autoencoder_range(rhp):
"""Tuning grid of the main autoencoder params."""
rhp.set_float("dropout", 0.01, 0.3)
rhp.set_float("gan_loss_factor", 0.01, 0.1)
rhp.set_float("bottleneck_l2_factor", 0.001, 0.1, scale=rhp.LOG_SCALE)
rhp.set_discrete("bottleneck_warmup_steps", [200, 2000])
rhp.set_float("gumbel_... | python | def autoencoder_range(rhp):
"""Tuning grid of the main autoencoder params."""
rhp.set_float("dropout", 0.01, 0.3)
rhp.set_float("gan_loss_factor", 0.01, 0.1)
rhp.set_float("bottleneck_l2_factor", 0.001, 0.1, scale=rhp.LOG_SCALE)
rhp.set_discrete("bottleneck_warmup_steps", [200, 2000])
rhp.set_float("gumbel_... | [
"def",
"autoencoder_range",
"(",
"rhp",
")",
":",
"rhp",
".",
"set_float",
"(",
"\"dropout\"",
",",
"0.01",
",",
"0.3",
")",
"rhp",
".",
"set_float",
"(",
"\"gan_loss_factor\"",
",",
"0.01",
",",
"0.1",
")",
"rhp",
".",
"set_float",
"(",
"\"bottleneck_l2_f... | Tuning grid of the main autoencoder params. | [
"Tuning",
"grid",
"of",
"the",
"main",
"autoencoder",
"params",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1304-L1311 |
22,668 | tensorflow/tensor2tensor | tensor2tensor/models/research/vqa_attention.py | question_encoder | def question_encoder(question, hparams, name="encoder"):
"""Question encoder, run LSTM encoder and get the last output as encoding."""
with tf.variable_scope(name, "encoder", values=[question]):
question = common_layers.flatten4d3d(question)
padding = common_attention.embedding_to_padding(question)
leng... | python | def question_encoder(question, hparams, name="encoder"):
"""Question encoder, run LSTM encoder and get the last output as encoding."""
with tf.variable_scope(name, "encoder", values=[question]):
question = common_layers.flatten4d3d(question)
padding = common_attention.embedding_to_padding(question)
leng... | [
"def",
"question_encoder",
"(",
"question",
",",
"hparams",
",",
"name",
"=",
"\"encoder\"",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"\"encoder\"",
",",
"values",
"=",
"[",
"question",
"]",
")",
":",
"question",
"=",
"common_layers... | Question encoder, run LSTM encoder and get the last output as encoding. | [
"Question",
"encoder",
"run",
"LSTM",
"encoder",
"and",
"get",
"the",
"last",
"output",
"as",
"encoding",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/vqa_attention.py#L245-L295 |
22,669 | tensorflow/tensor2tensor | tensor2tensor/trax/history.py | History.get | def get(self, mode, metric):
"""Get the history for the given metric and mode."""
if mode not in self._values:
logging.info("Metric %s not found for mode %s", metric, mode)
return []
return list(self._values[mode][metric]) | python | def get(self, mode, metric):
"""Get the history for the given metric and mode."""
if mode not in self._values:
logging.info("Metric %s not found for mode %s", metric, mode)
return []
return list(self._values[mode][metric]) | [
"def",
"get",
"(",
"self",
",",
"mode",
",",
"metric",
")",
":",
"if",
"mode",
"not",
"in",
"self",
".",
"_values",
":",
"logging",
".",
"info",
"(",
"\"Metric %s not found for mode %s\"",
",",
"metric",
",",
"mode",
")",
"return",
"[",
"]",
"return",
... | Get the history for the given metric and mode. | [
"Get",
"the",
"history",
"for",
"the",
"given",
"metric",
"and",
"mode",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/history.py#L58-L63 |
22,670 | tensorflow/tensor2tensor | tensor2tensor/trax/history.py | History.metrics_for_mode | def metrics_for_mode(self, mode):
"""Metrics available for a given mode."""
if mode not in self._values:
logging.info("Mode %s not found", mode)
return []
return sorted(list(self._values[mode].keys())) | python | def metrics_for_mode(self, mode):
"""Metrics available for a given mode."""
if mode not in self._values:
logging.info("Mode %s not found", mode)
return []
return sorted(list(self._values[mode].keys())) | [
"def",
"metrics_for_mode",
"(",
"self",
",",
"mode",
")",
":",
"if",
"mode",
"not",
"in",
"self",
".",
"_values",
":",
"logging",
".",
"info",
"(",
"\"Mode %s not found\"",
",",
"mode",
")",
"return",
"[",
"]",
"return",
"sorted",
"(",
"list",
"(",
"se... | Metrics available for a given mode. | [
"Metrics",
"available",
"for",
"a",
"given",
"mode",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/history.py#L70-L75 |
22,671 | tensorflow/tensor2tensor | tensor2tensor/models/resnet.py | batch_norm_relu | def batch_norm_relu(inputs,
is_training,
relu=True,
init_zero=False,
data_format="channels_first"):
"""Performs a batch normalization followed by a ReLU.
Args:
inputs: `Tensor` of shape `[batch, channels, ...]`.
is_training: `b... | python | def batch_norm_relu(inputs,
is_training,
relu=True,
init_zero=False,
data_format="channels_first"):
"""Performs a batch normalization followed by a ReLU.
Args:
inputs: `Tensor` of shape `[batch, channels, ...]`.
is_training: `b... | [
"def",
"batch_norm_relu",
"(",
"inputs",
",",
"is_training",
",",
"relu",
"=",
"True",
",",
"init_zero",
"=",
"False",
",",
"data_format",
"=",
"\"channels_first\"",
")",
":",
"if",
"init_zero",
":",
"gamma_initializer",
"=",
"tf",
".",
"zeros_initializer",
"(... | Performs a batch normalization followed by a ReLU.
Args:
inputs: `Tensor` of shape `[batch, channels, ...]`.
is_training: `bool` for whether the model is training.
relu: `bool` if False, omits the ReLU operation.
init_zero: `bool` if True, initializes scale parameter of batch
normalization wi... | [
"Performs",
"a",
"batch",
"normalization",
"followed",
"by",
"a",
"ReLU",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L41-L81 |
22,672 | tensorflow/tensor2tensor | tensor2tensor/models/resnet.py | residual_block | def residual_block(inputs,
filters,
is_training,
projection_shortcut,
strides,
final_block,
data_format="channels_first",
use_td=False,
targeting_rate=None,
... | python | def residual_block(inputs,
filters,
is_training,
projection_shortcut,
strides,
final_block,
data_format="channels_first",
use_td=False,
targeting_rate=None,
... | [
"def",
"residual_block",
"(",
"inputs",
",",
"filters",
",",
"is_training",
",",
"projection_shortcut",
",",
"strides",
",",
"final_block",
",",
"data_format",
"=",
"\"channels_first\"",
",",
"use_td",
"=",
"False",
",",
"targeting_rate",
"=",
"None",
",",
"keep... | Standard building block for residual networks with BN before convolutions.
Args:
inputs: `Tensor` of size `[batch, channels, height, width]`.
filters: `int` number of filters for the first two convolutions. Note that
the third and final convolution will use 4 times as many filters.
is_training: `... | [
"Standard",
"building",
"block",
"for",
"residual",
"networks",
"with",
"BN",
"before",
"convolutions",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L191-L257 |
22,673 | tensorflow/tensor2tensor | tensor2tensor/models/resnet.py | resnet_v2 | def resnet_v2(inputs,
block_fn,
layer_blocks,
filters,
data_format="channels_first",
is_training=False,
is_cifar=False,
use_td=False,
targeting_rate=None,
keep_prob=None):
"""Resnet model.
... | python | def resnet_v2(inputs,
block_fn,
layer_blocks,
filters,
data_format="channels_first",
is_training=False,
is_cifar=False,
use_td=False,
targeting_rate=None,
keep_prob=None):
"""Resnet model.
... | [
"def",
"resnet_v2",
"(",
"inputs",
",",
"block_fn",
",",
"layer_blocks",
",",
"filters",
",",
"data_format",
"=",
"\"channels_first\"",
",",
"is_training",
"=",
"False",
",",
"is_cifar",
"=",
"False",
",",
"use_td",
"=",
"False",
",",
"targeting_rate",
"=",
... | Resnet model.
Args:
inputs: `Tensor` images.
block_fn: `function` for the block to use within the model. Either
`residual_block` or `bottleneck_block`.
layer_blocks: list of 3 or 4 `int`s denoting the number of blocks to include
in each of the 3 or 4 block groups. Each group consists of blo... | [
"Resnet",
"model",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L427-L511 |
22,674 | tensorflow/tensor2tensor | tensor2tensor/utils/rouge.py | _len_lcs | def _len_lcs(x, y):
"""Returns the length of the Longest Common Subsequence between two seqs.
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
Args:
x: sequence of words
y: sequence of words
Returns
integer: Length of LCS between x and y
"""
table = _lcs(x, y)
n, m =... | python | def _len_lcs(x, y):
"""Returns the length of the Longest Common Subsequence between two seqs.
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
Args:
x: sequence of words
y: sequence of words
Returns
integer: Length of LCS between x and y
"""
table = _lcs(x, y)
n, m =... | [
"def",
"_len_lcs",
"(",
"x",
",",
"y",
")",
":",
"table",
"=",
"_lcs",
"(",
"x",
",",
"y",
")",
"n",
",",
"m",
"=",
"len",
"(",
"x",
")",
",",
"len",
"(",
"y",
")",
"return",
"table",
"[",
"n",
",",
"m",
"]"
] | Returns the length of the Longest Common Subsequence between two seqs.
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
Args:
x: sequence of words
y: sequence of words
Returns
integer: Length of LCS between x and y | [
"Returns",
"the",
"length",
"of",
"the",
"Longest",
"Common",
"Subsequence",
"between",
"two",
"seqs",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/rouge.py#L33-L47 |
22,675 | tensorflow/tensor2tensor | tensor2tensor/utils/rouge.py | _lcs | def _lcs(x, y):
"""Computes the length of the LCS between two seqs.
The implementation below uses a DP programming algorithm and runs
in O(nm) time where n = len(x) and m = len(y).
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
Args:
x: collection of words
y: collection of ... | python | def _lcs(x, y):
"""Computes the length of the LCS between two seqs.
The implementation below uses a DP programming algorithm and runs
in O(nm) time where n = len(x) and m = len(y).
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
Args:
x: collection of words
y: collection of ... | [
"def",
"_lcs",
"(",
"x",
",",
"y",
")",
":",
"n",
",",
"m",
"=",
"len",
"(",
"x",
")",
",",
"len",
"(",
"y",
")",
"table",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"n",
"+",
"1",
")",
":",
"for",
"j",
"in",
"range",
"(",
"m",
"+... | Computes the length of the LCS between two seqs.
The implementation below uses a DP programming algorithm and runs
in O(nm) time where n = len(x) and m = len(y).
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
Args:
x: collection of words
y: collection of words
Returns:
... | [
"Computes",
"the",
"length",
"of",
"the",
"LCS",
"between",
"two",
"seqs",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/rouge.py#L50-L74 |
22,676 | tensorflow/tensor2tensor | tensor2tensor/utils/rouge.py | _get_ngrams | def _get_ngrams(n, text):
"""Calculates n-grams.
Args:
n: which n-grams to calculate
text: An array of tokens
Returns:
A set of n-grams
"""
ngram_set = set()
text_length = len(text)
max_index_ngram_start = text_length - n
for i in range(max_index_ngram_start + 1):
ngram_set.add(tuple(t... | python | def _get_ngrams(n, text):
"""Calculates n-grams.
Args:
n: which n-grams to calculate
text: An array of tokens
Returns:
A set of n-grams
"""
ngram_set = set()
text_length = len(text)
max_index_ngram_start = text_length - n
for i in range(max_index_ngram_start + 1):
ngram_set.add(tuple(t... | [
"def",
"_get_ngrams",
"(",
"n",
",",
"text",
")",
":",
"ngram_set",
"=",
"set",
"(",
")",
"text_length",
"=",
"len",
"(",
"text",
")",
"max_index_ngram_start",
"=",
"text_length",
"-",
"n",
"for",
"i",
"in",
"range",
"(",
"max_index_ngram_start",
"+",
"1... | Calculates n-grams.
Args:
n: which n-grams to calculate
text: An array of tokens
Returns:
A set of n-grams | [
"Calculates",
"n",
"-",
"grams",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/rouge.py#L156-L171 |
22,677 | tensorflow/tensor2tensor | tensor2tensor/data_generators/multi_problem.py | flatten_zip_dataset | def flatten_zip_dataset(*args):
"""A list of examples to a dataset containing mixed examples.
Given a list of `n` dataset examples, flatten them by converting
each element into a dataset and concatenating them to convert into a
single dataset.
Args:
*args: A list containing one example each from `n` dif... | python | def flatten_zip_dataset(*args):
"""A list of examples to a dataset containing mixed examples.
Given a list of `n` dataset examples, flatten them by converting
each element into a dataset and concatenating them to convert into a
single dataset.
Args:
*args: A list containing one example each from `n` dif... | [
"def",
"flatten_zip_dataset",
"(",
"*",
"args",
")",
":",
"flattened",
"=",
"tf",
".",
"data",
".",
"Dataset",
".",
"from_tensors",
"(",
"args",
"[",
"0",
"]",
")",
"for",
"ex",
"in",
"args",
"[",
"1",
":",
"]",
":",
"flattened",
"=",
"flattened",
... | A list of examples to a dataset containing mixed examples.
Given a list of `n` dataset examples, flatten them by converting
each element into a dataset and concatenating them to convert into a
single dataset.
Args:
*args: A list containing one example each from `n` different datasets.
Returns:
flat... | [
"A",
"list",
"of",
"examples",
"to",
"a",
"dataset",
"containing",
"mixed",
"examples",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem.py#L111-L128 |
22,678 | tensorflow/tensor2tensor | tensor2tensor/data_generators/multi_problem.py | aggregate_task_lm_losses | def aggregate_task_lm_losses(hparams,
problem_hparams,
logits,
feature_name,
feature):
"""LM loss for multiproblems."""
summaries = []
vocab_size = problem_hparams.vocab_size[feature_name]
if voca... | python | def aggregate_task_lm_losses(hparams,
problem_hparams,
logits,
feature_name,
feature):
"""LM loss for multiproblems."""
summaries = []
vocab_size = problem_hparams.vocab_size[feature_name]
if voca... | [
"def",
"aggregate_task_lm_losses",
"(",
"hparams",
",",
"problem_hparams",
",",
"logits",
",",
"feature_name",
",",
"feature",
")",
":",
"summaries",
"=",
"[",
"]",
"vocab_size",
"=",
"problem_hparams",
".",
"vocab_size",
"[",
"feature_name",
"]",
"if",
"vocab_s... | LM loss for multiproblems. | [
"LM",
"loss",
"for",
"multiproblems",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem.py#L525-L553 |
22,679 | tensorflow/tensor2tensor | tensor2tensor/data_generators/multi_problem.py | MultiProblem.update_task_ids | def update_task_ids(self, encoder_vocab_size):
"""Generate task_ids for each problem.
These ids correspond to the index of the task in the task_list.
Args:
encoder_vocab_size: the size of the vocab which is used to compute
the index offset.
"""
for idx, task in enumerate(self.task_li... | python | def update_task_ids(self, encoder_vocab_size):
"""Generate task_ids for each problem.
These ids correspond to the index of the task in the task_list.
Args:
encoder_vocab_size: the size of the vocab which is used to compute
the index offset.
"""
for idx, task in enumerate(self.task_li... | [
"def",
"update_task_ids",
"(",
"self",
",",
"encoder_vocab_size",
")",
":",
"for",
"idx",
",",
"task",
"in",
"enumerate",
"(",
"self",
".",
"task_list",
")",
":",
"task",
".",
"set_task_id",
"(",
"idx",
"+",
"encoder_vocab_size",
")",
"tf",
".",
"logging",... | Generate task_ids for each problem.
These ids correspond to the index of the task in the task_list.
Args:
encoder_vocab_size: the size of the vocab which is used to compute
the index offset. | [
"Generate",
"task_ids",
"for",
"each",
"problem",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem.py#L385-L397 |
22,680 | tensorflow/tensor2tensor | tensor2tensor/data_generators/multi_problem.py | MultiProblem.get_max_num_classes | def get_max_num_classes(self):
"""Compute the maximum number of classes any subtask has.
This is useful for modifying the size of the softmax to include the output
labels for the classification tasks. Currently, labels from different tasks
are overloaded.
Returns:
num: Highest number of outp... | python | def get_max_num_classes(self):
"""Compute the maximum number of classes any subtask has.
This is useful for modifying the size of the softmax to include the output
labels for the classification tasks. Currently, labels from different tasks
are overloaded.
Returns:
num: Highest number of outp... | [
"def",
"get_max_num_classes",
"(",
"self",
")",
":",
"num",
"=",
"0",
"for",
"task",
"in",
"self",
".",
"task_list",
":",
"if",
"hasattr",
"(",
"task",
",",
"\"num_classes\"",
")",
":",
"if",
"num",
"<",
"task",
".",
"num_classes",
":",
"num",
"=",
"... | Compute the maximum number of classes any subtask has.
This is useful for modifying the size of the softmax to include the output
labels for the classification tasks. Currently, labels from different tasks
are overloaded.
Returns:
num: Highest number of output classes in any text classification ... | [
"Compute",
"the",
"maximum",
"number",
"of",
"classes",
"any",
"subtask",
"has",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem.py#L399-L416 |
22,681 | tensorflow/tensor2tensor | tensor2tensor/layers/transformer_memory.py | TransformerMemory._norm | def _norm(self, x):
"""Compute the safe norm."""
return tf.sqrt(tf.reduce_sum(tf.square(x), keepdims=True, axis=-1) + 1e-7) | python | def _norm(self, x):
"""Compute the safe norm."""
return tf.sqrt(tf.reduce_sum(tf.square(x), keepdims=True, axis=-1) + 1e-7) | [
"def",
"_norm",
"(",
"self",
",",
"x",
")",
":",
"return",
"tf",
".",
"sqrt",
"(",
"tf",
".",
"reduce_sum",
"(",
"tf",
".",
"square",
"(",
"x",
")",
",",
"keepdims",
"=",
"True",
",",
"axis",
"=",
"-",
"1",
")",
"+",
"1e-7",
")"
] | Compute the safe norm. | [
"Compute",
"the",
"safe",
"norm",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_memory.py#L226-L228 |
22,682 | tensorflow/tensor2tensor | tensor2tensor/layers/transformer_memory.py | TransformerMemory._address_content | def _address_content(self, x):
"""Address the memory based on content similarity.
Args:
x: a tensor in the shape of [batch_size, length, depth].
Returns:
the logits for each memory entry [batch_size, length, memory_size].
"""
mem_keys = tf.layers.dense(self.mem_vals, self.key_depth,
... | python | def _address_content(self, x):
"""Address the memory based on content similarity.
Args:
x: a tensor in the shape of [batch_size, length, depth].
Returns:
the logits for each memory entry [batch_size, length, memory_size].
"""
mem_keys = tf.layers.dense(self.mem_vals, self.key_depth,
... | [
"def",
"_address_content",
"(",
"self",
",",
"x",
")",
":",
"mem_keys",
"=",
"tf",
".",
"layers",
".",
"dense",
"(",
"self",
".",
"mem_vals",
",",
"self",
".",
"key_depth",
",",
"bias_initializer",
"=",
"tf",
".",
"constant_initializer",
"(",
"1.0",
")",... | Address the memory based on content similarity.
Args:
x: a tensor in the shape of [batch_size, length, depth].
Returns:
the logits for each memory entry [batch_size, length, memory_size]. | [
"Address",
"the",
"memory",
"based",
"on",
"content",
"similarity",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_memory.py#L230-L249 |
22,683 | tensorflow/tensor2tensor | tensor2tensor/layers/transformer_memory.py | TransformerMemory.read | def read(self, x):
"""Read from the memory.
An external component can use the results via a simple MLP,
e.g., fn(x W_x + retrieved_mem W_m).
Args:
x: a tensor in the shape of [batch_size, length, depth].
Returns:
access_logits: the logits for accessing the memory in shape of
... | python | def read(self, x):
"""Read from the memory.
An external component can use the results via a simple MLP,
e.g., fn(x W_x + retrieved_mem W_m).
Args:
x: a tensor in the shape of [batch_size, length, depth].
Returns:
access_logits: the logits for accessing the memory in shape of
... | [
"def",
"read",
"(",
"self",
",",
"x",
")",
":",
"access_logits",
"=",
"self",
".",
"_address_content",
"(",
"x",
")",
"weights",
"=",
"tf",
".",
"nn",
".",
"softmax",
"(",
"access_logits",
")",
"retrieved_mem",
"=",
"tf",
".",
"reduce_sum",
"(",
"tf",
... | Read from the memory.
An external component can use the results via a simple MLP,
e.g., fn(x W_x + retrieved_mem W_m).
Args:
x: a tensor in the shape of [batch_size, length, depth].
Returns:
access_logits: the logits for accessing the memory in shape of
[batch_size, length, memor... | [
"Read",
"from",
"the",
"memory",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_memory.py#L251-L270 |
22,684 | tensorflow/tensor2tensor | tensor2tensor/layers/transformer_memory.py | TransformerMemory.write | def write(self, x, access_logits):
"""Write to the memory based on a combination of similarity and least used.
Based on arXiv:1607.00036v2 [cs.LG].
Args:
x: a tensor in the shape of [batch_size, length, depth].
access_logits: the logits for accessing the memory.
Returns:
the update o... | python | def write(self, x, access_logits):
"""Write to the memory based on a combination of similarity and least used.
Based on arXiv:1607.00036v2 [cs.LG].
Args:
x: a tensor in the shape of [batch_size, length, depth].
access_logits: the logits for accessing the memory.
Returns:
the update o... | [
"def",
"write",
"(",
"self",
",",
"x",
",",
"access_logits",
")",
":",
"gamma",
"=",
"tf",
".",
"layers",
".",
"dense",
"(",
"x",
",",
"1",
",",
"activation",
"=",
"tf",
".",
"sigmoid",
",",
"name",
"=",
"\"gamma\"",
")",
"write_logits",
"=",
"acce... | Write to the memory based on a combination of similarity and least used.
Based on arXiv:1607.00036v2 [cs.LG].
Args:
x: a tensor in the shape of [batch_size, length, depth].
access_logits: the logits for accessing the memory.
Returns:
the update op. | [
"Write",
"to",
"the",
"memory",
"based",
"on",
"a",
"combination",
"of",
"similarity",
"and",
"least",
"used",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_memory.py#L272-L303 |
22,685 | tensorflow/tensor2tensor | tensor2tensor/layers/transformer_memory.py | TransformerMemory.reset | def reset(self, entries_to_reset):
"""Reset the entries in the memory.
Args:
entries_to_reset: a 1D tensor.
Returns:
the reset op.
"""
num_updates = tf.size(entries_to_reset)
update_vals = tf.scatter_update(
self.mem_vals, entries_to_reset,
tf.tile(tf.expand_dims(
... | python | def reset(self, entries_to_reset):
"""Reset the entries in the memory.
Args:
entries_to_reset: a 1D tensor.
Returns:
the reset op.
"""
num_updates = tf.size(entries_to_reset)
update_vals = tf.scatter_update(
self.mem_vals, entries_to_reset,
tf.tile(tf.expand_dims(
... | [
"def",
"reset",
"(",
"self",
",",
"entries_to_reset",
")",
":",
"num_updates",
"=",
"tf",
".",
"size",
"(",
"entries_to_reset",
")",
"update_vals",
"=",
"tf",
".",
"scatter_update",
"(",
"self",
".",
"mem_vals",
",",
"entries_to_reset",
",",
"tf",
".",
"ti... | Reset the entries in the memory.
Args:
entries_to_reset: a 1D tensor.
Returns:
the reset op. | [
"Reset",
"the",
"entries",
"in",
"the",
"memory",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_memory.py#L317-L337 |
22,686 | tensorflow/tensor2tensor | tensor2tensor/rl/ppo_learner.py | _define_train | def _define_train(
train_env,
ppo_hparams,
eval_env_fn=None,
sampling_temp=1.0,
**collect_kwargs
):
"""Define the training setup."""
memory, collect_summary, train_initialization = (
_define_collect(
train_env,
ppo_hparams,
"ppo_train",
eval_phase=Fa... | python | def _define_train(
train_env,
ppo_hparams,
eval_env_fn=None,
sampling_temp=1.0,
**collect_kwargs
):
"""Define the training setup."""
memory, collect_summary, train_initialization = (
_define_collect(
train_env,
ppo_hparams,
"ppo_train",
eval_phase=Fa... | [
"def",
"_define_train",
"(",
"train_env",
",",
"ppo_hparams",
",",
"eval_env_fn",
"=",
"None",
",",
"sampling_temp",
"=",
"1.0",
",",
"*",
"*",
"collect_kwargs",
")",
":",
"memory",
",",
"collect_summary",
",",
"train_initialization",
"=",
"(",
"_define_collect"... | Define the training setup. | [
"Define",
"the",
"training",
"setup",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/ppo_learner.py#L151-L186 |
22,687 | tensorflow/tensor2tensor | tensor2tensor/rl/ppo_learner.py | _rollout_metadata | def _rollout_metadata(batch_env):
"""Metadata for rollouts."""
batch_env_shape = batch_env.observ.get_shape().as_list()
batch_size = [batch_env_shape[0]]
shapes_types_names = [
# TODO(piotrmilos): possibly retrieve the observation type for batch_env
(batch_size + batch_env_shape[1:], batch_env.obser... | python | def _rollout_metadata(batch_env):
"""Metadata for rollouts."""
batch_env_shape = batch_env.observ.get_shape().as_list()
batch_size = [batch_env_shape[0]]
shapes_types_names = [
# TODO(piotrmilos): possibly retrieve the observation type for batch_env
(batch_size + batch_env_shape[1:], batch_env.obser... | [
"def",
"_rollout_metadata",
"(",
"batch_env",
")",
":",
"batch_env_shape",
"=",
"batch_env",
".",
"observ",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"batch_size",
"=",
"[",
"batch_env_shape",
"[",
"0",
"]",
"]",
"shapes_types_names",
"=",
"[",
... | Metadata for rollouts. | [
"Metadata",
"for",
"rollouts",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/ppo_learner.py#L254-L268 |
22,688 | tensorflow/tensor2tensor | tensor2tensor/models/vanilla_gan.py | sliced_gan | def sliced_gan():
"""Basic parameters for a vanilla_gan."""
hparams = common_hparams.basic_params1()
hparams.optimizer = "adam"
hparams.learning_rate_constant = 0.0002
hparams.learning_rate_warmup_steps = 500
hparams.learning_rate_schedule = "constant * linear_warmup"
hparams.label_smoothing = 0.0
hpara... | python | def sliced_gan():
"""Basic parameters for a vanilla_gan."""
hparams = common_hparams.basic_params1()
hparams.optimizer = "adam"
hparams.learning_rate_constant = 0.0002
hparams.learning_rate_warmup_steps = 500
hparams.learning_rate_schedule = "constant * linear_warmup"
hparams.label_smoothing = 0.0
hpara... | [
"def",
"sliced_gan",
"(",
")",
":",
"hparams",
"=",
"common_hparams",
".",
"basic_params1",
"(",
")",
"hparams",
".",
"optimizer",
"=",
"\"adam\"",
"hparams",
".",
"learning_rate_constant",
"=",
"0.0002",
"hparams",
".",
"learning_rate_warmup_steps",
"=",
"500",
... | Basic parameters for a vanilla_gan. | [
"Basic",
"parameters",
"for",
"a",
"vanilla_gan",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/vanilla_gan.py#L199-L217 |
22,689 | tensorflow/tensor2tensor | tensor2tensor/models/vanilla_gan.py | AbstractGAN.body | def body(self, features):
"""Body of the model.
Args:
features: a dictionary with the tensors.
Returns:
A pair (predictions, losses) where predictions is the generated image
and losses is a dictionary of losses (that get added for the final loss).
"""
features["targets"] = featur... | python | def body(self, features):
"""Body of the model.
Args:
features: a dictionary with the tensors.
Returns:
A pair (predictions, losses) where predictions is the generated image
and losses is a dictionary of losses (that get added for the final loss).
"""
features["targets"] = featur... | [
"def",
"body",
"(",
"self",
",",
"features",
")",
":",
"features",
"[",
"\"targets\"",
"]",
"=",
"features",
"[",
"\"inputs\"",
"]",
"is_training",
"=",
"self",
".",
"hparams",
".",
"mode",
"==",
"tf",
".",
"estimator",
".",
"ModeKeys",
".",
"TRAIN",
"... | Body of the model.
Args:
features: a dictionary with the tensors.
Returns:
A pair (predictions, losses) where predictions is the generated image
and losses is a dictionary of losses (that get added for the final loss). | [
"Body",
"of",
"the",
"model",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/vanilla_gan.py#L127-L160 |
22,690 | tensorflow/tensor2tensor | tensor2tensor/trax/inputs.py | inputs | def inputs(num_devices, dataset_name, data_dir=None, input_name=None,
num_chunks=0, append_targets=False):
"""Make Inputs for built-in datasets.
Args:
num_devices: how many devices to build the inputs for.
dataset_name: a TFDS or T2T dataset name. If it's a T2T dataset name, prefix
with "t... | python | def inputs(num_devices, dataset_name, data_dir=None, input_name=None,
num_chunks=0, append_targets=False):
"""Make Inputs for built-in datasets.
Args:
num_devices: how many devices to build the inputs for.
dataset_name: a TFDS or T2T dataset name. If it's a T2T dataset name, prefix
with "t... | [
"def",
"inputs",
"(",
"num_devices",
",",
"dataset_name",
",",
"data_dir",
"=",
"None",
",",
"input_name",
"=",
"None",
",",
"num_chunks",
"=",
"0",
",",
"append_targets",
"=",
"False",
")",
":",
"assert",
"data_dir",
",",
"\"Must provide a data directory\"",
... | Make Inputs for built-in datasets.
Args:
num_devices: how many devices to build the inputs for.
dataset_name: a TFDS or T2T dataset name. If it's a T2T dataset name, prefix
with "t2t_".
data_dir: data directory.
input_name: optional, name of the inputs from the dictionary.
num_chunks: optio... | [
"Make",
"Inputs",
"for",
"built",
"-",
"in",
"datasets",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/inputs.py#L58-L95 |
22,691 | tensorflow/tensor2tensor | tensor2tensor/trax/inputs.py | random_inputs | def random_inputs(
num_devices,
input_shape=gin.REQUIRED, input_dtype=np.int32, input_range=(0, 255),
output_shape=gin.REQUIRED, output_dtype=np.int32, output_range=(0, 9)):
"""Make random Inputs for debugging.
Args:
num_devices: how many devices to build the inputs for.
input_shape: the shape ... | python | def random_inputs(
num_devices,
input_shape=gin.REQUIRED, input_dtype=np.int32, input_range=(0, 255),
output_shape=gin.REQUIRED, output_dtype=np.int32, output_range=(0, 9)):
"""Make random Inputs for debugging.
Args:
num_devices: how many devices to build the inputs for.
input_shape: the shape ... | [
"def",
"random_inputs",
"(",
"num_devices",
",",
"input_shape",
"=",
"gin",
".",
"REQUIRED",
",",
"input_dtype",
"=",
"np",
".",
"int32",
",",
"input_range",
"=",
"(",
"0",
",",
"255",
")",
",",
"output_shape",
"=",
"gin",
".",
"REQUIRED",
",",
"output_d... | Make random Inputs for debugging.
Args:
num_devices: how many devices to build the inputs for.
input_shape: the shape of inputs (including batch dimension).
input_dtype: the type of the inputs (int32 by default).
input_range: the range of inputs (defaults to (0, 255)).
output_shape: the shape of ... | [
"Make",
"random",
"Inputs",
"for",
"debugging",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/inputs.py#L99-L143 |
22,692 | tensorflow/tensor2tensor | tensor2tensor/trax/inputs.py | dataset_to_stream | def dataset_to_stream(dataset, input_name, num_chunks=0, append_targets=False):
"""Takes a tf.Dataset and creates a numpy stream of ready batches."""
for example in tfds.as_numpy(dataset):
inp, out = example[0][input_name], example[1]
if len(out.shape) > 1 and out.shape[-1] == 1:
out = np.squeeze(out,... | python | def dataset_to_stream(dataset, input_name, num_chunks=0, append_targets=False):
"""Takes a tf.Dataset and creates a numpy stream of ready batches."""
for example in tfds.as_numpy(dataset):
inp, out = example[0][input_name], example[1]
if len(out.shape) > 1 and out.shape[-1] == 1:
out = np.squeeze(out,... | [
"def",
"dataset_to_stream",
"(",
"dataset",
",",
"input_name",
",",
"num_chunks",
"=",
"0",
",",
"append_targets",
"=",
"False",
")",
":",
"for",
"example",
"in",
"tfds",
".",
"as_numpy",
"(",
"dataset",
")",
":",
"inp",
",",
"out",
"=",
"example",
"[",
... | Takes a tf.Dataset and creates a numpy stream of ready batches. | [
"Takes",
"a",
"tf",
".",
"Dataset",
"and",
"creates",
"a",
"numpy",
"stream",
"of",
"ready",
"batches",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/inputs.py#L146-L157 |
22,693 | tensorflow/tensor2tensor | tensor2tensor/trax/inputs.py | _train_and_eval_batches | def _train_and_eval_batches(dataset, data_dir, input_name, num_devices):
"""Return train and eval batches with input name and shape."""
(train_data, eval_data, features_info, keys) = train_and_eval_dataset(
dataset, data_dir)
input_names, target_names = keys[0], keys[1]
train_batches = shuffle_and_batch_d... | python | def _train_and_eval_batches(dataset, data_dir, input_name, num_devices):
"""Return train and eval batches with input name and shape."""
(train_data, eval_data, features_info, keys) = train_and_eval_dataset(
dataset, data_dir)
input_names, target_names = keys[0], keys[1]
train_batches = shuffle_and_batch_d... | [
"def",
"_train_and_eval_batches",
"(",
"dataset",
",",
"data_dir",
",",
"input_name",
",",
"num_devices",
")",
":",
"(",
"train_data",
",",
"eval_data",
",",
"features_info",
",",
"keys",
")",
"=",
"train_and_eval_dataset",
"(",
"dataset",
",",
"data_dir",
")",
... | Return train and eval batches with input name and shape. | [
"Return",
"train",
"and",
"eval",
"batches",
"with",
"input",
"name",
"and",
"shape",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/inputs.py#L388-L405 |
22,694 | tensorflow/tensor2tensor | tensor2tensor/data_generators/multi_problem_v2.py | get_multi_dataset | def get_multi_dataset(datasets, pmf=None):
"""Returns a Dataset that samples records from one or more Datasets.
Args:
datasets: A list of one or more Dataset objects to sample from.
pmf: A tensor of shape [len(datasets)], the probabilities to sample each
dataset with. This tensor is often constructed... | python | def get_multi_dataset(datasets, pmf=None):
"""Returns a Dataset that samples records from one or more Datasets.
Args:
datasets: A list of one or more Dataset objects to sample from.
pmf: A tensor of shape [len(datasets)], the probabilities to sample each
dataset with. This tensor is often constructed... | [
"def",
"get_multi_dataset",
"(",
"datasets",
",",
"pmf",
"=",
"None",
")",
":",
"pmf",
"=",
"tf",
".",
"fill",
"(",
"[",
"len",
"(",
"datasets",
")",
"]",
",",
"1.0",
"/",
"len",
"(",
"datasets",
")",
")",
"if",
"pmf",
"is",
"None",
"else",
"pmf"... | Returns a Dataset that samples records from one or more Datasets.
Args:
datasets: A list of one or more Dataset objects to sample from.
pmf: A tensor of shape [len(datasets)], the probabilities to sample each
dataset with. This tensor is often constructed with the global_step. If
this is None, we... | [
"Returns",
"a",
"Dataset",
"that",
"samples",
"records",
"from",
"one",
"or",
"more",
"Datasets",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L205-L223 |
22,695 | tensorflow/tensor2tensor | tensor2tensor/data_generators/multi_problem_v2.py | get_schedule_distribution | def get_schedule_distribution(schedule, global_step=None):
"""Computes the pmf of a schedule given the global_step.
Args:
schedule: A schedule tuple, see encode_schedule for details.
global_step: A scalar tensor, the step to query the schedule.
Returns:
A 1-D tensor of probs, the sampling distributi... | python | def get_schedule_distribution(schedule, global_step=None):
"""Computes the pmf of a schedule given the global_step.
Args:
schedule: A schedule tuple, see encode_schedule for details.
global_step: A scalar tensor, the step to query the schedule.
Returns:
A 1-D tensor of probs, the sampling distributi... | [
"def",
"get_schedule_distribution",
"(",
"schedule",
",",
"global_step",
"=",
"None",
")",
":",
"interpolation",
",",
"steps",
",",
"pmfs",
"=",
"schedule",
"if",
"len",
"(",
"pmfs",
")",
"==",
"1",
":",
"# py_func doesn't seem to work on TPU - at least get the cons... | Computes the pmf of a schedule given the global_step.
Args:
schedule: A schedule tuple, see encode_schedule for details.
global_step: A scalar tensor, the step to query the schedule.
Returns:
A 1-D tensor of probs, the sampling distribution of the global_step. | [
"Computes",
"the",
"pmf",
"of",
"a",
"schedule",
"given",
"the",
"global_step",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L226-L253 |
22,696 | tensorflow/tensor2tensor | tensor2tensor/data_generators/multi_problem_v2.py | linear_interpolation | def linear_interpolation(x, xp, fp, **kwargs):
"""Multi-dimensional linear interpolation.
Returns the multi-dimensional piecewise linear interpolant to a function with
given discrete data points (xp, fp), evaluated at x.
Note that *N and *M indicate zero or more dimensions.
Args:
x: An array of shape [... | python | def linear_interpolation(x, xp, fp, **kwargs):
"""Multi-dimensional linear interpolation.
Returns the multi-dimensional piecewise linear interpolant to a function with
given discrete data points (xp, fp), evaluated at x.
Note that *N and *M indicate zero or more dimensions.
Args:
x: An array of shape [... | [
"def",
"linear_interpolation",
"(",
"x",
",",
"xp",
",",
"fp",
",",
"*",
"*",
"kwargs",
")",
":",
"yp",
"=",
"fp",
".",
"reshape",
"(",
"[",
"fp",
".",
"shape",
"[",
"0",
"]",
",",
"-",
"1",
"]",
")",
".",
"transpose",
"(",
")",
"y",
"=",
"... | Multi-dimensional linear interpolation.
Returns the multi-dimensional piecewise linear interpolant to a function with
given discrete data points (xp, fp), evaluated at x.
Note that *N and *M indicate zero or more dimensions.
Args:
x: An array of shape [*N], the x-coordinates of the interpolated values.
... | [
"Multi",
"-",
"dimensional",
"linear",
"interpolation",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L274-L294 |
22,697 | tensorflow/tensor2tensor | tensor2tensor/data_generators/multi_problem_v2.py | step_interpolation | def step_interpolation(x, xp, fp, **kwargs):
"""Multi-dimensional step interpolation.
Returns the multi-dimensional step interpolant to a function with
given discrete data points (xp, fp), evaluated at x.
Note that *N and *M indicate zero or more dimensions.
Args:
x: An array of shape [*N], the x-coord... | python | def step_interpolation(x, xp, fp, **kwargs):
"""Multi-dimensional step interpolation.
Returns the multi-dimensional step interpolant to a function with
given discrete data points (xp, fp), evaluated at x.
Note that *N and *M indicate zero or more dimensions.
Args:
x: An array of shape [*N], the x-coord... | [
"def",
"step_interpolation",
"(",
"x",
",",
"xp",
",",
"fp",
",",
"*",
"*",
"kwargs",
")",
":",
"del",
"kwargs",
"# Unused.",
"xp",
"=",
"np",
".",
"expand_dims",
"(",
"xp",
",",
"-",
"1",
")",
"lower",
",",
"upper",
"=",
"xp",
"[",
":",
"-",
"... | Multi-dimensional step interpolation.
Returns the multi-dimensional step interpolant to a function with
given discrete data points (xp, fp), evaluated at x.
Note that *N and *M indicate zero or more dimensions.
Args:
x: An array of shape [*N], the x-coordinates of the interpolated values.
xp: An np.a... | [
"Multi",
"-",
"dimensional",
"step",
"interpolation",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L297-L325 |
22,698 | tensorflow/tensor2tensor | tensor2tensor/data_generators/multi_problem_v2.py | epoch_rates_to_pmf | def epoch_rates_to_pmf(problems, epoch_rates=None):
"""Create a probability-mass-function based on relative epoch rates.
if epoch_rates=None, then we use uniform epoch rates [1.0] * len(problems)
i.e. it takes each problem the same time to go through one epoch.
If epoch_rates is given, then these are the rela... | python | def epoch_rates_to_pmf(problems, epoch_rates=None):
"""Create a probability-mass-function based on relative epoch rates.
if epoch_rates=None, then we use uniform epoch rates [1.0] * len(problems)
i.e. it takes each problem the same time to go through one epoch.
If epoch_rates is given, then these are the rela... | [
"def",
"epoch_rates_to_pmf",
"(",
"problems",
",",
"epoch_rates",
"=",
"None",
")",
":",
"if",
"epoch_rates",
"is",
"None",
":",
"epoch_rates",
"=",
"[",
"1.0",
"]",
"*",
"len",
"(",
"problems",
")",
"example_rates",
"=",
"[",
"epoch_rate",
"*",
"p",
"."... | Create a probability-mass-function based on relative epoch rates.
if epoch_rates=None, then we use uniform epoch rates [1.0] * len(problems)
i.e. it takes each problem the same time to go through one epoch.
If epoch_rates is given, then these are the relative numbers of epochs
of each problem to go through in... | [
"Create",
"a",
"probability",
"-",
"mass",
"-",
"function",
"based",
"on",
"relative",
"epoch",
"rates",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L353-L375 |
22,699 | tensorflow/tensor2tensor | tensor2tensor/data_generators/multi_problem_v2.py | encode_schedule | def encode_schedule(schedule):
"""Encodes a schedule tuple into a string.
Args:
schedule: A tuple containing (interpolation, steps, pmfs), where
interpolation is a string specifying the interpolation strategy, steps
is an int array_like of shape [N] specifying the global steps, and pmfs is
an... | python | def encode_schedule(schedule):
"""Encodes a schedule tuple into a string.
Args:
schedule: A tuple containing (interpolation, steps, pmfs), where
interpolation is a string specifying the interpolation strategy, steps
is an int array_like of shape [N] specifying the global steps, and pmfs is
an... | [
"def",
"encode_schedule",
"(",
"schedule",
")",
":",
"interpolation",
",",
"steps",
",",
"pmfs",
"=",
"schedule",
"return",
"interpolation",
"+",
"' '",
"+",
"' '",
".",
"join",
"(",
"'@'",
"+",
"str",
"(",
"s",
")",
"+",
"' '",
"+",
"' '",
".",
"joi... | Encodes a schedule tuple into a string.
Args:
schedule: A tuple containing (interpolation, steps, pmfs), where
interpolation is a string specifying the interpolation strategy, steps
is an int array_like of shape [N] specifying the global steps, and pmfs is
an array_like of shape [N, M] where pm... | [
"Encodes",
"a",
"schedule",
"tuple",
"into",
"a",
"string",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L378-L394 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.