project_name stringlengths 6 104 | file_name stringlengths 4 89 | full_name stringlengths 1 102 | func_name stringlengths 1 85 | docstring stringlengths 13 836 | docstring_tokens listlengths 4 122 | code stringlengths 23 39.7k | code_tokens stringlengths 29 44.6k | url int64 3 986k |
|---|---|---|---|---|---|---|---|---|
ajboyd2/vae_mpp | utils.py | xavier_truncated_normal | xavier_truncated_normal | Samples from a truncated normal where the standard deviation is automatically chosen based on size. | [
"Samples",
"from",
"a",
"truncated",
"normal",
"where",
"the",
"standard",
"deviation",
"is",
"automatically",
"chosen",
"based",
"on",
"size."
] | def xavier_truncated_normal(size, limit=2, no_average=False):
if isinstance(size, int):
size = (size,)
if len(size) == 1 or no_average:
n_avg = size[-1]
else:
(n_in, n_out) = (size[-2], size[-1])
n_avg = (n_in + n_out) / 2
return truncated_normal(size, scale=(1 / n_avg) *... | ['def', 'xavier_truncated_normal(size,', 'limit=2,', 'no_average=False):', 'if', 'isinstance(size,', 'int):', 'size', '=', '(size,)', 'if', 'len(size)', '==', '1', 'or', 'no_average:', 'n_avg', '=', 'size[-1]', 'else:', '(n_in,', 'n_out)', '=', '(size[-2],', 'size[-1])', 'n_avg', '=', '(n_in', '+', 'n_out)', '/', '2', ... | 930,827 |
LCBHSStudent/vanet-edge-caching-based-on-deep-reinforcement- | dqn_agent.py | DQNAgent.select_action | select_action | Select an action from the input state. | [
"Select",
"an",
"action",
"from",
"the",
"input",
"state."
] | def select_action(self, state: np.ndarray) -> np.ndarray:
selected_action = self.dqn(torch.FloatTensor(state).to(self.device)).argmax()
selected_action = selected_action.detach().cpu().numpy()
if not self.is_test:
self.transition = [state, selected_action]
return selected_action | ['def', 'select_action(self,', 'state:', 'np.ndarray)', '->', 'np.ndarray:', 'selected_action', '=', 'self.dqn(torch.FloatTensor(state).to(self.device)).argmax()', 'selected_action', '=', 'selected_action.detach().cpu().numpy()', 'if', 'not', 'self.is_test:', 'self.transition', '=', '[state,', 'selected_action]', 'retu... | 930,831 |
LCBHSStudent/vanet-edge-caching-based-on-deep-reinforcement- | dqn_agent.py | DQNAgent.step | step | Take an action and return the response of the env. | [
"Take",
"an",
"action",
"and",
"return",
"the",
"response",
"of",
"the",
"env."
] | def step(self, action: np.ndarray) -> Tuple[np.ndarray, np.float64, bool]:
(next_state, reward, done, _) = self.env.step(action)
if not self.is_test:
self.transition += [reward, next_state, done]
if self.use_n_step:
one_step_transition = self.memory_n.store(*self.transition)
... | ['def', 'step(self,', 'action:', 'np.ndarray)', '->', 'Tuple[np.ndarray,', 'np.float64,', 'bool]:', '(next_state,', 'reward,', 'done,', '_)', '=', 'self.env.step(action)', 'if', 'not', 'self.is_test:', 'self.transition', '+=', '[reward,', 'next_state,', 'done]', 'if', 'self.use_n_step:', 'one_step_transition', '=', 'se... | 930,832 |
LCBHSStudent/vanet-edge-caching-based-on-deep-reinforcement- | dqn_agent.py | DQNAgent.update_model | update_model | Update the model by gradient descent. | [
"Update",
"the",
"model",
"by",
"gradient",
"descent."
] | def update_model(self) -> torch.Tensor:
samples = self.memory.sample_batch(self.beta)
weights = torch.FloatTensor(samples['weights'].reshape(-1, 1)).to(self.device)
indices = samples['indices']
elementwise_loss = self._compute_dqn_loss(samples, self.gamma)
loss = torch.mean(elementwise_loss * weight... | ['def', 'update_model(self)', '->', 'torch.Tensor:', 'samples', '=', 'self.memory.sample_batch(self.beta)', 'weights', '=', "torch.FloatTensor(samples['weights'].reshape(-1,", '1)).to(self.device)', 'indices', '=', "samples['indices']", 'elementwise_loss', '=', 'self._compute_dqn_loss(samples,', 'self.gamma)', 'loss', ... | 930,833 |
LCBHSStudent/vanet-edge-caching-based-on-deep-reinforcement- | net.py | Network.reset_noise | reset_noise | Reset all noisy layers. | [
"Reset",
"all",
"noisy",
"layers."
] | def reset_noise(self):
self.advantage_hidden_layer.reset_noise()
self.advantage_layer.reset_noise()
self.value_hidden_layer.reset_noise()
self.value_layer.reset_noise() | ['def', 'reset_noise(self):', 'self.advantage_hidden_layer.reset_noise()', 'self.advantage_layer.reset_noise()', 'self.value_hidden_layer.reset_noise()', 'self.value_layer.reset_noise()'] | 930,835 |
LCBHSStudent/vanet-edge-caching-based-on-deep-reinforcement- | replay_buffer.py | PrioritizedReplayBuffer.store | store | Store experience and priority. | [
"Store",
"experience",
"and",
"priority."
] | def store(self, obs: np.ndarray, act: int, rew: float, next_obs: np.ndarray, done: bool) -> Tuple[np.ndarray, np.ndarray, float, np.ndarray, bool]:
transition = super().store(obs, act, rew, next_obs, done)
if transition:
self.sum_tree[self.tree_ptr] = self.max_priority ** self.alpha
self.min_tre... | ['def', 'store(self,', 'obs:', 'np.ndarray,', 'act:', 'int,', 'rew:', 'float,', 'next_obs:', 'np.ndarray,', 'done:', 'bool)', '->', 'Tuple[np.ndarray,', 'np.ndarray,', 'float,', 'np.ndarray,', 'bool]:', 'transition', '=', 'super().store(obs,', 'act,', 'rew,', 'next_obs,', 'done)', 'if', 'transition:', 'self.sum_tree[se... | 930,839 |
jaanli/variational-autoencoder | plot.py | make_canvas_gif | make_canvas_gif | Creates and saves gif from images generated by make_canvas(). | [
"Creates",
"and",
"saves",
"gif",
"from",
"images",
"generated",
"by",
"make_canvas()."
] | def make_canvas_gif():
images = [imread('../figs/canvas/' + file) for file in sorted(os.listdir(path='../figs/canvas/')) if file != '.gitkeep']
durations = list(np.diff(np.log(4 + np.arange(len(images)))))
clip = ImageSequenceClip(images, durations=durations)
clip.fps = 25
clip.write_gif('../canvas.... | ['def', 'make_canvas_gif():', 'images', '=', "[imread('../figs/canvas/'", '+', 'file)', 'for', 'file', 'in', "sorted(os.listdir(path='../figs/canvas/'))", 'if', 'file', '!=', "'.gitkeep']", 'durations', '=', 'list(np.diff(np.log(4', '+', 'np.arange(len(images)))))', 'clip', '=', 'ImageSequenceClip(images,', 'durations=... | 930,905 |
jaanli/variational-autoencoder | plot.py | make_spread_gif | make_spread_gif | Creates and saves gif from images generated by make_spread(). | [
"Creates",
"and",
"saves",
"gif",
"from",
"images",
"generated",
"by",
"make_spread()."
] | def make_spread_gif():
images = [imread('../figs/spread/' + file) for file in sorted(os.listdir(path='../figs/spread/')) if file != '.gitkeep']
clip = ImageSequenceClip(images, fps=5)
clip.write_gif('../spread.gif') | ['def', 'make_spread_gif():', 'images', '=', "[imread('../figs/spread/'", '+', 'file)', 'for', 'file', 'in', "sorted(os.listdir(path='../figs/spread/'))", 'if', 'file', '!=', "'.gitkeep']", 'clip', '=', 'ImageSequenceClip(images,', 'fps=5)', "clip.write_gif('../spread.gif')"] | 930,907 |
jaywalnut310/Vector-Quantized-Autoencoders | commons.py | embedding_to_padding | embedding_to_padding | Calculates the padding mask based on which embeddings are all zero. | [
"Calculates",
"the",
"padding",
"mask",
"based",
"on",
"which",
"embeddings",
"are",
"all",
"zero."
] | def embedding_to_padding(emb):
emb_sum = tf.reduce_sum(tf.abs(emb), axis=-1)
return tf.to_float(tf.equal(emb_sum, 0.0)) | ['def', 'embedding_to_padding(emb):', 'emb_sum', '=', 'tf.reduce_sum(tf.abs(emb),', 'axis=-1)', 'return', 'tf.to_float(tf.equal(emb_sum,', '0.0))'] | 931,021 |
jaywalnut310/Vector-Quantized-Autoencoders | commons.py | split_heads | split_heads | Split channels (dimension 2) into multiple heads (becomes dimension 1). | [
"Split",
"channels",
"(dimension",
"2)",
"into",
"multiple",
"heads",
"(becomes",
"dimension",
"1)."
] | def split_heads(x, num_heads):
return tf.transpose(split_last_dimension(x, num_heads), [0, 2, 1, 3]) | ['def', 'split_heads(x,', 'num_heads):', 'return', 'tf.transpose(split_last_dimension(x,', 'num_heads),', '[0,', '2,', '1,', '3])'] | 931,039 |
jaywalnut310/Vector-Quantized-Autoencoders | commons.py | compute_attention_component | compute_attention_component | Computes attention compoenent (query, key or value). | [
"Computes",
"attention",
"compoenent",
"(query,",
"key",
"or",
"value)."
] | def compute_attention_component(antecedent, total_depth, filter_width=1, padding='VALID', name='c'):
if filter_width == 1:
return tf.layers.dense(antecedent, total_depth, use_bias=False, name=name)
else:
return tf.layers.conv1d(antecedent, total_depth, filter_width, padding=padding, name=name) | ['def', 'compute_attention_component(antecedent,', 'total_depth,', 'filter_width=1,', "padding='VALID',", "name='c'):", 'if', 'filter_width', '==', '1:', 'return', 'tf.layers.dense(antecedent,', 'total_depth,', 'use_bias=False,', 'name=name)', 'else:', 'return', 'tf.layers.conv1d(antecedent,', 'total_depth,', 'filter_w... | 931,040 |
jaywalnut310/Vector-Quantized-Autoencoders | transformer_vq.py | init_vq_bottleneck | init_vq_bottleneck | Get lookup table for VQ bottleneck. | [
"Get",
"lookup",
"table",
"for",
"VQ",
"bottleneck."
] | def init_vq_bottleneck(bottleneck_size, hidden_size, mean_only=False):
means = tf.get_variable(name='means', shape=[bottleneck_size, hidden_size], initializer=tf.initializers.variance_scaling(distribution='uniform'))
if not mean_only:
ema_count = tf.get_variable(name='ema_count', shape=[bottleneck_size]... | ['def', 'init_vq_bottleneck(bottleneck_size,', 'hidden_size,', 'mean_only=False):', 'means', '=', "tf.get_variable(name='means',", 'shape=[bottleneck_size,', 'hidden_size],', "initializer=tf.initializers.variance_scaling(distribution='uniform'))", 'if', 'not', 'mean_only:', 'ema_count', '=', "tf.get_variable(name='ema_... | 931,049 |
jaywalnut310/Vector-Quantized-Autoencoders | transformer_vq.py | vq_discrete_bottleneck | vq_discrete_bottleneck | Simple vector quantized discrete bottleneck. | [
"Simple",
"vector",
"quantized",
"discrete",
"bottleneck."
] | def vq_discrete_bottleneck(x, hparams):
bottleneck_size = 2 ** hparams.bottleneck_bits
x_shape = commons.shape_list(x)
x = tf.reshape(x, [-1, hparams.hidden_size])
(x_means_hot, e_loss) = vq_nearest_neighbor(x, hparams)
if hparams.bottleneck_kind == 'mog':
loss = hparams.beta * e_loss
el... | ['def', 'vq_discrete_bottleneck(x,', 'hparams):', 'bottleneck_size', '=', '2', '**', 'hparams.bottleneck_bits', 'x_shape', '=', 'commons.shape_list(x)', 'x', '=', 'tf.reshape(x,', '[-1,', 'hparams.hidden_size])', '(x_means_hot,', 'e_loss)', '=', 'vq_nearest_neighbor(x,', 'hparams)', 'if', 'hparams.bottleneck_kind', '==... | 931,051 |
google-research/tensor2robot | meta_tfdata.py | expand_batch_dims | expand_batch_dims | Expands the first dimension of each tensor in structure to be batch_sizes. | [
"Expands",
"the",
"first",
"dimension",
"of",
"each",
"tensor",
"in",
"structure",
"to",
"be",
"batch_sizes."
] | def expand_batch_dims(structure, batch_sizes):
def _helper(tensor):
if isinstance(tensor, tf.Tensor):
shape = tf.shape(tensor)
return tf.reshape(tensor, tf.concat([batch_sizes, shape[1:]], axis=0))
else:
return tensor
return nest.map_structure(_helper, struct... | ['def', 'expand_batch_dims(structure,', 'batch_sizes):', 'def', '_helper(tensor):', 'if', 'isinstance(tensor,', 'tf.Tensor):', 'shape', '=', 'tf.shape(tensor)', 'return', 'tf.reshape(tensor,', 'tf.concat([batch_sizes,', 'shape[1:]],', 'axis=0))', 'else:', 'return', 'tensor', 'return', 'nest.map_structure(_helper,', 'st... | 908,185 |
google-research/tensor2robot | preprocessors.py | create_maml_label_spec | create_maml_label_spec | Create a meta feature from existing base_model specs. | [
"Create",
"a",
"meta",
"feature",
"from",
"existing",
"base_model",
"specs."
] | def create_maml_label_spec(label_spec):
return utils.flatten_spec_structure(utils.copy_tensorspec(label_spec, batch_size=-1, prefix='meta_labels')) | ['def', 'create_maml_label_spec(label_spec):', 'return', 'utils.flatten_spec_structure(utils.copy_tensorspec(label_spec,', 'batch_size=-1,', "prefix='meta_labels'))"] | 908,188 |
google-research/tensor2robot | preprocessors.py | stack_intra_task_episodes | stack_intra_task_episodes | Stacks together tensors from different episodes of the same task. | [
"Stacks",
"together",
"tensors",
"from",
"different",
"episodes",
"of",
"the",
"same",
"task."
] | def stack_intra_task_episodes(in_tensors, num_samples_per_task):
out_tensors = TSpecStructure()
key_set = set(['/'.join(key.split('/')[:-1]) for key in in_tensors.keys()])
for key in key_set:
data = []
for i in range(num_samples_per_task):
data.append(in_tensors['{:s}/{:d}'.forma... | ['def', 'stack_intra_task_episodes(in_tensors,', 'num_samples_per_task):', 'out_tensors', '=', 'TSpecStructure()', 'key_set', '=', "set(['/'.join(key.split('/')[:-1])", 'for', 'key', 'in', 'in_tensors.keys()])', 'for', 'key', 'in', 'key_set:', 'data', '=', '[]', 'for', 'i', 'in', 'range(num_samples_per_task):', "data.a... | 908,190 |
google-research/tensor2robot | preprocessors.py | MAMLPreprocessorV2.create_meta_map_fn | create_meta_map_fn | Creates a map function to construct meta features/labels. | [
"Creates",
"a",
"map",
"function",
"to",
"construct",
"meta",
"features/labels."
] | def create_meta_map_fn(self, num_condition_samples_per_task, num_inference_samples_per_task):
if num_condition_samples_per_task is None or num_condition_samples_per_task <= 0:
raise ValueError('num_condition_samples_per_task cannot be None and has to be positve but is {}.'.format(num_condition_samples_per_t... | ['def', 'create_meta_map_fn(self,', 'num_condition_samples_per_task,', 'num_inference_samples_per_task):', 'if', 'num_condition_samples_per_task', 'is', 'None', 'or', 'num_condition_samples_per_task', '<=', '0:', 'raise', "ValueError('num_condition_samples_per_task", 'cannot', 'be', 'None', 'and', 'has', 'to', 'be', 'p... | 908,191 |
google-research/tensor2robot | abstract_model.py | AbstractT2RModel.scaffold_fn | scaffold_fn | Returns a scaffold function object for model loading. | [
"Returns",
"a",
"scaffold",
"function",
"object",
"for",
"model",
"loading."
] | def scaffold_fn(self):
return self._scaffold_fn | ['def', 'scaffold_fn(self):', 'return', 'self._scaffold_fn'] | 908,198 |
google-research/tensor2robot | abstract_model.py | AbstractT2RModel.get_eval_hooks | get_eval_hooks | Get eval_hooks to be passed to estimator spec. | [
"Get",
"eval_hooks",
"to",
"be",
"passed",
"to",
"estimator",
"spec."
] | def get_eval_hooks(self, config, params):
logging.warning('This function is deprecated and will be replaced.')
hooks = []
summary_op = tf.summary.merge_all()
if summary_op is not None:
eval_name = 'eval'
if params is not None:
eval_name = params.get('eval_name', eval_name)
... | ['def', 'get_eval_hooks(self,', 'config,', 'params):', "logging.warning('This", 'function', 'is', 'deprecated', 'and', 'will', 'be', "replaced.')", 'hooks', '=', '[]', 'summary_op', '=', 'tf.summary.merge_all()', 'if', 'summary_op', 'is', 'not', 'None:', 'eval_name', '=', "'eval'", 'if', 'params', 'is', 'not', 'None:',... | 908,199 |
google-research/tensor2robot | abstract_model.py | AbstractT2RModel.create_train_op | create_train_op | Create the train_op of from the loss obtained from model_train_fn. | [
"Create",
"the",
"train_op",
"of",
"from",
"the",
"loss",
"obtained",
"from",
"model_train_fn."
] | def create_train_op(self, loss, optimizer, update_ops=None, train_outputs=None, filter_trainables_fn=None, **kwargs):
summarize_gradients = self._summarize_gradients
if self.is_device_tpu:
if self._summarize_gradients:
logging.info('We cannot use summarize_gradients on TPUs.')
summar... | ['def', 'create_train_op(self,', 'loss,', 'optimizer,', 'update_ops=None,', 'train_outputs=None,', 'filter_trainables_fn=None,', '**kwargs):', 'summarize_gradients', '=', 'self._summarize_gradients', 'if', 'self.is_device_tpu:', 'if', 'self._summarize_gradients:', "logging.info('We", 'cannot', 'use', 'summarize_gradien... | 908,202 |
google-research/tensor2robot | classification_model.py | ClassificationModel.pack_state_to_feature_spec | pack_state_to_feature_spec | Packs the state feature spec from the state. | [
"Packs",
"the",
"state",
"feature",
"spec",
"from",
"the",
"state."
] | def pack_state_to_feature_spec(self, state_params):
feature_spec = tensorspec_utils.TensorSpecStruct(state=state_params)
return feature_spec | ['def', 'pack_state_to_feature_spec(self,', 'state_params):', 'feature_spec', '=', 'tensorspec_utils.TensorSpecStruct(state=state_params)', 'return', 'feature_spec'] | 908,219 |
google-research/tensor2robot | optimizers.py | create_constant_learning_rate | create_constant_learning_rate | Returns the configured constant initial_learning_rate. | [
"Returns",
"the",
"configured",
"constant",
"initial_learning_rate."
] | def create_constant_learning_rate(initial_learning_rate=0.0001):
return initial_learning_rate | ['def', 'create_constant_learning_rate(initial_learning_rate=0.0001):', 'return', 'initial_learning_rate'] | 908,237 |
google-research/tensor2robot | optimizers.py | create_adam_optimizer | create_adam_optimizer | Creates a function that returns a configured Adam optimizer. | [
"Creates",
"a",
"function",
"that",
"returns",
"a",
"configured",
"Adam",
"optimizer."
] | def create_adam_optimizer(learning_rate_fn=create_constant_learning_rate):
def create_optimizer_fn(use_summaries):
learning_rate = learning_rate_fn()
if use_summaries:
tf.summary.scalar('learning_rate', learning_rate)
return tf.train.AdamOptimizer(learning_rate=learning_rate)
... | ['def', 'create_adam_optimizer(learning_rate_fn=create_constant_learning_rate):', 'def', 'create_optimizer_fn(use_summaries):', 'learning_rate', '=', 'learning_rate_fn()', 'if', 'use_summaries:', "tf.summary.scalar('learning_rate',", 'learning_rate)', 'return', 'tf.train.AdamOptimizer(learning_rate=learning_rate)', 're... | 908,239 |
google-research/tensor2robot | optimizers.py | create_gradient_descent_optimizer | create_gradient_descent_optimizer | Creates a function that returns a configured Gradient Descent Optimizer. | [
"Creates",
"a",
"function",
"that",
"returns",
"a",
"configured",
"Gradient",
"Descent",
"Optimizer."
] | def create_gradient_descent_optimizer(learning_rate_fn=create_constant_learning_rate):
def create_optimizer_fn(use_summaries):
learning_rate = learning_rate_fn()
if use_summaries:
tf.summary.scalar('learning_rate', learning_rate)
return tf.train.GradientDescentOptimizer(learning... | ['def', 'create_gradient_descent_optimizer(learning_rate_fn=create_constant_learning_rate):', 'def', 'create_optimizer_fn(use_summaries):', 'learning_rate', '=', 'learning_rate_fn()', 'if', 'use_summaries:', "tf.summary.scalar('learning_rate',", 'learning_rate)', 'return', 'tf.train.GradientDescentOptimizer(learning_ra... | 908,240 |
google-research/tensor2robot | optimizers.py | create_momentum_optimizer | create_momentum_optimizer | Creates a function that returns a configured Momentum Optimizer. | [
"Creates",
"a",
"function",
"that",
"returns",
"a",
"configured",
"Momentum",
"Optimizer."
] | def create_momentum_optimizer(learning_rate_fn=create_constant_learning_rate, momentum=0.9):
def create_optimizer_fn(use_summaries):
learning_rate = learning_rate_fn()
if use_summaries:
tf.summary.scalar('learning_rate', learning_rate)
return tf.train.MomentumOptimizer(learning_... | ['def', 'create_momentum_optimizer(learning_rate_fn=create_constant_learning_rate,', 'momentum=0.9):', 'def', 'create_optimizer_fn(use_summaries):', 'learning_rate', '=', 'learning_rate_fn()', 'if', 'use_summaries:', "tf.summary.scalar('learning_rate',", 'learning_rate)', 'return', 'tf.train.MomentumOptimizer(learning_... | 908,241 |
google-research/tensor2robot | policies.py | Policy.restore | restore | Restore policy parameters from a checkpoint. | [
"Restore",
"policy",
"parameters",
"from",
"a",
"checkpoint."
] | def restore(self):
if self._predictor is not None:
self._predictor.restore() | ['def', 'restore(self):', 'if', 'self._predictor', 'is', 'not', 'None:', 'self._predictor.restore()'] | 908,255 |
google-research/tensor2robot | policies.py | Policy.global_step | global_step | The global step the model was saved with. | [
"The",
"global",
"step",
"the",
"model",
"was",
"saved",
"with."
] | def global_step(self):
if self._predictor is not None:
return self._predictor.global_step
return 0 | ['def', 'global_step(self):', 'if', 'self._predictor', 'is', 'not', 'None:', 'return', 'self._predictor.global_step', 'return', '0'] | 908,256 |
google-research/tensor2robot | policies.py | CEMPolicy.get_cem_action | get_cem_action | Returns CEM approximate argmax on an objective_fn. | [
"Returns",
"CEM",
"approximate",
"argmax",
"on",
"an",
"objective_fn."
] | def get_cem_action(self, objective_fn):
def update_fn(params, elite_samples):
del params
return {'mean': np.mean(elite_samples, axis=0), 'stddev': np.std(elite_samples, axis=0, ddof=1)}
mu = np.zeros(self._action_size)
initial_params = {'mean': mu, 'stddev': np.ones(self._action_size)}
... | ['def', 'get_cem_action(self,', 'objective_fn):', 'def', 'update_fn(params,', 'elite_samples):', 'del', 'params', 'return', "{'mean':", 'np.mean(elite_samples,', 'axis=0),', "'stddev':", 'np.std(elite_samples,', 'axis=0,', 'ddof=1)}', 'mu', '=', 'np.zeros(self._action_size)', 'initial_params', '=', "{'mean':", 'mu,', "... | 908,258 |
google-research/tensor2robot | abstract_predictor.py | AbstractPredictor.model_version | model_version | The version of the model currently in use. | [
"The",
"version",
"of",
"the",
"model",
"currently",
"in",
"use."
] | def model_version(self):
return 0 | ['def', 'model_version(self):', 'return', '0'] | 908,266 |
google-research/tensor2robot | abstract_predictor.py | AbstractPredictor.global_step | global_step | The global step of the model currently in use. | [
"The",
"global",
"step",
"of",
"the",
"model",
"currently",
"in",
"use."
] | def global_step(self):
return 0 | ['def', 'global_step(self):', 'return', '0'] | 908,267 |
google-research/tensor2robot | abstract_predictor.py | AbstractPredictor.model_path | model_path | The path of the model currently in use. | [
"The",
"path",
"of",
"the",
"model",
"currently",
"in",
"use."
] | def model_path(self):
return '' | ['def', 'model_path(self):', 'return', "''"] | 908,268 |
google-research/tensor2robot | saved_model_v2_predictor.py | SavedModelPredictorBase.wait_and_restore | wait_and_restore | Wait and restores the model parameters. | [
"Wait",
"and",
"restores",
"the",
"model",
"parameters."
] | def wait_and_restore(self):
model_dirs = None
while model_dirs is None:
time.sleep(10)
model_dirs_tmp = sorted(tf.io.gfile.glob(os.path.join(self._saved_model_path, '*')), reverse=True)
model_dirs_tmp2 = []
for checkpoint_dir in model_dirs_tmp:
if re.match('.*\\/([0-9... | ['def', 'wait_and_restore(self):', 'model_dirs', '=', 'None', 'while', 'model_dirs', 'is', 'None:', 'time.sleep(10)', 'model_dirs_tmp', '=', 'sorted(tf.io.gfile.glob(os.path.join(self._saved_model_path,', "'*')),", 'reverse=True)', 'model_dirs_tmp2', '=', '[]', 'for', 'checkpoint_dir', 'in', 'model_dirs_tmp:', 'if', "r... | 908,299 |
google-research/tensor2robot | distortion.py | maybe_distort_image_batch | maybe_distort_image_batch | Applies data augmentation to given images. | [
"Applies",
"data",
"augmentation",
"to",
"given",
"images."
] | def maybe_distort_image_batch(images, mode):
if mode == tf_estimator.ModeKeys.TRAIN:
images = image_transformations.ApplyPhotometricImageDistortions([images])[0]
return images | ['def', 'maybe_distort_image_batch(images,', 'mode):', 'if', 'mode', '==', 'tf_estimator.ModeKeys.TRAIN:', 'images', '=', 'image_transformations.ApplyPhotometricImageDistortions([images])[0]', 'return', 'images'] | 908,313 |
google-research/tensor2robot | image_transformations.py | CustomCropImages | CustomCropImages | Crop a list of images at with a custom crop location and size. | [
"Crop",
"a",
"list",
"of",
"images",
"at",
"with",
"a",
"custom",
"crop",
"location",
"and",
"size."
] | def CustomCropImages(images, input_shape, target_shape, target_locations):
if len(input_shape) != 3:
raise ValueError('The input shape has to be of the form (height, width, channels) but has len {}'.format(len(input_shape)))
if len(target_shape) != 2:
raise ValueError('The target shape has to be... | ['def', 'CustomCropImages(images,', 'input_shape,', 'target_shape,', 'target_locations):', 'if', 'len(input_shape)', '!=', '3:', 'raise', "ValueError('The", 'input', 'shape', 'has', 'to', 'be', 'of', 'the', 'form', '(height,', 'width,', 'channels)', 'but', 'has', 'len', "{}'.format(len(input_shape)))", 'if', 'len(targe... | 908,319 |
google-research/tensor2robot | image_transformations.py | ApplyRandomFlips | ApplyRandomFlips | Randomly flips images across x-axis and y-axis. | [
"Randomly",
"flips",
"images",
"across",
"x-axis",
"and",
"y-axis."
] | def ApplyRandomFlips(images):
with tf.name_scope('random_flips'):
left_flip = tf.random_uniform([]) > 0.5
up_flip = tf.random_uniform([]) > 0.5
images = tf.cond(left_flip, lambda : tf.image.flip_left_right(images), lambda : images)
images = tf.cond(up_flip, lambda : tf.image.flip_up_... | ['def', 'ApplyRandomFlips(images):', 'with', "tf.name_scope('random_flips'):", 'left_flip', '=', 'tf.random_uniform([])', '>', '0.5', 'up_flip', '=', 'tf.random_uniform([])', '>', '0.5', 'images', '=', 'tf.cond(left_flip,', 'lambda', ':', 'tf.image.flip_left_right(images),', 'lambda', ':', 'images)', 'images', '=', 'tf... | 908,323 |
google-research/tensor2robot | image_transformations.py | ApplyDepthImageDistortions | ApplyDepthImageDistortions | Apply photometric distortions to the input depth images. | [
"Apply",
"photometric",
"distortions",
"to",
"the",
"input",
"depth",
"images."
] | def ApplyDepthImageDistortions(depth_images, random_noise_level=0.05, random_noise_apply_probability=0.5, scaling_noise=True, gamma_shape=1000.0, gamma_scale_inverse=1000.0, min_depth_allowed=0.25, max_depth_allowed=2.5):
assert depth_images[0].get_shape().as_list()[-1] == 1
with tf.variable_scope('distortions_... | ['def', 'ApplyDepthImageDistortions(depth_images,', 'random_noise_level=0.05,', 'random_noise_apply_probability=0.5,', 'scaling_noise=True,', 'gamma_shape=1000.0,', 'gamma_scale_inverse=1000.0,', 'min_depth_allowed=0.25,', 'max_depth_allowed=2.5):', 'assert', 'depth_images[0].get_shape().as_list()[-1]', '==', '1', 'wit... | 908,324 |
google-research/tensor2robot | spec_transformation_preprocessor.py | SpecTransformationPreprocessor.update_spec | update_spec | Helper function to allow to alter a specific tensorspec in the structure. | [
"Helper",
"function",
"to",
"allow",
"to",
"alter",
"a",
"specific",
"tensorspec",
"in",
"the",
"structure."
] | def update_spec(self, tensor_spec_struct, key, **kwargs_for_tensorspec):
tensor_spec_struct[key] = tensorspec_utils.ExtendedTensorSpec.from_spec(spec=tensor_spec_struct[key], **kwargs_for_tensorspec) | ['def', 'update_spec(self,', 'tensor_spec_struct,', 'key,', '**kwargs_for_tensorspec):', 'tensor_spec_struct[key]', '=', 'tensorspec_utils.ExtendedTensorSpec.from_spec(spec=tensor_spec_struct[key],', '**kwargs_for_tensorspec)'] | 908,333 |
google-research/tensor2robot | model.py | spatial_softmax_network | spatial_softmax_network | Spatial-Softmax based image-to-action network. | [
"Spatial-Softmax",
"based",
"image-to-action",
"network."
] | def spatial_softmax_network(features, is_training, pose_components, num_waypoints, condition_input=None):
with tf.variable_scope('vision_model', reuse=tf.AUTO_REUSE):
(feature_points, _) = vision_layers.BuildImagesToFeaturesModel(features.image, is_training=is_training, normalizer_fn=slim.layer_norm)
... | ['def', 'spatial_softmax_network(features,', 'is_training,', 'pose_components,', 'num_waypoints,', 'condition_input=None):', 'with', "tf.variable_scope('vision_model',", 'reuse=tf.AUTO_REUSE):', '(feature_points,', '_)', '=', 'vision_layers.BuildImagesToFeaturesModel(features.image,', 'is_training=is_training,', 'norma... | 908,343 |
google-research/tensor2robot | model.py | compute_stop_state_loss | compute_stop_state_loss | Constructs loss for the stop_state_prediction. | [
"Constructs",
"loss",
"for",
"the",
"stop_state_prediction."
] | def compute_stop_state_loss(stop_state_labels, stop_state_predictions, class_weights=gin.REQUIRED):
class_weights = tf.constant(class_weights)
weights = tf.reduce_sum(stop_state_labels * class_weights, -1)
return tf.losses.softmax_cross_entropy(stop_state_labels, stop_state_predictions, weights=weights) | ['def', 'compute_stop_state_loss(stop_state_labels,', 'stop_state_predictions,', 'class_weights=gin.REQUIRED):', 'class_weights', '=', 'tf.constant(class_weights)', 'weights', '=', 'tf.reduce_sum(stop_state_labels', '*', 'class_weights,', '-1)', 'return', 'tf.losses.softmax_cross_entropy(stop_state_labels,', 'stop_stat... | 908,346 |
google-research/tensor2robot | model.py | get_gripper_accuracy_metrics | get_gripper_accuracy_metrics | Return metrics for gripper close prediction accuracy. | [
"Return",
"metrics",
"for",
"gripper",
"close",
"prediction",
"accuracy."
] | def get_gripper_accuracy_metrics(inference_outputs, features, labels):
key = 'target_close'
current = features.present[key]
dtype = labels.future[key].dtype
thresh = 0
predicted_is_closing = tf.cast(inference_outputs[key][:, 0] - current > thresh, dtype)
label_is_closing = tf.cast(labels.future[... | ['def', 'get_gripper_accuracy_metrics(inference_outputs,', 'features,', 'labels):', 'key', '=', "'target_close'", 'current', '=', 'features.present[key]', 'dtype', '=', 'labels.future[key].dtype', 'thresh', '=', '0', 'predicted_is_closing', '=', 'tf.cast(inference_outputs[key][:,', '0]', '-', 'current', '>', 'thresh,',... | 908,348 |
google-research/tensor2robot | model.py | BCZModel.pack_features | pack_features | Pass-through function, as environment should do the feature packing. | [
"Pass-through",
"function,",
"as",
"environment",
"should",
"do",
"the",
"feature",
"packing."
] | def pack_features(self, state, prev_episode_data, timestep):
del prev_episode_data, timestep
return state | ['def', 'pack_features(self,', 'state,', 'prev_episode_data,', 'timestep):', 'del', 'prev_episode_data,', 'timestep', 'return', 'state'] | 908,349 |
google-research/tensor2robot | model.py | BCZModel.add_summaries | add_summaries | Summary function to support visualization in meta learning inner loop. | [
"Summary",
"function",
"to",
"support",
"visualization",
"in",
"meta",
"learning",
"inner",
"loop."
] | def add_summaries(self, features, labels, inference_outputs, train_loss, train_outputs, mode, config=None, params=None):
if not self.use_summaries(params):
return
if 'image' in features.keys():
tf.summary.image('image', inference_outputs['image'])
if train_outputs:
for (key, value) i... | ['def', 'add_summaries(self,', 'features,', 'labels,', 'inference_outputs,', 'train_loss,', 'train_outputs,', 'mode,', 'config=None,', 'params=None):', 'if', 'not', 'self.use_summaries(params):', 'return', 'if', "'image'", 'in', 'features.keys():', "tf.summary.image('image',", "inference_outputs['image'])", 'if', 'trai... | 908,352 |
google-research/tensor2robot | model_test.py | BCZModelTest.test_all_components | test_all_components | Train with all pose components. | [
"Train",
"with",
"all",
"pose",
"components."
] | def test_all_components(self):
model_name = 'BCZModel'
pose_components = [('xyz', 3, True, 100.0), ('quaternion', 4, False, 10.0), ('axis_angle', 3, True, 10.0), ('arm_joints', 7, True, 1.0), ('target_close', 1, False, 1.0)]
gin.bind_parameter('BCZModel.action_components', pose_components)
gin.parse_con... | ['def', 'test_all_components(self):', 'model_name', '=', "'BCZModel'", 'pose_components', '=', "[('xyz',", '3,', 'True,', '100.0),', "('quaternion',", '4,', 'False,', '10.0),', "('axis_angle',", '3,', 'True,', '10.0),', "('arm_joints',", '7,', 'True,', '1.0),', "('target_close',", '1,', 'False,', '1.0)]', "gin.bind_par... | 908,353 |
google-research/tensor2robot | run_env.py | run_tfagents_env | run_tfagents_env | Runs agent+TF-Agents env loop num_episodes times, logging performance. | [
"Runs",
"agent+TF-Agents",
"env",
"loop",
"num_episodes",
"times,",
"logging",
"performance."
] | def run_tfagents_env(env, policy=None, explore_schedule=None, episode_to_transitions_fn=None, replay_writer=None, root_dir=None, task=0, global_step=0, num_episodes=100, tag='collect'):
return _run_env(env, reset_fn=_tfagents_env_reset, step_fn=_tfagents_env_step, policy=policy, explore_schedule=explore_schedule, e... | ['def', 'run_tfagents_env(env,', 'policy=None,', 'explore_schedule=None,', 'episode_to_transitions_fn=None,', 'replay_writer=None,', 'root_dir=None,', 'task=0,', 'global_step=0,', 'num_episodes=100,', "tag='collect'):", 'return', '_run_env(env,', 'reset_fn=_tfagents_env_reset,', 'step_fn=_tfagents_env_step,', 'policy=p... | 908,357 |
google-research/tensor2robot | tf_modules.py | argscope | argscope | Default TF argscope used for convnet-based grasping models. | [
"Default",
"TF",
"argscope",
"used",
"for",
"convnet-based",
"grasping",
"models."
] | def argscope(is_training=None, normalizer_fn=slim.layer_norm):
with slim.arg_scope([slim.batch_norm, slim.dropout], is_training=is_training):
with slim.arg_scope([slim.conv2d, slim.fully_connected], weights_initializer=tf.truncated_normal_initializer(stddev=0.01), activation_fn=tf.nn.relu, normalizer_fn=nor... | ['def', 'argscope(is_training=None,', 'normalizer_fn=slim.layer_norm):', 'with', 'slim.arg_scope([slim.batch_norm,', 'slim.dropout],', 'is_training=is_training):', 'with', 'slim.arg_scope([slim.conv2d,', 'slim.fully_connected],', 'weights_initializer=tf.truncated_normal_initializer(stddev=0.01),', 'activation_fn=tf.nn.... | 908,358 |
google-research/tensor2robot | grasp2vec_model.py | maybe_crop_images | maybe_crop_images | Helper function to crop a list of image tensors randomly. | [
"Helper",
"function",
"to",
"crop",
"a",
"list",
"of",
"image",
"tensors",
"randomly."
] | def maybe_crop_images(images, params, mode):
(min_offset_height, max_offset_height, target_height, min_offset_width, max_offset_width, target_width) = params
if mode == TRAIN:
offset_height = tf.random_uniform((), minval=min_offset_height, maxval=max_offset_height, dtype=tf.int32)
offset_width =... | ['def', 'maybe_crop_images(images,', 'params,', 'mode):', '(min_offset_height,', 'max_offset_height,', 'target_height,', 'min_offset_width,', 'max_offset_width,', 'target_width)', '=', 'params', 'if', 'mode', '==', 'TRAIN:', 'offset_height', '=', 'tf.random_uniform((),', 'minval=min_offset_height,', 'maxval=max_offset_... | 908,361 |
google-research/tensor2robot | losses.py | SendToZeroLoss | SendToZeroLoss | Calculates the distance of the inputs from zero. | [
"Calculates",
"the",
"distance",
"of",
"the",
"inputs",
"from",
"zero."
] | def SendToZeroLoss(tensor, mask):
mask = tf.cast(mask, tf.int32)
mask = tf.reshape(mask, (-1,))
def _ComputeLoss():
distances = tf.norm(tensor, axis=1)
(_, mask1_data) = tf.dynamic_partition(distances, mask, 2)
loss = tf.cast(tf.reduce_mean(mask1_data), tf.float32)
return lo... | ['def', 'SendToZeroLoss(tensor,', 'mask):', 'mask', '=', 'tf.cast(mask,', 'tf.int32)', 'mask', '=', 'tf.reshape(mask,', '(-1,))', 'def', '_ComputeLoss():', 'distances', '=', 'tf.norm(tensor,', 'axis=1)', '(_,', 'mask1_data)', '=', 'tf.dynamic_partition(distances,', 'mask,', '2)', 'loss', '=', 'tf.cast(tf.reduce_mean(ma... | 908,366 |
google-research/tensor2robot | resnet.py | get_resnet_model | get_resnet_model | Creates a Resnet model with specific parameters. | [
"Creates",
"a",
"Resnet",
"model",
"with",
"specific",
"parameters."
] | def get_resnet_model(image, training):
resnet_size = 50
if resnet_size < 50:
bottleneck = False
final_size = 512
else:
bottleneck = True
final_size = 2048
model = Model(resnet_size=resnet_size, bottleneck=bottleneck, num_classes=1001, num_filters=64, kernel_size=7, conv_s... | ['def', 'get_resnet_model(image,', 'training):', 'resnet_size', '=', '50', 'if', 'resnet_size', '<', '50:', 'bottleneck', '=', 'False', 'final_size', '=', '512', 'else:', 'bottleneck', '=', 'True', 'final_size', '=', '2048', 'model', '=', 'Model(resnet_size=resnet_size,', 'bottleneck=bottleneck,', 'num_classes=1001,', ... | 908,376 |
google-research/tensor2robot | visualization.py | plot_distances | plot_distances | Plot evaluation metrics for grasp2vec. | [
"Plot",
"evaluation",
"metrics",
"for",
"grasp2vec."
] | def plot_distances(pregrasp, goal, postgrasp):
correct_distances = tf.norm(pregrasp - (goal + postgrasp), axis=1)
incorrect_distances = tf.norm(pregrasp - pregrasp[::-1], axis=1)
goal_distances = tf.norm(goal - goal[::-1], axis=1)
tf.summary.histogram('correct_distances', correct_distances)
tf.summa... | ['def', 'plot_distances(pregrasp,', 'goal,', 'postgrasp):', 'correct_distances', '=', 'tf.norm(pregrasp', '-', '(goal', '+', 'postgrasp),', 'axis=1)', 'incorrect_distances', '=', 'tf.norm(pregrasp', '-', 'pregrasp[::-1],', 'axis=1)', 'goal_distances', '=', 'tf.norm(goal', '-', 'goal[::-1],', 'axis=1)', "tf.summary.hist... | 908,379 |
google-research/tensor2robot | visualization.py | add_heatmap_summary | add_heatmap_summary | Plots dot produce of feature_query on feature_map. | [
"Plots",
"dot",
"produce",
"of",
"feature_query",
"on",
"feature_map."
] | def add_heatmap_summary(feature_query, feature_map, name):
(batch, dim) = feature_query.shape
reshaped_query = tf.reshape(feature_query, (int(batch), 1, 1, int(dim)))
heatmaps = tf.reduce_sum(tf.multiply(feature_map, reshaped_query), axis=3, keep_dims=True)
tf.summary.image(name, heatmaps)
shape = t... | ['def', 'add_heatmap_summary(feature_query,', 'feature_map,', 'name):', '(batch,', 'dim)', '=', 'feature_query.shape', 'reshaped_query', '=', 'tf.reshape(feature_query,', '(int(batch),', '1,', '1,', 'int(dim)))', 'heatmaps', '=', 'tf.reduce_sum(tf.multiply(feature_map,', 'reshaped_query),', 'axis=3,', 'keep_dims=True)'... | 908,380 |
google-research/tensor2robot | visualization.py | add_spatial_soft_argmax_viz | add_spatial_soft_argmax_viz | Generates TensorBoard visualization summaries for spatial softmax models. | [
"Generates",
"TensorBoard",
"visualization",
"summaries",
"for",
"spatial",
"softmax",
"models."
] | def add_spatial_soft_argmax_viz(image, softmax, locations, max_outputs=3, num_groups=1, num_rows=1):
tf.summary.histogram('x', locations[:, :, 0])
tf.summary.histogram('y', locations[:, :, 1])
softmax_avg_channel = tf.reduce_mean(softmax, 3, keep_dims=True)
tf.summary.image('SpatialSoftmax/softmax_avg',... | ['def', 'add_spatial_soft_argmax_viz(image,', 'softmax,', 'locations,', 'max_outputs=3,', 'num_groups=1,', 'num_rows=1):', "tf.summary.histogram('x',", 'locations[:,', ':,', '0])', "tf.summary.histogram('y',", 'locations[:,', ':,', '1])', 'softmax_avg_channel', '=', 'tf.reduce_mean(softmax,', '3,', 'keep_dims=True)', "... | 908,382 |
google-research/tensor2robot | visualization.py | get_softmax_viz | get_softmax_viz | Arrange softmax maps in a grid and superimpose them on the image. | [
"Arrange",
"softmax",
"maps",
"in",
"a",
"grid",
"and",
"superimpose",
"them",
"on",
"the",
"image."
] | def get_softmax_viz(image, softmax, nrows=None):
softmax_shape = tf.shape(softmax)
batch_size = softmax_shape[0]
target_height = softmax_shape[1] * 2
target_width = softmax_shape[2] * 2
num_points = softmax_shape[3]
if nrows is None:
num_points_float = tf.cast(num_points, tf.float32)
... | ['def', 'get_softmax_viz(image,', 'softmax,', 'nrows=None):', 'softmax_shape', '=', 'tf.shape(softmax)', 'batch_size', '=', 'softmax_shape[0]', 'target_height', '=', 'softmax_shape[1]', '*', '2', 'target_width', '=', 'softmax_shape[2]', '*', '2', 'num_points', '=', 'softmax_shape[3]', 'if', 'nrows', 'is', 'None:', 'num... | 908,383 |
google-research/tensor2robot | episode_to_transitions.py | episode_to_transitions_pose_toy | episode_to_transitions_pose_toy | Converts pose toy env episode data to transition Examples. | [
"Converts",
"pose",
"toy",
"env",
"episode",
"data",
"to",
"transition",
"Examples."
] | def episode_to_transitions_pose_toy(episode_data):
transitions = []
for transition in episode_data:
(obs_t, action, reward, obs_tp1, done, debug) = transition
del obs_tp1
del done
features = {}
obs_t = Image.fromarray(obs_t)
features['state/image'] = _bytes_featur... | ['def', 'episode_to_transitions_pose_toy(episode_data):', 'transitions', '=', '[]', 'for', 'transition', 'in', 'episode_data:', '(obs_t,', 'action,', 'reward,', 'obs_tp1,', 'done,', 'debug)', '=', 'transition', 'del', 'obs_tp1', 'del', 'done', 'features', '=', '{}', 'obs_t', '=', 'Image.fromarray(obs_t)', "features['st... | 908,385 |
google-research/tensor2robot | pose_env_models.py | PoseEnvRegressionModel.get_config | get_config | This model trains fairly quickly so evaluate frequently. | [
"This",
"model",
"trains",
"fairly",
"quickly",
"so",
"evaluate",
"frequently."
] | def get_config(self):
return tf_estimator.RunConfig(save_checkpoints_steps=2000, keep_checkpoint_max=5) | ['def', 'get_config(self):', 'return', 'tf_estimator.RunConfig(save_checkpoints_steps=2000,', 'keep_checkpoint_max=5)'] | 908,388 |
google-research/tensor2robot | networks.py | GraspingModel.create_grasp_params_input | create_grasp_params_input | Creates grasp params input from translation and rotation parameters. | [
"Creates",
"grasp",
"params",
"input",
"from",
"translation",
"and",
"rotation",
"parameters."
] | def create_grasp_params_input(self, model_input, concat_axis=1):
return tf.concat([model_input[grasp_input] for grasp_input in self.grasp_model_input_keys], concat_axis) | ['def', 'create_grasp_params_input(self,', 'model_input,', 'concat_axis=1):', 'return', 'tf.concat([model_input[grasp_input]', 'for', 'grasp_input', 'in', 'self.grasp_model_input_keys],', 'concat_axis)'] | 908,391 |
google-research/tensor2robot | networks.py | GraspingModel.add_losses | add_losses | Add the losses to train the model. | [
"Add",
"the",
"losses",
"to",
"train",
"the",
"model."
] | def add_losses(self, config, logits, end_points, label, loss_type, use_tpu=False):
logits = tf.check_numerics(logits, 'Logits is not a number.')
label = tf.check_numerics(label, 'Label is not a number.')
if loss_type == 'cross_entropy':
slim.losses.softmax_cross_entropy(logits, label)
elif loss_... | ['def', 'add_losses(self,', 'config,', 'logits,', 'end_points,', 'label,', 'loss_type,', 'use_tpu=False):', 'logits', '=', 'tf.check_numerics(logits,', "'Logits", 'is', 'not', 'a', "number.')", 'label', '=', 'tf.check_numerics(label,', "'Label", 'is', 'not', 'a', "number.')", 'if', 'loss_type', '==', "'cross_entropy':"... | 908,394 |
google-research/tensor2robot | networks.py | Grasping44FlexibleGraspParams.model | model | Creates a tensorflow graph for this model. | [
"Creates",
"a",
"tensorflow",
"graph",
"for",
"this",
"model."
] | def model(self, images, grasp_params, num_classes=1, is_training=False, softmax=False, restore=True, grasp_param_names=None, goal_spatial_fn=None, goal_vector_fn=None, scope=None, reuse=None, **kwargs):
del kwargs
if not restore:
raise ValueError("This model doesn't yet support restore=False")
batch... | ['def', 'model(self,', 'images,', 'grasp_params,', 'num_classes=1,', 'is_training=False,', 'softmax=False,', 'restore=True,', 'grasp_param_names=None,', 'goal_spatial_fn=None,', 'goal_vector_fn=None,', 'scope=None,', 'reuse=None,', '**kwargs):', 'del', 'kwargs', 'if', 'not', 'restore:', 'raise', 'ValueError("This', 'mo... | 908,398 |
google-research/tensor2robot | t2r_models.py | pack_features_kuka_e2e | pack_features_kuka_e2e | Crop, Convert, Maybe Distort images. | [
"Crop,",
"Convert,",
"Maybe",
"Distort",
"images."
] | def pack_features_kuka_e2e(tf_model, *policy_inputs):
del tf_model, policy_inputs
raise NotImplementedError | ['def', 'pack_features_kuka_e2e(tf_model,', '*policy_inputs):', 'del', 'tf_model,', 'policy_inputs', 'raise', 'NotImplementedError'] | 908,401 |
google-research/tensor2robot | t2r_models.py | LegacyGraspingModelWrapper.get_variables | get_variables | Returns list of model variables. | [
"Returns",
"list",
"of",
"model",
"variables."
] | def get_variables(self):
return contrib_framework.get_variables(self.legacy_model_class.__name__) | ['def', 'get_variables(self):', 'return', 'contrib_framework.get_variables(self.legacy_model_class.__name__)'] | 908,403 |
google-research/tensor2robot | t2r_models.py | LegacyGraspingModelWrapper.create_optimizer | create_optimizer | Create the optimizer and scaffold used for training. | [
"Create",
"the",
"optimizer",
"and",
"scaffold",
"used",
"for",
"training."
] | def create_optimizer(self, params):
config = self.get_run_config()
original_optimizer = self._create_optimizer_fn(self.use_summaries(params))
use_avg_model_params = self.hparams.use_avg_model_params
def scaffold_fn():
scaffold = tf.train.Scaffold()
if use_avg_model_params:
s... | ['def', 'create_optimizer(self,', 'params):', 'config', '=', 'self.get_run_config()', 'original_optimizer', '=', 'self._create_optimizer_fn(self.use_summaries(params))', 'use_avg_model_params', '=', 'self.hparams.use_avg_model_params', 'def', 'scaffold_fn():', 'scaffold', '=', 'tf.train.Scaffold()', 'if', 'use_avg_mode... | 908,405 |
google-research/tensor2robot | t2r_models.py | LegacyGraspingModelWrapper.create_train_op | create_train_op | Create the train of from the loss obtained from model_train_fn. | [
"Create",
"the",
"train",
"of",
"from",
"the",
"loss",
"obtained",
"from",
"model_train_fn."
] | def create_train_op(self, loss, optimizer, update_ops=None, train_outputs=None):
variables_to_train = self.get_trainable_variables()
summarize_gradients = self._summarize_gradients
if self.is_device_tpu:
if self._summarize_gradients:
logging.info('We cannot use summarize_gradients on TPU... | ['def', 'create_train_op(self,', 'loss,', 'optimizer,', 'update_ops=None,', 'train_outputs=None):', 'variables_to_train', '=', 'self.get_trainable_variables()', 'summarize_gradients', '=', 'self._summarize_gradients', 'if', 'self.is_device_tpu:', 'if', 'self._summarize_gradients:', "logging.info('We", 'cannot', 'use', ... | 908,406 |
google-research/tensor2robot | discrete.py | GetDiscreteBins | GetDiscreteBins | Compute bin centers for discretizing the provided range into bins. | [
"Compute",
"bin",
"centers",
"for",
"discretizing",
"the",
"provided",
"range",
"into",
"bins."
] | def GetDiscreteBins(num_bins, output_min, output_max):
action_range = output_max - output_min
bin_sizes = action_range / float(num_bins)
return np.array([output_min + bin_sizes * (bin_i + 0.5) for bin_i in range(num_bins)]) | ['def', 'GetDiscreteBins(num_bins,', 'output_min,', 'output_max):', 'action_range', '=', 'output_max', '-', 'output_min', 'bin_sizes', '=', 'action_range', '/', 'float(num_bins)', 'return', 'np.array([output_min', '+', 'bin_sizes', '*', '(bin_i', '+', '0.5)', 'for', 'bin_i', 'in', 'range(num_bins)])'] | 908,407 |
google-research/tensor2robot | discrete.py | GetDiscreteActions | GetDiscreteActions | Compute the discrete actions corresponding to the input logits. | [
"Compute",
"the",
"discrete",
"actions",
"corresponding",
"to",
"the",
"input",
"logits."
] | def GetDiscreteActions(logits, action_size, num_bins, bin_centers):
action_probabilities = tf.nn.softmax(tf.reshape(logits, (-1, action_size, num_bins)))
actions_onehot = tf.one_hot(tf.argmax(action_probabilities, -1), num_bins)
bin_centers = tf.constant(np.transpose(bin_centers), dtype=tf.float32)
acti... | ['def', 'GetDiscreteActions(logits,', 'action_size,', 'num_bins,', 'bin_centers):', 'action_probabilities', '=', 'tf.nn.softmax(tf.reshape(logits,', '(-1,', 'action_size,', 'num_bins)))', 'actions_onehot', '=', 'tf.one_hot(tf.argmax(action_probabilities,', '-1),', 'num_bins)', 'bin_centers', '=', 'tf.constant(np.transp... | 908,408 |
google-research/tensor2robot | discrete.py | GetDiscreteActionLoss | GetDiscreteActionLoss | Convert labels to one-hot, compute cross-entropy loss, and return loss. | [
"Convert",
"labels",
"to",
"one-hot,",
"compute",
"cross-entropy",
"loss,",
"and",
"return",
"loss."
] | def GetDiscreteActionLoss(logits, action_labels, bin_centers, num_bins):
action_labels = tf.expand_dims(action_labels, -2)
bin_centers = tf.constant(bin_centers, dtype=tf.float32)
while len(bin_centers.shape) < len(action_labels.shape):
bin_centers = tf.expand_dims(bin_centers, 0)
discrete_label... | ['def', 'GetDiscreteActionLoss(logits,', 'action_labels,', 'bin_centers,', 'num_bins):', 'action_labels', '=', 'tf.expand_dims(action_labels,', '-2)', 'bin_centers', '=', 'tf.constant(bin_centers,', 'dtype=tf.float32)', 'while', 'len(bin_centers.shape)', '<', 'len(action_labels.shape):', 'bin_centers', '=', 'tf.expand_... | 908,409 |
google-research/tensor2robot | episode_to_transitions.py | make_fixed_length | make_fixed_length | Create a fixed length list by sampling entries from input_list. | [
"Create",
"a",
"fixed",
"length",
"list",
"by",
"sampling",
"entries",
"from",
"input_list."
] | def make_fixed_length(input_list, fixed_length, always_include_endpoints=True, randomized=True):
original_length = len(input_list)
if original_length <= 2:
return None
if not randomized:
indices = np.sort(np.mod(np.arange(fixed_length), original_length))
return [input_list[i] for i i... | ['def', 'make_fixed_length(input_list,', 'fixed_length,', 'always_include_endpoints=True,', 'randomized=True):', 'original_length', '=', 'len(input_list)', 'if', 'original_length', '<=', '2:', 'return', 'None', 'if', 'not', 'randomized:', 'indices', '=', 'np.sort(np.mod(np.arange(fixed_length),', 'original_length))', '... | 908,410 |
google-research/tensor2robot | episode_to_transitions.py | episode_to_transitions_reacher | episode_to_transitions_reacher | Converts reacher env data to transition examples. | [
"Converts",
"reacher",
"env",
"data",
"to",
"transition",
"examples."
] | def episode_to_transitions_reacher(episode_data, is_demo=False):
transitions = []
for (i, transition) in enumerate(episode_data):
del i
feature_dict = {}
(obs_t, action, reward, obs_tp1, done, debug) = transition
del debug
feature_dict['pose_t'] = _float_feature(obs_t)
... | ['def', 'episode_to_transitions_reacher(episode_data,', 'is_demo=False):', 'transitions', '=', '[]', 'for', '(i,', 'transition)', 'in', 'enumerate(episode_data):', 'del', 'i', 'feature_dict', '=', '{}', '(obs_t,', 'action,', 'reward,', 'obs_tp1,', 'done,', 'debug)', '=', 'transition', 'del', 'debug', "feature_dict['pos... | 908,411 |
google-research/tensor2robot | episode_to_transitions.py | episode_to_transitions_metareacher | episode_to_transitions_metareacher | Converts metareacher env data to transition examples. | [
"Converts",
"metareacher",
"env",
"data",
"to",
"transition",
"examples."
] | def episode_to_transitions_metareacher(episode_data):
context_features = {}
feature_lists = collections.defaultdict(list)
context_features['is_demo'] = _int64_feature([int(episode_data[0][-1]['is_demo'])])
context_features['target_idx'] = _int64_feature([episode_data[0][-1]['target_idx']])
for (i, t... | ['def', 'episode_to_transitions_metareacher(episode_data):', 'context_features', '=', '{}', 'feature_lists', '=', 'collections.defaultdict(list)', "context_features['is_demo']", '=', "_int64_feature([int(episode_data[0][-1]['is_demo'])])", "context_features['target_idx']", '=', "_int64_feature([episode_data[0][-1]['tar... | 908,412 |
google-research/tensor2robot | maf.py | maf_bijector | maf_bijector | Construct a chain of MAF flows into a single bijector. | [
"Construct",
"a",
"chain",
"of",
"MAF",
"flows",
"into",
"a",
"single",
"bijector."
] | def maf_bijector(event_size, num_flows, hidden_layers):
bijectors = []
for i in range(num_flows):
bijectors.append(tfb.MaskedAutoregressiveFlow(shift_and_log_scale_fn=tfb.masked_autoregressive_default_template(hidden_layers=hidden_layers)))
bijectors.append(tfb.Permute(permutation=init_once(np.r... | ['def', 'maf_bijector(event_size,', 'num_flows,', 'hidden_layers):', 'bijectors', '=', '[]', 'for', 'i', 'in', 'range(num_flows):', 'bijectors.append(tfb.MaskedAutoregressiveFlow(shift_and_log_scale_fn=tfb.masked_autoregressive_default_template(hidden_layers=hidden_layers)))', "bijectors.append(tfb.Permute(permutation=... | 908,414 |
google-research/tensor2robot | vrgripper_env_models.py | VRGripperDomainAdaptiveModel.single_batch_a_func | single_batch_a_func | Single step action predictor when there is a single batch dim. | [
"Single",
"step",
"action",
"predictor",
"when",
"there",
"is",
"a",
"single",
"batch",
"dim."
] | def single_batch_a_func(self, features, scope, mode, context_fn, reuse, config, params):
del config
with tf.variable_scope(scope, reuse=reuse, use_resource=True):
with tf.variable_scope('state_features', reuse=reuse, use_resource=True):
(feature_points, end_points) = vision_layers.BuildImage... | ['def', 'single_batch_a_func(self,', 'features,', 'scope,', 'mode,', 'context_fn,', 'reuse,', 'config,', 'params):', 'del', 'config', 'with', 'tf.variable_scope(scope,', 'reuse=reuse,', 'use_resource=True):', 'with', "tf.variable_scope('state_features',", 'reuse=reuse,', 'use_resource=True):', '(feature_points,', 'end_... | 908,421 |
google-research/tensor2robot | vrgripper_env_models.py | VRGripperDomainAdaptiveModel.model_train_fn | model_train_fn | Output learned loss if inner loop, or behavior clone if outer loop. | [
"Output",
"learned",
"loss",
"if",
"inner",
"loop,",
"or",
"behavior",
"clone",
"if",
"outer",
"loop."
] | def model_train_fn(self, features, labels, inference_outputs, mode, config=None, params=None):
if params and params.get('is_outer_loss', False):
return self.loss_fn(labels, inference_outputs, mode, params)
with tf.variable_scope('learned_loss', reuse=tf.AUTO_REUSE, use_resource=True):
(predicted... | ['def', 'model_train_fn(self,', 'features,', 'labels,', 'inference_outputs,', 'mode,', 'config=None,', 'params=None):', 'if', 'params', 'and', "params.get('is_outer_loss',", 'False):', 'return', 'self.loss_fn(labels,', 'inference_outputs,', 'mode,', 'params)', 'with', "tf.variable_scope('learned_loss',", 'reuse=tf.AUTO... | 908,423 |
google-research/tensor2robot | vrgripper_env_wtl_models.py | pack_wtl_meta_features | pack_wtl_meta_features | Combines current state and conditioning data into MetaExample spec. | [
"Combines",
"current",
"state",
"and",
"conditioning",
"data",
"into",
"MetaExample",
"spec."
] | def pack_wtl_meta_features(state, prev_episode_data, timestep, fixed_length, num_condition_samples_per_task, vision=False, deterministic_condition=True):
del timestep
if len(prev_episode_data) < 1:
raise ValueError('prev_episode_data should at least contain one (demo) episode.')
meta_features = tens... | ['def', 'pack_wtl_meta_features(state,', 'prev_episode_data,', 'timestep,', 'fixed_length,', 'num_condition_samples_per_task,', 'vision=False,', 'deterministic_condition=True):', 'del', 'timestep', 'if', 'len(prev_episode_data)', '<', '1:', 'raise', "ValueError('prev_episode_data", 'should', 'at', 'least', 'contain', '... | 908,424 |
google-research/tensor2robot | vrgripper_env_wtl_models.py | VRGripperEnvSimpleTrialModel.pack_features | pack_features | Combine current state and previous episode data into a MetaExample spec. | [
"Combine",
"current",
"state",
"and",
"previous",
"episode",
"data",
"into",
"a",
"MetaExample",
"spec."
] | def pack_features(self, state, prev_episode_data, timestep):
return pack_wtl_meta_features(state, prev_episode_data, timestep, self._episode_length, self.preprocessor.num_condition_samples_per_task) | ['def', 'pack_features(self,', 'state,', 'prev_episode_data,', 'timestep):', 'return', 'pack_wtl_meta_features(state,', 'prev_episode_data,', 'timestep,', 'self._episode_length,', 'self.preprocessor.num_condition_samples_per_task)'] | 908,427 |
google-research/tensor2robot | cross_entropy.py | NormalCrossEntropyMethod | NormalCrossEntropyMethod | Uses CEM with a normal distribution as the sampling function. | [
"Uses",
"CEM",
"with",
"a",
"normal",
"distribution",
"as",
"the",
"sampling",
"function."
] | def NormalCrossEntropyMethod(objective_fn, mean, stddev, num_samples, num_elites, num_iterations=1):
size = np.broadcast(mean, stddev).size
def _SampleFn(mean, stddev):
return mean + stddev * np.random.randn(num_samples, size)
def _UpdateFn(params, elite_samples):
del params
return... | ['def', 'NormalCrossEntropyMethod(objective_fn,', 'mean,', 'stddev,', 'num_samples,', 'num_elites,', 'num_iterations=1):', 'size', '=', 'np.broadcast(mean,', 'stddev).size', 'def', '_SampleFn(mean,', 'stddev):', 'return', 'mean', '+', 'stddev', '*', 'np.random.randn(num_samples,', 'size)', 'def', '_UpdateFn(params,', '... | 908,434 |
google-research/tensor2robot | subsample.py | get_np_subsample_indices | get_np_subsample_indices | Same behavior as get_subsample_indices, but in numpy format. | [
"Same",
"behavior",
"as",
"get_subsample_indices,",
"but",
"in",
"numpy",
"format."
] | def get_np_subsample_indices(sequence_lengths, min_length):
def get_indices(sequence_length):
if min_length == 1:
return np.random.randint(0, sequence_length, size=(1,))
elif sequence_length >= min_length:
arr = np.arange(1, sequence_length - 1)
np.random.shuffle... | ['def', 'get_np_subsample_indices(sequence_lengths,', 'min_length):', 'def', 'get_indices(sequence_length):', 'if', 'min_length', '==', '1:', 'return', 'np.random.randint(0,', 'sequence_length,', 'size=(1,))', 'elif', 'sequence_length', '>=', 'min_length:', 'arr', '=', 'np.arange(1,', 'sequence_length', '-', '1)', 'np.... | 908,449 |
google-research/tensor2robot | t2r_test_fixture.py | T2RModelFixture.recordio_train | recordio_train | Trains the model with a RecordIO dataset for a few steps. | [
"Trains",
"the",
"model",
"with",
"a",
"RecordIO",
"dataset",
"for",
"a",
"few",
"steps."
] | def recordio_train(self, module_name, model_name, file_patterns, **module_kwargs):
tf_model = getattr(module_name, model_name)(**module_kwargs)
params = self._get_params(model_dir=self._test_case.create_tempdir().full_path, **module_kwargs)
input_generator = default_input_generator.DefaultRecordInputGenerat... | ['def', 'recordio_train(self,', 'module_name,', 'model_name,', 'file_patterns,', '**module_kwargs):', 'tf_model', '=', 'getattr(module_name,', 'model_name)(**module_kwargs)', 'params', '=', 'self._get_params(model_dir=self._test_case.create_tempdir().full_path,', '**module_kwargs)', 'input_generator', '=', 'default_inp... | 908,452 |
google-research/tensor2robot | tensorspec_utils.py | cast_float32_to_bfloat16 | cast_float32_to_bfloat16 | Casts tensors with dtype float32 to bfloat16 depending on the out spec. | [
"Casts",
"tensors",
"with",
"dtype",
"float32",
"to",
"bfloat16",
"depending",
"on",
"the",
"out",
"spec."
] | def cast_float32_to_bfloat16(tensor_spec_struct, output_spec):
for (key, value) in output_spec.items():
if value is not None and value.dtype == tf.bfloat16:
if tensor_spec_struct[key].dtype != tf.float32:
raise ValueError('Attempting to convert non tf.float32 type {} to tf.bfloat... | ['def', 'cast_float32_to_bfloat16(tensor_spec_struct,', 'output_spec):', 'for', '(key,', 'value)', 'in', 'output_spec.items():', 'if', 'value', 'is', 'not', 'None', 'and', 'value.dtype', '==', 'tf.bfloat16:', 'if', 'tensor_spec_struct[key].dtype', '!=', 'tf.float32:', 'raise', "ValueError('Attempting", 'to', 'convert',... | 908,456 |
google-research/tensor2robot | tensorspec_utils.py | cast_bfloat16_to_float32 | cast_bfloat16_to_float32 | Casts tensors with dtype bfloat16 to float32. | [
"Casts",
"tensors",
"with",
"dtype",
"bfloat16",
"to",
"float32."
] | def cast_bfloat16_to_float32(tensor_spec_struct):
for (key, value) in tensor_spec_struct.items():
if value is not None and value.dtype == tf.bfloat16:
tensor_spec_struct[key] = tf.cast(value, dtype=tf.float32)
return tensor_spec_struct | ['def', 'cast_bfloat16_to_float32(tensor_spec_struct):', 'for', '(key,', 'value)', 'in', 'tensor_spec_struct.items():', 'if', 'value', 'is', 'not', 'None', 'and', 'value.dtype', '==', 'tf.bfloat16:', 'tensor_spec_struct[key]', '=', 'tf.cast(value,', 'dtype=tf.float32)', 'return', 'tensor_spec_struct'] | 908,457 |
google-research/tensor2robot | tensorspec_utils.py | copy_tensorspec | copy_tensorspec | Returns a copy of the namedtuple with tensor names having a new prefix. | [
"Returns",
"a",
"copy",
"of",
"the",
"namedtuple",
"with",
"tensor",
"names",
"having",
"a",
"new",
"prefix."
] | def copy_tensorspec(spec_structure, prefix='', batch_size=None):
assert_valid_spec_structure(spec_structure)
if prefix:
prefix += '/'
def map_spec(spec):
name = spec.name
if name is None:
name = ''
return spec.from_spec(spec, name=prefix + name, batch_size=batch_... | ['def', 'copy_tensorspec(spec_structure,', "prefix='',", 'batch_size=None):', 'assert_valid_spec_structure(spec_structure)', 'if', 'prefix:', 'prefix', '+=', "'/'", 'def', 'map_spec(spec):', 'name', '=', 'spec.name', 'if', 'name', 'is', 'None:', 'name', '=', "''", 'return', 'spec.from_spec(spec,', 'name=prefix', '+', '... | 908,458 |
google-research/tensor2robot | tensorspec_utils.py | make_placeholders | make_placeholders | Create placeholder equivalents of spec_structure. | [
"Create",
"placeholder",
"equivalents",
"of",
"spec_structure."
] | def make_placeholders(spec_structure, batch_size=None):
assert_valid_spec_structure(spec_structure)
def make_placeholder(t):
t = ExtendedTensorSpec.from_spec(t)
shape = tuple(t.shape.as_list())
if t.is_sequence:
shape = (None,) + shape
if batch_size is None:
... | ['def', 'make_placeholders(spec_structure,', 'batch_size=None):', 'assert_valid_spec_structure(spec_structure)', 'def', 'make_placeholder(t):', 't', '=', 'ExtendedTensorSpec.from_spec(t)', 'shape', '=', 'tuple(t.shape.as_list())', 'if', 't.is_sequence:', 'shape', '=', '(None,)', '+', 'shape', 'if', 'batch_size', 'is', ... | 908,459 |
google-research/tensor2robot | tensorspec_utils.py | make_random_numpy | make_random_numpy | Create random numpy inputs for tensor_spec (for unit testing). | [
"Create",
"random",
"numpy",
"inputs",
"for",
"tensor_spec",
"(for",
"unit",
"testing)."
] | def make_random_numpy(spec_structure, batch_size=2, sequence_length=3):
assert_valid_spec_structure(spec_structure)
def make_random(t):
maxval = 255 if t.dtype in [tf.uint8, tf.int32, tf.int64] else 1.0
shape = tuple(t.shape.as_list())
if isinstance(t, ExtendedTensorSpec) and t.is_seque... | ['def', 'make_random_numpy(spec_structure,', 'batch_size=2,', 'sequence_length=3):', 'assert_valid_spec_structure(spec_structure)', 'def', 'make_random(t):', 'maxval', '=', '255', 'if', 't.dtype', 'in', '[tf.uint8,', 'tf.int32,', 'tf.int64]', 'else', '1.0', 'shape', '=', 'tuple(t.shape.as_list())', 'if', 'isinstance(t,... | 908,462 |
google-research/tensor2robot | tensorspec_utils.py | maybe_ignore_batch | maybe_ignore_batch | Optionally strips the batch dimension and returns new spec. | [
"Optionally",
"strips",
"the",
"batch",
"dimension",
"and",
"returns",
"new",
"spec."
] | def maybe_ignore_batch(spec_or_tensors, ignore_batch=False):
if ignore_batch:
def map_fn(spec):
if isinstance(spec, np.ndarray):
spec = tf.convert_to_tensor(spec)
if isinstance(spec, tf.Tensor):
return ExtendedTensorSpec.from_tensor(spec[0])
... | ['def', 'maybe_ignore_batch(spec_or_tensors,', 'ignore_batch=False):', 'if', 'ignore_batch:', 'def', 'map_fn(spec):', 'if', 'isinstance(spec,', 'np.ndarray):', 'spec', '=', 'tf.convert_to_tensor(spec)', 'if', 'isinstance(spec,', 'tf.Tensor):', 'return', 'ExtendedTensorSpec.from_tensor(spec[0])', 'else:', 'return', 'Ext... | 908,467 |
google-research/tensor2robot | tensorspec_utils.py | assert_required | assert_required | Asserts two TensorSpecs have the same structure for required TensorSpecs. | [
"Asserts",
"two",
"TensorSpecs",
"have",
"the",
"same",
"structure",
"for",
"required",
"TensorSpecs."
] | def assert_required(expected_spec, actual_tensors_or_spec, ignore_batch=False):
flat_actual_spec = flatten_spec_structure(actual_tensors_or_spec)
actual_tensors_or_spec = pack_flat_sequence_to_spec_structure(expected_spec, flat_actual_spec)
flat_actual_spec = flatten_spec_structure(actual_tensors_or_spec)
... | ['def', 'assert_required(expected_spec,', 'actual_tensors_or_spec,', 'ignore_batch=False):', 'flat_actual_spec', '=', 'flatten_spec_structure(actual_tensors_or_spec)', 'actual_tensors_or_spec', '=', 'pack_flat_sequence_to_spec_structure(expected_spec,', 'flat_actual_spec)', 'flat_actual_spec', '=', 'flatten_spec_struct... | 908,470 |
google-research/tensor2robot | tensorspec_utils.py | validate_and_pack | validate_and_pack | Validate that TensorSpecs (required) are fulfilled and pack the result. | [
"Validate",
"that",
"TensorSpecs",
"(required)",
"are",
"fulfilled",
"and",
"pack",
"the",
"result."
] | def validate_and_pack(expected_spec, actual_tensors_or_spec, ignore_batch=False):
assert_valid_spec_structure(expected_spec)
assert_valid_spec_structure(actual_tensors_or_spec)
if not is_flat_spec_or_tensors_structure(actual_tensors_or_spec):
actual_tensors_or_spec = flatten_spec_structure(actual_te... | ['def', 'validate_and_pack(expected_spec,', 'actual_tensors_or_spec,', 'ignore_batch=False):', 'assert_valid_spec_structure(expected_spec)', 'assert_valid_spec_structure(actual_tensors_or_spec)', 'if', 'not', 'is_flat_spec_or_tensors_structure(actual_tensors_or_spec):', 'actual_tensors_or_spec', '=', 'flatten_spec_stru... | 908,472 |
google-research/tensor2robot | tensorspec_utils.py | add_sequence_length_specs | add_sequence_length_specs | Augments a TensorSpecStruct with key + '_length' specs. | [
"Augments",
"a",
"TensorSpecStruct",
"with",
"key",
"+",
"'_length'",
"specs."
] | def add_sequence_length_specs(spec_structure):
flat_spec_structure = flatten_spec_structure(spec_structure)
for (key, value) in flat_spec_structure.items():
if value.is_sequence:
flat_spec_structure[key + '_length'] = ExtendedTensorSpec(shape=(), dtype=tf.int64, name=value.name + '_length')
... | ['def', 'add_sequence_length_specs(spec_structure):', 'flat_spec_structure', '=', 'flatten_spec_structure(spec_structure)', 'for', '(key,', 'value)', 'in', 'flat_spec_structure.items():', 'if', 'value.is_sequence:', 'flat_spec_structure[key', '+', "'_length']", '=', 'ExtendedTensorSpec(shape=(),', 'dtype=tf.int64,', 'n... | 908,473 |
google-research/tensor2robot | tensorspec_utils.py | is_flat_spec_or_tensors_structure | is_flat_spec_or_tensors_structure | Check that the spec_structure or tensor_structure is flattend. | [
"Check",
"that",
"the",
"spec_structure",
"or",
"tensor_structure",
"is",
"flattend."
] | def is_flat_spec_or_tensors_structure(spec_or_tensors):
if isinstance(spec_or_tensors, dict) or isinstance(spec_or_tensors, collections.OrderedDict):
for value in spec_or_tensors.values():
if isinstance(value, contrib_framework.TensorSpec):
continue
if isinstance(valu... | ['def', 'is_flat_spec_or_tensors_structure(spec_or_tensors):', 'if', 'isinstance(spec_or_tensors,', 'dict)', 'or', 'isinstance(spec_or_tensors,', 'collections.OrderedDict):', 'for', 'value', 'in', 'spec_or_tensors.values():', 'if', 'isinstance(value,', 'contrib_framework.TensorSpec):', 'continue', 'if', 'isinstance(val... | 908,477 |
google-research/tensor2robot | tensorspec_utils.py | is_encoded_image_spec | is_encoded_image_spec | Determines whether the passed tensor_spec speficies an encoded image. | [
"Determines",
"whether",
"the",
"passed",
"tensor_spec",
"speficies",
"an",
"encoded",
"image."
] | def is_encoded_image_spec(tensor_spec):
if hasattr(tensor_spec, 'data_format'):
return tensor_spec.data_format is not None and tensor_spec.data_format.upper() in ['JPEG', 'PNG']
else:
logging.warn('Using a deprecated tensor specification. Use ExtendedTensorSpec.')
return 'image' in tenso... | ['def', 'is_encoded_image_spec(tensor_spec):', 'if', 'hasattr(tensor_spec,', "'data_format'):", 'return', 'tensor_spec.data_format', 'is', 'not', 'None', 'and', 'tensor_spec.data_format.upper()', 'in', "['JPEG',", "'PNG']", 'else:', "logging.warn('Using", 'a', 'deprecated', 'tensor', 'specification.', 'Use', "ExtendedT... | 908,480 |
google-research/tensor2robot | tensorspec_utils.py | write_t2r_assets_to_file | write_t2r_assets_to_file | Writes feature and label specifications to file. | [
"Writes",
"feature",
"and",
"label",
"specifications",
"to",
"file."
] | def write_t2r_assets_to_file(t2r_assets, filename):
with tf.io.gfile.GFile(filename, 'w') as f:
f.write(text_format.MessageToString(t2r_assets)) | ['def', 'write_t2r_assets_to_file(t2r_assets,', 'filename):', 'with', 'tf.io.gfile.GFile(filename,', "'w')", 'as', 'f:', 'f.write(text_format.MessageToString(t2r_assets))'] | 908,483 |
google-research/tensor2robot | tensorspec_utils.py | ExtendedTensorSpec.is_optional | is_optional | Returns if the tensor is optional or required. | [
"Returns",
"if",
"the",
"tensor",
"is",
"optional",
"or",
"required."
] | def is_optional(self):
return self._is_optional | ['def', 'is_optional(self):', 'return', 'self._is_optional'] | 908,489 |
google-research/tensor2robot | tfdata.py | infer_data_format | infer_data_format | Infer the data format from a file pattern. | [
"Infer",
"the",
"data",
"format",
"from",
"a",
"file",
"pattern."
] | def infer_data_format(file_patterns):
data_format = None
for key in DATA_FORMAT:
if key in file_patterns:
if data_format is not None:
raise ValueError('More than one data_format {} and {} have been found in {}.'.format(key, data_format, file_patterns))
data_format... | ['def', 'infer_data_format(file_patterns):', 'data_format', '=', 'None', 'for', 'key', 'in', 'DATA_FORMAT:', 'if', 'key', 'in', 'file_patterns:', 'if', 'data_format', 'is', 'not', 'None:', 'raise', "ValueError('More", 'than', 'one', 'data_format', '{}', 'and', '{}', 'have', 'been', 'found', 'in', "{}.'.format(key,", 'd... | 908,501 |
google-research/tensor2robot | tfdata.py | get_data_format_and_filenames_list | get_data_format_and_filenames_list | Obtain data format and list of filenames from comma-separated patterns. | [
"Obtain",
"data",
"format",
"and",
"list",
"of",
"filenames",
"from",
"comma-separated",
"patterns."
] | def get_data_format_and_filenames_list(file_patterns):
data_format = infer_data_format(file_patterns)
file_patterns = file_patterns.replace('{}:'.format(data_format), '')
filenames_list = [tf.io.gfile.glob(pattern) for pattern in file_patterns.split(',')]
for filenames in filenames_list:
if not ... | ['def', 'get_data_format_and_filenames_list(file_patterns):', 'data_format', '=', 'infer_data_format(file_patterns)', 'file_patterns', '=', "file_patterns.replace('{}:'.format(data_format),", "'')", 'filenames_list', '=', '[tf.io.gfile.glob(pattern)', 'for', 'pattern', 'in', "file_patterns.split(',')]", 'for', 'filenam... | 908,502 |
google-research/tensor2robot | tfdata.py | get_data_format_and_filenames | get_data_format_and_filenames | Obtain the data format and filenames from comma-separated file patterns. | [
"Obtain",
"the",
"data",
"format",
"and",
"filenames",
"from",
"comma-separated",
"file",
"patterns."
] | def get_data_format_and_filenames(file_patterns):
(data_format, filenames_list) = get_data_format_and_filenames_list(file_patterns)
filenames = list(itertools.chain.from_iterable(filenames_list))
return (data_format, filenames) | ['def', 'get_data_format_and_filenames(file_patterns):', '(data_format,', 'filenames_list)', '=', 'get_data_format_and_filenames_list(file_patterns)', 'filenames', '=', 'list(itertools.chain.from_iterable(filenames_list))', 'return', '(data_format,', 'filenames)'] | 908,503 |
google-research/tensor2robot | tfdata.py | get_dataset_metadata | get_dataset_metadata | Get approximate dataset size for optimal shuffling parameters. | [
"Get",
"approximate",
"dataset",
"size",
"for",
"optimal",
"shuffling",
"parameters."
] | def get_dataset_metadata(file_patterns):
(data_format, files) = get_data_format_and_filenames(file_patterns=file_patterns)
num_shards = len(files)
logging.info('Estimating dataset size from %s...', files[0])
if data_format == 'sstable':
num_examples_per_shard = len(sstable.SSTable(files[0]))
... | ['def', 'get_dataset_metadata(file_patterns):', '(data_format,', 'files)', '=', 'get_data_format_and_filenames(file_patterns=file_patterns)', 'num_shards', '=', 'len(files)', "logging.info('Estimating", 'dataset', 'size', 'from', "%s...',", 'files[0])', 'if', 'data_format', '==', "'sstable':", 'num_examples_per_shard',... | 908,504 |
google-research/tensor2robot | tfdata.py | get_input_fn | get_input_fn | Input function for record-backed data. | [
"Input",
"function",
"for",
"record-backed",
"data."
] | def get_input_fn(feature_spec, label_spec, file_patterns, mode, batch_size, preprocess_fn):
def input_fn(params=None):
used_batch_size = get_batch_size(params, batch_size)
dataset = default_input_fn_tmpl(file_patterns=file_patterns, batch_size=used_batch_size, feature_spec=feature_spec, label_spec=... | ['def', 'get_input_fn(feature_spec,', 'label_spec,', 'file_patterns,', 'mode,', 'batch_size,', 'preprocess_fn):', 'def', 'input_fn(params=None):', 'used_batch_size', '=', 'get_batch_size(params,', 'batch_size)', 'dataset', '=', 'default_input_fn_tmpl(file_patterns=file_patterns,', 'batch_size=used_batch_size,', 'featur... | 908,511 |
google-research/tensor2robot | train_eval.py | print_spec | print_spec | Iterate over a spec and print its values in sorted order. | [
"Iterate",
"over",
"a",
"spec",
"and",
"print",
"its",
"values",
"in",
"sorted",
"order."
] | def print_spec(tensor_spec):
for (key, value) in sorted(tensorspec_utils.flatten_spec_structure(tensor_spec).items()):
logging.info('%s: %s', key, value) | ['def', 'print_spec(tensor_spec):', 'for', '(key,', 'value)', 'in', 'sorted(tensorspec_utils.flatten_spec_structure(tensor_spec).items()):', "logging.info('%s:", "%s',", 'key,', 'value)'] | 908,512 |
google-research/tensor2robot | train_eval.py | print_specification | print_specification | Print the specification for the model and its preprocessor. | [
"Print",
"the",
"specification",
"for",
"the",
"model",
"and",
"its",
"preprocessor."
] | def print_specification(t2r_model):
for mode in [tf_estimator.ModeKeys.TRAIN, tf_estimator.ModeKeys.PREDICT]:
logging.info('Preprocessor in feature specification for mode %s', mode)
print_spec(t2r_model.preprocessor.get_in_feature_specification(mode))
logging.info('Preprocessor in label spec... | ['def', 'print_specification(t2r_model):', 'for', 'mode', 'in', '[tf_estimator.ModeKeys.TRAIN,', 'tf_estimator.ModeKeys.PREDICT]:', "logging.info('Preprocessor", 'in', 'feature', 'specification', 'for', 'mode', "%s',", 'mode)', 'print_spec(t2r_model.preprocessor.get_in_feature_specification(mode))', "logging.info('Prep... | 908,513 |
google-research/tensor2robot | train_eval.py | provide_input_generator_with_model_information | provide_input_generator_with_model_information | Fill the input generator with information provided by a TFModel instance. | [
"Fill",
"the",
"input",
"generator",
"with",
"information",
"provided",
"by",
"a",
"TFModel",
"instance."
] | def provide_input_generator_with_model_information(input_generator_instance, t2r_model, mode):
tf.logging.info('!' * 80)
tf.logging.info('guzzler_use_compression %s', str(guzzler_use_compression))
tf.logging.info('!' * 80)
if not isinstance(input_generator_instance, abstract_input_generator.AbstractInpu... | ['def', 'provide_input_generator_with_model_information(input_generator_instance,', 't2r_model,', 'mode):', "tf.logging.info('!'", '*', '80)', "tf.logging.info('guzzler_use_compression", "%s',", 'str(guzzler_use_compression))', "tf.logging.info('!'", '*', '80)', 'if', 'not', 'isinstance(input_generator_instance,', 'abs... | 908,514 |
google-research/tensor2robot | train_eval.py | create_tpu_estimator | create_tpu_estimator | Wrapper for TPUEstimator to provide a common interface for instantiation. | [
"Wrapper",
"for",
"TPUEstimator",
"to",
"provide",
"a",
"common",
"interface",
"for",
"instantiation."
] | def create_tpu_estimator(t2r_model, model_dir, train_batch_size=32, eval_batch_size=1, use_tpu_hardware=True, params=None, export_to_cpu=True, export_to_tpu=True, **kwargs):
del kwargs
return contrib_tpu.TPUEstimator(model_fn=t2r_model.model_fn, model_dir=model_dir, config=t2r_model.get_tpu_run_config(), use_tp... | ['def', 'create_tpu_estimator(t2r_model,', 'model_dir,', 'train_batch_size=32,', 'eval_batch_size=1,', 'use_tpu_hardware=True,', 'params=None,', 'export_to_cpu=True,', 'export_to_tpu=True,', '**kwargs):', 'del', 'kwargs', 'return', 'contrib_tpu.TPUEstimator(model_fn=t2r_model.model_fn,', 'model_dir=model_dir,', 'config... | 908,515 |
google-research/tensor2robot | train_eval.py | create_default_exporters | create_default_exporters | Creates a list of Exporter to export saved models during evaluation. | [
"Creates",
"a",
"list",
"of",
"Exporter",
"to",
"export",
"saved",
"models",
"during",
"evaluation."
] | def create_default_exporters(t2r_model, export_generator, compare_fn=create_valid_result_smaller, use_numpy_exporters=True, use_tfexample_exporters=True, use_servo_exporter=True, exports_to_keep=None, valid_eval_name=None):
multi_eval_name = default_input_generator.get_multi_eval_name()
if valid_eval_name and m... | ['def', 'create_default_exporters(t2r_model,', 'export_generator,', 'compare_fn=create_valid_result_smaller,', 'use_numpy_exporters=True,', 'use_tfexample_exporters=True,', 'use_servo_exporter=True,', 'exports_to_keep=None,', 'valid_eval_name=None):', 'multi_eval_name', '=', 'default_input_generator.get_multi_eval_name... | 908,519 |
google-research/tensor2robot | train_eval.py | create_backup_checkpoint_for_eval | create_backup_checkpoint_for_eval | Creates a backup of a checkpoint for evaluation. | [
"Creates",
"a",
"backup",
"of",
"a",
"checkpoint",
"for",
"evaluation."
] | def create_backup_checkpoint_for_eval(checkpoint_path, max_num_copy_attempts=10, backup_checkpoint_folder_name='current_eval_checkpoint', max_copy_attempts_per_file=5):
for attempt in range(max_num_copy_attempts):
current_eval_checkpoint = os.path.join(os.path.dirname(checkpoint_path), backup_checkpoint_fol... | ['def', 'create_backup_checkpoint_for_eval(checkpoint_path,', 'max_num_copy_attempts=10,', "backup_checkpoint_folder_name='current_eval_checkpoint',", 'max_copy_attempts_per_file=5):', 'for', 'attempt', 'in', 'range(max_num_copy_attempts):', 'current_eval_checkpoint', '=', 'os.path.join(os.path.dirname(checkpoint_path)... | 908,522 |
google-research/tensor2robot | train_eval.py | save_copy | save_copy | Copy a file while catching errors and retrying a set amount of times. | [
"Copy",
"a",
"file",
"while",
"catching",
"errors",
"and",
"retrying",
"a",
"set",
"amount",
"of",
"times."
] | def save_copy(src_filename, dest_filename, overwrite=False, num_retries=3, sleep_time=0.5):
if tf.io.gfile.exists(dest_filename):
logging.warn('Could not copy file "%s" to "%s", because the destination already exists.', src_filename, dest_filename)
return False
for _ in range(num_retries):
... | ['def', 'save_copy(src_filename,', 'dest_filename,', 'overwrite=False,', 'num_retries=3,', 'sleep_time=0.5):', 'if', 'tf.io.gfile.exists(dest_filename):', "logging.warn('Could", 'not', 'copy', 'file', '"%s"', 'to', '"%s",', 'because', 'the', 'destination', 'already', "exists.',", 'src_filename,', 'dest_filename)', 'ret... | 908,523 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.