seed
stringlengths
25
2.89k
seed_api
stringlengths
14
102
index
int64
0
14.8k
import tensorflow as tf e = compute_energy(hidden_states, state, encoder, input_length=encoder_input_length, **kwargs) mask = tf.sequence_mask(encoder_input_length, maxlen=tf.shape(hidden_states)[1], dtype=tf.float32) e *= mask if encoder.attn_norm_fun == 'none': weights = e elif encoder.attn_norm_fun == 'sigmoid': weights = tf.nn.sigmoid(e) elif encoder.attn_norm_fun == 'max': weights = tf.one_hot(tf.argmax(e, -1), depth=tf.shape(e)[1]) else: e -= tf.reduce_max(e, axis=1, keep_dims=True) T = encoder.attn_temperature or 1.0 exp = tf.exp(e / T) * mask weights = exp / tf.reduce_sum(exp, axis=-1, keep_dims=True) weighted_average = tf.reduce_sum(tf.expand_dims(weights, 2) * hidden_states, axis=1) return weighted_average, weights
tensorflow.shape
6,800
import tensorflow as tf initializer = tf.random_uniform_initializer(minval=-weight_scale, maxval=weight_scale) else: initializer = tf.random_normal_initializer(stddev=weight_scale) with tf.device('/cpu:0'): # embeddings can take a very large amount of memory, so # storing them in GPU memory can be impractical if encoder.binary: embeddings = None # inputs are token ids, which need to be mapped to vectors (embeddings)
tensorflow.device
6,801
import tensorflow as tf dtype=tf.float32) start_features = tf.einsum("lbh,bl->bh", output, start_index) start_features = tf.tile(start_features[None], [seq_len, 1, 1]) end_logits = tf.layers.dense( tf.concat([output, start_features], axis=-1), xlnet_config.d_model, kernel_initializer=initializer, activation=tf.tanh, name="dense_0") end_logits = tf.contrib.layers.layer_norm( end_logits, begin_norm_axis=-1)
tensorflow.concat
6,802
import tensorflow as tf """ :description: Placeholders """ def _setup_placeholders(self): if self.demo: self.c = tf.placeholder(tf.int32, [None, self.config.max_p_len], "context") self.q = tf.placeholder(tf.int32, [None, self.config.max_q_len], "question") self.ch = tf.placeholder(tf.int32, [None, self.config.max_p_len, self.config.max_ch_len], "context_char") self.qh = tf.placeholder(tf.int32, [None, self.config.max_q_len, self.config.max_ch_len], "question_char") self.start_label = tf.placeholder(tf.int32, [None], "answer_label1") self.end_label = tf.placeholder(tf.int32, [None], "answer_label2") else: self.c = tf.placeholder(tf.int32, [self.config.batch_size * self.max_p_num, self.config.max_p_len], "context") self.q = tf.placeholder(tf.int32, [self.config.batch_size * self.max_p_num, self.config.max_q_len], "question") self.ch = tf.placeholder(tf.int32, [self.config.batch_size * self.max_p_num, self.config.max_p_len, self.config.max_ch_len], "context_char") self.qh = tf.placeholder(tf.int32, [self.config.batch_size * self.max_p_num, self.config.max_q_len, self.config.max_ch_len], "question_char") self.start_label = tf.placeholder(tf.int32, [self.config.batch_size], "answer_label1")
tensorflow.placeholder
6,803
import tensorflow as tf cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=False) return tf.nn.seq2seq.embedding_tied_rnn_seq2seq(
tensorflow.nn.seq2seq.embedding_tied_rnn_seq2seq
6,804
import tensorflow as tf S = optimized_trilinear_for_attention([c, q], self.c_maxlen, self.q_maxlen, input_keep_prob = 1.0 - self.dropout) mask_q = tf.expand_dims(self.q_mask, 1)
tensorflow.expand_dims
6,805
import tensorflow as tf if bias is None: bias = tf.get_variable("{}_dense_b".format(name), initializer=tf.zeros(shape=hidden_dims))
tensorflow.zeros
6,806
import tensorflow as tf tf.app.flags.DEFINE_string('comment', '', 'Comment to leave by the model') tf.app.flags.DEFINE_float('test_max', 10000, 'max number of examples in the test set') tf.app.flags.DEFINE_integer('max_epochs', 0, 'Train for at most this number of epochs')
tensorflow.app.flags.DEFINE_float
6,807
from tensorflow.python.platform import tf_logging as logging input_feature_key=self._input_feature_key, use_deprecated_input_fn=self._use_deprecated_input_fn) except RuntimeError: # Currently we are not syncronized with saving checkpoints, which leads to # runtime errors when we are calling export on the same global step. # Exports depend on saved checkpoints for constructing the graph and # getting the global step from the graph instance saved in the checkpoint. # If the checkpoint is stale with respect to current step, the global step # is taken to be the last saved checkpoint's global step and exporter # doesn't export the same checkpoint again with the following error. logging.info("Skipping exporting because the existing checkpoint has " "already been exported. " "Consider exporting less frequently.") def end(self, session=None): super(ExportMonitor, self).end(session=session) latest_path = saver_lib.latest_checkpoint(self._estimator.model_dir) if latest_path is None: logging.info("Skipping export at the end since model has not been saved " "yet.")
tensorflow.python.platform.tf_logging.info
6,808
import tensorflow as tf lang1_fname = filename + ".lang1" lang2_fname = filename + ".lang2" if tf.gfile.Exists(lang1_fname) and tf.gfile.Exists(lang2_fname): tf.logging.info("Skipping compile data, found files:\n%s\n%s", lang1_fname,
tensorflow.gfile.Exists
6,809
import tensorflow as tf lambda: 0.) # On the first step, prev_log_r = 0. log_r = tf.cond( tf.less(t + 1, self.max_seq_len), lambda: self.tilt(rnn_out, latent_encoded, self.targets_ta.read(t+1)),
tensorflow.less
6,810
import tensorflow as tf filename = os.path.join(test_dir, "metafile") saver0_ckpt = os.path.join(test_dir, "saver0.ckpt") saver1_ckpt = os.path.join(test_dir, "saver1.ckpt") with self.test_session(graph=tf.Graph()) as sess: # Creates a graph. v0 = tf.Variable(10.0, name="v0") v1 = tf.Variable(11.0, name="v1") # Creates 2 savers. saver0 = tf.train.Saver({"v0": v0}, name="saver0") saver1 = tf.train.Saver({"v1": v1}, name="saver1") tf.add_to_collection("savers", saver0) tf.add_to_collection("savers", saver1) tf.initialize_all_variables().run() # Saves to different checkpoints. 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() # Verifies that there is no saver_def in meta_graph_def. self.assertFalse(meta_graph_def.HasField("saver_def")) # Verifies that there is saver_def in meta_graph_def0 and 1.
tensorflow.initialize_all_variables
6,811
import tensorflow as tf if is_fm_loss: global_pool_head = self.end_points_D['global_pool'] real_data_features = tf.slice(global_pool_head, [0, 0], [batch_size_train, num_classes]) fake_data_features = tf.slice(global_pool_head, [batch_size_train, 0], [batch_size_train, num_classes])
tensorflow.slice
6,812
import tensorflow as tf #from keras import backend as K def din_attention(query, facts, attention_size, mask=None, stag='null', mode='SUM', softmax_stag=1, time_major=False, return_alphas=False): if isinstance(facts, tuple): # In case of Bi-RNN, concatenate the forward and the backward RNN outputs. facts = tf.concat(facts, 2) print ("query_size mismatch") query = tf.concat(values = [ query, query, ], axis=1) if time_major: # (T,B,D) => (B,T,D)
tensorflow.concat
6,813
import tensorflow as tf 'omega_%s' % layer, tf.constant(0.)) if self.lesion_kappa: setattr( self, 'kappa_%s' % layer, tf.constant(0.)) if self.reuse: # Make the batchnorm variables scopes = ['g1_bn', 'g2_bn', 'c1_bn', 'c2_bn'] bn_vars = ['moving_mean', 'moving_variance', 'gamma'] for s in scopes: with tf.variable_scope(s): for v in bn_vars: tf.get_variable( trainable=self.param_trainable[v], name=v, dtype=self.dtype, shape=[self.hgru_k[idx]], collections=self.param_collections[v], initializer=self.param_initializer[v]) self.param_initializer = None def resize_x_to_y( self, x, y, kernel,
tensorflow.get_variable
6,814
import tensorflow as tf def batch_norm(x, train, name, decay=0.99, epsilon=1e-5): shape = x.get_shape().as_list() with tf.variable_scope(name): beta = tf.get_variable('beta', [shape[-1]], initializer=tf.constant_initializer(0.)) gamma = tf.get_variable('gamma', [shape[-1]], initializer=tf.random_normal_initializer(1., 0.02)) pop_mean = tf.get_variable('pop_mean', [shape[-1]], initializer=tf.constant_initializer(0.), trainable=False) pop_var = tf.get_variable('pop_var', [shape[-1]], initializer=tf.constant_initializer(1.), trainable=False) if pop_mean not in tf.moving_average_variables(): tf.add_to_collection(tf.GraphKeys.MOVING_AVERAGE_VARIABLES, pop_mean) tf.add_to_collection(tf.GraphKeys.MOVING_AVERAGE_VARIABLES, pop_var) def func1(): # execute at training time batch_mean, batch_var = tf.nn.moments(x, range(len(shape) - 1)) update_mean = tf.assign_sub(pop_mean, (1 - decay)*(pop_mean - batch_mean)) update_var = tf.assign_sub(pop_var, (1 - decay)*(pop_var - batch_var))
tensorflow.moving_average_variables
6,815
import tensorflow as tf weight_l2: an optional weight to modulate the l2 loss. name: Optional scope/name for op_scope. Returns: the l1+L2 loss op. """ with tf.name_scope(name): weight_l1_t = tf.convert_to_tensor(weight_l1, dtype=var.dtype.base_dtype, name='weight_l1') weight_l2_t = tf.convert_to_tensor(weight_l2, dtype=var.dtype.base_dtype, name='weight_l2') reg_l1 = tf.multiply(weight_l1_t, tf.reduce_sum(tf.abs(var)), name='value_l1') reg_l2 = tf.multiply(weight_l2_t, tf.nn.l2_loss(var), name='value_l2') return tf.add(reg_l1, reg_l2, name='value')
tensorflow.convert_to_tensor
6,816
import tensorflow as tf filename = os.path.join(tmp_dir, filename) lang1_fname = filename + ".lang1" lang2_fname = filename + ".lang2" if tf.gfile.Exists(lang1_fname) and tf.gfile.Exists(lang2_fname): tf.logging.info("Skipping compile data, found files:\n%s\n%s", lang1_fname, lang2_fname) return filename with tf.gfile.GFile(lang1_fname, mode="w") as lang1_resfile:
tensorflow.logging.info
6,817
import tensorflow as tf # add batch dimension (assume batch_size==1) #assert image.get_shape()[0] == 1 boxes = tf.expand_dims(boxes, dim=0) image = tf.image.draw_bounding_boxes(image, boxes) # 在image上画gt_truth return tf.summary.image('ground_truth', image) def _add_act_summary(self, tensor): tf.summary.histogram('ACT/' + tensor.op.name + '/activations', tensor) tf.summary.scalar('ACT/' + tensor.op.name + '/zero_fraction', tf.nn.zero_fraction(tensor)) def _add_score_summary(self, key, tensor): tf.summary.histogram('SCORE/' + tensor.op.name + '/' + key + '/scores', tensor) def _add_train_summary(self, var):
tensorflow.summary.histogram
6,818
import tensorflow as tf bert_config=bert_config, num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate, num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_tpu=FLAGS.use_tpu, use_one_hot_embeddings=FLAGS.use_tpu) # If TPU is not available, this will fall back to normal Estimator on CPU # or GPU. estimator = tf.contrib.tpu.TPUEstimator( use_tpu=FLAGS.use_tpu, model_fn=model_fn, config=run_config, train_batch_size=FLAGS.train_batch_size, eval_batch_size=FLAGS.eval_batch_size, predict_batch_size=FLAGS.predict_batch_size) if FLAGS.do_train: train_file = os.path.join(FLAGS.output_dir, "train.tf_record") file_based_convert_examples_to_features(
tensorflow.contrib.tpu.TPUEstimator
6,819
import tensorflow as tf # the word embeddings with tf.device("/cpu:0"): self.embedding_weights = tf.get_variable( "embedding", [self._n_tokens_vocab, projection_dim], dtype=DTYPE, ) self.embedding = tf.nn.embedding_lookup(self.embedding_weights, self.ids_placeholder) def _build_lstms(self): # now the LSTMs # these will collect the initial states for the forward
tensorflow.nn.embedding_lookup
6,820
from tensorflow.python.platform import gfile s2 = save.save(sess, os.path.join(save_dir, "s2")) self.assertEqual([s3, s2], save.last_checkpoints) self.assertFalse(gfile.Exists(s1)) self.assertFalse(gfile.Exists(save._MetaGraphFilename(s1))) self.assertTrue(gfile.Exists(s3)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s3))) self.assertTrue(gfile.Exists(s2)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s2))) # Adding s1 (s3 should now be deleted as oldest in list) s1 = save.save(sess, os.path.join(save_dir, "s1")) self.assertEqual([s2, s1], save.last_checkpoints) self.assertFalse(gfile.Exists(s3)) self.assertFalse(gfile.Exists(save._MetaGraphFilename(s3))) self.assertTrue(gfile.Exists(s2)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s2))) self.assertTrue(gfile.Exists(s1)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s1))) # Exercise the second helper. # Adding s2 again (old s2 is removed first, then new s2 appended) s2 = save2.save(sess, os.path.join(save_dir, "s2")) self.assertEqual([s3, s2], save2.last_checkpoints)
tensorflow.python.platform.gfile.Exists
6,821
import tensorflow as tf kl = tfd.kl_divergence(a, b) kl_ = self.evaluate(kl) self.assertAllEqual(np.inf, kl_) if __name__ == "__main__": tf.test.main()
tensorflow.test.main
6,822
import tensorflow as tf op = tf.assign(perturbed_var, var) perturb_ops.append(op) assert len(perturb_ops) == len(all_vars) return tf.group(*perturb_ops) # Set up functionality to re-compute `param_noise_scale`. This perturbs yet another copy # of the network and measures the effect of that perturbation in action space. If the perturbation # is too big, reduce scale of perturbation, otherwise increase. q_values_adaptive = q_func(observations_ph.get(), num_actions, scope="adaptive_q_func") perturb_for_adaption = perturb_vars(original_scope="q_func", perturbed_scope="adaptive_q_func") kl = tf.reduce_sum(tf.nn.softmax(q_values) * (tf.log(tf.nn.softmax(q_values)) - tf.log(tf.nn.softmax(q_values_adaptive))), axis=-1) mean_kl = tf.reduce_mean(kl) def update_scale(): with tf.control_dependencies([perturb_for_adaption]): update_scale_expr = tf.cond(mean_kl < param_noise_threshold, lambda: param_noise_scale.assign(param_noise_scale * 1.01), lambda: param_noise_scale.assign(param_noise_scale / 1.01), ) return update_scale_expr # Functionality to update the threshold for parameter space noise. update_param_noise_threshold_expr = param_noise_threshold.assign(tf.cond(update_param_noise_threshold_ph >= 0,
tensorflow.reduce_mean
6,823
import tensorflow as tf train_losses_slbo = deque(maxlen=slbo_n_model_iters // FLAGS.model.validation_freq) val_losses_warmup = deque(maxlen=warmup_n_model_iters // FLAGS.model.validation_freq) val_losses_slbo = deque(maxlen=slbo_n_model_iters // FLAGS.model.validation_freq) # NOTE: For each test task, we should reset model to the loaded one, and randomly initialize policy and vfn #if test: # saver.load_state_dict(np.load(model_load, allow_pickle=True)[()]) # logger.warning('Load model from %s', model_load) if test: logger.info("################################################## TESTING TASK %d ################################################", TEST_TASK_NUM) logger.info(f'TEST_TASK_NUM={TEST_TASK_NUM}, TASK_NUM={TASK_NUM}') logger.warning('Revert model and normalizers') tf.get_default_session().run(sync_model_from_lazymodel) tf.get_default_session().run(revert_normalizers) else: logger.info("################################################## TRAINING TASK %d ################################################", TASK_NUM) if test: test_returns = [] test_summary['warmupprocess'].append([]) test_summary['slbo'].append([]) if not test: #and FLAGS.task.method == 'random': if inittask != 'none' and TASK_NUM == 1: if 'HClinearstate' in taskname: task.init([0.2] * task.n_params) else:
tensorflow.get_default_session
6,824
import tensorflow as tf def triplet_loss(anchor, positive, negative, alpha=0.2, name='triplet_loss'): """Calculate the triplet loss according to the FaceNet paper. Args: anchor: 2-D `tensor` [batch_size, embedding_size], the embeddings for the anchor images. positive: 2-D `tensor` [batch_size, embedding_size], the embeddings for the positive images. negative: 2-D `tensor` [batch_size, embedding_size], the embeddings for the negative images. alpha: positive to negative triplet distance margin Returns: the triplet loss. """ with tf.name_scope(name): pos_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, positive)), 1) neg_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, negative)), 1) basic_loss = tf.add(tf.subtract(pos_dist, neg_dist), alpha) loss = tf.reduce_mean(tf.maximum(basic_loss, 0.0), 0) return loss def decov_loss(xs, name='decov_loss'): """Decov loss as described in https://arxiv.org/pdf/1511.06068.pdf 'Reducing Overfitting In Deep Networks by Decorrelating Representation'. Args: xs: 4-D `tensor` [batch_size, height, width, channels], input
tensorflow.subtract
6,825
import tensorflow as tf ------- tf.Tensor A biased tensor with the same shape as the input tensor. """ if init is None: init = tf.zeros([tensor.get_shape()[-1].value]) with tf.name_scope(name, tensor.op.name, [tensor]): b = tf.Variable(init, name='b') return tf.nn.bias_add(tensor, b) def dropout(tensor, dropout_prob, training=True, training_only=True):
tensorflow.name_scope
6,826
import tensorflow as tf metrics = {'normalized_error': ne_mertric, 'last_pred_mse':last_pred_mse} predictions = {'normalized_error': ne_mertric[1]} ne_mertric = tf.identity(ne_mertric[1], name='ne_mertric') base_learning_rate = params['learning_rate'] mse_loss_list = [] if params['use_ohkm']: base_learning_rate = 1. * base_learning_rate for pred_ind in list(range(len(pred_outputs) - 1)): mse_loss_list.append(0.5 * tf.losses.mean_squared_error(targets_list[pred_ind], pred_outputs[pred_ind], weights=1.0 / tf.cast(cur_batch_size, tf.float32), scope='loss_{}'.format(pred_ind), loss_collection=None,#tf.GraphKeys.LOSSES, # mean all elements of all pixels in all batch reduction=tf.losses.Reduction.MEAN))# SUM, SUM_OVER_BATCH_SIZE, default mean by all elements temp_loss = tf.reduce_mean(tf.reshape(tf.losses.mean_squared_error(targets_list[-1], pred_outputs[-1], weights=1.0, loss_collection=None, reduction=tf.losses.Reduction.NONE), [cur_batch_size, config.class_num_joints[(params['model_scope'] if 'all' not in params['model_scope'] else '*')], -1]), axis=-1) num_topk = config.class_num_joints[(params['model_scope'] if 'all' not in params['model_scope'] else '*')] // 2 gather_col = tf.nn.top_k(temp_loss, k=num_topk, sorted=True)[1] gather_row = tf.reshape(tf.tile(tf.reshape(tf.range(cur_batch_size), [-1, 1]), [1, num_topk]), [-1, 1])
tensorflow.cast
6,827
from tensorflow.python.ops import array_ops return expanded ones = array_ops.ones_like(array_ops.shape(tensor))
tensorflow.python.ops.array_ops.shape
6,828
import tensorflow as tf rpn_scores.set_shape([None, 1]) return rois, rpn_scores def _crop_pool_layer(self, bottom, rois, name): with tf.variable_scope(name): # tf.squeeze()返回一个张量,这个张量是将原始input中所有维度中为1的那些维都删掉的结果 batch_ids = tf.squeeze(tf.slice(rois, [0, 0], [-1, 1], name="batch_id"), [1]) # Get the normalized coordinates of bboxes bottom_shape = tf.shape(bottom) height = (tf.to_float(bottom_shape[1]) - 1.) * np.float32(self._feat_stride[0]) width = (tf.to_float(bottom_shape[2]) - 1.) * np.float32(self._feat_stride[0]) # rois除以h,w就得到了rois在特征图上的位置 x1 = tf.slice(rois, [0, 1], [-1, 1], name="x1") / width y1 = tf.slice(rois, [0, 2], [-1, 1], name="y1") / height x2 = tf.slice(rois, [0, 3], [-1, 1], name="x2") / width y2 = tf.slice(rois, [0, 4], [-1, 1], name="y2") / height # Won't be backpropagated to rois anyway, but to save time bboxes = tf.stop_gradient(tf.concat([y1, x1, y2, x2], axis=1)) # 'roi_pooling_size', 7
tensorflow.to_float
6,829
import tensorflow as tf self.sess = tf.Session(config=config) self.s_dim, self.a_dim = env.observation_space.shape, env.action_space.shape[0] self.a_bound = (env.action_space.high - env.action_space.low) / 2 self.actions = tf.placeholder(tf.float32, [None, self.a_dim], 'action') self.state = tf.placeholder(tf.float32, [None, self.s_dim[0]], 'state') self.advantage = tf.placeholder(tf.float32, [None, 1], 'advantage') self.rewards = tf.placeholder(tf.float32, [None, 1], 'discounted_r') # Dateset with experiennce replay self.dataset = tf.data.Dataset.from_tensor_slices({'state': self.state, 'actions': self.actions, 'rewards': self.rewards, 'advantage': self.advantage}) self.dataset = self.dataset.shuffle(buffer_size=10000) self.dataset = self.dataset.batch(self.MINIBATCH) self.dataset = self.dataset.cache() self.dataset = self.dataset.repeat(self.EPOCHS) self.data_iter = self.dataset.make_initializable_iterator() batch = self.data_iter.get_next()
tensorflow.data.Dataset.from_tensor_slices
6,830
import tensorflow as tf 'swish':swish, 'gelu':gelu } lr_schedules = { 'warmup_cosine':warmup_cosine, 'warmup_linear':warmup_linear, 'warmup_constant':warmup_constant, } def _norm(x, g=None, b=None, e=1e-5, axis=[1]): u = tf.reduce_mean(x, axis=axis, keep_dims=True) s = tf.reduce_mean(tf.square(x-u), axis=axis, keep_dims=True) x = (x - u) * tf.rsqrt(s + e) if g is not None and b is not None: x = x*g + b return x def norm(x, scope, axis=[-1]): with tf.variable_scope(scope): n_state = shape_list(x)[-1] g = tf.get_variable("g", [n_state], initializer=tf.constant_initializer(1)) b = tf.get_variable("b", [n_state], initializer=tf.constant_initializer(0)) return _norm(x, g, b, axis=axis) def dropout(x, pdrop, train):
tensorflow.rsqrt
6,831
import tensorflow as tf 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]])
tensorflow.layers.dense
6,832
import tensorflow as tf inputs = tf.nn.dropout(inputs, config.keep_prob) output, state = self._build_rnn_graph(inputs, config, is_training) softmax_w = tf.get_variable( "softmax_w", [size, vocab_size], dtype=data_type()) softmax_b = tf.get_variable("softmax_b", [vocab_size], dtype=data_type()) logits = tf.nn.xw_plus_b(output, softmax_w, softmax_b) # Reshape logits to be a 3-D tensor for sequence loss logits = tf.reshape(logits, [self.batch_size, self.num_steps, vocab_size]) # Use the contrib sequence loss and average over the batches loss = tf.contrib.seq2seq.sequence_loss( logits, input_.targets, tf.ones([self.batch_size, self.num_steps], dtype=data_type()), average_across_timesteps=False, average_across_batch=True)
tensorflow.reshape
6,833
import tensorflow as tf self.interaction = gmf(uid=self.user_id, iid=self.item_id, num_users=self.train_set.num_users, num_items=self.train_set.num_items, emb_size=self.num_factors, reg_user=self.regs[0], reg_item=self.regs[1], seed=self.seed) logits = tf.layers.dense(self.interaction, units=1, name='logits', kernel_initializer=tf.initializers.lecun_uniform(self.seed)) self.prediction = tf.nn.sigmoid(logits) self.loss = loss_fn(labels=self.labels, logits=logits) train_op = train_fn(self.loss, learning_rate=self.learning_rate, learner=self.learner) initializer = tf.global_variables_initializer()
tensorflow.nn.sigmoid
6,834
import tensorflow as tf with tf.Session() as sess: "initialize the variables" sess.run(tf.global_variables_initializer())
tensorflow.global_variables_initializer
6,835
from tensorflow.python.ops import array_ops self._gate_linear = _Linear( [inputs, state], 2 * self._num_units, True, bias_initializer=bias_ones, kernel_initializer=self._kernel_initializer) value = math_ops.sigmoid(self._gate_linear([inputs, state])) r, u = array_ops.split(value=value, num_or_size_splits=2, axis=1) r_state = r * state if self._candidate_linear is None: with vs.variable_scope("candidate"): self._candidate_linear = _Linear( [inputs, r_state], self._num_units,
tensorflow.python.ops.array_ops.split
6,836
import tensorflow as tf self.translated_z = trans_z s_h, s_w = self.output_height, self.output_width s_h0, s_h1, s_h2, s_h3 = \ int(s_h/ns0), int(s_h/ns0/ns1), int(s_h/ns0/ns1/ns2), int(s_h/ns0/ns1/ns2/ns3) s_w0, s_w1, s_w2, s_w3 = \ int(s_w/ns0), int(s_w/ns0/ns1), int(s_w/ns0/ns1/ns2), int(s_w/ns0/ns1/ns2/ns3) def decode(z, skip_h3, skip_h2, skip_h1, skip_h0): z_ = lrelu(linear(tf.nn.dropout(z, keep_prob), nf3*s_h3*s_w3, 'd_h0_lin')) h0 = tf.nn.dropout(tf.reshape(z_, [-1, s_h3, s_w3, nf3]), keep_prob) h1 = lrelu(deconv2d(tf.concat([h0, skip_h3], 3), [self.batch_size, s_h2, s_w2, nf2], name='d_h1', d_h=ns3, d_w=ns3)) h2 = lrelu(deconv2d(tf.concat([h1, skip_h2], 3), [self.batch_size, s_h1, s_w1, nf1], name='d_h2', d_h=ns2, d_w=ns2)) h3 = lrelu(deconv2d(tf.concat([h2, skip_h1], 3), [self.batch_size, s_h0, s_w0, nf0], name='d_h3', d_h=ns1, d_w=ns1)) print(h3.get_shape()) h4 = deconv2d(tf.concat([h3, skip_h0], 3), [self.batch_size, s_h, s_w, self.c_dim], name='d_h4', d_h=ns0, d_w=ns0) return h4 with tf.variable_scope("deconv") as scope: output_h4 = decode(trans_z, tgtctx_h3, tgtctx_h2, tgtctx_h1, tgtctx_h0) scope.reuse_variables() truthoutput_h4 = decode(tgtimg_z, tgtctx_h3, tgtctx_h2, tgtctx_h1, tgtctx_h0) self.simloss = tf.reduce_mean((trans_z - tgtimg_z) ** 2) * 1e3 print(tgtimg_z.get_shape()) self.out = output_h4 self.out2 = truthoutput_h4
tensorflow.concat
6,837
import tensorflow as tf # execute at test time return tf.nn.batch_normalization(x, pop_mean, pop_var, beta, gamma, epsilon) return tf.cond(train, func1, func2) def average_gradients(tower_grads): average_grads = [] for grad_and_vars in zip(*tower_grads): grads = [] for g, _ in grad_and_vars: expanded_g = tf.expand_dims(g, 0) grads.append(expanded_g) grad = tf.concat(grads, 0) grad = tf.reduce_mean(grad, 0) var = grad_and_vars[0][1] grad_and_var = (grad, var) average_grads.append(grad_and_var) return average_grads def binary_mask(shape, p=0.7): samples = tf.random_uniform(shape, minval=0.0, maxval=1.0) mask = tf.less_equal(samples, p) return tf.cast(mask, tf.float32)
tensorflow.concat
6,838
import tensorflow as tf vars_ = self.model.trainable_variables self.assertTrue(isinstance(grads, list)) self.assertTrue(isinstance(vars_, list)) self.assertEqual(len(grads), len(vars_)) for grad, var in zip(grads, vars_): if grad is not None: self.assertEqual(grad.shape, var.shape) def test_training_graph(self): """Test model training in graph mode.""" with tf.Graph().as_default(): config = config_.get_hparams_cifar_38() config.add_hparam("n_classes", 10) config.add_hparam("dataset", "cifar-10") x = tf.random_normal( shape=(self.config.batch_size,) + self.config.input_shape) t = tf.random_uniform( shape=(self.config.batch_size,), minval=0, maxval=self.config.n_classes, dtype=tf.int32) global_step = tf.Variable(0., trainable=False) model = revnet.RevNet(config=config) _, saved_hidden = model(x) grads, _ = model.compute_gradients(saved_hidden=saved_hidden, labels=t) optimizer = tf.train.AdamOptimizer(learning_rate=1e-3) train_op = optimizer.apply_gradients( zip(grads, model.trainable_variables), global_step=global_step)
tensorflow.random_normal
6,839
import tensorflow as tf b = tf.get_variable('b', [2048], initializer=tf.constant_initializer(1.0)) out = tf.matmul(self.flatten, w) + b self.fc1 = tf.nn.relu(out) # fc2 with tf.variable_scope('fc2'): w = tf.get_variable('w', [self.fc1.get_shape()[1], 2048], initializer=he_normal, regularizer=regularizer) b = tf.get_variable('b', [2048], initializer=tf.constant_initializer(1.0)) out = tf.matmul(self.fc1, w) + b self.fc2 = tf.nn.relu(out) # fc3 with tf.variable_scope('fc3'): w = tf.get_variable('w', [self.fc2.get_shape()[1], num_classes], initializer=initializer, regularizer=regularizer) b = tf.get_variable('b', [num_classes], initializer=tf.constant_initializer(1.0)) self.fc3 = tf.matmul(self.fc2, w) + b
tensorflow.matmul
6,840
import tensorflow as tf # Net loss check_shape([loss_policy, loss_q, entropy], [[]] * 3) loss = loss_policy + self.q_coef * loss_q - self.ent_coef * entropy tf.summary.scalar('entropy_loss', entropy) tf.summary.scalar('policy_gradient_loss', loss_policy) tf.summary.scalar('value_function_loss', loss_q) tf.summary.scalar('loss', loss) norm_grads_q, norm_grads_policy, avg_norm_grads_f = None, None, None avg_norm_k, avg_norm_g, avg_norm_k_dot_g, avg_norm_adj = None, None, None, None
tensorflow.summary.scalar
6,841
import tensorflow as tf eval_metric_ops=eval_metric_ops ) assert mode == tf.estimator.ModeKeys.TRAIN with tf.variable_scope('learning_rate'): global_step = tf.train.get_global_step() learning_rate = tf.train.cosine_decay( params['initial_learning_rate'], global_step, decay_steps=params['num_steps'] ) tf.summary.scalar('learning_rate', learning_rate)
tensorflow.train.cosine_decay
6,842
import tensorflow as tf vname = var.name from_name = vname var_value = tf.contrib.framework.load_variable(MODEL_DIR, from_name) assign_ops.append(tf.assign(var, var_value))
tensorflow.contrib.framework.load_variable
6,843
import tensorflow as tf self._options, self._weight_file, ids_placeholder, embedding_weight_file=self._embedding_weight_file, use_character_inputs=self._use_character_inputs, max_batch_size=self._max_batch_size) ops = self._build_ops(lm_graph) self._ops[ids_placeholder] = ops self._graphs[ids_placeholder] = lm_graph ret = ops return ret def _build_ops(self, lm_graph): with tf.control_dependencies([lm_graph.update_state_op]): # get the LM embeddings token_embeddings = lm_graph.embedding layers = [ tf.concat([token_embeddings, token_embeddings], axis=2) ] n_lm_layers = len(lm_graph.lstm_outputs['forward']) for i in range(n_lm_layers): layers.append( tf.concat( [lm_graph.lstm_outputs['forward'][i], lm_graph.lstm_outputs['backward'][i]], axis=-1 )
tensorflow.control_dependencies
6,844
import tensorflow as tf def file_based_input_fn_builder(input_file, seq_length, is_training, drop_remainder): """Creates an `input_fn` closure to be passed to TPUEstimator.""" 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([], tf.int64), "is_real_example": tf.FixedLenFeature([], tf.int64),
tensorflow.FixedLenFeature
6,845
import tensorflow as tf reduce_instance_dims: By default collapses the batch and instance dimensions to arrive at a single scalar output. If False, only collapses the batch dimension and outputs a vector of the same shape as the input. name: (Optional) A name for this operation. Returns: Two `Tensor`s. Both have the same type as `x`. Raises: TypeError: If the type of `x` is not supported. """ with tf.compat.v1.name_scope(name, 'min_and_max'): output_dtype = x.dtype if (not reduce_instance_dims and isinstance(x, tf.SparseTensor) and x.dtype.is_floating): combine_fn = np.nanmax default_accumulator_value = (np.nan if x.dtype.is_floating else -output_dtype.max) elif not reduce_instance_dims and isinstance(x, tf.RaggedTensor): raise NotImplementedError( 'Elemenwise min_and_max does not support RaggedTensors.') else:
tensorflow.compat.v1.name_scope
6,846
import tensorflow as tf def _attn(q, k, v, train=False, scale=False): #w=[-1,head,n_ctx,n_ctx] w = tf.matmul(q, k) if scale: n_state = shape_list(v)[-1] w = w*tf.rsqrt(tf.cast(n_state, tf.float32)) w = mask_attn_weights(w) w = tf.nn.softmax(w) w = dropout(w, attn_pdrop, train) #w=[-1,head,n_ctx,n_ctx],v=[-1,head,n_ctx,emb] a = tf.matmul(w, v) return a def split_states(x, n): x_shape = shape_list(x) m = x_shape[-1] new_x_shape = x_shape[:-1]+[n, m//n] return tf.reshape(x, new_x_shape) def merge_states(x): x_shape = shape_list(x) new_x_shape = x_shape[:-2]+[np.prod(x_shape[-2:])] return tf.reshape(x, new_x_shape)
tensorflow.matmul
6,847
import tensorflow as tf if not FLAGS.do_train and not FLAGS.do_eval: raise ValueError("At least one of `do_train` or `do_eval` must be True.") bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) tf.gfile.MakeDirs(FLAGS.output_dir) input_files = [] for input_pattern in FLAGS.input_file.split(","): input_files.extend(tf.gfile.Glob(input_pattern)) tf.logging.info("*** Input Files ***") for input_file in input_files: tf.logging.info(" %s" % input_file) tpu_cluster_resolver = None if FLAGS.use_tpu and FLAGS.tpu_name: tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver( FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
tensorflow.gfile.Glob
6,848
import tensorflow as tf masked_lm_ids = tf.reshape(masked_lm_ids, [-1]) masked_lm_weights = tf.reshape(masked_lm_weights, [-1]) masked_lm_accuracy = tf.metrics.accuracy( labels=masked_lm_ids, predictions=masked_lm_predictions, weights=masked_lm_weights, ) masked_lm_mean_loss = tf.metrics.mean( values=masked_lm_example_loss, weights=masked_lm_weights ) next_sentence_log_probs = tf.reshape( next_sentence_log_probs, [-1, next_sentence_log_probs.shape[-1]] ) next_sentence_predictions = tf.argmax( next_sentence_log_probs, axis=-1, output_type=tf.int32 ) next_sentence_labels = tf.reshape(next_sentence_labels, [-1]) next_sentence_accuracy = tf.metrics.accuracy( labels=next_sentence_labels, predictions=next_sentence_predictions ) next_sentence_mean_loss = tf.metrics.mean(
tensorflow.reshape
6,849
import tensorflow as tf self._is_training = is_training self._input = input_ self._rnn_params = None self._cell = None self.batch_size = input_.batch_size self.num_steps = input_.num_steps size = config.hidden_size vocab_size = config.vocab_size with tf.device("/cpu:0"): embedding = tf.get_variable( "embedding", [vocab_size, size], dtype=data_type()) inputs = tf.nn.embedding_lookup(embedding, input_.input_data) if is_training and config.keep_prob < 1: inputs = tf.nn.dropout(inputs, config.keep_prob) output, state = self._build_rnn_graph(inputs, config, is_training) softmax_w = tf.get_variable( "softmax_w", [size, vocab_size], dtype=data_type()) softmax_b = tf.get_variable("softmax_b", [vocab_size], dtype=data_type()) logits = tf.nn.xw_plus_b(output, softmax_w, softmax_b) # Reshape logits to be a 3-D tensor for sequence loss
tensorflow.nn.embedding_lookup
6,850
import tensorflow as tf batch_size = y_pred.shape[0] num_of_joints = y_pred.shape[-1] pred = tf.reshape(tensor=y_pred, shape=(batch_size, -1, num_of_joints)) heatmap_pred_list = tf.split(value=pred, num_or_size_splits=num_of_joints, axis=-1) gt = tf.reshape(tensor=target, shape=(batch_size, -1, num_of_joints)) heatmap_gt_list = tf.split(value=gt, num_or_size_splits=num_of_joints, axis=-1) loss = 0.0 for i in range(num_of_joints): heatmap_pred = tf.squeeze(heatmap_pred_list[i]) heatmap_gt = tf.squeeze(heatmap_gt_list[i])
tensorflow.split
6,851
import tensorflow as tf def _create_regularizers_hook(self, config): wb_regularizers = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) # see keras_utils.py: activity_and_contractive_regularizers ac_regularizers = tf.get_collection(AC_REGULARIZATION) custom_regularizers = tf.get_collection(CUSTOM_REGULARIZATION) if wb_regularizers: wb_regularizers_names = [r.name for r in wb_regularizers] else: wb_regularizers = [tf.zeros([1])] wb_regularizers_names = ["none"] wb_regularizers_fileNames = {"fileName" : "wb_regularizers"} if ac_regularizers: ac_regularizers_names = [r.name for r in ac_regularizers] else: ac_regularizers = [tf.zeros([1])] ac_regularizers_names = ["none"] ac_regularizers_fileNames = {"fileName" : "ac_regularizers"}
tensorflow.zeros
6,852
import tensorflow as tf env = gym.make(ENV_NAME) env.seed(1) STATE_DIM = env.observation_space.shape[0] # 24 ACTION_DIM = env.action_space.shape[0] # 4 ACTION_BOUND = env.action_space.high # [1, 1, 1, 1] # all placeholder for tf with tf.name_scope('S'): S = tf.placeholder(tf.float32, shape=[None, STATE_DIM], name='s') with tf.name_scope('R'): R = tf.placeholder(tf.float32, [None, 1], name='r') with tf.name_scope('S_'): S_ = tf.placeholder(tf.float32, shape=[None, STATE_DIM], name='s_') ############################### Actor #################################### class Actor(object): def __init__(self, sess, action_dim, action_bound, learning_rate, t_replace_iter): self.sess = sess self.a_dim = action_dim self.action_bound = action_bound self.lr = learning_rate
tensorflow.placeholder
6,853
import tensorflow as tf def _SparseTensorValue_1x1x1(self): ind = np.array([[0, 0, 0]]).astype(np.int64) val = np.array([0]).astype(np.int32) shape = np.array([3, 4, 5]).astype(np.int64) return tf.SparseTensorValue(ind, val, shape) def testAddTakeMany(self): with self.test_session(graph=tf.Graph(), use_gpu=False) as sess: sp_input0 = self._SparseTensorValue_5x6(np.arange(6)) sp_input1 = self._SparseTensorValue_3x4(np.arange(6)) handle0 = add_sparse_to_tensors_map(sp_input0, shared_name="a") handle1 = add_sparse_to_tensors_map(sp_input1, shared_name="a") self.assertEqual(handle0.get_shape(), ()) handles_concat = tf.stack([handle0, handle1])
tensorflow.Graph
6,854
import tensorflow as tf if scale > 1: X = self.conv(name + '_downsample', X, filter, scale, scale, (not norm) and use_bias, "VALID", stddev) else: X = self.conv(name + '_conf', X, filter, f_size, 1, (not norm) and use_bias, "VALID", stddev) if norm == 'I': X = tf.contrib.layers.instance_norm(X, scope=scope, reuse=reuse) elif norm == 'B': X = tf.layers.batch_normalization(X, reuse=reuse, training=is_train, name=name) elif norm == 'G': X = tf.contrib.layers.group_norm(X, groups=16, scope=scope, reuse=reuse) if dropout > 0.0: X = tf.layers.dropout(X, dropout, training=is_train) if slope < 1.0: X = tf.nn.leaky_relu(X, slope) if slope > 0.0 else tf.nn.relu(X) return X def decoder_conf(name, X, filter, f_size, scale, norm, reuse, is_train, dropout=0.0, stddev=-1.0, slope=0.00,
tensorflow.contrib.layers.group_norm
6,855
import tensorflow as tf # Lstm Units. self.num_units = 16 def buildLstmLayer(self): return tf.keras.layers.StackedRNNCells([ tf.lite.experimental.nn.TFLiteLSTMCell( self.num_units, use_peepholes=True, forget_bias=1.0, name="rnn1"), tf.lite.experimental.nn.TFLiteLSTMCell( self.num_units, num_proj=8, forget_bias=1.0, name="rnn2"), tf.lite.experimental.nn.TFLiteLSTMCell( self.num_units // 2, use_peepholes=True, num_proj=8, forget_bias=0, name="rnn3"), tf.lite.experimental.nn.TFLiteLSTMCell( self.num_units, forget_bias=1.0, name="rnn4") ])
tensorflow.lite.experimental.nn.TFLiteLSTMCell
6,856
import tensorflow as tf src_features = tf.gather(src_features, indices, axis=0) src_features = tf.stop_gradient(src_features)
tensorflow.stop_gradient
6,857
import tensorflow as tf def get_gtboxes_and_label(self, gtboxes_and_label_h, gtboxes_and_label_r, num_objects): return gtboxes_and_label_h[:, :int(max(num_objects)), :].astype(np.float32), \ gtboxes_and_label_r[:, :int(max(num_objects)), :].astype(np.float32) def main(self): with tf.Graph().as_default() as graph, tf.device('/cpu:0'): num_gpu = len(cfgs.GPU_GROUP.strip().split(',')) global_step = slim.get_or_create_global_step() lr = self.warmup_lr(cfgs.LR, global_step, cfgs.WARM_SETP, num_gpu*cfgs.BATCH_SIZE)
tensorflow.Graph
6,858
import tensorflow as tf batch = 1 rows = 8 cols = 24 block_length = 4 block_width = 2 hparams = tf.contrib.training.HParams( block_raster_scan=True, hidden_size=2, likelihood=likelihood, mode=tf.estimator.ModeKeys.PREDICT, num_mixtures=num_mixtures, query_shape=[block_length, block_width], ) inputs = tf.random_uniform([batch, rows, cols, hparams.hidden_size], minval=-1., maxval=1.) outputs = common_image_attention.postprocess_image( inputs, rows, cols, hparams) num_blocks_rows = rows // block_length num_blocks_cols = cols // block_width self.assertEqual(outputs.shape, (batch, num_blocks_rows, num_blocks_cols, block_length, block_width, depth)) @parameterized.parameters( (common_image_attention.DistributionType.DMOL, 5, 50), (common_image_attention.DistributionType.CAT, None, 256),
tensorflow.random_uniform
6,859
import tensorflow as tf Returns: Path to resulting file. """ if not tf.gfile.Exists(work_directory): tf.gfile.MakeDirs(work_directory) filepath = os.path.join(work_directory, filename) if not tf.gfile.Exists(filepath):
tensorflow.gfile.Exists
6,860
from tensorflow.python.ops import variables def test_categorical_variable(self): random_seed.set_random_seed(42) with self.cached_session() as sess: cat_var_idx = array_ops.placeholder(dtypes.int64, [2, 2]) embeddings = ops.categorical_variable( cat_var_idx, n_classes=5, embedding_size=10, name="my_cat_var") sess.run(variables.global_variables_initializer()) emb1 = sess.run(embeddings, feed_dict={cat_var_idx.name: [[0, 1], [2, 3]]}) emb2 = sess.run(embeddings, feed_dict={cat_var_idx.name: [[0, 2], [1, 3]]}) self.assertEqual(emb1.shape, emb2.shape) self.assertAllEqual(np.transpose(emb2, axes=[1, 0, 2]), emb1)
tensorflow.python.ops.variables.global_variables_initializer
6,861
import tensorflow as tf tf.identity(truncated_learning_rate, name='learning_rate') tf.summary.scalar('learning_rate', truncated_learning_rate) optimizer = tf.train.MomentumOptimizer(learning_rate=truncated_learning_rate, momentum=params['momentum'])
tensorflow.train.MomentumOptimizer
6,862
import tensorflow as tf None, ] + tu.shape_to_tf_shape(input_shape), "INPUT1") # If the input is a string, then convert each string to the # equivalent int32 value. if tf_input_dtype == tf.string: in0 = tf.strings.to_number(in0, tf.int32) in1 = tf.strings.to_number(in1, tf.int32) add = tf.add(in0, in1, "ADD") sub = tf.subtract(in0, in1, "SUB") # Cast or convert result to the output dtype. if tf_output0_dtype == tf.string:
tensorflow.strings.to_number
6,863
import tensorflow as tf Parameters ---------- x: Tensor or variable. y: Tensor or variable. Returns ------- A tensor, dot product of x and y. """ if get_ndim(x) is not None and (get_ndim(x) > 2 or get_ndim(y) > 2): x_shape = [] for i, s in zip(int_shape(x), tf.unstack(tf.shape(x))): if i is not None: x_shape.append(i) else: x_shape.append(s) x_shape = tuple(x_shape) y_shape = [] for i, s in zip(int_shape(y), tf.unstack(tf.shape(y))): if i is not None: y_shape.append(i) else: y_shape.append(s)
tensorflow.shape
6,864
import tensorflow as tf batch_size = input_shape[0] passage_len = input_shape[1] with variable_scope.variable_scope("attention_decoder"): encoder_features = tf.expand_dims(encoder_states, axis=2) # now is shape [batch_size, passage_len, 1, encoder_dim] W_h = variable_scope.get_variable("W_h", [1, 1, encoder_dim, options.attention_vec_size]) self.W_h = W_h encoder_features = nn_ops.conv2d(encoder_features, W_h, [1, 1, 1, 1], "SAME") # [batch_size, passage_len, 1, attention_vec_size]
tensorflow.expand_dims
6,865
import tensorflow as tf counter = tf.Variable( 0, name="counter", trainable=False, dtype=tf.int32) with tf.name_scope('AccumGradOptimizer'): ops = [] for s, gv in zip(slots, grads_and_vars): g, v = gv ops.append(s.assign_add(g)) update_counter = tf.assign_add(counter, 1, name='update_counter') update_slot_op = tf.group(update_counter, *ops, name='update_slot') def update_grad(): update_op = self._opt.apply_gradients(slots_and_vars) with tf.control_dependencies([update_op]): clear_ops = [tf.assign(s, tf.zeros_like(s)) for s in slots] return tf.group(*clear_ops, name='update_grad') pred = tf.equal(tf.mod(counter, self._niter), 0) with tf.control_dependencies([update_slot_op]): if name is None: name = 'cond_update_grad' op = tf.cond(pred, update_grad, tf.no_op, name=name).op return op if __name__ == '__main__': # run it with "python -m tensorpack.tfutils.optimizer" x = tf.get_variable('x', shape=[6]) cost = tf.reduce_sum(tf.abs(x), name='cost')
tensorflow.group
6,866
import tensorflow as tf """ parameters = dict(locals()) # Convert the covariance_matrix up to a scale_tril and call MVNTriL. with tf.name_scope(name) as name: with tf.name_scope("init", values=[loc, covariance_matrix]): dtype = dtype_util.common_dtype([loc, covariance_matrix], tf.float32) loc = loc if loc is None else tf.convert_to_tensor( loc, name="loc", dtype=dtype) if covariance_matrix is None:
tensorflow.name_scope
6,867
import tensorflow as tf # Performance tuning flags. tf.flags.DEFINE_boolean('winograd_nonfused', True, """Enable/disable using the Winograd non-fused
tensorflow.flags.DEFINE_boolean
6,868
import tensorflow as tf step = tf.to_float(global_step) warmup_steps = tf.to_float(params.warmup_steps)
tensorflow.to_float
6,869
import tensorflow as tf def _float_feature(value): return tf.train.Feature(float_list=tf.train.FloatList(value=value.flatten())) def _bytes_feature(value): if isinstance(value, str): value = value.encode('utf-8') return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def make_tf_example(d): feature = { 'bounding_box_samples': _float_feature(d['bounding_box_samples']), 'depth_renders': _float_feature(d['depth_renders']),
tensorflow.train.BytesList
6,870
import tensorflow as tf if batch_size == num_tasks: indices = tf.transpose(tf.stack([orig_indices, orig_indices], axis=0))
tensorflow.stack
6,871
import tensorflow as tf best_target_per_prior_index = tf.tensor_scatter_nd_update(best_target_per_prior_index, tf.expand_dims(best_prior_per_target_index, 1), targets) # 2.0 is used to make sure every target has a prior assigned best_target_per_prior = tf.tensor_scatter_nd_update(best_target_per_prior, tf.expand_dims(best_prior_per_target_index, 1), tf.ones_like(best_prior_per_target_index, dtype=tf.float32)*2.0) # size: num_priors labels = tf.gather(gt_labels, best_target_per_prior_index) labels = tf.where(tf.less(best_target_per_prior, iou_threshold), tf.constant(0, dtype='int64'), labels) # labels[best_target_per_prior < iou_threshold] = 0 # the backgournd id
tensorflow.gather
6,872
import tensorflow as tf # Saver with no arg, defaults to 'all variables'. save = tf.train.Saver()
tensorflow.train.Saver
6,873
import tensorflow as tf self._p = p def _compute(self, x, y): self._dim = x._rank() kernel = np.zeros((tf.size(x), tf.size(y))) for l in tf.range(start=0, limit=tf.size(x), delta=1, dtype=None, name='l_range'): for m in tf.range(start=0, limit=tf.size(y), delta=1, dtype=None, name='m_range'):
tensorflow.size
6,874
import tensorflow as tf anchor_match_negative_indicator_matrix = tf.math.logical_not( tf.eye(num_anchors, dtype=tf.bool))
tensorflow.eye
6,875
import tensorflow as tf 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) layer_a2 = tf.layers.dense(layer_a1, 256, tf.nn.relu, kernel_regularizer=reg) mu = tf.layers.dense(layer_a2, self.a_dim, tf.nn.tanh, kernel_regularizer=reg) # sigma = tf.layers.dense(layer_a2, self.a_dim, tf.nn.softplus, kernel_regularizer=reg) sigma = tf.get_variable(name='pi_sigma', shape=self.a_dim, initializer=tf.constant_initializer(0.5)) sigma = tf.clip_by_value(sigma, 0.0, 1.0) norm_dist = tf.distributions.Normal(loc=mu * self.a_bound, scale=sigma) params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=name) return norm_dist, params
tensorflow.constant_initializer
6,876
import tensorflow as tf sub_loop(keypoint_model_fn, m, detail_params[m]['model_dir'], run_config, detail_params[m]['train_epochs'], detail_params[m]['epochs_per_eval'], detail_params[m]['lr_decay_factors'], detail_params[m]['decay_boundaries'], detail_params[m]['checkpoint_path'], detail_params[m]['checkpoint_exclude_scopes'], detail_params[m]['checkpoint_model_scope'], detail_params[m]['ignore_missing_vars']) if __name__ == '__main__': tf.logging.set_verbosity(tf.logging.INFO) tf.app.run()
tensorflow.logging.set_verbosity
6,877
import tensorflow as tf 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): self.learning_rate = tf.placeholder(tf.float32) self.d_optimizer = tf.train.AdamOptimizer(self.learning_rate,beta1=self.beta1,beta2=self.beta2).minimize(self.discriminator_loss,var_list=self.d_variables) self.g_optimizer = tf.train.AdamOptimizer(self.learning_rate,beta1=self.beta1,beta2=self.beta2).minimize(self.generator_loss,var_list=self.g_variables) self.init_op = tf.global_variables_initializer() self.sess = tf.Session() self.sess.run(self.init_op) #self.dataset_dir = '/home/santanu/Downloads/DiscoGAN/edges2handbags/train/' self.writer = tf.summary.FileWriter("./logs", self.sess.graph) count = 1 start_time = time.time() for epoch in range(self.epoch): data_A = os.listdir(self.dataset_dir + 'trainA/') data_B = os.listdir(self.dataset_dir + 'trainB/') data_A = [ (self.dataset_dir + 'trainA/' + str(file_name)) for file_name in data_A ]
tensorflow.Session
6,878
import tensorflow as tf mask = np.expand_dims(mask, 0) print(image.shape) print(mask.shape) input_image = np.concatenate([image, mask], axis=2) print(input_image.shape) sess_config = tf.ConfigProto() sess_config.gpu_options.allow_growth = True with tf.Session(config=sess_config) as sess: input_image = tf.constant(input_image, dtype=tf.float32) output = MODEL.build_server_graph(FLAGS, input_image) output = (output + 1.) * 127.5 output = tf.reverse(output, [-1]) output = tf.saturate_cast(output, tf.uint8) # load pretrained model vars_list = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES) assign_ops = [] for var in vars_list:
tensorflow.constant
6,879
import tensorflow as tf def compile_data(tmp_dir, datasets, filename): """Concatenate all `datasets` and save to `filename`.""" filename = os.path.join(tmp_dir, filename) # lang1_fname = filename + ".lang1" # lang2_fname = filename + ".lang2" lang1_fname = filename + ".source" lang2_fname = filename + ".target" if tf.gfile.Exists(lang1_fname) and tf.gfile.Exists(lang2_fname): tf.logging.info("Skipping compile data, found files:\n%s\n%s", lang1_fname, lang2_fname) return filename with tf.gfile.GFile(lang1_fname, mode="w") as lang1_resfile: with tf.gfile.GFile(lang2_fname, mode="w") as lang2_resfile: for dataset in datasets: url = dataset[0] compressed_filename = os.path.basename(url) compressed_filepath = os.path.join(tmp_dir, compressed_filename) if url.startswith("http"):
tensorflow.logging.info
6,880
from tensorflow.python.ops import variable_scope options = self.options with variable_scope.variable_scope("attention_decoder"): v = variable_scope.get_variable("v", [options.attention_vec_size]) v = tf.expand_dims(tf.expand_dims(v, axis=0), axis=0) w_c = None if options.use_coverage: with variable_scope.variable_scope("coverage"): w_c = variable_scope.get_variable("w_c", [options.attention_vec_size]) w_c = tf.expand_dims(tf.expand_dims(w_c, axis=0), axis=0) word_t_representation = self.embedding_lookup(word_t) (state_t, context_t, coverage_t, attn_dist_t, p_gen_t, output_t) = self.one_step_decoder( state_t_1, context_t_1, coverage_t_1, word_t_representation, encoder_states, encoder_features, passage_word_idx, passage_mask, v, w_c, word_vocab)
tensorflow.python.ops.variable_scope.get_variable
6,881
import tensorflow as tf layer_idx=1) if self.batch_norm: with tf.variable_scope( 'l3_h2_bn',
tensorflow.variable_scope
6,882
import tensorflow as tf 'WS: pruning ratio protocol (\'uniform\' | \'heurist\' | \'optimal\')') tf.app.flags.DEFINE_integer('ws_nb_rlouts', 200, 'WS: # of roll-outs for the RL agent') tf.app.flags.DEFINE_integer('ws_nb_rlouts_min', 50, 'WS: minimal # of roll-outs for the RL agent to start training') tf.app.flags.DEFINE_string('ws_reward_type', 'single-obj', 'WS: reward type (\'single-obj\' OR \'multi-obj\')') tf.app.flags.DEFINE_float('ws_lrn_rate_rg', 3e-2, 'WS: learning rate for layerwise regression') tf.app.flags.DEFINE_integer('ws_nb_iters_rg', 20, 'WS: # of iterations for layerwise regression') tf.app.flags.DEFINE_float('ws_lrn_rate_ft', 3e-4, 'WS: learning rate for global fine-tuning') tf.app.flags.DEFINE_integer('ws_nb_iters_ft', 400, 'WS: # of iterations for global fine-tuning') tf.app.flags.DEFINE_integer('ws_nb_iters_feval', 25, 'WS: # of iterations for fast evaluation') tf.app.flags.DEFINE_float('ws_prune_ratio_exp', 3.0, 'WS: pruning ratio\'s exponent term') tf.app.flags.DEFINE_float('ws_iter_ratio_beg', 0.1, 'WS: iteration ratio (at starting time)') tf.app.flags.DEFINE_float('ws_iter_ratio_end', 0.5, 'WS: iteration ratio (at ending time)') tf.app.flags.DEFINE_float('ws_mask_update_step', 500, 'WS: step size for updating the pruning mask') def calc_prune_ratio(vars_list): """Calculate the overall pruning ratio for the given list of variables.
tensorflow.app.flags.DEFINE_integer
6,883
from tensorflow.python.ops import math_ops # term from the formula above. # `relevant_precision_per_k` (float64) - Relevant precisions; i.e., # precisions at all k for which relevance indicator is true. relevant_per_k = _sparse_true_positive_at_k( predictions_idx_per_k, labels_per_k, name='relevant_per_k') tp_per_k = math_ops.cumsum(relevant_per_k, axis=-1, name='tp_per_k') retrieved_per_k = math_ops.cumsum( array_ops.ones_like(relevant_per_k), axis=-1, name='retrieved_per_k') precision_per_k = math_ops.div( math_ops.to_double(tp_per_k), math_ops.to_double(retrieved_per_k),
tensorflow.python.ops.math_ops.cumsum
6,884
import tensorflow as tf x = tf.transpose(observations, [0, 2, 3, 1, 4]) x_shape = common_layers.shape_list(x) x = tf.reshape(x, x_shape[:-2] + [-1]) dropout = getattr(self.hparams, "dropout_ppo", 0.0) with tf.variable_scope("feed_forward_cnn_small"): x = tf.cast(x, tf.float32) / 255.0 x = tf.nn.dropout(x, rate=dropout) x = tf.layers.conv2d( x, 32, (4, 4), strides=(2, 2), name="conv1", activation=common_layers.belu, padding="SAME") x = tf.nn.dropout(x, rate=dropout) x = tf.layers.conv2d( x, 64, (4, 4), strides=(2, 2), name="conv2", activation=common_layers.belu, padding="SAME") x = tf.nn.dropout(x, rate=dropout) x = tf.layers.conv2d( x, 128, (4, 4), strides=(2, 2), name="conv3", activation=common_layers.belu, padding="SAME") flat_x = tf.layers.flatten(x)
tensorflow.nn.dropout
6,885
from tensorflow.contrib.slim.python.slim import queues with session.Session('') as sess: with queues.QueueRunners(sess):
tensorflow.contrib.slim.python.slim.queues.QueueRunners
6,886
import tensorflow as tf def _to_dataset(x, dtype=tf.int32): x = tf.ragged.constant(x, dtype=dtype) d = tf.data.Dataset.from_tensor_slices(x) d = d.map(lambda x: x)
tensorflow.data.Dataset.from_tensor_slices
6,887
from tensorflow.python.ops import array_ops b_list = [b[i] for i in range(numTensors)] b_grads = b_module.bspmm(a_indices, a_values, a_shape, grad, adjoint_a=True, adjoint_b=False) 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.array_ops.transpose
6,888
import tensorflow as tf batch_size = tf.shape(attention_weights)[0] src_len = tf.shape(attention_weights)[2]
tensorflow.shape
6,889
import tensorflow as tf else: log_probs = tf.nn.log_softmax(logits, axis=-1) label_ids = tf.reshape(label_ids, [-1]) label_weights = tf.reshape(label_weights, [-1])
tensorflow.reshape
6,890
import tensorflow as tf def evaluate_spherical_harmonics( degree_l: TensorLike, order_m: TensorLike, theta: TensorLike, phi: TensorLike, name: str = "spherical_harmonics_evaluate_spherical_harmonics") -> TensorLike: # pylint: disable=line-too-long with tf.name_scope(name): degree_l = tf.convert_to_tensor(value=degree_l) order_m = tf.convert_to_tensor(value=order_m) theta = tf.convert_to_tensor(value=theta) phi = tf.convert_to_tensor(value=phi) var_type = theta.dtype sign_m = tf.math.sign(order_m) order_m = tf.abs(order_m) zeros = tf.zeros_like(order_m) result_m_zero = _spherical_harmonics_normalization(
tensorflow.convert_to_tensor
6,891
import tensorflow as tf v1 = sess.graph.get_tensor_by_name("v1:0") self.assertEqual(11.0, v1.eval()) def testMultiSaverCollection(self): self._testMultiSaverCollectionSave() self._testMultiSaverCollectionRestore() def testBinaryAndTextFormat(self): test_dir = self._TestDir("binary_and_text") filename = os.path.join(test_dir, "metafile") with self.test_session(graph=tf.Graph()): # Creates a graph. tf.Variable(10.0, name="v0") # Exports the graph as binary format. tf.train.export_meta_graph(filename, as_text=False) with self.test_session(graph=tf.Graph()): # Imports the binary format graph. saver = tf.train.import_meta_graph(filename) # Exports the graph as text format. saver.export_meta_graph(filename, as_text=True) with self.test_session(graph=tf.Graph()): # Imports the text format graph. tf.train.import_meta_graph(filename) # Writes wrong contents to the file. tf.train.write_graph(saver.as_saver_def(), os.path.dirname(filename), os.path.basename(filename)) with self.test_session(graph=tf.Graph()): # Import should fail. with self.assertRaisesWithPredicateMatch( IOError, lambda e: "Cannot parse file"):
tensorflow.Graph
6,892
import tensorflow as tf """ box1 = box1.numpy() if isinstance(box1, tf.Tensor) else box1 box2 = box2.numpy() if isinstance(box2, tf.Tensor) else box2 box1 = box1.astype(np.float32) box2 = box2.astype(np.float32) # rotates around z, while we rotate around y so need to swap center_1 = tf.reshape(box1[0:3][[0, 2, 1]], [1, 3]) center_2 = tf.reshape(box2[0:3][[0, 2, 1]], [1, 3]) rotation_z_1 = tf.reshape(box1[-1], [1]) rotation_z_2 = tf.reshape(box2[-1], [1]) length_1 = tf.reshape(box1[3 + 0], [1]) height_1 = tf.reshape(box1[3 + 2], [1]) width_1 = tf.reshape(box1[3 + 1], [1]) length_2 = tf.reshape(box2[3 + 0], [1]) height_2 = tf.reshape(box2[3 + 2], [1]) width_2 = tf.reshape(box2[3 + 1], [1]) iou = np.squeeze(np_box_ops.iou3d_7dof_box( length_1, height_1, width_1, center_1, rotation_z_1, length_2, height_2, width_2, center_2, rotation_z_2)) return iou
tensorflow.reshape
6,893
import tensorflow as tf tf.summary.scalar(scope+'/loss', loss) return loss def accuracy(logits, labels): ''' Evaluate the quality of the logits at predicting the label ''' # for summary with tf.name_scope('accuracy') as scope: correct = tf.equal(tf.arg_max(logits,1), tf.arg_max(labels,1)) correct = tf.cast(correct, tf.float32) accuracy = tf.reduce_mean(correct)*100.0 tf.summary.scalar(scope+'accuracy',accuracy) return accuracy def num_correct_prediction(logits, labels): ''' Evaluate the quality of the logits at predicting the label ''' correct = tf.equal(tf.arg_max(logits,1), tf.arg_max(labels,1))
tensorflow.cast
6,894
import tensorflow as tf 'adj': tf.sparse_placeholder(tf.float32), 'adj_orig': tf.sparse_placeholder(tf.float32),
tensorflow.sparse_placeholder
6,895
from tensorflow.contrib import layers nn_activations = [layers.fully_connected(data, self.params.layer_size)] for _ in range(1, self.params.num_layers): # pylint: disable=W0106 nn_activations.append( layers.fully_connected( nn_activations[-1], self.params.layer_size)) nn_activations_tensor = array_ops.concat(
tensorflow.contrib.layers.fully_connected
6,896
import tensorflow as tf images, labels = input_name.build_input( FLAGS.dataset, FLAGS.eval_data_path, hps.batch_size, FLAGS.mode) # FLAGS.mode='attack', batch_size=200 Res = model_name.ResNet(hps, images, FLAGS.mode, Reuse=False) Res.build_graph() saver = tf.train.Saver() adv_images = adv_craft_func(hps, images, FLAGS.attack_method, eps=FLAGS.eps, RCE_train=FLAGS.RCE_train) model_nor = model_name.ResNet(hps, images, FLAGS.mode, Reuse=True) model_nor.build_graph()
tensorflow.train.Saver
6,897
import tensorflow as tf # Recompute rewards and done flags states, tasks = self._task_distribution.split(experience.observation[:, 0]) next_states, next_tasks = self._task_distribution.split( experience.observation[:, 1]) rewards, dones = self._task_distribution.evaluate(states, experience.action[:, 0], tasks) # Strictly speaking, we don't need to relabel the next rewards and next # dones because they end up being thrown away. Only the current rewards # and dones end up being important. next_rewards, next_dones = self._task_distribution.evaluate( next_states, experience.action[:, 1], next_tasks) new_rewards = tf.concat([rewards[:, None], next_rewards[:, None]], axis=1) new_dones = tf.concat([dones[:, None], next_dones[:, None]], axis=1) # 0 if episode is done, 1 if episode is continuing new_discount = 1.0 - tf.cast(new_dones, tf.float32) assert new_rewards.shape == experience.reward.shape assert new_discount.shape == experience.discount.shape experience = experience.replace(reward=new_rewards, discount=new_discount) return experience def _soft_relabel(self, experience): """Reassigns tasks to each state and next state. Does not recompute the rewards or done flags.
tensorflow.concat
6,898
import tensorflow as tf self.dropout_output = args.dropout_output self.dropout_input = args.dropout_input self.clip_norm = args.clip_norm self.embedding_init = embedding_init self.x = tf.placeholder(tf.int32, [None, None], 'input') self.y = tf.placeholder(tf.int32, [None, self.num_classes], 'labels') self.seq_len = tf.placeholder(tf.int64, [None], 'input_length') def inference(self, forward_only=None): embed_inputs = tf.nn.embedding_lookup(self.embedding_init, self.x) ## (batch_size, seq_len, 100) with tf.variable_scope('hidden', reuse=forward_only): with tf.variable_scope('lstm_cell'): lstm_cell = tf.nn.rnn_cell.LSTMCell(num_units=self.num_hidden, use_peepholes=False, # forget_bias=0.0, activation=tf.nn.relu, # initializer=tf.truncated_normal_initializer(stddev=0.1), # initializer=tf.random_uniform_initializer(-0.003, 0.003), initializer=tf.contrib.layers.xavier_initializer(), state_is_tuple=True) if not forward_only:
tensorflow.nn.embedding_lookup
6,899