seed
stringlengths
25
2.89k
seed_api
stringlengths
14
102
index
int64
0
14.8k
import tensorflow as tf weighted_average = tf.reduce_sum(tf.expand_dims(weights, 2) * hidden_states, axis=1) return weighted_average, weights def no_attention(state, hidden_states, *args, **kwargs): batch_size = tf.shape(state)[0] weighted_average = tf.zeros(shape=tf.stack([batch_size, 0])) weights = tf.zeros(shape=[batch_size, tf.shape(hidden_states)[1]]) return weighted_average, weights def average_attention(hidden_states, encoder_input_length, *args, **kwargs):
tensorflow.shape
7,300
import tensorflow as tf kernel_initializer=self._kernel_initializer) c = self._activation(self._candidate_linear([inputs, r_state])) u = (1.0 - att_score) * u new_h = u * state + (1 - u) * c return new_h, new_h def prelu(_x, scope=''): """parametric ReLU activation""" with tf.variable_scope(name_or_scope=scope, default_name="prelu"): _alpha = tf.get_variable("prelu_"+scope, shape=_x.get_shape()[-1], dtype=_x.dtype, initializer=tf.constant_initializer(0.1)) _zero = tf.constant(0,dtype=_x.dtype) # return tf.maximum(0.0, _x) + _alpha * tf.minimum(0.0, _x) return tf.maximum(_zero, _x) + _alpha * tf.minimum(_zero, _x) def calc_auc(raw_arr): """Summary Args: raw_arr (TYPE): Description Returns:
tensorflow.constant
7,301
from tensorflow.contrib.opt import ScipyOptimizerInterface if type(method) is str: success_msg = "SciPy optimizer completed successfully." options = {'maxiter': maxiter, 'disp': True} options.update(kw) optimizer = ScipyOptimizerInterface( loss, var_list=variables, method=method, options=options )
tensorflow.contrib.opt.ScipyOptimizerInterface
7,302
import tensorflow as tf from atari_wrappers import * def atari_model(img_in, num_actions, scope, reuse=False): # as described in https://storage.googleapis.com/deepmind-data/assets/papers/DeepMindNature14236Paper.pdf with tf.variable_scope(scope, reuse=reuse): out = img_in with tf.variable_scope("convnet"): # original architecture out = layers.convolution2d(out, num_outputs=32, kernel_size=8, stride=4, activation_fn=tf.nn.relu) out = layers.convolution2d(out, num_outputs=64, kernel_size=4, stride=2, activation_fn=tf.nn.relu) out = layers.convolution2d(out, num_outputs=64, kernel_size=3, stride=1, activation_fn=tf.nn.relu) out = layers.flatten(out) with tf.variable_scope("action_value"): out = layers.fully_connected(out, num_outputs=512, activation_fn=tf.nn.relu) out = layers.fully_connected(out, num_outputs=num_actions, activation_fn=None) return out def atari_learn(env, session, num_timesteps): # This is just a rough estimate num_iterations = float(num_timesteps) / 4.0 lr_multiplier = 1.0
tensorflow.variable_scope
7,303
import tensorflow as tf # 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)
tensorflow.image.random_crop
7,304
import tensorflow as tf self.mat_cores.append( self.add_weight(name='mat_core_%d' % (i + 1), shape=[self.out_modes[i] * self.mat_ranks[i + 1], self.mat_ranks[i] * self.inp_modes[i]], initializer=self.kernel_initializer, trainable=True)) if self.use_bias: self.bias = self.add_weight(name="bias", shape=(np.prod(self.out_modes),), initializer=self.bias_initializer, trainable=True) super(TTLayerDense, self).build(input_shape) def call(self, input_): dim = self.order out = tf.reshape(input_, [-1, np.prod(self.inp_modes)]) self.image_max_size = max(self.image_max_size, np.prod(self.inp_modes)) out = tf.transpose(out, [1, 0]) for i in range(dim): out = tf.reshape(out, [self.mat_ranks[i] * self.inp_modes[i], -1]) out = tf.matmul(self.mat_cores[i], out) out = tf.reshape(out, [self.out_modes[i], -1]) out = tf.transpose(out, [1, 0]) out = tf.reshape(out, [-1, np.prod(self.out_modes)]) # self.image_max_size = max(self.image_max_size, np.prod([val.value for val in out.get_shape()[1:]])) if self.use_bias: out = tf.add(out, self.bias, name='out') if self.activation is not None:
tensorflow.transpose
7,305
import tensorflow as tf def __init__(self, params): super(TestInputGenerator, self).__init__(params) self._input_batch_size = tf.constant(1)
tensorflow.constant
7,306
import tensorflow as tf :return: """ def f1(): input_shape = input_tensor.get_shape().as_list() noise_shape = tf.constant(value=[input_shape[0], 1, 1, input_shape[3]]) return tf.nn.dropout(input_tensor, keep_prob, noise_shape, seed=seed, name="spatial_dropout") def f2(): return input_tensor with tf.variable_scope(name_or_scope=name): output = tf.cond(is_training, f1, f2) return output @staticmethod def lrelu(inputdata, name, alpha=0.2): """ :param inputdata: :param alpha: :param name: :return: """
tensorflow.cond
7,307
import tensorflow as tf inputs = [tf.constant(0), tf.constant(0.0)] cond = lambda i, x: tf.less(i, 100) def body(i, x): return tf.add(i, 1), gan_train_ops.discriminator_train_op dis_train_op = while_loop(cond, body, inputs)
tensorflow.add
7,308
import tensorflow as tf gamma = tf.Variable(tf.constant(1.0, shape=[c]), dtype=tf.float32, name='gamma') beta = tf.Variable(tf.constant(0.0, shape=[c]), dtype=tf.float32, name='beta') gamma = tf.reshape(gamma, [1, c, 1, 1]) beta = tf.reshape(beta, [1, c, 1, 1])
tensorflow.reshape
7,309
import tensorflow as tf # now to upscale to actual image size deconv_shape1 = image_net["pool4"].get_shape() W_t1 = utils.weight_variable([4, 4, deconv_shape1[3].value, 278], name="W_t1") b_t1 = utils.bias_variable([deconv_shape1[3].value], name="b_t1") conv_t1 = utils.conv2d_transpose_strided(concat1, W_t1, b_t1, output_shape=tf.shape(image_net["pool4"])) fuse_1 = tf.add(conv_t1, image_net["pool4"], name="fuse_1") deconv_shape2 = image_net["pool3"].get_shape() W_t2 = utils.weight_variable([4, 4, deconv_shape2[3].value, deconv_shape1[3].value], name="W_t2") b_t2 = utils.bias_variable([deconv_shape2[3].value], name="b_t2") conv_t2 = utils.conv2d_transpose_strided(fuse_1, W_t2, b_t2, output_shape=tf.shape(image_net["pool3"])) fuse_2 = tf.add(conv_t2, image_net["pool3"], name="fuse_2") shape = tf.shape(image) deconv_shape3 = tf.stack([shape[0], shape[1], shape[2], 3]) W_t3 = utils.weight_variable([16, 16, 3, deconv_shape2[3].value], name="W_t3") b_t3 = utils.bias_variable([3], name="b_t3") conv_t3 = tf.nn.relu(utils.conv2d_transpose_strided(fuse_2, W_t3, b_t3, output_shape=deconv_shape3, stride=8)) annotation_pred = tf.argmax(conv_t3, dimension=3, name="prediction")
tensorflow.shape
7,310
import tensorflow as tf max_predictions_per_seq=FLAGS.max_predictions_per_seq, is_training=True, batch_size=FLAGS.train_batch_size, use_hvd=FLAGS.use_hvd) tf.logging.info("***** Running evaluation *****") tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size) eval_input_fn = input_fn_builder( input_files=validation_input_files, max_seq_length=FLAGS.max_seq_length, max_predictions_per_seq=FLAGS.max_predictions_per_seq, is_training=False,
tensorflow.logging.info
7,311
import tensorflow as tf var = tf.Variable(tf.constant(0, dtype=tf.int64)) count_up_to = var.count_up_to(3) input_queue = tf.FIFOQueue(30, tf.float32, shared_name="collection_queue") qr = tf.train.QueueRunner(input_queue, [count_up_to]) tf.initialize_all_variables() # Creates a saver. save = tf.train.Saver({"v0": v0}) # Adds a set of collections. tf.add_to_collection("int_collection", 3) tf.add_to_collection("float_collection", 3.5) tf.add_to_collection("string_collection", "hello") tf.add_to_collection("variable_collection", v0) # Add QueueRunners. tf.train.add_queue_runner(qr) # Adds user_defined proto in three formats: string, bytes and Any. queue_runner = queue_runner_pb2.QueueRunnerDef(queue_name="test_queue")
tensorflow.add_to_collection
7,312
import tensorflow as tf def _compute_loss(self): def focal_loss(logits, labels, weights=None, alpha=0.25, gamma=2): logits = tf.nn.sigmoid(logits) zeros = array_ops.zeros_like(logits, dtype=logits.dtype) pos_p_sub = array_ops.where(labels > zeros, labels - logits, zeros) neg_p_sub = array_ops.where(labels > zeros, zeros, logits) cross_ent = - alpha * (pos_p_sub ** gamma) * tf.log(tf.clip_by_value(logits, 1e-8, 1.0)) \ - (1 - alpha) * (neg_p_sub ** gamma) * tf.log(tf.clip_by_value(1.0 - logits, 1e-8, 1.0)) return tf.reduce_sum(cross_ent, 1) start_label = tf.one_hot(self.start_label, tf.shape(self.logits1)[1], axis=1) end_label = tf.one_hot(self.end_label, tf.shape(self.logits2)[1], axis=1) if self.config.loss_type == 'cross_entropy': start_loss = tf.nn.softmax_cross_entropy_with_logits( logits=self.logits1, labels=start_label) end_loss = tf.nn.softmax_cross_entropy_with_logits( logits=self.logits2, labels=end_label) self.loss = tf.reduce_mean(start_loss + end_loss) else: start_loss = focal_loss(tf.nn.softmax(self.logits1, -1), start_label) end_loss = focal_loss(tf.nn.softmax(self.logits2, -1), end_label) self.loss = tf.reduce_mean(start_loss + end_loss) self.logger.info("loss type %s" % self.config.loss_type) self.all_params = tf.trainable_variables() if self.config.l2_norm is not None:
tensorflow.nn.softmax_cross_entropy_with_logits
7,313
import tensorflow as tf qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, lower_cutoff=1.0, upper_cutoff=10.0, mu=tf.zeros(batch_shape), sigma=tf.ones(batch_shape)) self.assertEqual(batch_shape, qdist.get_batch_shape()) self.assertAllEqual(batch_shape, qdist.batch_shape().eval()) self.assertEqual((), qdist.get_event_shape())
tensorflow.ones
7,314
import tensorflow as tf loss_dict = { 'localization_loss': tf.reduce_sum(location_losses), 'classification_loss': tf.reduce_sum(cls_losses),
tensorflow.reduce_sum
7,315
import tensorflow as tf self.value_target_n = value_target_n with tf.variable_scope("loss", reuse=False): # Take the min of the two Q-Values (Double-Q Learning) min_qf_pi = tf.minimum(qf1_pi, qf2_pi) # Target for Q value regression q_backup = tf.stop_gradient( self.rewards_ph + (1 - self.terminals_ph) * self.gamma * self.value_target ) # Compute Q-Function loss # TODO: test with huber loss (it would avoid too high values) qf1_loss = 0.5 * tf.reduce_mean(((q_backup - qf1) ** 2)*self.weight_ph) qf1_loss_col = tf.reduce_mean(((q_backup - qf1) ** 2),1) qf2_loss = 0.5 * tf.reduce_mean(((q_backup - qf2) ** 2)*self.weight_ph) if self.n_step: q_backup_n = tf.stop_gradient( self.rewards_ph_n + (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
tensorflow.reduce_mean
7,316
import tensorflow as tf random.seed(111) np.random.seed(111) enc_inp = [tf.constant(i + 1, tf.int32, shape=[batch_size]) for i in range(num_enc_timesteps)] dec_inp_fp_true = [tf.constant(i, tf.int32, shape=[batch_size]) for i in range(num_dec_timesteps)] dec_inp_holder_fp_false = [tf.placeholder(tf.int32, shape=[batch_size]) for _ in range(num_dec_timesteps)] targets = [tf.constant(i + 1, tf.int32, shape=[batch_size]) for i in range(num_dec_timesteps)] weights = [tf.constant(1.0, shape=[batch_size]) for i in range(num_dec_timesteps)]
tensorflow.placeholder
7,317
import tensorflow as tf # add mask for glabels and cls_pred here glabels = tf.boolean_mask(tf.clip_by_value(glabels, 0, FLAGS.num_classes), tf.stop_gradient(final_mask)) cls_pred = tf.boolean_mask(cls_pred, tf.stop_gradient(final_mask)) location_pred = tf.boolean_mask(location_pred, tf.stop_gradient(positive_mask)) gtargets = tf.boolean_mask(gtargets, tf.stop_gradient(positive_mask)) predictions = { 'classes': tf.argmax(cls_pred, axis=-1), 'probabilities': tf.reduce_max(tf.nn.softmax(cls_pred, name='softmax_tensor'), axis=-1), 'bboxes_predict': tf.reshape(bboxes_pred, [-1, 4]) } if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)
tensorflow.argmax
7,318
import tensorflow as tf output_ = dense(output_, deep_layer_size, use_bias=False, name='deep_output') output_ = tf.contrib.layers.layer_norm(output_, activation_fn=tf.nn.tanh, scope='output_layer_norm') else: output_ = dense(output_, deep_layer_size, activation=tf.tanh, use_bias=True, name='deep_output') if decoder.use_dropout: size = tf.shape(output_)[1] noise_shape = [1, size] if decoder.pervasive_dropout else None output_ = tf.nn.dropout(output_, keep_prob=decoder.deep_layer_keep_prob, noise_shape=noise_shape) else: if decoder.pred_maxout_layer: maxout_size = decoder.maxout_size or cell_output_size output_ = dense(output_, maxout_size, use_bias=True, name='maxout') if decoder.old_maxout: # for back-compatibility with old models output_ = tf.nn.pool(tf.expand_dims(output_, axis=2), window_shape=[2], pooling_type='MAX', padding='SAME', strides=[2]) output_ = tf.squeeze(output_, axis=2) else: output_ = tf.maximum(*tf.split(output_, num_or_size_splits=2, axis=1)) if decoder.pred_embed_proj: # intermediate projection to embedding size (before projecting to vocabulary size) # this is useful to reduce the number of parameters, and # to use the output embeddings for output projection (tie_embeddings parameter) output_ = dense(output_, decoder.embedding_size, use_bias=False, name='softmax0') if decoder.tie_embeddings and (decoder.pred_embed_proj or decoder.pred_deep_layer): bias = get_variable('softmax1/bias', shape=[decoder.vocab_size])
tensorflow.expand_dims
7,319
import tensorflow as tf ans_feature = tf.layers.dense( ans_feature, xlnet_config.d_model, activation=tf.tanh, kernel_initializer=initializer, name="dense_0") ans_feature = tf.layers.dropout(ans_feature, FLAGS.dropout, training=is_training) cls_logits = tf.layers.dense( ans_feature, 1, kernel_initializer=initializer, name="dense_1", use_bias=False) cls_logits = tf.squeeze(cls_logits, -1)
tensorflow.layers.dense
7,320
import tensorflow as tf def restore_param(self): Saver = tf.train.Saver() self.sess.run(tf.global_variables_initializer()) checkpoint = tf.train.get_checkpoint_state("saved_networks")
tensorflow.train.Saver
7,321
import tensorflow as tf index (int): index of this tower, only used in training. vs_name (str): Open a new variable scope with this name. """ self._name = tower_name self._is_training = bool(is_training) if not self._is_training: assert index == 0, \ "TowerContext(index) is only valid in training!" self._index = int(index) self._vs_name = vs_name if len(vs_name): assert len(tower_name), "TowerContext(vs_name) cannot be used with an empty tower_name!" self._initial_vs_reuse = tf.get_variable_scope().reuse if self.has_own_variables: assert not self._initial_vs_reuse, \ "Cannot create tower {} with reuse=True!".format(tower_name) self._collection_guard = CollectionGuard( self._name, check_diff=not self.is_main_training_tower, freeze_keys=self._keys_to_freeze()) @property def is_main_training_tower(self): return self.is_training and self._index == 0 @property
tensorflow.get_variable_scope
7,322
from tensorflow.contrib import layers raise ValueError("n_classes should be greater than 1. Given: {}".format( n_classes)) target_column = layers.multi_class_target( n_classes=n_classes,
tensorflow.contrib.layers.multi_class_target
7,323
import tensorflow as tf x = self.input_tensor x = tf.pad(x, [[0, 0], [3, 3], [3, 3], [0, 0]], 'CONSTANT') x = self.__conv2d("conv_1", x, filter_depth=64, kernel_size=7, stride=2, padding='valid') x = self.__batch_norm("bn_1", x) x = tf.nn.relu(x) x = tf.keras.layers.MaxPool2D(pool_size = 3, strides = 2, padding = 'same')(x) x = self.__conv_block(stage=0, block=0, inputs=x, filter_depths=[32, 32, 128], kernel_size=3, stride=1)
tensorflow.nn.relu
7,324
import tensorflow as tf val = val[permutation] shape = np.array([5, 6]).astype(np.int64) return tf.SparseTensorValue(ind, val, shape) def _SparseTensorValue_3x4(self, permutation):
tensorflow.SparseTensorValue
7,325
from tensorflow.python.client import session height = 300 width = 280 with self.cached_session(): test_dataset = _create_tfrecord_dataset(dataset_dir) provider = dataset_data_provider.DatasetDataProvider(test_dataset) key, image, label = provider.get(['record_key', 'image', 'label']) image = _resize_image(image, height, width) with session.Session('') as sess: with queues.QueueRunners(sess): key, image, label = sess.run([key, image, label]) split_key = key.decode('utf-8').split(':') self.assertEqual(2, len(split_key)) self.assertEqual(test_dataset.data_sources[0], split_key[0]) self.assertTrue(split_key[1].isdigit()) self.assertListEqual([height, width, 3], list(image.shape)) self.assertListEqual([1], list(label.shape))
tensorflow.python.client.session.Session
7,326
import tensorflow as tf self.g_variables = [var for var in trainable_variables if 'generator' in var.name] print ('Variable printing start :' ) for var in self.d_variables: print(var.name) self.test_image_A = tf.placeholder(tf.float32,[None, self.image_size,self.image_size,self.input_dim], name='test_A') self.test_image_B = tf.placeholder(tf.float32,[None, self.image_size, self.image_size,self.output_c_dim], name='test_B') self.saver = tf.train.Saver() def train_network(self):
tensorflow.placeholder
7,327
import tensorflow as tf cell = tf.nn.rnn_cell.MultiRNNCell([tf.nn.rnn_cell.GRUCell(24)] * 2, state_is_tuple=True) return tf.nn.seq2seq.embedding_attention_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=classes, num_decoder_symbols=classes, embedding_size=24, output_projection=(w, b)) targets = [dec_inp[i+1] for i in range(len(dec_inp) - 1)] + [0] def SampledLoss(labels, inputs): labels = tf.reshape(labels, [-1, 1]) return tf.nn.sampled_softmax_loss(w_t, b, inputs, labels, 8, classes) return tf.nn.seq2seq.model_with_buckets( enc_inp, dec_inp, targets, weights, buckets, GRUSeq2Seq, softmax_loss_function=SampledLoss) # 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)]
tensorflow.nn.sampled_softmax_loss
7,328
import tensorflow as tf # Implement an exponential learning rate decay every 1000 epochs #Implement a dynamical learning rate global_step = tf.Variable(0., trainable=False) rate = tf.train.exponential_decay(starter_learning, global_step, 500, 0.9) #exponential learning rate decay #rate = starter_learning tvars = tf.trainable_variables() #list of trainable variables
tensorflow.train.exponential_decay
7,329
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] beta = tf.nn.softmax(s) # attention map print('attention beta dims: ' + str(s.get_shape().as_list())) h = tf.reshape(h, shape=[-1, h.shape[1]*h.shape[2], h.shape[-1]]) print('attention h flat dims: ' + str(h.get_shape().as_list())) o = tf.matmul(beta, h) # [bs, N, C] print('attention o dims: ' + str(o.get_shape().as_list())) gamma = tf.get_variable("gamma", [1], initializer=tf.constant_initializer(0.0)) o = tf.reshape(o, shape=[-1, height, width, num_channels // 2]) # [bs, h, w, C] o = conv(o, scope='attn_conv', filter_dims=[1, 1, channels], stride_dims=[1, 1], non_linear_fn=act_func) x = gamma * o + x return x
tensorflow.matmul
7,330
import tensorflow as tf return tf.sqrt(tf.clip_by_value(x, clip_low, x)) def argus_integral_phalf(m_low, m_high, m0, c): """ Only valid for argus_pdf with p=0.5! Otherwise need to do numerical integral. """ def F(m_bound, name=None): with tf.name_scope(name, "argus_integral_phalf_primitive"): a = tf.minimum(m_bound, m0) x = 1 - tf.pow(a / m0, 2) primitive = -0.5 * m0 * m0 * (tf.exp(c * x) * tf.sqrt(x) / c + 0.5 / tf.pow(-c, 1.5) * tf.sqrt(pi) * tf.erf(gradsafe_sqrt(-c * x))) # We have to safeguard the sqrt, because otherwise the analytic # derivative blows up for x = 0 return primitive area = tf.sub(F(m_high, name="F2"), F(m_low, name="F1"), name="argus_integral_phalf") return area def argus_pdf_phalf_WN(m, m0, c, m_low, m_high): """ WN: with normalization
tensorflow.sqrt
7,331
import tensorflow as tf d3, _ = tf.nn.seq2seq.embedding_rnn_seq2seq( enc_inp, dec_inp2, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, feed_previous=tf.constant(True)) sess.run([tf.global_variables_initializer()]) tf.get_variable_scope().reuse_variables() d1, _ = tf.nn.seq2seq.embedding_rnn_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, feed_previous=True) d2, _ = tf.nn.seq2seq.embedding_rnn_seq2seq( enc_inp, dec_inp2, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, feed_previous=True)
tensorflow.nn.seq2seq.embedding_rnn_seq2seq
7,332
import tensorflow as tf name="{}2b".format(conv_name_base), inputs=x, filter_depth=filter_depth2, kernel_size=kernel_size, padding="same", stride=1 ) x = self.__batch_norm("{}2b".format(bn_name_base), x) x = tf.nn.relu(x) x = self.__conv2d( name="{}2c".format(conv_name_base), inputs=x, filter_depth=filter_depth3, kernel_size=1,
tensorflow.nn.relu
7,333
import tensorflow as tf param_noise_filter_func=param_noise_filter_func) else: act_f = build_act(make_obs_ph, q_func, num_actions, scope=scope, reuse=reuse) with tf.variable_scope(scope, reuse=reuse): # set up placeholders obs_t_input = make_obs_ph("obs_t") act_t_ph = tf.placeholder(tf.int32, [None], name="action") rew_t_ph = tf.placeholder(tf.float32, [None], name="reward") obs_tp1_input = make_obs_ph("obs_tp1") done_mask_ph = tf.placeholder(tf.float32, [None], name="done") importance_weights_ph = tf.placeholder(tf.float32, [None], name="weight") # q network evaluation
tensorflow.placeholder
7,334
import tensorflow as tf pos = tf.nn.sigmoid(tf.matmul(tf.nn.tanh(tf.matmul(state, wp)), vp)) pos = tf.floor(encoder_input_length * pos)
tensorflow.floor
7,335
import tensorflow as tf tf.summary.scalar('Loss/Value', loss_vf) tf.summary.scalar('Loss/Entropy', loss_entropy) tf.summary.scalar('Loss/Total', loss) tf.summary.scalar('Var/Epsilon', epsilon_decay) tf.summary.scalar('Var/Policy Mode', tf.reduce_mean(pi.mode())) tf.summary.scalar('Var/Policy Sigma', tf.reduce_mean(pi.stddev())) tf.summary.scalar('Var/Value', tf.reduce_mean(self.vf)) self.summarise = tf.summary.merge(tf.get_collection(tf.GraphKeys.SUMMARIES)) # AC net def build_anet(self, state_in, name, reuse=False): reg = tf.contrib.layers.l2_regularizer(1e-3) with tf.variable_scope(name, reuse=reuse): layer_a1 = tf.layers.dense(state_in, 512, tf.nn.relu, kernel_regularizer=reg)
tensorflow.get_collection
7,336
import tensorflow as tf output_weights = tf.get_variable( "output_weights", shape=[2, bert_config.hidden_size], initializer=modeling.create_initializer(bert_config.initializer_range), ) output_bias = tf.get_variable( "output_bias", shape=[2], 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) labels = tf.reshape(labels, [-1]) one_hot_labels = tf.one_hot(labels, depth=2, 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, log_probs) def gather_indexes(sequence_tensor, positions): """Gathers the vectors at the specific positions over a minibatch.""" sequence_shape = modeling.get_shape_list(sequence_tensor, expected_rank=3)
tensorflow.nn.log_softmax
7,337
import tensorflow as tf image_placeholder = tf.placeholder(dtype=tf.uint8) encoded_image = tf.image.encode_png(image_placeholder) with tf.Session('') as sess: for j in range(num_images): sys.stdout.write('\r>> Reading file [%s] image %d' % ( filename, offset + 1)) sys.stdout.flush() if ('train' == name) and ( math.floor(offset / images_per_shard) > shard) : tfrecord_writer.close() shard = shard + 1 record_filename = _get_output_filename(dataset_dir, name, shard, FLAGS.train_shards) tfrecord_writer = tf.python_io.TFRecordWriter(record_filename) image = np.squeeze(images[j]).transpose((1, 2, 0)) label = labels[j] png_string = sess.run(encoded_image, feed_dict={image_placeholder: image}) example = dataset_utils.image_to_tfexample( png_string, 'png', _IMAGE_SIZE, _IMAGE_SIZE, label, _CLASS_NAMES[label]) tfrecord_writer.write(example.SerializeToString()) offset = offset + 1 tfrecord_writer.close()
tensorflow.python_io.TFRecordWriter
7,338
import tensorflow as tf num_channels_in = input_dims[-1] height = input_dims[1] width = input_dims[2] with tf.variable_scope(scope): if output_length == 1: pool = tf.nn.avg_pool(input_data, [1, height, width, 1], strides=[1, 1, 1, 1], padding=padding) pool = tf.reduce_mean(pool, axis=[1, 2]) pool = tf.squeeze(pool, axis=[1, 2]) return pool else: if num_channels_in != output_length: conv_weight = tf.Variable(tf.truncated_normal([1, 1, num_channels_in, output_length], stddev=0.1, dtype=tf.float32)) conv = tf.nn.conv2d(input_data, conv_weight, strides=[1, 1, 1, 1], padding='SAME') pool = tf.nn.avg_pool(conv, ksize=[1, height, width, 1], strides=[1, 1, 1, 1], padding=padding)
tensorflow.squeeze
7,339
from tensorflow.python.ops import math_ops bg_row=tf.shape(b_grads[0])[0] bg_col=tf.shape(b_grads[0])[1] b_grads = tf.reshape(b_grads, (numTensors * bg_row, bg_col)) if adj_b: b_grads = [array_ops.transpose(b_g) for b_g in b_grads] for t in range(numTensors): rows = a_indices[t][:, 0] cols = a_indices[t][:, 1] parts_a = array_ops.gather(grad[t], rows if not adj_a else cols) parts_b = array_ops.gather(b_list[t] if not adj_b else array_ops.transpose(b_list[t]), cols if not adj_a else rows) a_values_grads.append(math_ops.reduce_sum(parts_a * parts_b, reduction_indices=1)) return_val = [None for _ in range(numTensors)] + a_values_grads + [None for _ in range(numTensors)] + [b_grads] return tuple(return_val)
tensorflow.python.ops.math_ops.reduce_sum
7,340
import tensorflow as tf for i in range(num_dims): curr_core_shape = (1, shape[i], shape[i], 1) tt_cores[i] = tf.reshape(tf.eye(shape[i], dtype=dtype), curr_core_shape)
tensorflow.eye
7,341
import tensorflow as tf highway_input = highwaynet(highway_input, 'highway_%d' % (i + 1), half_depth) rnn_input = highway_input # Bidirectional RNN outputs, states = tf.nn.bidirectional_dynamic_rnn( GRUCell(half_depth), GRUCell(half_depth), rnn_input, sequence_length=input_lengths, dtype=tf.float32) return tf.concat(outputs, axis=2) # Concat forward and backward def highwaynet(inputs, scope, depth): with tf.variable_scope(scope): H = tf.layers.dense( inputs, units=depth, activation=tf.nn.relu, name='H') T = tf.layers.dense( inputs, units=depth, activation=tf.nn.sigmoid, name='T', bias_initializer=tf.constant_initializer(-1.0)) return H * T + inputs * (1.0 - T)
tensorflow.variable_scope
7,342
import tensorflow as tf return logits, prediction def general_conv2d(self, input_data, filters = 64, kernel_size = 7, stride = 1, stddev = 0.02, activation_function = "relu", padding = "VALID", do_norm=True, relu_factor = 0, name="conv2d"): with tf.variable_scope(name): conv = tf.layers.conv2d(input_data, filters, kernel_size, stride, padding, activation=None)
tensorflow.variable_scope
7,343
import tensorflow as tf dim, name, train=True, epsilon=1e-8, decay=.1, axes=[0], reuse=None, bn_lag=DEFAULT_BN_LAG): """Batch normalization with corresponding log determinant Jacobian.""" if reuse is None: reuse = not train # create variables with tf.variable_scope(name) as scope: if reuse: scope.reuse_variables() var = variable_on_cpu( "var", [dim], tf.constant_initializer(1.), trainable=False) mean = variable_on_cpu( "mean", [dim], tf.constant_initializer(0.), trainable=False) step = variable_on_cpu("step", [], tf.constant_initializer(0.), trainable=False) # choose the appropriate moments if train: used_mean, used_var = tf.nn.moments(input_, axes, name="batch_norm") cur_mean, cur_var = used_mean, used_var
tensorflow.variable_scope
7,344
import tensorflow as tf manager_loss = -tf.reduce_sum((self.r - cutoff_vf_manager) * dcos) cutoff_vf_worker = tf.reshape(tf.stop_gradient(self.worker_vf), [-1]) log_p = tf.reduce_sum(self.log_pi * self.ac, [1]) worker_loss = (self.r + self.alpha * self.ri - cutoff_vf_worker) * log_p worker_loss = -tf.reduce_sum(worker_loss, axis=0)
tensorflow.reduce_sum
7,345
import tensorflow as tf example: An example dict containing an image and a label. random_crop_pad: By how many pixels should the image be padded on each side before cropping. Returns: An example with the same label and an augmented version of the image. """ image, label = example['image'], example['label'] image = tf.image.random_flip_left_right(image) image_shape = tf.shape(image) image = tf.pad( image, [[random_crop_pad, random_crop_pad], [random_crop_pad, random_crop_pad], [0, 0]], mode='REFLECT') image = tf.image.random_crop(image, image_shape) return {'image': image, 'label': label}
tensorflow.shape
7,346
import tensorflow as tf end_logits, 1, kernel_initializer=initializer, name="dense_1") end_logits = tf.reshape(end_logits, [seq_len, -1, FLAGS.start_n_top]) end_logits = tf.transpose(end_logits, [1, 2, 0]) end_logits_masked = end_logits * ( 1 - p_mask[:, None]) - 1e30 * p_mask[:, None] end_log_probs = tf.nn.log_softmax(end_logits_masked, -1) end_top_log_probs, end_top_index = tf.nn.top_k( end_log_probs, k=FLAGS.end_n_top) end_top_log_probs = tf.reshape( end_top_log_probs, [-1, FLAGS.start_n_top * FLAGS.end_n_top]) end_top_index = tf.reshape( end_top_index, [-1, FLAGS.start_n_top * FLAGS.end_n_top])
tensorflow.nn.top_k
7,347
import tensorflow as tf target_samples -= tf.reduce_mean(target_samples, 0) source_samples = tf.nn.l2_normalize(source_samples, 1) target_samples = tf.nn.l2_normalize(target_samples, 1) source_cov = tf.matmul(tf.transpose(source_samples), source_samples) target_cov = tf.matmul(tf.transpose(target_samples), target_samples) corr_loss = tf.reduce_mean(tf.square(source_cov - target_cov)) * weight assert_op = tf.Assert(tf.is_finite(corr_loss), [corr_loss])
tensorflow.transpose
7,348
from tensorflow.contrib.eager.python.examples.revnet import blocks_test self.assertEqual(len(g2_all.shape), 1) degree = blocks_test.compute_degree(g1_all, g2_all) self.assertLessEqual(degree, 1e0)
tensorflow.contrib.eager.python.examples.revnet.blocks_test.compute_degree
7,349
import tensorflow as tf strides=[1, 1, 1, 1], padding="SAME", nonlinearity=None, bias=False, weight_norm=False, scale=False): """Convolutional layer.""" with tf.variable_scope(name) as scope: weights = variable_on_cpu( "weights", filter_size + [dim_in, dim_out], tf.random_uniform_initializer( minval=-stddev, maxval=stddev)) # weight normalization if weight_norm: weights /= tf.sqrt(tf.reduce_sum(tf.square(weights), [0, 1, 2])) if scale: magnitude = variable_on_cpu( "magnitude", [dim_out], tf.constant_initializer( stddev * numpy.sqrt(dim_in * numpy.prod(filter_size) / 12.))) weights *= magnitude res = input_ # handling filter size bigger than image size if hasattr(input_, "shape"): if input_.get_shape().as_list()[1] < filter_size[0]: pad_1 = tf.zeros([ input_.get_shape().as_list()[0], filter_size[0] - input_.get_shape().as_list()[1], input_.get_shape().as_list()[2],
tensorflow.square
7,350
from tensorflow.python.framework import ops new_size = size + batch_size array_size = array_ops.shape_internal(array, optimize=False)[0] maybe_reallocate_op = control_flow_ops.cond( new_size > array_size, reallocate, control_flow_ops.no_op) with ops.control_dependencies([maybe_reallocate_op]): append_values_op = array[size:new_size].assign(batch_values) with ops.control_dependencies([append_values_op]): update_op = size.assign(new_size) if metrics_collections: ops.add_to_collections(metrics_collections, value)
tensorflow.python.framework.ops.control_dependencies
7,351
import tensorflow as tf v_norm = tf.nn.l2_normalize(self.v,axis=[0,1,3]) t = tf.nn.conv2d_transpose(input_var,v_norm, output_shape=shapes, strides=self.strides, padding='SAME', data_format='NHWC') mu,var = tf.nn.moments(t,axes=[0,1,2]) std = tf.sqrt(var+self.epsilon) return [tf.assign(self.g,1/std),tf.assign(self.b,-1.*mu/std)] require_init = tf.reduce_any(tf.is_nan(self.g)) init_ops = tf.cond(require_init,_init,lambda : [self.g,self.b]) with tf.control_dependencies(init_ops): w = tf.reshape(self.g,[1,1,tf.shape(self.v)[2],1]) * tf.nn.l2_normalize(self.v,axis=[0,1,3]) return tf.nn.bias_add( tf.nn.conv2d_transpose(input_var,w, output_shape=shapes, strides=self.strides, padding='SAME', data_format='NHWC'), self.b,data_format='NHWC',name=name) def get_variables(self): #TODO: self.v should be l2-normalized or not? / currently not. return {'v':self.v,'b':self.b,'g':self.g} class LayerNorm(): def __init__(self,name,axis,out_dim=None,epsilon=1e-7,data_format='NHWC') :
tensorflow.shape
7,352
import tensorflow as tf saver0.save(sess, saver0_ckpt) saver1.save(sess, saver1_ckpt) # Generates MetaGraphDef. meta_graph_def = tf.train.export_meta_graph(filename) meta_graph_def0 = saver0.export_meta_graph() meta_graph_def1 = saver1.export_meta_graph()
tensorflow.train.export_meta_graph
7,353
import tensorflow as tf input_shape = tf.shape(encoder_states) batch_size = input_shape[0] passage_len = input_shape[1] # map decoder inputs to word embeddings decoder_inputs = tf.unstack(decoder_inputs, axis=1) # max_enc_steps * [batch_size] answer_batch_unstack = tf.unstack(answer_batch, axis=1) # initialize all the variables state_t_1 = init_state
tensorflow.unstack
7,354
import tensorflow as tf if self.ms_task: with tf.variable_scope('mixed'): #add fake pc as a rotation class num_to_add = int(max(self.batch_size/self.num_angles, 1)) idx = tf.range(0, self.batch_size, 1) idx = tf.random_shuffle(idx)[0:num_to_add] self.fake_to_add = tf.gather(self.generator_out, idx) self.mixed_pc = tf.concat([self.real_pc_rotated, self.fake_to_add], 0) self.mixed_label = tf.concat([self.rot_label_pl, tf.constant(self.num_angles, shape = (num_to_add,))], axis = 0) mixed_idx = tf.range(0, self.mixed_label.get_shape().as_list()[0], 1) mixed_idx = tf.random_shuffle(mixed_idx)[0:self.batch_size] self.mixed_pc = tf.gather(self.mixed_pc, mixed_idx)
tensorflow.gather
7,355
import tensorflow as tf def contra_step_lossV1(pred, tgt, temp=10.0): # Step-wise contrastive loss pred1, pred2 = tf.split(pred, 2, axis=0) tgt1, tgt2 = tf.split(tgt, 2, axis=0) soft_sign = tf.tanh((tgt1 - tgt2) * temp) loss = tf.maximum(0.0, soft_sign * ((tgt1 - tgt2) - (pred1 - pred2))) loss = tf.reduce_mean(loss) return loss def contra_step_lossV2(pred, tgt): # 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)) loss = tf.reduce_mean(loss) return loss def contra_step_lossV3(pred, tgt, margin=1.0): # Step-wise contrastive loss
tensorflow.split
7,356
import tensorflow as tf flags.DEFINE_integer("max_eval_steps", None, "Maximum number of eval steps.") flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.") tf.flags.DEFINE_string( "tpu_name", None, "The Cloud TPU to use for training. This should be either the name " "used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 " "url.") tf.flags.DEFINE_string( "tpu_zone", None, "[Optional] GCE zone where the Cloud TPU is located in. If not " "specified, we will attempt to automatically detect the GCE project from " "metadata.") tf.flags.DEFINE_string( "gcp_project", None, "[Optional] Project name for the Cloud TPU-enabled project. If not " "specified, we will attempt to automatically detect the GCE project from " "metadata.")
tensorflow.flags.DEFINE_string
7,357
import tensorflow as tf temp_val_data['X'][i * 2, :, :, :] = self.val_data['X'][i, :, :sh[2] // 2, :] temp_val_data['X'][i * 2 + 1, :, :, :] = self.val_data['X'][i, :, sh[2] // 2:, :] temp_val_data['Y'][i * 2, :, :] = self.val_data['Y'][i, :, :sh[2] // 2] temp_val_data['Y'][i * 2 + 1, :, :] = self.val_data['Y'][i, :, sh[2] // 2:] self.val_data = temp_val_data def init_tfdata(self, batch_size, main_dir, resize_shape, mode='train'): self.data_session = tf.Session() print("Creating the iterator for training data") with tf.device('/cpu:0'): segdl = SegDataLoader(main_dir, batch_size, (resize_shape[0], resize_shape[1]), resize_shape, # * 2), resize_shape, 'data/cityscapes_tfdata/train.txt') iterator = Iterator.from_structure(segdl.data_tr.output_types, segdl.data_tr.output_shapes) next_batch = iterator.get_next() self.init_op = iterator.make_initializer(segdl.data_tr) self.data_session.run(self.init_op)
tensorflow.device
7,358
import tensorflow as tf return tf.contrib.summary.all_summary_ops() # To log the loss, current learning rate, and epoch for Tensorboard, the # summary op needs to be run on the host CPU via host_call. host_call # expects [batch_size, ...] Tensors, thus reshape to introduce a batch # dimension. These Tensors are implicitly concatenated to # [params['batch_size']]. global_step_t = tf.reshape(global_step, [1]) total_loss_t = tf.reshape(total_loss, [1]) total_rpn_loss_t = tf.reshape(total_rpn_loss, [1]) rpn_score_loss_t = tf.reshape(rpn_score_loss, [1]) rpn_box_loss_t = tf.reshape(rpn_box_loss, [1]) total_fast_rcnn_loss_t = tf.reshape(total_fast_rcnn_loss, [1]) fast_rcnn_class_loss_t = tf.reshape(fast_rcnn_class_loss, [1]) fast_rcnn_box_loss_t = tf.reshape(fast_rcnn_box_loss, [1]) mask_loss_t = tf.reshape(mask_loss, [1]) learning_rate_t = tf.reshape(learning_rate, [1]) host_call = (host_call_fn, [global_step_t, total_loss_t, total_rpn_loss_t, rpn_score_loss_t, rpn_box_loss_t, total_fast_rcnn_loss_t,
tensorflow.reshape
7,359
import tensorflow as tf decay_steps = int(num_batches_per_epoch * cifar10.NUM_EPOCHS_PER_DECAY) # Decay the learning rate exponentially based on the number of steps. lr = tf.train.exponential_decay(cifar10.INITIAL_LEARNING_RATE, global_step, decay_steps, cifar10.LEARNING_RATE_DECAY_FACTOR, staircase=True) # Create an optimizer that performs gradient descent. opt = tf.train.GradientDescentOptimizer(lr) # Calculate the gradients for each model tower. tower_grads = [] with tf.variable_scope(tf.get_variable_scope()): for i in xrange(FLAGS.num_gpus): with tf.device('/gpu:%d' % i): with tf.name_scope('%s_%d' % (cifar10.TOWER_NAME, i)) as scope: # Calculate the loss for one tower of the CIFAR model. This function # constructs the entire CIFAR model but shares the variables across # all towers. loss = tower_loss(scope) # Reuse variables for the next tower. tf.get_variable_scope().reuse_variables() # Retain the summaries from the final tower. summaries = tf.get_collection(tf.GraphKeys.SUMMARIES, scope)
tensorflow.get_variable_scope
7,360
import tensorflow as tf anchor_negative_distances, anchor_negative_mining_distances = ( compute_hard_negative_distances( anchor_match_distance_matrix, anchor_match_negative_indicator_matrix, use_semi_hard=use_semi_hard, anchor_positive_mining_distances=anchor_positive_mining_distances, anchor_match_mining_distance_matrix=( anchor_match_mining_distance_matrix))) def compute_triplet_loss(positive_distances, negative_distances): losses = tf.nn.relu(positive_distances + margin - negative_distances) losses = tf.where( tf.stop_gradient(losses < losses.dtype.max), losses, tf.zeros_like(losses)) num_nonzero_losses = tf.math.count_nonzero(losses) loss = tf.math.reduce_mean(losses) return loss, num_nonzero_losses loss, num_active_triplets = compute_triplet_loss(anchor_positive_distances, anchor_negative_distances) mining_loss, num_active_mining_triplets = compute_triplet_loss( anchor_positive_mining_distances, anchor_negative_mining_distances) return (loss, num_active_triplets, anchor_negative_distances, mining_loss, num_active_mining_triplets, anchor_negative_mining_distances)
tensorflow.stop_gradient
7,361
import tensorflow as tf std = std[::-1] image_mean = tf.constant(mean, dtype=tf.float32) * 255.
tensorflow.constant
7,362
import tensorflow as tf if add_flipped_images: scales_to_logits_reversed = ( outputs_to_scales_to_logits_reversed[output]) logits_reversed = tf.image.resize_bilinear( tf.reverse_v2(scales_to_logits_reversed[_MERGED_LOGITS_SCOPE], [2]), tf.shape(images)[1:3], align_corners=True) outputs_to_predictions[output].append( tf.expand_dims(tf.nn.softmax(logits_reversed), 4)) for output in sorted(outputs_to_predictions):
tensorflow.shape
7,363
import tensorflow as tf layers.append((X, w, h, comb_ch)) def _combine_cell_blocks(self, cell_inputs, blocks, cell_arch, w, h, block_ch, is_train=False): # Count usage of inputs input_use_counts = [0] * len(cell_inputs + blocks) for (idx1, _, idx2, _) in cell_arch: input_use_counts[idx1] += 1 input_use_counts[idx2] += 1 # Concat only unused blocks with tf.variable_scope('combine'): block_use_counts = input_use_counts[len(cell_inputs):] out_blocks = [block for (block, use_count) in zip(blocks, block_use_counts) if use_count == 0] comb_ch = len(out_blocks) * block_ch X = tf.concat(out_blocks, axis=3) return (X, comb_ch) def _combine_cell_blocks_dynamic(self, cell_inputs, blocks, cell_arch, w, h, block_ch, is_train=False): ni = len(cell_inputs + blocks) b = len(blocks) # Count usage of inputs block_uses = [] for bi in range(b): idx1 = cell_arch[bi][0] idx2 = cell_arch[bi][2] block_use = tf.one_hot(idx1, ni, dtype=tf.int32) + tf.one_hot(idx2, ni, dtype=tf.int32) block_uses.append(block_use)
tensorflow.concat
7,364
from tensorflow.python.framework import ops sequence_var = tf.Variable(tf.range(start=6, limit=15, delta=3)) # Generates [6, 9, 12] doesn't include the end sess.run(linear_var.initializer) sess.run(sequence_var.initializer) print(sess.run(linear_var)) print(sess.run(sequence_var)) rnorm_var = tf.random_normal([row_dim, col_dim], mean=0.0, stddev=1.0) runif_var = tf.random_uniform([row_dim, col_dim], minval=0, maxval=4) print(sess.run(rnorm_var)) print(sess.run(runif_var)) ops.reset_default_graph() sess = tf.Session() my_var = tf.Variable(tf.zeros([1,20])) merged = tf.summary.merge_all() writer = tf.summary.FileWriter("./logs", graph=sess.graph) initialize_op = tf.global_variables_initializer() sess.run(initialize_op)
tensorflow.python.framework.ops.reset_default_graph
7,365
import tensorflow as tf """Add prediction layer""" with tf.variable_scope('softmax'): W = tf.get_variable('W', [state_size, input_size_y]) b = tf.get_variable('b', [input_size_y], initializer=tf.constant_initializer(0.0)) rnn_outputs = tf.reshape(rnn_outputs, [-1, state_size]) predictions = tf.matmul(rnn_outputs, W) + b yy = tf.reshape(y, [-1, input_size_y]) #batch_size*num_steps when yo udefine a placeholder in Tensorflow, the shape of the input during the session should be the same as the shape of the plcae holder "Mean squared error loss" loss=tf.reduce_mean(tf.square(tf.reshape(predictions,[-1])-tf.reshape(yy,[-1]))) "Adding regularization" if lambda_l2_reg > 0 : cell_l2 = tf.reduce_sum([tf.nn.l2_loss(tf_var) for tf_var in tf.trainable_variables() if not ("noreg" in tf_var.name or "Bias" in tf_var.name)]) Predict_l2 = tf.nn.l2_loss(W) #+ tf.nn.l2_loss(b) total_loss = tf.reduce_sum(loss + lambda_l2_reg* tf.reduce_sum(cell_l2+Predict_l2) ) else: total_loss = loss "Define the train_step" train_step = tf.train.AdamOptimizer(learning_rate).minimize(total_loss) return dict(x=x, y=y, batch_size=batch_size,
tensorflow.trainable_variables
7,366
from tensorflow.python.ops import clip_ops summary.scalar("loss", loss) # Add histograms for variables, gradients and gradient norms. for gradient, variable in gradients: if isinstance(gradient, ops.IndexedSlices): grad_values = gradient.values else: grad_values = gradient 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])) if clip_gradients is not None and ("global_gradient_norm" in summaries or "gradient_norm" in summaries): summary.scalar("global_norm/clipped_gradient_norm", clip_ops.global_norm(list(zip(*gradients))[0])) # Create gradient updates. grad_updates = opt.apply_gradients( gradients, global_step=global_step if increment_global_step else None, name="train") # Ensure the train_tensor computes grad_updates. train_tensor = control_flow_ops.with_dependencies([grad_updates], loss)
tensorflow.python.ops.clip_ops.global_norm
7,367
import tensorflow as tf self.top_size = depth return output def inception_module(self, name, cols, input_layer=None, in_size=None): if input_layer is None: input_layer = self.top_layer if in_size is None: in_size = self.top_size name += str(self.counts[name]) self.counts[name] += 1 with tf.variable_scope(name): col_layers = [] col_layer_sizes = [] for c, col in enumerate(cols): col_layers.append([]) col_layer_sizes.append([]) for l, layer in enumerate(col): ltype, args = layer[0], layer[1:] kwargs = { 'input_layer': input_layer,
tensorflow.variable_scope
7,368
import tensorflow as tf print(sess.run(tf.transpose(C))) print('\ntranspose(D)=') print(sess.run(tf.transpose(D))) print('\ninverse(D)=') print(sess.run(tf.matrix_inverse(D))) print('\ndeterminant(D)={:.1f}'.format(sess.run(tf.matrix_determinant(D)))) print('\ncholesky(D):') print(sess.run(tf.cholesky(identity_matrix))) print('\nselfAdjointEig(D):') print(sess.run(tf.self_adjoint_eig(D)))
tensorflow.matrix_determinant
7,369
import tensorflow as tf # This index is specified exactly and we want to collapse this axis. if remainder is None: remainder = sliced_core else: remainder = tf.matmul(remainder, sliced_core) else: if remainder is not None: # Add reminder from the previous collapsed cores to the current
tensorflow.matmul
7,370
from tensorflow.python.framework import tensor_shape else: for i, dim in enumerate(input_shape.dims): if i not in reduction_indices: returned_dims.append(dim) return [tensor_shape.TensorShape(returned_dims)] @ops.RegisterShape("SegmentMax")
tensorflow.python.framework.tensor_shape.TensorShape
7,371
import tensorflow as tf assert num_written_lines == num_actual_predict_examples if __name__ == "__main__": flags.mark_flag_as_required("data_dir") flags.mark_flag_as_required("task_name") flags.mark_flag_as_required("vocab_file") flags.mark_flag_as_required("bert_config_file") flags.mark_flag_as_required("output_dir") tf.app.run()
tensorflow.app.run
7,372
import tensorflow as tf # Merge the logits from all the multi-scale inputs. for output in sorted(model_options.outputs_to_num_classes): # Concatenate the multi-scale logits for each output type. all_logits = [ tf.expand_dims(logits, axis=4) for logits in outputs_to_scales_to_logits[output].values() ] all_logits = tf.concat(all_logits, 4) merge_fn = ( tf.reduce_max if model_options.merge_method == 'max' else tf.reduce_mean) outputs_to_scales_to_logits[output][_MERGED_LOGITS_SCOPE] = merge_fn( all_logits, axis=4)
tensorflow.concat
7,373
import tensorflow as tf return losses, [outputs], encoder_state, attention_states, attention_weights, samples, beam_fun, initial_data def softmax(logits, dim=-1, mask=None): e = tf.exp(logits) if mask is not None: e *= mask return e / tf.clip_by_value(tf.reduce_sum(e, axis=dim, keep_dims=True), 10e-37, 10e+37) def sequence_loss(logits, targets, weights, average_across_timesteps=False, average_across_batch=True, rewards=None): batch_size = tf.shape(targets)[0] time_steps = tf.shape(targets)[1] logits_ = tf.reshape(logits, tf.stack([time_steps * batch_size, logits.get_shape()[2].value])) targets_ = tf.reshape(targets, tf.stack([time_steps * batch_size])) crossent = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits_, labels=targets_) crossent = tf.reshape(crossent, tf.stack([batch_size, time_steps])) if rewards is not None: crossent *= tf.stop_gradient(rewards) log_perp = tf.reduce_sum(crossent * weights, axis=1)
tensorflow.shape
7,374
import tensorflow as tf self.sample_action = tf.squeeze(pi_eval.sample(1), axis=0) self.eval_action = pi_eval.mode() self.global_step = tf.train.get_or_create_global_step() self.saver = tf.train.Saver() # Loss functions and training loss_pg = - tf.reduce_mean(pi.log_prob(batch['actions']) * batch['advantage']) - 0.01 * tf.reduce_mean(pi.entropy()) loss_vf = 0.5 * tf.reduce_mean(tf.square(batch['rewards'] - self.vf)) self.a_grads = tf.gradients(loss_pg, self.pi_params) self.c_grads = tf.gradients(loss_vf, self.vf_params) self.a_grads, _ = tf.clip_by_global_norm(self.a_grads, 20.0) self.c_grads, _ = tf.clip_by_global_norm(self.c_grads, 20.0) opt = tf.train.AdamOptimizer(self.LR) self.update_a_op = opt.apply_gradients(zip(self.a_grads, self.pi_params)) self.update_c_op = opt.apply_gradients(zip(self.c_grads, self.vf_params)) self.sess.run(tf.global_variables_initializer())
tensorflow.gradients
7,375
import tensorflow as tf NUMBER_OF_CLASSES = 2 def get_input_function(): """A function to get test inputs. Returns an image with one box.""" image = tf.random_uniform([32, 32, 3], dtype=tf.float32) key = tf.constant('image_000000') class_label = tf.random_uniform( [1], minval=0, maxval=NUMBER_OF_CLASSES, dtype=tf.int32) box_label = tf.random_uniform( [1, 4], minval=0.4, maxval=0.6, dtype=tf.float32) return { fields.InputDataFields.image: image, fields.InputDataFields.key: key, fields.InputDataFields.groundtruth_classes: class_label, fields.InputDataFields.groundtruth_boxes: box_label }
tensorflow.random_uniform
7,376
import tensorflow as tf step=global_step, ) max_q = tf.reduce_max(logits_vec, axis=1) tf.compat.v2.summary.scalar( name="max_q", data=tf.reduce_mean(max_q), step=global_step) ### End metrics # For both state-centric and goal-centric relabelling, the implementation of # mixing is the same: we randomly replace some of the indices with the # diagonal. relabelled_tasks = tf.gather(candidate_tasks, tf.squeeze(relabel_indices)) if self._relabel_prob == 0: relabelled_tasks = orig_tasks elif 0 < self._relabel_prob < 1: logits = tf.log([1.0 - self._relabel_prob, self._relabel_prob]) mask = tf.squeeze( tf.random.categorical( logits[None], num_samples=self._sample_batch_size)) mask = tf.cast(mask, tf.float32)[:, None] relabelled_tasks = mask * orig_tasks + (1 - mask) * relabelled_tasks
tensorflow.squeeze
7,377
import tensorflow as tf y += dense(hidden, encoder.attn_size, use_bias=False, name='U_a') if encoder.position_bias and input_length is not None and time is not None: src_pos = tf.tile(tf.expand_dims(tf.range(time_steps), axis=0), [batch_size, 1]) trg_pos = tf.tile(tf.reshape(time, [1, 1]), [batch_size, time_steps]) src_len = tf.tile(tf.expand_dims(input_length, axis=1), [1, time_steps]) # - 1 pos_feats = tf.to_float(tf.stack([src_pos, trg_pos, src_len], axis=2))
tensorflow.range
7,378
import tensorflow as tf variables_averages_op = variable_averages.apply(tf.trainable_variables()) # Group all updates to into a single train op. train_op = tf.group(apply_gradient_op, variables_averages_op) # Create a saver. saver = tf.train.Saver(tf.global_variables()) # Build the summary operation from the last tower summaries. summary_op = tf.summary.merge(summaries) # Build an initialization operation to run below. init = tf.global_variables_initializer() # Start running operations on the Graph. allow_soft_placement must be set to # True to build towers on GPU, as some of the ops do not have GPU # implementations. sess = tf.Session(config=tf.ConfigProto( allow_soft_placement=True, log_device_placement=FLAGS.log_device_placement)) sess.run(init) # Start the queue runners. tf.train.start_queue_runners(sess=sess)
tensorflow.global_variables_initializer
7,379
import tensorflow as tf embedded_text_expand = tf.expand_dims(self.embedded_characters, -1) with tf.device('/cpu:0'), tf.name_scope("embedding_tags"): W_tags = tf.get_variable("embed_W_tags", [tags_vocab_size, embedding_size], initializer=initializer) embedded_tags = tf.nn.embedding_lookup(W_tags, self.input_tags) embedded_tags_expanded = tf.expand_dims(embedded_tags, -1) with tf.device('/cpu:0'), tf.name_scope("embedding_deps"):
tensorflow.nn.embedding_lookup
7,380
import tensorflow as tf # Test with state_is_tuple=False. with tf.variable_scope("no_tuple"): cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=False) dec, mem = tf.nn.seq2seq.embedding_attention_seq2seq(
tensorflow.nn.rnn_cell.BasicLSTMCell
7,381
import tensorflow as tf def cnn_model(x, amp_factor=1): with tf.variable_scope('model'): conv1 = tf.layers.conv2d(x, filters=32*amp_factor, kernel_size=[5, 3], data_format='channels_last', padding= "same", strides=(2, 1),
tensorflow.layers.conv2d
7,382
import tensorflow as tf mode=mode, loss=total_loss, train_op=train_op, scaffold=scaffold_fn ) elif mode == tf.estimator.ModeKeys.EVAL: def metric_fn(per_example_loss, label_ids, logits, is_real_example): # predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) # ones=tf.get_variable('ones',shape=logits.shape,initializer=tf.ones_initializer) # zeros=tf.get_variable('zeros',shape=logits.shape,initializer=tf.zeros_initializer) predictions=tf.where(logits>=0,tf.ones(tf.shape(logits)),tf.zeros(tf.shape(logits))) accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions, weights=is_real_example) loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example) return { "eval_accuracy": accuracy, "eval_loss": loss, } eval_metrics = (metric_fn, [per_example_loss, label_ids, logits, is_real_example])
tensorflow.shape
7,383
import tensorflow as tf bstrides = _calc_block_strides(bsize, ksize, strides) # Pad mask. mask_ = tf.expand_dims(mask, 3) mask_ = _pad_input(mask_, ksize, strides, padding, bsize=bsize, bstrides=bstrides) mask_ = tf.nn.max_pool(mask_, bsize, bstrides, 'VALID') # Blocks are always valid conv. mask_ = tf.squeeze(mask_, [3]) indices = tf.where(tf.greater(mask_, tol)) indices = tf.cast(indices, tf.int32) return indices def convert_mask_to_block_indices(mask, bsize, ksize, strides, padding, tol): """ Converts a binary mask to block sparse indices.
tensorflow.greater
7,384
import tensorflow as tf # Add a prefix to the node names in the current graph and Restore using # remapped names. with self.test_session() as sess: v0 = tf.Variable(-1.0, name="restore_prefix/v0") v1 = tf.Variable(-1.0, name="restore_prefix/v1") with self.assertRaisesOpError("uninitialized value restore_prefix/v0"): sess.run(v0)
tensorflow.Variable
7,385
from tensorflow.python.framework import ops @ops.RegisterShape("Div") @ops.RegisterShape("Equal") @ops.RegisterShape("Greater") @ops.RegisterShape("GreaterEqual") @ops.RegisterShape("Less") @ops.RegisterShape("LessEqual") @ops.RegisterShape("LogicalAnd") @ops.RegisterShape("LogicalOr") @ops.RegisterShape("Maximum") @ops.RegisterShape("Minimum") @ops.RegisterShape("Mod") @ops.RegisterShape("Mul") @ops.RegisterShape("NotEqual") @ops.RegisterShape("Pow")
tensorflow.python.framework.ops.RegisterShape
7,386
import tensorflow as tf >>> samples.dtype dtype('float64') >>> m.dtype = tf.float32 >>> samples = m.compute_prior_samples(test_points, 1, 2) >>> samples.dtype dtype('float32') """ mu, var = self.build_prior_mean_var(test_points, num_latent, True) jitter = tfhacks.eye(tf.shape(mu)[0], var.dtype) * 1e-06 L = tf.batch_cholesky(tf.transpose(var, (2, 0, 1)) + jitter) V_shape = [tf.shape(L)[0], tf.shape(L)[1], num_samples] V = tf.random_normal(V_shape, dtype=L.dtype) samples = tf.expand_dims(tf.transpose(mu), -1) + tf.batch_matmul(L, V) return tf.transpose(samples) @autoflow((tf.float64, [None, None]), (tf.float64, [None, None]), (tf.float64, [None, None])) def compute_posterior_mean_var(self, X, Y, test_points): """Computes the means and variances of the posterior(s). This is just an autoflowed version of
tensorflow.shape
7,387
import tensorflow as tf new_factor = ( weight * state[self.FACTOR_STATE_KEY] + (1 - weight) / norm_mean) return {self.FACTOR_STATE_KEY: new_factor} def get_params(self, state): """See base class.""" params = {self.FACTOR_PARAM_KEY: state[self.FACTOR_STATE_KEY]} return params, params def encode(self, x, encode_params): """See base class.""" return (self._stage.encode(x, encode_params), { self.NORM_STATE_UPDATE_KEY: tf.norm(x) }) def decode(self, encoded_tensors, decode_params, num_summands=None, shape=None): """See base class.""" return self._stage.decode(encoded_tensors, decode_params, num_summands, shape)
tensorflow.norm
7,388
import tensorflow as tf for g, v in grads_and_vars: tf.summary.histogram(v.name[:-2] + '_hist', v) tf.summary.histogram(v.name[:-2] + '_grad_hist', g)
tensorflow.summary.histogram
7,389
import tensorflow as tf num_decoder_symbols = 5 batch_size = 2 num_enc_timesteps = 2 num_dec_timesteps = 3 def TestModel(seq2seq): with self.test_session(graph=tf.Graph()) as sess: tf.set_random_seed(111) random.seed(111) np.random.seed(111) enc_inp = [tf.constant(i + 1, tf.int32, shape=[batch_size]) for i in range(num_enc_timesteps)] dec_inp_fp_true = [tf.constant(i, tf.int32, shape=[batch_size]) for i in range(num_dec_timesteps)] dec_inp_holder_fp_false = [tf.placeholder(tf.int32, shape=[batch_size]) for _ in range(num_dec_timesteps)] targets = [tf.constant(i + 1, tf.int32, shape=[batch_size]) for i in range(num_dec_timesteps)] weights = [tf.constant(1.0, shape=[batch_size]) for i in range(num_dec_timesteps)] def ForwardBackward(enc_inp, dec_inp, feed_previous): scope_name = "fp_{}".format(feed_previous) with tf.variable_scope(scope_name): dec_op, _ = seq2seq(enc_inp, dec_inp, feed_previous=feed_previous)
tensorflow.constant
7,390
import tensorflow as tf if tf.DeviceSpec.from_string(device.name).device_type == "GPU": if "K20" in device.physical_device_desc: return (16,) if "P100" in device.physical_device_desc: return (16, 32, 64) if tf.DeviceSpec.from_string(device.name).device_type == "TPU": return (32,) return (16, 32) def _force_device_sync(self): """Shamelessly copied from `resnet50_test.py`.""" tf.constant(1.).cpu() def _report(self, label, start, num_iters, device, batch_size, data_format): avg_time = (time.time() - start) / num_iters dev = tf.DeviceSpec.from_string(device).device_type.lower() name = "%s_%s_batch_%d_%s" % (label, dev, batch_size, data_format) extras = {"examples_per_sec": batch_size / avg_time} self.report_benchmark( iters=num_iters, wall_time=avg_time, name=name, extras=extras) def _benchmark_eager_apply(self,
tensorflow.constant
7,391
import tensorflow as tf assert (bsize[2] - ksize[1]) % strides[2] == 0, ERR_MSG_DIV.format( strides[2], bsize[2], ksize[1]) assert strides[0] == strides[3] == 1, ERR_MSG_DIM.format(strides) bstrides = _calc_block_strides(bsize, ksize, strides) # Pad mask. mask_ = tf.expand_dims(mask, 3) mask_ = _pad_input(mask_, ksize, strides, padding, bsize=bsize, bstrides=bstrides) mask_ = tf.nn.max_pool(mask_, bsize, bstrides, 'VALID') # Blocks are always valid conv. mask_ = tf.squeeze(mask_, [3]) indices = tf.where(tf.greater(mask_, tol)) indices = tf.cast(indices, tf.int32) return indices def convert_mask_to_block_indices(mask, bsize, ksize, strides, padding, tol): """
tensorflow.nn.max_pool
7,392
import tensorflow as tf global_step=tf.train.get_or_create_global_step()) self._new_lr = tf.placeholder( tf.float32, shape=[], name="new_learning_rate") self._lr_update = tf.assign(self._lr, self._new_lr) def _build_rnn_graph(self, inputs, config, is_training): if config.rnn_mode == CUDNN:
tensorflow.assign
7,393
import tensorflow as tf def get_next_sentence_output(bert_config, input_tensor, labels): """Get loss and log probs for the next sentence prediction.""" # Simple binary classification. Note that 0 is "next sentence" and 1 is # "random sentence". This weight matrix is not used after pre-training. with tf.variable_scope("cls/seq_relationship"): output_weights = tf.get_variable( "output_weights", shape=[2, bert_config.hidden_size], initializer=modeling.create_initializer(bert_config.initializer_range), ) output_bias = tf.get_variable( "output_bias", shape=[2], 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) labels = tf.reshape(labels, [-1]) one_hot_labels = tf.one_hot(labels, depth=2, 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, log_probs)
tensorflow.zeros_initializer
7,394
import tensorflow as tf else: grads = tf.gradients(loss, self.params) norm_grads = None if self.max_grad_norm is not None: grads, norm_grads = tf.clip_by_global_norm(grads, self.max_grad_norm) grads = list(zip(grads, self.params)) with tf.variable_scope("input_info", reuse=False): tf.summary.scalar('rewards', tf.reduce_mean(self.reward_ph)) tf.summary.scalar('learning_rate', tf.reduce_mean(self.learning_rate)) tf.summary.scalar('advantage', tf.reduce_mean(adv)) tf.summary.scalar('action_probability', tf.reduce_mean(self.mu_ph)) if self.full_tensorboard_log: tf.summary.histogram('rewards', self.reward_ph) tf.summary.histogram('learning_rate', self.learning_rate) tf.summary.histogram('advantage', adv) tf.summary.histogram('action_probability', self.mu_ph) if tf_util.is_image(self.observation_space):
tensorflow.reduce_mean
7,395
from tensorflow.python.framework import tensor_util @ops.RegisterShape("Range") def _RangeShape(op): start_value = tensor_util.ConstantValue(op.inputs[0]) limit_value = tensor_util.ConstantValue(op.inputs[1]) delta_value = tensor_util.ConstantValue(op.inputs[2]) if start_value is None or limit_value is None or delta_value is None: return [tensor_shape.vector(None)] else:
tensorflow.python.framework.tensor_util.ConstantValue
7,396
import tensorflow as tf if len(input_dims) == 4: _, input_h, input_w, num_channels = input_dims in_dim = input_h * input_w * num_channels flat_input = tf.reshape(input_data, [-1, in_dim]) else: in_dim = input_dims[-1] flat_input = input_data 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)) fc_bias = tf.get_variable("bias", shape=[out_dim], initializer=tf.constant_initializer(0.0)) else: fc_weight = tf.get_variable("weights", initializer=initial_value[0]) fc_bias = tf.get_variable("bias", shape=[out_dim], initializer=initial_value[1]) if use_bias: output = tf.add(tf.matmul(flat_input, fc_weight), fc_bias) else: output = tf.matmul(flat_input, fc_weight) if non_linear_fn is None: return output else: activation = non_linear_fn(output) return activation
tensorflow.get_variable
7,397
import tensorflow as tf tf.flags.DEFINE_string( "tpu_name", None, "The Cloud TPU to use for training. This should be either the name " "used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 " "url.") tf.flags.DEFINE_string( "tpu_zone", None, "[Optional] GCE zone where the Cloud TPU is located in. If not " "specified, we will attempt to automatically detect the GCE project from " "metadata.") tf.flags.DEFINE_string(
tensorflow.flags.DEFINE_string
7,398
from tensorflow.python.ops import math_ops fn = _sparse_false_negative_at_k( predictions_idx=predictions_idx, labels=labels, class_id=class_id, weights=weights) batch_total_fn = math_ops.to_double(math_ops.reduce_sum(fn)) var = contrib_variables.local_variable(
tensorflow.python.ops.math_ops.reduce_sum
7,399