seed
stringlengths
25
2.89k
seed_api
stringlengths
14
102
index
int64
0
14.8k
from tensorflow.python.framework import ops def __init__(self, learning_rate=0.001, use_locking=False, name="OMD"): super(OptimisticMirrorDescentOptimizer, self).__init__(use_locking, name) self._lr = learning_rate # Tensor versions of the constructor arguments, created in _prepare(). self._lr_t = None def _prepare(self): self._lr_t = ops.convert_to_tensor(self._lr, name="learning_rate") def _create_slots(self, var_list): # Create slots for the first and second moments. for v in var_list: self._zeros_slot(v, "g", self._name) def _apply_dense(self, grad, var):
tensorflow.python.framework.ops.convert_to_tensor
8,800
import tensorflow as tf loss_loc = _smooth_l1_loss(tf.boolean_mask(loc_true, mask_pos_b), tf.boolean_mask(loc_pred, mask_pos_b)) loss_loc = tf.reduce_mean(loss_loc) # classification loss (crossentropy) # 1. compute max conf across batch for hard negative mining loss_class = tf.where(mask_neg, 1 - class_pred[:, 0][..., tf.newaxis], 0) # 2. hard negative mining loss_class = tf.reshape(loss_class, [num_batch, num_prior]) loss_class_idx = tf.argsort(loss_class, axis=1, direction='DESCENDING') loss_class_idx_rank = tf.argsort(loss_class_idx, axis=1) mask_pos_per_batch = tf.reshape(mask_pos, [num_batch, num_prior]) num_pos_per_batch = tf.reduce_sum( tf.cast(mask_pos_per_batch, tf.float32), 1, keepdims=True) num_pos_per_batch = tf.maximum(num_pos_per_batch, 1) num_neg_per_batch = tf.minimum(neg_pos_ratio * num_pos_per_batch, tf.cast(num_prior, tf.float32) - 1) mask_hard_neg = tf.reshape( tf.cast(loss_class_idx_rank, tf.float32) < num_neg_per_batch, [num_batch * num_prior, 1]) # 3. classification loss including positive and negative examples
tensorflow.argsort
8,801
import tensorflow as tf epsilon = _to_tensor(_EPSILON, output.dtype.base_dtype) output = tf.clip_by_value(output, epsilon, 1. - epsilon)
tensorflow.clip_by_value
8,802
import tensorflow as tf def file_based_input_fn_builder(input_file, seq_length, is_training, drop_remainder): name_to_features = { "input_ids": tf.FixedLenFeature([seq_length], tf.int64), "input_mask": tf.FixedLenFeature([seq_length], tf.int64), "segment_ids": tf.FixedLenFeature([seq_length], tf.int64), "label_ids": tf.FixedLenFeature([seq_length], tf.int64),
tensorflow.FixedLenFeature
8,803
import tensorflow as tf if isinstance(facts, tuple): # In case of Bi-RNN, concatenate the forward and the backward RNN outputs. facts = tf.concat(facts, 2) if len(facts.get_shape().as_list()) == 2: facts = tf.expand_dims(facts, 1) if time_major: # (T,B,D) => (B,T,D) facts = tf.array_ops.transpose(facts, [1, 0, 2]) # Trainable parameters mask = tf.equal(mask, tf.ones_like(mask)) facts_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer querry_size = query.get_shape().as_list()[-1] query = tf.layers.dense(query, facts_size, activation=None, name='f1' + stag) query = prelu(query) queries = tf.tile(query, [1, tf.shape(facts)[1]]) queries = tf.reshape(queries, tf.shape(facts)) din_all = tf.concat([queries, facts, queries-facts, queries*facts], axis=-1) d_layer_1_all = tf.layers.dense(din_all, 80, activation=tf.nn.sigmoid, name='f1_att' + stag) d_layer_2_all = tf.layers.dense(d_layer_1_all, 40, activation=tf.nn.sigmoid, name='f2_att' + stag) d_layer_3_all = tf.layers.dense(d_layer_2_all, 1, activation=None, name='f3_att' + stag) d_layer_3_all = tf.reshape(d_layer_3_all, [-1, 1, tf.shape(facts)[1]]) scores = d_layer_3_all # Mask # key_masks = tf.sequence_mask(facts_length, tf.shape(facts)[1]) # [B, T] key_masks = tf.expand_dims(mask, 1) # [B, 1, T] paddings = tf.ones_like(scores) * (-2 ** 32 + 1) if not forCnn: scores = tf.where(key_masks, scores, paddings) # [B, 1, T]
tensorflow.shape
8,804
import tensorflow as tf queries = tf.reshape(queries, tf.shape(facts)) din_all = tf.concat([queries, facts, queries-facts, queries*facts], axis=-1) d_layer_1_all = tf.layers.dense(din_all, 80, activation=tf.nn.sigmoid, name='f1_att' + stag) d_layer_2_all = tf.layers.dense(d_layer_1_all, 40, activation=tf.nn.sigmoid, name='f2_att' + stag) d_layer_3_all = tf.layers.dense(d_layer_2_all, 1, activation=None, name='f3_att' + stag) d_layer_3_all = tf.reshape(d_layer_3_all, [-1, 1, tf.shape(facts)[1]]) scores = d_layer_3_all # Mask # key_masks = tf.sequence_mask(facts_length, tf.shape(facts)[1]) # [B, T] key_masks = tf.expand_dims(mask, 1) # [B, 1, T] paddings = tf.ones_like(scores) * (-2 ** 32 + 1) scores = tf.where(key_masks, scores, paddings) # [B, 1, T] # Scale # scores = scores / (facts.get_shape().as_list()[-1] ** 0.5) # Activation if softmax_stag: scores = tf.nn.softmax(scores) # [B, 1, T] # Weighted sum if mode == 'SUM':
tensorflow.where
8,805
import tensorflow as tf tf.saved_model.load( self._sess, [tag_constants.SERVING], self._model_path) self._image_tensor = self._sess.graph.get_tensor_by_name( 'serving_default_input_1:0') self._output_tensor = self._sess.graph.get_tensor_by_name( 'StatefulPartitionedCall:0') self._boxes = tf.placeholder( tf.float32, shape=(None, None, None, 4)) self._scores = tf.placeholder( tf.float32, shape=(None, None, self._num_classes)) self._boxes_predi, self._scores_predi, self._classes_predi,\ self._valid_detections_predi = \ tf.image.combined_non_max_suppression( boxes=self._boxes, scores=self._scores,
tensorflow.placeholder
8,806
import tensorflow as tf grads, self.grad_norms = tf.clip_by_global_norm(self.gradients, GRAD_CLIP) # Apply local gradients to global network global_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, GLOBAL_NET_SCOPE+'/qvalues') self.apply_grads = trainer.apply_gradients(zip(grads, global_vars))
tensorflow.get_collection
8,807
import tensorflow as tf H1 = tf.add(tf.matmul(H, W1), b) H2 = tf.matmul(H, W2) Y = tf.add(H1 * H2, H1) return Y def fwd_gradients_0(self, U, x): g = tf.gradients(U, x, grad_ys=self.dummy_x0_tf)[0] return tf.gradients(g, self.dummy_x0_tf)[0] def fwd_gradients_1(self, U, x): g = tf.gradients(U, x, grad_ys=self.dummy_x1_tf)[0] return tf.gradients(g, self.dummy_x1_tf)[0] def net_U0(self, x):
tensorflow.gradients
8,808
import tensorflow as tf return d.apply( tf.contrib.data.map_and_batch( self._decode_tfrecord, batch_size=params["batch_size"], drop_remainder=True ) ) return input_fn def _decode_tfrecord(self, record): """Decodes a record to a TensorFlow example.""" example = tf.parse_single_example(record, self._name_to_feature_config) # tf.Example only supports tf.int64, but the TPU only supports tf.int32. # So cast all int64 to int32. for name, tensor in example.items(): if tensor.dtype == tf.int64: example[name] = tf.cast(tensor, tf.int32) else: example[name] = tensor
tensorflow.parse_single_example
8,809
from tensorflow.python.framework import tensor_shape # NOTE(mrry): Shapes are conditionally set in the Python wrapper. ops.RegisterShape("Variable")(common_shapes.unknown_shape) @ops.RegisterShape("TemporaryVariable") def _TemporaryVariableShape(op): """Shape function for the TemporaryVariable op.""" shape = tensor_util.TensorShapeProtoToList(op.get_attr("shape")) return [tensor_shape.TensorShape(shape)] @ops.RegisterShape("DestroyTemporaryVariable") def _DestroyTemporaryVariableShape(op): """Shape function for the DestroyTemporaryVariable op.""" return [op.inputs[0].get_shape()]
tensorflow.python.framework.tensor_shape.TensorShape
8,810
import tensorflow as tf ret_columns_list.append(matrix_shape[-1]) ret_columns = tf.add_n(ret_columns_list) row_blocks = [] current_column = 0 for matrix in matrices: matrix_shape = tf.shape(matrix) row_before_length = current_column current_column += matrix_shape[-1] row_after_length = ret_columns - current_column row_blocks.append(tf.pad(
tensorflow.shape
8,811
import tensorflow as tf dim_state = int(np.prod(env.observation_space.shape)) dim_action = int(np.prod(env.action_space.shape)) env.verify() normalizers = Normalizers(dim_action=dim_action, dim_state=dim_state) normalizers_copy = Normalizers(dim_action=dim_action, dim_state=dim_state) normalizers_parameters = normalizers.parameters(trainable=False, non_trainable=True) normalizers_copy_parameters = normalizers_copy.parameters(trainable=False, non_trainable=True) copy_normalizers = tf.group(*[tf.assign(w_v, p_v) for w_v, p_v in zip(normalizers_copy_parameters, normalizers_parameters)]) revert_normalizers = tf.group(*[tf.assign(w_v, p_v) for w_v, p_v in zip(normalizers_parameters, normalizers_copy_parameters)]) dtype = gen_dtype(env, 'state action next_state reward done timeout') train_set = Dataset(dtype, FLAGS.rollout.max_buf_size) dev_set = Dataset(dtype, FLAGS.rollout.max_buf_size) task_train_sets = [Dataset(dtype, FLAGS.rollout.max_buf_size) for i in range(100)] task_dev_sets = [Dataset(dtype, FLAGS.rollout.max_buf_size) for i in range(100)] print ("state and action dim:", dim_state, dim_action) policy = GaussianMLPPolicy(dim_state, dim_action, normalizer=normalizers.state, **FLAGS.policy.as_dict())
tensorflow.assign
8,812
import tensorflow as tf idx1 = cell_arch[bi][0] op1 = cell_arch[bi][1] idx2 = cell_arch[bi][2] op2 = cell_arch[bi][3] with tf.variable_scope('X1'): X1 = self._add_op_dynamic(cell_inputs, blocks, idx1, op1, w, h, block_ch, is_train=is_train) X1 = self._add_drop_path(X1, drop_path_keep_prob) with tf.variable_scope('X2'):
tensorflow.variable_scope
8,813
import tensorflow as tf unconnected_gradients=tf.UnconnectedGradients.NONE) emb_grads, other_grads = grads[:len(emb_var)], grads[len(emb_var):] if "plugin" in args.optimizer: emb_train_op = emb_opt.apply_gradients(zip(emb_grads, emb_var)) else: with sok.OptimizerScope(emb_var): emb_train_op = emb_opt.apply_gradients(zip(emb_grads, emb_var)) with tf.control_dependencies([*emb_grads]): # in case NCCL runs concurrently via SOK and horovod other_grads = strategy.reduce("sum", other_grads) other_train_op = dense_opt.apply_gradients(zip(other_grads, other_var)) with tf.control_dependencies([emb_train_op, other_train_op]): total_loss = strategy.reduce("sum", loss)
tensorflow.control_dependencies
8,814
import tensorflow as tf
tensorflow.contrib.layers.l2_regularizer
8,815
from tensorflow.python.framework import ops Returns: A `Tensor` of the same type as `a`. """ with ops.op_scope([a, b], name, "MatMul") as name: a = ops.convert_to_tensor(a, name="a") b = ops.convert_to_tensor(b, name="b") if a.dtype == types.float32 and (a_is_sparse or b_is_sparse): return sparse_matmul(a, b, transpose_a=transpose_a,
tensorflow.python.framework.ops.convert_to_tensor
8,816
import tensorflow as tf fast_antecedent_scores += self.get_fast_antecedent_scores(top_span_emb) # [k, k] _, top_antecedents = tf.nn.top_k(fast_antecedent_scores, c, sorted=False) # [k, c] top_antecedents_mask = util.batch_gather(antecedents_mask, top_antecedents) # [k, c] top_fast_antecedent_scores = util.batch_gather(fast_antecedent_scores, top_antecedents) # [k, c] top_antecedent_offsets = util.batch_gather(antecedent_offsets, top_antecedents) # [k, c] return top_antecedents, top_antecedents_mask, top_fast_antecedent_scores, top_antecedent_offsets def distance_pruning(self, top_span_emb, top_span_mention_scores, c): k = util.shape(top_span_emb, 0) top_antecedent_offsets = tf.tile(tf.expand_dims(tf.range(c) + 1, 0), [k, 1]) # [k, c] raw_top_antecedents = tf.expand_dims(tf.range(k), 1) - top_antecedent_offsets # [k, c] top_antecedents_mask = raw_top_antecedents >= 0 # [k, c] top_antecedents = tf.maximum(raw_top_antecedents, 0) # [k, c] top_fast_antecedent_scores = tf.expand_dims(top_span_mention_scores, 1) + tf.gather(top_span_mention_scores, top_antecedents) # [k, c] top_fast_antecedent_scores += tf.log(tf.to_float(top_antecedents_mask)) # [k, c] return top_antecedents, top_antecedents_mask, top_fast_antecedent_scores, top_antecedent_offsets def get_predictions_and_loss(self, tokens, context_word_emb, head_word_emb, lm_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids):
tensorflow.range
8,817
import tensorflow as tf if not tf.gfile.Exists(eval_file) or not FLAGS.data_converted: file_based_convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file) tf.logging.info("***** Running evaluation *****") tf.logging.info(" Num examples = %d (%d actual, %d padding)", len(eval_examples), num_actual_eval_examples, len(eval_examples) - num_actual_eval_examples)
tensorflow.logging.info
8,818
import tensorflow as tf # Read the file containing the pairs used for testing pairs = lfw.read_pairs(os.path.expanduser(args.lfw_pairs)) # Get the paths for the corresponding images paths, actual_issame = lfw.get_paths(os.path.expanduser(args.lfw_dir), pairs) image_paths_placeholder = tf.placeholder(tf.string, shape=(None,1), name='image_paths') labels_placeholder = tf.placeholder(tf.int32, shape=(None,1), name='labels') batch_size_placeholder = tf.placeholder(tf.int32, name='batch_size') control_placeholder = tf.placeholder(tf.int32, shape=(None,1), name='control') phase_train_placeholder = tf.placeholder(tf.bool, name='phase_train') nrof_preprocess_threads = 4 image_size = (args.image_size, args.image_size)
tensorflow.placeholder
8,819
import tensorflow as tf # Now we construct the copy model. batch_size = 8 inp = [tf.placeholder(tf.int32, shape=[None]) for _ in range(8)] out = [tf.placeholder(tf.int32, shape=[None]) for _ in range(8)] weights = [tf.ones_like(inp[0], dtype=tf.float32) for _ in range(8)] with tf.variable_scope("root"): _, losses = SampleGRUSeq2Seq(inp, out, weights) updates = [] params = tf.global_variables() optimizer = tf.train.AdamOptimizer(0.03, epsilon=1e-5) for i in range(len(buckets)): full_grads = tf.gradients(losses[i], params) grads, _ = tf.clip_by_global_norm(full_grads, 30.0) update = optimizer.apply_gradients(zip(grads, params)) updates.append(update) sess.run([tf.global_variables_initializer()]) steps = 6 for _ in range(steps): bucket = random.choice(np.arange(len(buckets))) length = buckets[bucket][0] i = [np.array([np.random.randint(9) + 1 for _ in range(batch_size)], dtype=np.int32) for _ in range(length)] # 0 is our "GO" symbol here.
tensorflow.gradients
8,820
import tensorflow as tf sess.run([tf.global_variables_initializer()]) tf.get_variable_scope().reuse_variables() d1, _ = tf.nn.seq2seq.embedding_tied_rnn_seq2seq( enc_inp, dec_inp, cell, num_symbols=5, embedding_size=2, feed_previous=True) d2, _ = tf.nn.seq2seq.embedding_tied_rnn_seq2seq( enc_inp, dec_inp2, cell, num_symbols=5, embedding_size=2, feed_previous=True) res1 = sess.run(d1) res2 = sess.run(d2)
tensorflow.nn.seq2seq.embedding_tied_rnn_seq2seq
8,821
import tensorflow as tf else: covariance_matrix = tf.convert_to_tensor( covariance_matrix, name="covariance_matrix", dtype=dtype) if validate_args: covariance_matrix = control_flow_ops.with_dependencies([ tf.assert_near( covariance_matrix, tf.matrix_transpose(covariance_matrix), message="Matrix was not symmetric") ], covariance_matrix) # No need to validate that covariance_matrix is non-singular. # LinearOperatorLowerTriangular has an assert_non_singular method that # is called by the Bijector. # However, cholesky() ignores the upper triangular part, so we do need # to separately assert symmetric. scale_tril = tf.cholesky(covariance_matrix) super(MultivariateNormalFullCovariance, self).__init__( loc=loc, scale_tril=scale_tril, validate_args=validate_args, allow_nan_stats=allow_nan_stats, name=name) self._parameters = parameters
tensorflow.cholesky
8,822
import tensorflow as tf return (tf.no_op(), tf.no_op()) # Only make the ops if we know that `is_training=True`, or the value of # `is_training` is unknown. is_training_const = utils.constant_value(is_training) if is_training_const is None or is_training_const: update_mean_op, update_variance_op = utils.smart_cond( is_training, build_update_ops, build_no_ops, ) # Every new connection creates a new op which adds its contribution # to the running average when ran. tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_mean_op) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_variance_op) def _build_update_ops_second_moment(self, mean, second_moment, is_training): """Builds the moving average update ops when using the moving second moment. Args: mean: The mean value to update with. second_moment: The second_moment value to update with. is_training: Boolean Tensor to indicate if we're currently in training mode. """ def build_update_ops():
tensorflow.add_to_collection
8,823
import tensorflow as tf isms = input_score_maps_split[i] igms = input_geo_maps_split[i] itms = input_training_masks_split[i] total_loss, model_loss = tower_loss(iis, isms, igms, itms, reuse_variables) batch_norm_updates_op = tf.group(*tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope)) reuse_variables = True grads = opt.compute_gradients(total_loss) tower_grads.append(grads) grads = average_gradients(tower_grads) apply_gradient_op = opt.apply_gradients(grads, global_step=global_step) summary_op = tf.summary.merge_all() # save moving average variable_averages = tf.train.ExponentialMovingAverage( FLAGS.moving_average_decay, global_step) variables_averages_op = variable_averages.apply(tf.trainable_variables()) # batch norm updates with tf.control_dependencies([variables_averages_op, apply_gradient_op, batch_norm_updates_op]): train_op = tf.no_op(name='train_op') saver = tf.train.Saver(tf.global_variables()) summary_writer = tf.summary.FileWriter(FLAGS.checkpoint_path, tf.get_default_graph()) init = tf.global_variables_initializer() if FLAGS.pretrained_model_path is not None: variable_restore_op = slim.assign_from_checkpoint_fn(FLAGS.pretrained_model_path, slim.get_trainable_variables(), ignore_missing_vars=True)
tensorflow.train.ExponentialMovingAverage
8,824
import tensorflow as tf outputs.append(tf.concat([out_fw, out_bw], axis=2)) if concat_layers: res = tf.concat(outputs[1:], axis=2) else: res = outputs[-1] res = tf.transpose(res, [1, 0, 2]) return res class native_gru:
tensorflow.transpose
8,825
import tensorflow as tf print('attention f flat dims: ' + str(f.get_shape().as_list())) s = tf.matmul(g, f, transpose_b=True) # # [bs, N, N]
tensorflow.matmul
8,826
import tensorflow as tf if initial_value is None: fc_weight = tf.get_variable("weights", shape=[in_dim, out_dim], initializer=tf.random_normal_initializer(mean=0., stddev=0.01))
tensorflow.random_normal_initializer
8,827
import tensorflow as tf # Now try a restore with the sharded filename. with tf.Session( target="", config=tf.ConfigProto(device_count={"CPU": 2})) as sess: with sess.graph.device("/cpu:0"): v0 = tf.Variable(111, name="v0") with sess.graph.device("/cpu:1"): v1 = tf.Variable(222, name="v1") save = tf.train.Saver({"v0": v0, "v1": v1}, sharded=True) tf.initialize_all_variables().run() self.assertEqual(111, v0.eval()) self.assertEqual(222, v1.eval()) save_path = os.path.join(self.get_temp_dir(), "sharded") save.restore(sess, save_path + "-?????-of-?????")
tensorflow.Variable
8,828
import tensorflow as tf return pooling_result def scaled_tanh(x, scale=5.): return scale * tf.nn.tanh(1./scale * x)
tensorflow.nn.tanh
8,829
from tensorflow.contrib.eager.python.examples.spinn import data logdir=os.path.join(self._temp_data_dir, "logdir"), inference_sentences=("( foo ( bar . ) )", None)) with self.assertRaises(ValueError): spinn.train_or_infer_spinn(embed, word2index, None, None, None, config) def testTrainSpinn(self): """Test with fake toy SNLI data and GloVe vectors.""" # 1. Create and load a fake SNLI data file and a fake GloVe embedding file. snli_1_0_dir = os.path.join(self._temp_data_dir, "snli/snli_1.0") fake_train_file = self._create_test_data(snli_1_0_dir) vocab = data.load_vocabulary(self._temp_data_dir) word2index, embed = data.load_word_vectors(self._temp_data_dir, vocab) train_data = data.SnliData(fake_train_file, word2index) dev_data = data.SnliData(fake_train_file, word2index) test_data = data.SnliData(fake_train_file, word2index) # 2. Create a fake config. config = _test_spinn_config( data.WORD_VECTOR_LEN, 4, logdir=os.path.join(self._temp_data_dir, "logdir")) # 3. Test training of a SPINN model. trainer = spinn.train_or_infer_spinn(
tensorflow.contrib.eager.python.examples.spinn.data.load_word_vectors
8,830
import tensorflow as tf "output_weights", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias = tf.get_variable( "output_bias", [num_labels], initializer=tf.zeros_initializer()) with tf.variable_scope("loss"): if is_training: # I.e., 0.1 dropout output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) logits = tf.matmul(output_layer, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias) probabilities = tf.nn.softmax(logits, axis=-1) log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1) loss = tf.reduce_mean(per_example_loss) return (loss, per_example_loss, logits, probabilities)
tensorflow.matmul
8,831
from tensorflow.python.framework import ops ops.RegisterShape("Conv2D")(common_shapes.conv2d_shape) ops.RegisterShape("DepthwiseConv2dNative")( common_shapes.depthwise_conv2d_native_shape) ops.RegisterShape("AvgPool")(common_shapes.avg_pool_shape) ops.RegisterShape("MaxPool")(common_shapes.max_pool_shape) @ops.RegisterShape("MaxPoolWithArgmax") def _MaxPoolWithArgMaxShape(op): """Shape function for MaxPoolWithArgmax op.""" return common_shapes.max_pool_shape(op) * 2 @ops.RegisterShape("AvgPoolGrad") def _AvgPoolGradShape(op): """Shape function for the AvgPoolGrad op.""" orig_input_shape = tensor_util.constant_value(op.inputs[0]) if orig_input_shape is not None: return [tensor_shape.TensorShape(orig_input_shape.tolist())] else: # NOTE(mrry): We could in principle work out the shape from the # gradients and the attrs, but if we do not know orig_input_shape # statically, then we are unlikely to know the shape of the # gradients either. return [tensor_shape.unknown_shape(ndims=4)] @ops.RegisterShape("Conv2DBackpropFilter")
tensorflow.python.framework.ops.RegisterShape
8,832
import tensorflow as tf if len(self.env.observation_space.shape) == 1: # This means we are running on low-dimensional observations (e.g. RAM) input_shape = self.env.observation_space.shape else: img_h, img_w, img_c = self.env.observation_space.shape input_shape = (img_h, img_w, frame_history_len * img_c) self.num_actions = self.env.action_space.n # set up placeholders # placeholder for current observation (or state) self.obs_t_ph = tf.placeholder( tf.float32 if lander else tf.uint8, [None] + list(input_shape)) # placeholder for current action self.act_t_ph = tf.placeholder(tf.int32, [None]) # placeholder for current reward self.rew_t_ph = tf.placeholder(tf.float32, [None]) # placeholder for next observation (or state) self.obs_tp1_ph = tf.placeholder( tf.float32 if lander else tf.uint8, [None] + list(input_shape)) # placeholder for end of episode mask # this value is 1 if the next state corresponds to the end of an episode, # in which case there is no Q-value at the next state; at the end of an # episode, only the current state reward contributes to the target, not the # next state Q-value (i.e. target is just rew_t_ph, not rew_t_ph + gamma * q_tp1) self.done_mask_ph = tf.placeholder(tf.float32, [None])
tensorflow.placeholder
8,833
from tensorflow.python.summary import summary if grad_values is not None: var_name = variable.name.replace(":", "_") if "gradients" in summaries: summary.histogram("gradients/%s" % var_name, grad_values) if "gradient_norm" in summaries: summary.scalar("gradient_norm/%s" % var_name, clip_ops.global_norm([grad_values]))
tensorflow.python.summary.summary.histogram
8,834
import tensorflow as tf self.lstm_state_sizes[direction].append(lstm_cell.state_size) self.lstm_init_states[direction].append(init_states) self.lstm_final_states[direction].append(final_state) if direction == 'forward': self.lstm_outputs[direction].append(layer_output) else: self.lstm_outputs[direction].append( tf.reverse_sequence( layer_output, sequence_lengths, seq_axis=1, batch_axis=0 ) ) with tf.control_dependencies([layer_output]): # update the initial states for i in range(2): new_state = tf.concat( [final_state[i][:batch_size, :], init_states[i][batch_size:, :]], axis=0) state_update_op = tf.assign(init_states[i], new_state) update_ops.append(state_update_op) layer_input = layer_output self.mask = mask self.sequence_lengths = sequence_lengths self.update_state_op = tf.group(*update_ops)
tensorflow.control_dependencies
8,835
import tensorflow as tf def get_conv_var(self, filter_size, in_channels, out_channels, name): initial_value = tf.truncated_normal([filter_size, filter_size, in_channels, out_channels], 0.0, stddev = 1 / math.sqrt(float(filter_size * filter_size))) filters = self.get_var(initial_value = initial_value, name = name, idx = 'weights', var_name = "_filters") initial_value = tf.truncated_normal([out_channels], 0.0, 1.0) biases = self.get_var(initial_value = initial_value, name = name, idx = 'biases', var_name = "_biases") return filters, biases def get_fc_var(self, in_size, out_size, name):
tensorflow.truncated_normal
8,836
import tensorflow as tf self.batch_size = imgshape[1] featsize = 1024 srcimg = image[0] tgtimg = image[2] tgtctx = image[1] with tf.variable_scope("conv_context") as scope: tgtctx_h0 = lrelu(conv2d(tgtctx, self.df_dim, name='h0_conv')) tgtctx_h1 = lrelu(conv2d(tgtctx_h0, self.df_dim*2, name='h1_conv')) tgtctx_h2 = lrelu(conv2d(tgtctx_h1, self.df_dim*4, name='h2_conv')) tgtctx_h3 = lrelu(conv2d(tgtctx_h2, self.df_dim*8, name='h3_conv')) tgtctx_h4 = lrelu(linear(tf.reshape(tgtctx_h3, [self.batch_size, -1]), featsize, 'h4_lin'))
tensorflow.variable_scope
8,837
import tensorflow as tf loss = None train_op = None eval_metric_ops = None # 3. Create predictions predictions_dict = {"predicted": predictions} # 4. Create export outputs export_outputs = {"predict_export_outputs": tf.estimator.export.PredictOutput(outputs = predictions)} # 4. Return EstimatorSpec return tf.estimator.EstimatorSpec( mode = mode, predictions = predictions_dict, loss = loss, train_op = train_op,
tensorflow.estimator.export.PredictOutput
8,838
import tensorflow as tf logging.warn('The following variables in the checkpoint were not loaded:') for varname_not_loaded in not_loaded: logging.info('%s', varname_not_loaded) else: # just get model vars. for v in model_vars: mapping[v.op.name] = v return mapping def get_imagenet_vars_to_restore(imagenet_ckpt): """Returns dict of variables to restore from ImageNet-checkpoint.""" vars_to_restore_imagenet = {} ckpt_var_names = tf.contrib.framework.list_variables(imagenet_ckpt) ckpt_var_names = [name for (name, unused_shape) in ckpt_var_names] model_vars = tf.global_variables() for v in model_vars: if 'global_step' in v.op.name: continue mvname_noprefix = v.op.name.replace('depth_prediction/', '') mvname_noprefix = mvname_noprefix.replace('moving_mean', 'mu') mvname_noprefix = mvname_noprefix.replace('moving_variance', 'sigma') if mvname_noprefix in ckpt_var_names: vars_to_restore_imagenet[mvname_noprefix] = v else: logging.info('The following variable will not be restored from '
tensorflow.contrib.framework.list_variables
8,839
import tensorflow as tf loss = tf.maximum(0.0, (tgt_larg - tgt_small) - (pred_larg - pred_small) + margin) loss = tf.reduce_mean(loss) return loss def contra_step_lossV4(pred, tgt): # 50*50 # Step-wise contrastive loss even = [2 * i for i in range(25)] odd = [2 * i + 1 for i in range(25)] pred1 = tf.gather(pred, even) pred2 = tf.gather(pred, odd) tgt1 = tf.gather(tgt, even) tgt2 = tf.gather(tgt, odd) geq = tf.cast((tgt1 - tgt2) > 0, tf.bool) tgt_larg = tf.where(geq, tgt1, tgt2) tgt_small = tf.where(geq, tgt2, tgt1) pred_larg = tf.where(geq, pred1, pred2) pred_small = tf.where(geq, pred2, pred1)
tensorflow.gather
8,840
import tensorflow as tf for class_id in range(self.max_num_classes): # Do the same for the ground truth and predictions sdf_values = tf.zeros_like(samples_world)[:, 0:1] for mtype, (classes, sdfs, poses) in enumerate([ (labeled_classes, labeled_sdfs, labeled_poses), (predicted_classes, predicted_sdfs, predicted_poses)]): for i in range(classes.shape[0]): if class_id == classes[i]: sdf = tf.expand_dims(sdfs[i], -1) sdf = sdf * -1.0 # inside positive, outside zero samples_object = centernet_utils.transform_pointcloud( tf.reshape(samples_world, [1, 1, -1, 3]), tf.reshape(poses[2][i], [1, 1, 3]), tf.reshape(poses[0][i], [1, 1, 3, 3]), tf.reshape(poses[1][i], [1, 1, 3]), inverse=True) * 2.0 samples_object = \ (samples_object * (29.0/32.0) / 2.0 + 0.5) * 32.0 - 0.5 samples = tf.squeeze(samples_object) interpolated = trilinear.interpolate(sdf, samples) sdf_values += tf.math.sign(tf.nn.relu(interpolated + self.tol)) status2 = False if status2: a = 2 values = interpolated inter = tf.reshape(values, [self.resolution, self.resolution, self.resolution])
tensorflow.reshape
8,841
import tensorflow as tf input_tensor, units=bert_config.hidden_size, activation=modeling.get_activation(bert_config.hidden_act), kernel_initializer=modeling.create_initializer( bert_config.initializer_range)) input_tensor = modeling.layer_norm(input_tensor) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. output_bias = tf.get_variable( "output_bias", shape=[bert_config.vocab_size], initializer=tf.zeros_initializer()) logits = tf.matmul(input_tensor, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias) log_probs = tf.nn.log_softmax(logits, axis=-1) label_ids = tf.reshape(label_ids, [-1]) one_hot_labels = tf.one_hot( label_ids, depth=bert_config.vocab_size, dtype=tf.float32) per_example_loss = -tf.reduce_sum(log_probs * one_hot_labels, axis=[-1]) loss = tf.reshape(per_example_loss, [-1, tf.shape(positions)[1]]) # TODO: dynamic gather from per_example_loss return loss
tensorflow.nn.bias_add
8,842
import tensorflow as tf tf.app.flags.DEFINE_integer( 'tf_random_seed', 20180417, 'Random seed for TensorFlow initializers.') tf.app.flags.DEFINE_float( 'weight_decay', 1e-5, 'The weight decay on the model weights.')
tensorflow.app.flags.DEFINE_float
8,843
import tensorflow as tf gtboxes_and_label_h = get_horizen_minAreaRectangle( tf.reshape(gtboxes_and_label_batch[start:end], [-1, 9])) gtboxes_and_label_h = tf.reshape(gtboxes_and_label_h, [cfgs.BATCH_SIZE, -1, 5])
tensorflow.reshape
8,844
import tensorflow as tf tf.int32) a = tf.assign_sub(p, tf.fill([1024, 1024], 0)) with self.assertRaisesOpError("use uninitialized"): a.op.run() # NOTE(mrry): See also # dense_update_ops_no_tsan_test.AssignOpTest, which contains a benign # data race and must run without TSAN. def testParallelUpdateWithLocking(self): with self.test_session() as sess: zeros_t = tf.fill([1024, 1024], 0.0) ones_t = tf.fill([1024, 1024], 1.0) p = tf.Variable(zeros_t) adds = [tf.assign_add(p, ones_t, use_locking=True) for _ in range(20)] p.initializer.run() def run_add(add_op): sess.run(add_op) threads = [ self.checkedThread(target=run_add, args=(add_op,)) for add_op in adds] for t in threads: t.start() for t in threads:
tensorflow.Variable
8,845
from tensorflow.python.framework import tensor_shape filter_shape = tensor_util.constant_value(op.inputs[1]) if filter_shape is not None: return [tensor_shape.TensorShape(filter_shape.tolist())] else: # NOTE(mrry): We could in principle work out the shape from the # gradients and the attrs, but if we do not know filter_shape # statically, then we are unlikely to know the shape of the # gradients either. return [tensor_shape.unknown_shape(ndims=4)] @ops.RegisterShape("Conv2DBackpropInput") def _Conv2DBackpropInputShape(op): """Shape function for the Conv2DBackpropInput op.""" input_shape = tensor_util.constant_value(op.inputs[0]) if input_shape is not None:
tensorflow.python.framework.tensor_shape.unknown_shape
8,846
import tensorflow as tf (1 - self.terminals_ph_n) *( self.gamma**self.n_step_length ) * self.value_target_n) qf1_loss_n = 0.5 * tf.reduce_mean(((q_backup_n - qf1) ** 2)*self.weight_ph) qf1_loss_n_col = tf.reduce_mean(((q_backup_n - qf1) ** 2),1) qf2_loss_n = 0.5 * tf.reduce_mean(((q_backup_n - qf2) ** 2)*self.weight_ph) if self.n_step: value_for_priority = qf1_loss_col + qf1_loss_n_col else: value_for_priority = qf1_loss_col # Compute the entropy temperature loss # it is used when the entropy coefficient is learned ent_coef_loss, entropy_optimizer = None, None if not isinstance(self.ent_coef, float): ent_coef_loss = -tf.reduce_mean( self.log_ent_coef * tf.stop_gradient(logp_pi + self.target_entropy)*self.weight_ph) entropy_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate_ph) # Compute the policy loss # Alternative: policy_kl_loss = tf.reduce_mean(logp_pi - min_qf_pi) policy_kl_loss = tf.reduce_mean((self.ent_coef * logp_pi - min_qf_pi)*self.weight_ph) actor_for_priority = tf.reduce_mean(self.ent_coef * logp_pi - min_qf_pi,1) # NOTE: in the original implementation, they have an additional # regularization loss for the Gaussian parameters # this is not used for now # policy_loss = (policy_kl_loss + policy_regularization_loss) min_q = tf.minimum(dtm_qf1,dtm_qf2)
tensorflow.stop_gradient
8,847
import tensorflow as tf commitment loss, embedding training loss. """ x_means_hot = self.nearest_neighbor(x, means) x_means_hot_flat = tf.reshape( x_means_hot, [-1, self.hparams.num_blocks, self.hparams.block_v_size]) x_means = tf.matmul(tf.transpose(x_means_hot_flat, perm=[1, 0, 2]), means) x_means = tf.transpose(x_means, [1, 0, 2]) q_loss = tf.reduce_mean( tf.squared_difference(tf.stop_gradient(x), x_means)) e_loss = tf.reduce_mean( tf.squared_difference(x, tf.stop_gradient(x_means))) return x_means_hot, x_means, q_loss, e_loss def bit_to_int(self, x_bit, num_bits, base=2): """Turn x_bit representing numbers bitwise (lower-endian) to int tensor. Args: x_bit: Tensor containing numbers in a particular base to be converted to int.
tensorflow.stop_gradient
8,848
import tensorflow as tf Returns: prediction_dict: a dictionary holding prediction tensors to be passed to the Loss or Postprocess functions. """ flattened_inputs = tf.contrib.layers.flatten(preprocessed_inputs) class_prediction = tf.contrib.layers.fully_connected( flattened_inputs, self._num_classes) box_prediction = tf.contrib.layers.fully_connected(flattened_inputs, 4) return { 'class_predictions_with_background': tf.reshape( class_prediction, [-1, 1, self._num_classes]), 'box_encodings': tf.reshape(box_prediction, [-1, 1, 4]) }
tensorflow.contrib.layers.fully_connected
8,849
import tensorflow as tf if self.trust_region: # [n_envs * n_steps, n_act] grad = tf.gradients(- (loss_policy - self.ent_coef * entropy) * self.n_steps * self.n_envs, phi_i) # [n_envs * n_steps, n_act] # Directly computed gradient of KL divergence wrt f kl_grad = - f_polyak_i / (f_i_ + eps) k_dot_g = tf.reduce_sum(kl_grad * grad, axis=-1) adj = tf.maximum(0.0, (tf.reduce_sum(kl_grad * grad, axis=-1) - self.delta) / ( tf.reduce_sum(tf.square(kl_grad), axis=-1) + eps)) # [n_envs * n_steps] # Calculate stats (before doing adjustment) for logging. avg_norm_k = avg_norm(kl_grad) avg_norm_g = avg_norm(grad) avg_norm_k_dot_g = tf.reduce_mean(tf.abs(k_dot_g)) avg_norm_adj = tf.reduce_mean(tf.abs(adj))
tensorflow.square
8,850
import tensorflow as tf name='rightmost_transposed_ndims') rightmost_transposed_ndims_ = tf.get_static_value( rightmost_transposed_ndims) with tf.control_dependencies(_maybe_validate_rightmost_transposed_ndims( rightmost_transposed_ndims, validate_args)): rightmost_transposed_ndims = tf.identity(rightmost_transposed_ndims) perm = tf.range( start=rightmost_transposed_ndims - 1, limit=-1, delta=-1, name='perm') else: # perm is not None: perm = tf.convert_to_tensor(value=perm, dtype=np.int32, name='perm') rightmost_transposed_ndims = tf.size( input=perm, name='rightmost_transposed_ndims') rightmost_transposed_ndims_ = tf.get_static_value( rightmost_transposed_ndims) with tf.control_dependencies(_maybe_validate_perm(perm, validate_args)): perm = tf.identity(perm) # TODO(b/110828604): If bijector base class ever supports dynamic # `min_event_ndims`, then this class already works dynamically and the # following five lines can be removed. if rightmost_transposed_ndims_ is None:
tensorflow.convert_to_tensor
8,851
import tensorflow as tf def max_pool(self, bottom, name): return tf.nn.max_pool(bottom, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name) def conv_layer(self, bottom, name): with tf.variable_scope(name): filt = self.get_conv_filter(name) conv = tf.nn.conv2d(bottom, filt, [1, 1, 1, 1], padding='SAME') conv_biases = self.get_bias(name) bias = tf.nn.bias_add(conv, conv_biases) relu = tf.nn.relu(bias) return relu def fc_layer(self, bottom, name): with tf.variable_scope(name): shape = bottom.get_shape().as_list() dim = 1 for d in shape[1:]: dim *= d x = tf.reshape(bottom, [-1, dim]) weights = self.get_fc_weight(name) biases = self.get_bias(name)
tensorflow.nn.relu
8,852
import tensorflow as tf ------- A tensor. """ if axis < 0: dims = get_ndim(tensors[0]) if dims: axis = axis % dims else: axis = 0 try: return tf.concat_v2([x for x in tensors], axis) except AttributeError: return tf.concat(axis=axis, values=[x for x in tensors]) def _normalize_axis(axis, ndim): if isinstance(axis, tuple): axis = list(axis) if isinstance(axis, list): for i, a in enumerate(axis): if a is not None and a < 0: axis[i] = a % ndim else: if axis is not None and axis < 0: axis = axis % ndim
tensorflow.concat
8,853
import tensorflow as tf FLAGS.enable_check_numerics = False with self.session(): tf.global_variables_initializer().run() self.assertFalse(has_nan_or_inf.eval()) self.assertEqual(1.0, grad_scale.eval()) # The final gradient must be finite. self.assertFalse(tf.is_nan(final_var_grads.a[1]).eval()) self.assertTrue(tf.is_finite(final_var_grads.a[1]).eval()) def testScaleGradientsInf(self): FLAGS.enable_check_numerics = False p = self.TestParams() p.input = base_input_generator.BaseSequenceInputGenerator.Params()
tensorflow.is_nan
8,854
import tensorflow as tf tf.flags.DEFINE_integer('batch_size', 0, 'batch size per compute device') tf.flags.DEFINE_integer('num_batches', 100, 'number of batches to run, excluding warmup') tf.flags.DEFINE_integer('num_warmup_batches', None, 'number of batches to run before timing') tf.flags.DEFINE_integer('autotune_threshold', None, 'The autotune threshold for the models') tf.flags.DEFINE_integer('num_gpus', 1, 'the number of GPUs to run on') tf.flags.DEFINE_integer('display_every', 10, """Number of local steps after which progress is printed out""") tf.flags.DEFINE_string('data_dir', None, """Path to dataset in TFRecord format (aka Example protobufs). If not specified, synthetic data will be used.""") tf.flags.DEFINE_string('data_name', None, """Name of dataset: imagenet or flowers.
tensorflow.flags.DEFINE_integer
8,855
import tensorflow as tf used_var -= (1 - bn_lag) * (used_var - tf.stop_gradient(var)) used_mean /= (1. - bn_lag**(step + 1)) used_var /= (1. - bn_lag**(step + 1)) else: used_mean, used_var = mean, var cur_mean, cur_var = used_mean, used_var # normalize res = (input_ - used_mean) / tf.sqrt(used_var + epsilon) # de-normalize if scale: res *= gamma res += beta # update variables if train:
tensorflow.sqrt
8,856
import tensorflow as tf # [batch*n_agents, 1] self.q_selected = tf.reduce_sum(tf.multiply(self.q_eval, self.a), axis=1) # ------------------ build mixing_net ------------------ with tf.variable_scope('mixing_net'): # [batch, n_agents] self.q_concat = tf.reshape(self.q_selected, [-1, self.n_agents]) self.q_concat_ =tf.reshape(self.q_m_, [-1, self.n_agents]) with tf.variable_scope('eval_hyper'): self.Q_tot = Qmix_mixer(self.q_concat, self.S, self.num_global_s, self.n_agents, 32) with tf.variable_scope('target_hyper'): self.Q_tot_ = Qmix_mixer(self.q_concat_, self.S_, self.num_global_s, self.n_agents, 32) # with tf.variable_scope('layer_mix_eval'): # lin1 = tf.matmul(tf.reshape(self.q_concat, shape=[-1, 1, self.n_agents]), self.w1) + tf.reshape(self.b1, shape=[-1, 1, 32]) # a1 = tf.nn.elu(lin1, name='a1') # self.Q_tot = tf.reshape(tf.matmul(a1, self.w2), shape=[-1, 1]) + self.b2 # with tf.variable_scope('layer_mix_target'): # lin1_ = tf.matmul(tf.reshape(self.q_concat_, shape=[-1, 1, self.n_agents]), self.w1_) + tf.reshape(self.b1_, shape=[-1, 1, 32]) # a1_ = tf.nn.elu(lin1_, name='a1_') # self.Q_tot_ = tf.reshape(tf.matmul(a1_, self.w2_), shape=[-1, 1]) + self.b2_
tensorflow.variable_scope
8,857
import tensorflow as tf def testAttentionDecoder1(self): with self.test_session() as sess: with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): cell = tf.nn.rnn_cell.GRUCell(2) inp = [tf.constant(0.5, shape=[2, 2])] * 2 enc_outputs, enc_state = tf.nn.rnn(cell, inp, dtype=tf.float32) attn_states = tf.concat(1, [tf.reshape(e, [-1, 1, cell.output_size]) for e in enc_outputs]) dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3 dec, mem = tf.nn.seq2seq.attention_decoder( dec_inp, enc_state, attn_states, cell, output_size=4) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].shape)
tensorflow.nn.seq2seq.attention_decoder
8,858
import tensorflow as tf rnd_pred_cri_in_dim = rnd_pred_cri_in_ph.shape.as_list()[1] rnd_pred_cri_dropout_mask_generator = DropoutMaskGenerator(rnd_pred_cri_in_dim, hidden_sizes, model_prob=1.0 - dropout_rate) rnd_pred_cri_dropout_mask_phs = rnd_pred_cri_dropout_mask_generator.generate_dropout_mask_placeholders() rnd_pred_cri, rnd_pred_cri_reg = mlp_variational(rnd_pred_cri_in_ph, rnd_pred_cri_dropout_mask_phs, list(hidden_sizes) + [1], activation, None, dropout_rate) rnd_pred_cri = tf.squeeze(rnd_pred_cri, axis=2) return rnd_targ_act,\ rnd_pred_act, rnd_pred_act_reg, rnd_pred_act_dropout_mask_generator, rnd_pred_act_dropout_mask_phs,\ rnd_targ_cri,\ rnd_pred_cri, rnd_pred_cri_reg, rnd_pred_cri_dropout_mask_generator, rnd_pred_cri_dropout_mask_phs """ Actor-Critics
tensorflow.squeeze
8,859
import tensorflow as tf train_file, task_name) tf.logging.info("***** Running training *****") tf.logging.info(" Num examples = %d", len(train_examples)) tf.logging.info(" Batch size = %d", FLAGS.train_batch_size) tf.logging.info(" Num steps = %d", FLAGS.train_step) train_input_fn = classifier_utils.file_based_input_fn_builder( input_file=train_file, seq_length=FLAGS.max_seq_length,
tensorflow.logging.info
8,860
from tensorflow.python.client import graph_util """Calculates the on-disk weight parameters for BiasAdd.""" bias_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[1])
tensorflow.python.client.graph_util.tensor_shape_from_node_def_name
8,861
import tensorflow as tf # HACK: inputs to concatenate have to be in list (not tuple) format # see "tensorflow_core/python/keras/layers/merge.py", line 378 @gin.configurable def merge_obs_w_ac_layer(): def f(layer_input): return tf.keras.layers.concatenate(list(layer_input), axis=-1) return tf.keras.layers.Lambda(f) @gin.configurable def extract_observation_layer(): return tf.keras.layers.Lambda(lambda obs: obs['observation'])
tensorflow.keras.layers.Lambda
8,862
import tensorflow as tf weights, states, attns, initial_weights, samples, initial_context), parallel_iterations=decoder.parallel_iterations, swap_memory=decoder.swap_memory) outputs = outputs.stack() weights = weights.stack() # batch_size, encoders, output time, input time states = states.stack() attns = attns.stack() samples = samples.stack() # put batch_size as first dimension outputs = tf.transpose(outputs, perm=(1, 0, 2)) weights = tf.transpose(weights, perm=(1, 0, 2)) states = tf.transpose(states, perm=(1, 0, 2)) attns = tf.transpose(attns, perm=(1, 0, 2)) samples = tf.transpose(samples) return outputs, weights, states, attns, samples, get_logits, initial_data def encoder_decoder(encoders, decoders, encoder_inputs, targets, feed_previous, align_encoder_id=0, encoder_input_length=None, feed_argmax=True, rewards=None, use_baseline=True, training=True, global_step=None, monotonicity_weight=None, monotonicity_dist=None, monotonicity_decay=None, **kwargs): decoder = decoders[0] targets = targets[0] # single decoder
tensorflow.transpose
8,863
import tensorflow as tf out = s(buffers, transitions, training=True) self.assertEqual(tf.float32, out.dtype) self.assertEqual((1, embedding_dims), out.shape) def testSNLIClassifierAndTrainer(self): with tf.device(self._test_device): vocab_size = 40 batch_size = 2 d_embed = 10 sequence_length = 15
tensorflow.device
8,864
import tensorflow as tf horizon_tgt1, horizon_tgt2 = tf.split(horizon_tgt, 2, axis=0) pred_flat1, pred_flat2 = tf.reshape(horizon_pred1, [-1, 1]), tf.reshape(horizon_pred2, [1, -1]) tgt_flat1, tgt_flat2 = tf.reshape(horizon_tgt1, [-1, 1]), tf.reshape(horizon_tgt2, [1, -1]) tgt_dif = tgt_flat1 - tgt_flat2
tensorflow.reshape
8,865
from tensorflow.python.framework import ops with ops.control_dependencies([total_compute_op, count_compute_op]): update_op = _safe_div(total, count, 'update_op') if metrics_collections: ops.add_to_collections(metrics_collections, mean) if updates_collections: ops.add_to_collections(updates_collections, update_op)
tensorflow.python.framework.ops.add_to_collections
8,866
import tensorflow as tf prem_trans = tf.constant(np.array( [[3, 3, 2, 3, 3, 3, 2, 2, 2, 3, 3, 3, 2, 3, 3, 2, 2, 3, 3, 3, 2, 2, 2, 2, 3, 2, 2]] * batch_size, dtype=np.int64).T) hypo = tf.random_uniform( (sequence_length, batch_size), maxval=vocab_size, dtype=tf.int64) hypo_trans = tf.constant(np.array( [[3, 3, 2, 3, 3, 3, 2, 2, 2, 3, 3, 3,
tensorflow.random_uniform
8,867
import tensorflow as tf with tf.name_scope(name): tt_cores = [None] * num_dims for i in range(num_dims): curr_core_shape = (1, shape[0][i], shape[1][i], 1) tt_cores[i] = tf.ones(curr_core_shape, dtype=dtype) return TensorTrain(tt_cores, shape, tt_rank)
tensorflow.ones
8,868
import tensorflow as tf 'image/object/bbox/xmin': tf.VarLenFeature(dtype=tf.float32), 'image/object/bbox/ymin': tf.VarLenFeature(dtype=tf.float32),
tensorflow.VarLenFeature
8,869
import tensorflow as tf tokens = tf.concat([[self.prepend_token], tokens], 0) # Optionally append a special token if self.append_token is not None: tokens = tf.concat([tokens, [self.append_token]], 0) sequence[self.tokens_feature_name] = tokens # Merge context and sequence features example = {}
tensorflow.concat
8,870
import tensorflow as tf loss = tf.maximum(0.0, (tgt_larg - tgt_small) - (pred_larg - pred_small)) loss = tf.reduce_mean(loss) return loss def contra_step_lossV3(pred, tgt, margin=1.0): # Step-wise contrastive loss pred1, pred2 = tf.split(pred, 2, axis=0) tgt1, tgt2 = tf.split(tgt, 2, axis=0) geq = tf.cast((tgt1 - tgt2) > 0, tf.bool) tgt_larg = tf.where(geq, tgt1, tgt2) tgt_small = tf.where(geq, tgt2, tgt1) pred_larg = tf.where(geq, pred1, pred2) pred_small = tf.where(geq, pred2, pred1) loss = tf.maximum(0.0, (tgt_larg - tgt_small) - (pred_larg - pred_small) + margin) loss = tf.reduce_mean(loss) return loss def contra_step_lossV4(pred, tgt): # 50*50 # Step-wise contrastive loss even = [2 * i for i in range(25)] odd = [2 * i + 1 for i in range(25)] pred1 = tf.gather(pred, even) pred2 = tf.gather(pred, odd) tgt1 = tf.gather(tgt, even)
tensorflow.where
8,871
import tensorflow as tf """Calculates the per-example cross-entropy loss for a sequence of logits and masks out all losses passed the sequence length. Args: logits: Logits of shape `[T, B, vocab_size]` targets: Target classes of shape `[T, B]` sequence_length: An int32 tensor of shape `[B]` corresponding to the length of each input Returns: A tensor of shape [T, B] that contains the loss per example, per time step. """ with tf.name_scope("cross_entropy_sequence_loss"): losses = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=targets) loss_mask = tf.sequence_mask(tf.to_int32(sequence_length), tf.to_int32(tf.shape(targets)[0])) losses = losses * tf.transpose(tf.to_float(loss_mask), [1, 0]) return losses def dice_loss(predictions, targets, weights=1., name='dice_loss'): with tf.name_scope(name): # predictions = tf.to_float(predictions) targets = tf.to_float(targets) intersection = 2 * tf.reduce_sum(predictions * targets) + weights union = weights + tf.reduce_sum(predictions) + tf.reduce_sum(targets) loss = -(intersection / (union)) return loss
tensorflow.to_float
8,872
import tensorflow as tf import tensorflow as tf def make_parallel(model, gpu_count): def get_slice(data, idx, parts): shape = tf.shape(data) size = tf.concat(0, [shape[:1] // parts, shape[1:]]) stride = tf.concat(0, [shape[:1] // parts, shape[1:] * 0]) start = stride * idx return tf.slice(data, start, size) outputs_all = []
tensorflow.concat
8,873
from tensorflow.python.framework import ops @ops.RegisterShape("LogicalOr") @ops.RegisterShape("Maximum") @ops.RegisterShape("Minimum") @ops.RegisterShape("Mod") @ops.RegisterShape("Mul") @ops.RegisterShape("NotEqual") @ops.RegisterShape("Pow") @ops.RegisterShape("Sub") def _BroadcastShape(op): """Common shape function for binary operators that broadcast their inputs.""" shape_x = op.inputs[0].get_shape() shape_y = op.inputs[1].get_shape()
tensorflow.python.framework.ops.RegisterShape
8,874
import tensorflow as tf def data_map(self, img_path): n_bits = config.model.data.n_bits n_bins = 2**n_bits rgb = tf.image.decode_png(tf.read_file(img_path), channels=3, dtype=tf.uint8) h = config.model.data.dimensions.h w = config.model.data.dimensions.w c = config.model.data.dimensions.c # rgb.set_shape([h,w,c]) # don't set because going to crop anyway # crop for lsun 96, see realnvp and glow for specifics rgb = tf.image.random_crop(rgb,size=[h,w,c]) # crop for patch training crop_h = h//self.crop_factor crop_w = w//self.crop_factor rgb = tf.image.random_crop(rgb,size=[crop_h,crop_w,c]) # random left-right flops rgb = tf.image.random_flip_left_right(rgb) # cast, bit conversion, compress domain, center rgb = tf.cast(rgb, tf.float32)
tensorflow.image.random_crop
8,875
import tensorflow as tf 'gpu_memory_fraction', 1., 'GPU memory fraction to use.') # scaffold related configuration tf.app.flags.DEFINE_string( 'data_dir', '../Datasets/tfrecords',#'/media/rs/0E06CD1706CD0127/Kapok/Chi/Datasets/tfrecords', 'The directory where the dataset input data is stored.') tf.app.flags.DEFINE_string( 'dataset_name', '{}_????', 'The pattern of the dataset name to load.') tf.app.flags.DEFINE_string( 'model_dir', './logs_sext_cpn/', 'The parent directory where the model will be stored.') tf.app.flags.DEFINE_integer( 'log_every_n_steps', 10, 'The frequency with which logs are print.') tf.app.flags.DEFINE_integer( 'save_summary_steps', 100, 'The frequency with which summaries are saved, in seconds.') tf.app.flags.DEFINE_integer( 'save_checkpoints_secs', 3600, 'The frequency with which the model is saved, in seconds.') # model related configuration
tensorflow.app.flags.DEFINE_integer
8,876
import tensorflow as tf def deconv3d(x, shape, output_shape, name, bias=False, stride=2, padding='SAME'): with tf.variable_scope(name): W = weight_variable(shape)
tensorflow.variable_scope
8,877
import tensorflow as tf tgt_posi_dif = tf.where(geq, tgt_dif, -tgt_dif) pred_posi_dif = tf.where(geq, pred_dif, -pred_dif) loss = tf.maximum(0., tgt_posi_dif - pred_posi_dif) cstr_pct = tf.math.count_nonzero(loss, dtype=tf.float32) / tf.cast(tf.reduce_prod(tf.shape(loss)), tf.float32) final_loss = tf.reduce_mean(loss) return final_loss, cstr_pct
tensorflow.math.count_nonzero
8,878
from tensorflow.python.framework import ops return self._saved_model_loader_value def _init_batch_counters(self, *args, **kwargs): # pylint: disable=g-doc-args """Overriding this method because Model's implementation creates variables. These Variables are not needed for TransformFeaturesLayer. """ pass def call( self, inputs: Mapping[str, common_types.TensorType] ) -> Dict[str, common_types.TensorType]: if self._exported_as_v1 and not ops.executing_eagerly_outside_functions(): tf.compat.v1.logging.warning('Falling back to transform_raw_features...') return self._tft_output._transform_raw_features_compat_v1( # pylint: disable=protected-access inputs, drop_unused_features=True) else: return self._saved_model_loader.apply_transform_model(inputs) def _make_method_override(name): @doc_controls.do_not_generate_docs def method_override(*args, **kwargs):
tensorflow.python.framework.ops.executing_eagerly_outside_functions
8,879
import tensorflow as tf epsilon = 1e-5 mean, var = tf.nn.moments(x, [1, 2], keep_dims=True) scale = tf.get_variable('scale',[x.get_shape()[-1]], initializer=tf.truncated_normal_initializer(mean=1.0, stddev=0.02)) offset = tf.get_variable('offset',[x.get_shape()[-1]],initializer=tf.constant_initializer(0.0)) out = scale*tf.div(x-mean, tf.sqrt(var+epsilon)) + offset return out
tensorflow.constant_initializer
8,880
import tensorflow as tf def input_fn(params): """The actual input function.""" batch_size = params["batch_size"] name_to_features = { "input_ids": tf.FixedLenFeature([max_seq_length], tf.int64), "input_mask": tf.FixedLenFeature([max_seq_length], tf.int64), "segment_ids": tf.FixedLenFeature([max_seq_length], tf.int64), "masked_lm_positions": tf.FixedLenFeature([max_predictions_per_seq], tf.int64),
tensorflow.FixedLenFeature
8,881
import tensorflow as tf unused_indices = tf.reshape(tf.cast(tf.where(tf.equal(block_uses, 0)), tf.int32), [-1]) num_out_blocks = tf.size(unused_indices) # Select only unused blocks with tf.variable_scope('select'): stacked_blocks = tf.stack(cell_inputs + blocks) out_blocks = tf.gather(stacked_blocks, unused_indices, axis=0) out_blocks = tf.transpose(out_blocks, (1, 2, 3, 0, 4)) # Combine to constant channels with tf.variable_scope('combine'): W = self._make_var('W', (ni, block_ch * block_ch)) W = tf.gather(W, unused_indices, axis=0) W = tf.reshape(W, (1, 1, num_out_blocks * block_ch, block_ch)) X = tf.reshape(out_blocks, (-1, w, h, num_out_blocks * block_ch)) X = tf.nn.relu(X) X = tf.nn.conv2d(X, W, (1, 1, 1, 1), padding='SAME') X = self._add_batch_norm(X, block_ch, is_train=is_train) return (X, block_ch) def _add_op(self, cell_inputs, blocks, input_idx, op, w, h, ch, is_reduction=False, is_train=False): ni = len(cell_inputs + blocks) inputs = cell_inputs + blocks op_map = self._get_op_map() # Just build output for select operation X = inputs[input_idx] op_no = OPS[op] op_method = op_map[op_no]
tensorflow.nn.relu
8,882
import tensorflow as tf Treats each document (tweet) as a single "word," which is fed through c2v, and the output "embedding" sized to be a vector of language predictions. """ def __init__(self, out_vocab_size=None, batch_size=10, model_params=None, c2v=None, max_sequence_len=None, dropout_keep_prob=None, weights=None): self.params = model_params self._out_vocab_size = out_vocab_size # num. of languages self.weights = tf.constant(weights, dtype=tf.float32, name='class_weights') with tf.variable_scope("tweetff"): hidden = tf.get_variable("ff_hidden", [c2v.embedding_dims, out_vocab_size]) bias = tf.get_variable('ff_bias', [out_vocab_size]) #probably useless. at least I don't want to use it self.seq_lens = tf.placeholder(tf.int64, [batch_size], name='seq_lens') self.x = tf.placeholder(tf.int32, [batch_size, max_sequence_len], name='x') self.y = tf.placeholder(tf.float32, [batch_size, out_vocab_size], name='y')
tensorflow.variable_scope
8,883
import tensorflow as tf tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver( FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project) is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2 run_config = tf.contrib.tpu.RunConfig( cluster=tpu_cluster_resolver, master=FLAGS.master, model_dir=FLAGS.output_dir, save_checkpoints_steps=FLAGS.save_checkpoints_steps, tpu_config=tf.contrib.tpu.TPUConfig( iterations_per_loop=FLAGS.iterations_per_loop, num_shards=FLAGS.num_tpu_cores, per_host_input_for_training=is_per_host)) train_examples = None num_train_steps = None num_warmup_steps = None if FLAGS.do_train:
tensorflow.contrib.tpu.TPUConfig
8,884
from tensorflow.python.ops import array_ops if isinstance(x, ops.IndexedSlices): return x x_shape = array_ops.shape(x) return ops.IndexedSlices(x, range(0, x_shape[0]), x_shape)
tensorflow.python.ops.array_ops.shape
8,885
import tensorflow as tf pred2 = tf.slice(batch2, [0, 0], [num_sam, 1]) tgt1 = tf.slice(batch1, [0, 1], [num_sam, 1]) tgt2 = tf.slice(batch2, [0, 1], [num_sam, 1]) loss = cur_loss + compute_contra_loss(pred1, pred2, tgt1, tgt2)
tensorflow.slice
8,886
import tensorflow as tf
tensorflow.zeros
8,887
import tensorflow as tf def spc_tokenize(tokenizer, features, targets): del targets tokenized_text = tokenizer.tokenize(features['text']) features['targets'] = tf.cast(tokenized_text, tf.int64) features['inputs'] = features['targets'] return features, features['targets']
tensorflow.cast
8,888
import tensorflow as tf return test_acc, test_loss, summary def resnet_model_fn(inputs, training): """Our model_fn for ResNet to be used with our Estimator.""" network = resnet_model.imagenet_resnet_v2( resnet_size=18, num_classes=class_num, mode='se', data_format=None) inputs= network(inputs=inputs, is_training=training) feat = tf.nn.l2_normalize(inputs, 1, 1e-10, name='feat') inputs = tf.layers.dense(inputs=inputs, units=class_num) # inputs = tf.layers.dense(inputs=feat, units=class_num) inputs = tf.identity(inputs, 'final_dense') return inputs, feat # image_size = 32, img_channels = 3, class_num = 10 in cifar10 x = tf.placeholder(tf.float32, shape=[None, image_size, image_size, img_channels]) label = tf.placeholder(tf.float32, shape=[None,]) one_hot_labels = tf.one_hot(indices=tf.cast(label, tf.int32), depth=class_num) training_flag = tf.placeholder(tf.bool) learning_rate = tf.placeholder(tf.float32, name='learning_rate')
tensorflow.identity
8,889
import tensorflow as tf hidden_size = output_layer.shape[-1].value output_weight = tf.get_variable( "output_weights", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02) ) output_bias = tf.get_variable( "output_bias", [num_labels], initializer=tf.zeros_initializer() ) with tf.variable_scope("loss"): if is_training: output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) output_layer = tf.reshape(output_layer, [-1, hidden_size]) logits = tf.matmul(output_layer, output_weight, transpose_b=True)
tensorflow.zeros_initializer
8,890
import tensorflow as tf @gin.configurable(module='trax.data', denylist=['dataset', 'training']) def lm_token_preprocessing(dataset, training): """Concatenates inputs, 0, targets, with masking only for targets.""" del training def concat_and_add_mask(x): inp = x['inputs'] targets = x['targets'] pad = tf.expand_dims(tf.zeros_like(inp[0]), axis=0) concat = tf.concat([inp, pad, targets], axis=0) mask = tf.concat([tf.zeros_like(inp), pad, tf.ones_like(targets)], axis=0) x['inputs'] = concat x['targets'] = concat x['mask'] = mask return x dataset = dataset.map(concat_and_add_mask) return dataset
tensorflow.zeros_like
8,891
import tensorflow as tf key_vocabulary_filename=key_vocabulary_filename) if key_vocabulary_filename is not None: return key_values key, minus_x_min, x_max = key_values return ( key, tf.cast(0 - minus_x_min, output_dtype), tf.cast(x_max, output_dtype)) def _sum_combine_fn_and_dtype( input_dtype: tf.DType ) -> Tuple[tf.DType, Callable[[np.ndarray], np.ndarray]]: output_dtype = _SUM_OUTPUT_DTYPE_MAP.get(input_dtype) if output_dtype is None: raise TypeError('Tensor type %r is not supported' % input_dtype)
tensorflow.cast
8,892
import tensorflow as tf for i in range(hparams.tacotron_num_gpus): tf.summary.histogram("mel_outputs %d" % i, model.tower_linear_outputs[i]) tf.summary.histogram("mel_targets %d" % i, model.tower_linear_targets[i]) tf.summary.scalar("regularization_loss", model.regularization_loss) tf.summary.scalar("stop_token_loss", model.stop_token_loss) tf.summary.scalar("loss", model.loss) tf.summary.scalar("learning_rate", model.learning_rate) # Control learning rate decay speed if hparams.tacotron_teacher_forcing_mode == "scheduled": tf.summary.scalar("teacher_forcing_ratio", model.ratio) # Control teacher forcing # ratio decay when mode = "scheduled" gradient_norms = [tf.norm(grad) for grad in model.gradients] tf.summary.histogram("gradient_norm", gradient_norms) tf.summary.scalar("max_gradient_norm", tf.reduce_max(gradient_norms)) # visualize
tensorflow.summary.scalar
8,893
from tensorflow.python.ops import variable_scope as vs r_state = r * state if self._candidate_linear is None: with vs.variable_scope("candidate"): self._candidate_linear = _Linear( [inputs, r_state],
tensorflow.python.ops.variable_scope.variable_scope
8,894
import tensorflow as tf src_logits, dst_logits = get_model_logits(src_features, finetune_features, mode, num_classes, target_num_classes) loss, _, _ = get_final_loss(src_logits, src_one_hot_labels, dst_logits, finetune_one_hot_labels, global_step, loss_weights, inst_weights) update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) with tf.control_dependencies(update_ops): src_train_op, _ = get_src_train_op(loss) with tf.control_dependencies([src_train_op]): target_avg_pool = get_logits( target_features, mode, FLAGS.target_dataset, reuse=True) target_logits = do_cls(
tensorflow.get_collection
8,895
import tensorflow as tf rnn_output = tf.reshape(tf.concat(outputs, axis=1), [batch_size * rnn_nunroll, rnn_size])
tensorflow.concat
8,896
from tensorflow.python.framework import constant_op ]) expected_out = self._sparse_tensor([['11_X_batch1-FC2-F1'], [ '333_X_batch2-FC2-F1', '333_X_batch2-FC2-F2', '55555_X_batch2-FC2-F1', '55555_X_batch2-FC2-F2' ]]) with self.test_session() as sess: self._assert_sparse_tensor_equals(expected_out, sess.run(op)) def test_integer_mixed_string_dense(self): """Tests mixed dense inputs. """ op = sparse_feature_cross_op.sparse_feature_cross([ constant_op.constant([[11, 333], [55555, 999999]], dtypes.int64), constant_op.constant([['batch1-FC2-F1', 'batch1-FC2-F2'], ['batch2-FC2-F1', 'batch2-FC2-F2']], dtypes.string), ]) expected_out = self._sparse_tensor([[ '11_X_batch1-FC2-F1', '11_X_batch1-FC2-F2', '333_X_batch1-FC2-F1', '333_X_batch1-FC2-F2' ], [ '55555_X_batch2-FC2-F1', '55555_X_batch2-FC2-F2', '999999_X_batch2-FC2-F1', '999999_X_batch2-FC2-F2' ]])
tensorflow.python.framework.constant_op.constant
8,897
import tensorflow as tf filters *= 2 x = common_attention.add_timing_signal_nd(x) x = tf.layers.conv2d(x, filters, kernel, activation=common_layers.belu, strides=(2, 2), padding="SAME") x = common_layers.layer_norm(x) else: x = common_layers.double_discriminator(x) x = tf.expand_dims(tf.expand_dims(x, axis=1), axis=1) x = tf.tanh(tf.layers.dense(x, hparams.bottleneck_bits, name="bottleneck")) d = x + tf.stop_gradient(2.0 * tf.to_float(tf.less(0.0, x)) - 1.0 - x) if hparams.mode == tf.estimator.ModeKeys.TRAIN: noise = tf.random_uniform(common_layers.shape_list(x)) noise = 2.0 * tf.to_float(tf.less(hparams.bottleneck_noise, noise)) - 1.0 d *= noise z = tf.layers.dense(d, final_filters, name="unbottleneck") return layer + z, 0.0 @registry.register_hparams def next_frame_basic_stochastic(): """Basic 2-frame conv model with stochastic tower.""" hparams = basic_deterministic_params.next_frame_basic_deterministic() hparams.stochastic_model = True hparams.add_hparam("latent_channels", 1)
tensorflow.less
8,898
import tensorflow as tf if mode == tf.estimator.ModeKeys.TRAIN or mode == tf.estimator.ModeKeys.EVAL: loss = tf.losses.mean_squared_error(labels, predictions) train_op = tf.contrib.layers.optimize_loss( loss = loss, global_step = tf.train.get_global_step(), learning_rate = 0.01, optimizer = "SGD") eval_metric_ops = { "rmse": tf.metrics.root_mean_squared_error(labels, predictions) } else: loss = None train_op = None eval_metric_ops = None # 3. Create predictions
tensorflow.metrics.root_mean_squared_error
8,899