seed
stringlengths
25
2.89k
seed_api
stringlengths
14
102
index
int64
0
14.8k
import tensorflow as tf self.c_maxlen = tf.reduce_max(self.c_len) self.q_maxlen = tf.reduce_max(self.q_len) self.c = tf.slice(self.c, [0, 0], [N, self.c_maxlen]) self.q = tf.slice(self.q, [0, 0], [N, self.q_maxlen]) self.c_mask = tf.slice(self.c_mask, [0, 0], [N, self.c_maxlen]) self.q_mask = tf.slice(self.q_mask, [0, 0], [N, self.q_maxlen]) self.ch = tf.slice(self.ch, [0, 0, 0], [N, self.c_maxlen, CL]) self.qh = tf.slice(self.qh, [0, 0, 0], [N, self.q_maxlen, CL]) self.y1 = tf.argmax(tf.slice(self.y1, [0, 0], [N, self.c_maxlen]),axis=-1) self.y2 = tf.argmax(tf.slice(self.y2, [0, 0], [N, self.c_maxlen]),axis=-1)
tensorflow.slice
1,500
import tensorflow as tf ) self.loss = loss_action + loss_arguments tf.scalar_summary('loss', self.loss) with tf.name_scope('accuracy'): correct_prediction_action = tf.equal( tf.argmax(one_hot_labels_action, 1), tf.argmax(self.predictions_action, 1) ) self.accuracy_action = tf.reduce_mean(tf.cast(correct_prediction_action, 'float'))
tensorflow.name_scope
1,501
import tensorflow as tf ns3 = 2 # with tf.variable_scope("conv_context") as scope: def encode(img): img_h0 = lrelu(conv2d(img, nf0, d_h=ns0, d_w=ns0, name='h0_conv')) img_h1 = lrelu(conv2d(img_h0, nf1, d_h=ns1, d_w=ns1, name='h1_conv')) img_h2 = lrelu(conv2d(img_h1, nf2, d_h=ns2, d_w=ns2, name='h2_conv')) img_h3 = lrelu(conv2d(img_h2, nf3, d_h=ns3, d_w=ns3, name='h3_conv')) print(img_h3.get_shape()) img_h4 = lrelu(linear(tf.nn.dropout(tf.reshape(img_h3, [self.batch_size, -1]), keep_prob), featsize, 'h4_lin')) img_z = lrelu(linear(tf.nn.dropout(img_h4, keep_prob), featsize, 'hz_lin')) return img_h0, img_h1, img_h2, img_h3, img_h4, img_z with tf.variable_scope("conv") as scope: srcimg_h0, srcimg_h1, srcimg_h2, srcimg_h3, srcimg_h4, srcimg_z = encode(srcimg) scope.reuse_variables() tgtimg_h0, tgtimg_h1, tgtimg_h2, tgtimg_h3, tgtimg_h4, tgtimg_z = encode(tgtimg) tgtctx_h0, tgtctx_h1, tgtctx_h2, tgtctx_h3, tgtctx_h4, tgtctx_z = encode(tgtctx)
tensorflow.reshape
1,502
import tensorflow as tf else: train= False init = tf.ones_initializer()
tensorflow.ones_initializer
1,503
from tensorflow.python.platform import gfile 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) # Created by the first helper. self.assertTrue(gfile.Exists(s1))
tensorflow.python.platform.gfile.Exists
1,504
import tensorflow as tf vector_batch_as_matricies = tf.expand_dims(vector, [1]) mult_result = tf.matmul(vector_batch_as_matricies, matrix) squeezed_result = tf.squeeze(mult_result, [1]) return squeezed_result def euclidean_loss_layer(a, b, multiplier=100.0, use_l1=False, eps=0.01): """ Math: out = (action - mlp_out)'*precision*(action-mlp_out) = (u-uhat)'*A*(u-uhat)""" multiplier = tf.constant(multiplier, dtype='float') #for bc #10000 uP =a*multiplier-b*multiplier if use_l1: return tf.reduce_mean(eps*tf.square(uP) + tf.abs(uP)) return tf.reduce_mean(tf.square(uP)) def conv2d(img, w, b, strides=[1, 1, 1, 1], is_dilated=False): if is_dilated:
tensorflow.constant
1,505
import tensorflow as tf >>> y = tf.nn.relu(tf.matmul(inputs, W) + b) Notes ----- If the layer input has more than two axes, it needs to be flatten by using :class:`FlattenLayer`. """ @deprecated_alias(layer='prev_layer', end_support_version=1.9) # TODO remove this line for the 1.9 release def __init__( self, prev_layer, n_units=100, act=tf.identity, W_init=tf.truncated_normal_initializer(stddev=0.1), b_init=tf.constant_initializer(value=0.0), W_init_args=None, b_init_args=None, name='dense', ): super(DenseLayer, self).__init__(prev_layer=prev_layer, name=name) logging.info("DenseLayer %s: %d %s" % (name, n_units, act.__name__)) self.inputs = prev_layer.outputs self.n_units = n_units if W_init_args is None: W_init_args = {} if b_init_args is None:
tensorflow.constant_initializer
1,506
from tensorflow.python.framework import ops name: `String`. The name prepended to Ops created by this class. Raises: ValueError: if either `batch_ndims` or `event_ndims` are: `None`, negative, not `int32`. """ if batch_ndims is None: raise ValueError("batch_ndims cannot be None") if event_ndims is None: raise ValueError("event_ndims cannot be None") self._batch_ndims = batch_ndims self._event_ndims = event_ndims self._validate_args = validate_args with ops.name_scope(name) as ns: self._name = ns with ops.name_scope("init"): self._batch_ndims = self._assert_non_negative_int32_scalar( ops.convert_to_tensor( batch_ndims, name="batch_ndims")) self._batch_ndims_static, self._batch_ndims_is_0 = ( self._introspect_ndims(self._batch_ndims)) self._event_ndims = self._assert_non_negative_int32_scalar( ops.convert_to_tensor( event_ndims, name="event_ndims")) self._event_ndims_static, self._event_ndims_is_0 = ( self._introspect_ndims(self._event_ndims)) @property def name(self): """Name given to ops created by this class.""" return self._name
tensorflow.python.framework.ops.convert_to_tensor
1,507
import tensorflow as tf # We use as_list since TensorShape comparison does not work correctly for # unknown values, ie, Dimension(None). self.assertAllEqual([6, 7, 2, 3, 5], y.shape.as_list()) x = tf.placeholder_with_default( input=np.ones((6, 7, 2, 3, 5), dtype=np.float32), shape=None) dist = fake_distribution(batch_shape=[None, 3], event_shape=[5]) sample_shape = tf.convert_to_tensor([6, 7], dtype=tf.int32) y = dist._set_sample_static_shape(x, sample_shape) self.assertAllEqual([6, 7, None, 3, 5], y.shape.as_list()) x = tf.placeholder_with_default( input=np.ones((6, 7, 2, 3, 5), dtype=np.float32), shape=None) dist = fake_distribution(batch_shape=[None, 3], event_shape=[None])
tensorflow.convert_to_tensor
1,508
import tensorflow as tf with tf.device('/cpu:0'), tf.name_scope("embedding"): if use_he_uniform: self.embedding_W = tf.get_variable(name='lookup_W', shape=[num_quantized_chars, embedding_size], initializer=tf.contrib.layers.variance_scaling_initializer()) else: self.embedding_W = tf.Variable(tf.random_uniform([num_quantized_chars, embedding_size], -1.0, 1.0),name="embedding_W") self.embedded_characters = tf.nn.embedding_lookup(self.embedding_W, self.input_x) 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)
tensorflow.nn.embedding_lookup
1,509
from tensorflow.contrib.eager.python.examples.linear_regression import linear_regression batch_size=batch_size, num_batches=num_batches) burn_in_dataset = dataset.take(10) model = linear_regression.LinearModel() with tf.device(device()): optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1)
tensorflow.contrib.eager.python.examples.linear_regression.linear_regression.LinearModel
1,510
import tensorflow as tf self.a_grads = tf.gradients(self.q, a)[0] # tensor of gradients of each sample (None, a_dim) def _build_net(self, s, a, scope, trainable): with tf.variable_scope(scope): init_w = tf.random_normal_initializer(0., 0.01) init_b = tf.constant_initializer(0.01) with tf.variable_scope('l1'): n_l1 = 700 # combine the action and states together in this way w1_s = tf.get_variable('w1_s', [self.s_dim, n_l1], initializer=init_w, trainable=trainable) w1_a = tf.get_variable('w1_a', [self.a_dim, n_l1], initializer=init_w, trainable=trainable) b1 = tf.get_variable('b1', [1, n_l1], initializer=init_b, trainable=trainable) net = tf.nn.relu(tf.matmul(s, w1_s) + tf.matmul(a, w1_a) + b1) with tf.variable_scope('l2'): net = tf.layers.dense(net, 20, activation=tf.nn.relu, kernel_initializer=init_w, bias_initializer=init_b, name='l2', trainable=trainable) with tf.variable_scope('q'): q = tf.layers.dense(net, 1, kernel_initializer=init_w, bias_initializer=init_b, trainable=trainable) # Q(s,a) return q def learn(self, s, a, r, s_, ISW): _, abs_td = self.sess.run([self.train_op, self.abs_td], feed_dict={S: s, self.a: a, R: r, S_: s_, self.ISWeights: ISW}) if self.t_replace_counter % self.t_replace_iter == 0: self.sess.run([tf.assign(t, e) for t, e in zip(self.t_params, self.e_params)]) self.t_replace_counter += 1
tensorflow.matmul
1,511
import tensorflow as tf # print("----y_conv-----") # print(y_conv) # exit() # Exchange dim 1 and dim 0 # Start at: [0,1,2] = [batch_size, 128, 9] => [batch_size, 32, 36] feature_mat = tf.transpose(feature_mat, [1, 0, 2]) # New feature_mat's shape: [time_steps, batch_size, n_inputs] [128, batch_size, 9] print("----feature_mat-----") print(feature_mat) # exit() # Temporarily crush the feature_mat's dimensions feature_mat = tf.reshape(feature_mat, [-1, config.n_inputs]) # 9 # New feature_mat's shape: [time_steps*batch_size, n_inputs] # 128 * batch_size, 9 # Linear activation, reshaping inputs to the LSTM's number of hidden: hidden = tf.nn.relu(tf.matmul( feature_mat, config.W['hidden'] ) + config.biases['hidden']) # New feature_mat (hidden) shape: [time_steps*batch_size, n_hidden] [128*batch_size, 32] print("--n_steps--") print(config.n_steps) print("--hidden--") print(hidden)
tensorflow.reshape
1,512
from tensorflow.contrib.eager.python.examples.l2hmc import l2hmc tf.reset_default_graph() with tf.Graph().as_default(): energy_fn, _, _ = l2hmc.get_scg_energy_fn() x = tf.random_normal([hparams.n_samples, hparams.x_dim],
tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.get_scg_energy_fn
1,513
import tensorflow as tf # Deletes the file gfile.Remove(filename) with self.assertRaisesWithPredicateMatch( IOError, lambda e: "does not exist"): tf.train.import_meta_graph(filename) def testSliceVariable(self): test_dir = self._TestDir("slice_saver") filename = os.path.join(test_dir, "metafile") with self.test_session(): v1 = tf.Variable([20.0], name="v1") v2 = tf.Variable([20.0], name="v2") v2._set_save_slice_info(tf.Variable.SaveSliceInfo("v1", [1], [0], [1])) # The names are different and will work. slice_saver = tf.train.Saver({"first": v1, "second": v2}) tf.initialize_all_variables().run() # Exports to meta_graph meta_graph_def = slice_saver.export_meta_graph(filename) with tf.Graph().as_default(): # Restores from MetaGraphDef. new_saver = tf.train.import_meta_graph(filename) # Generates a new MetaGraphDef. new_meta_graph_def = new_saver.export_meta_graph() # It should be the same as the original. self.assertProtoEquals(meta_graph_def, new_meta_graph_def) def _testGraphExtensionSave(self): test_dir = self._TestDir("graph_extension")
tensorflow.train.Saver
1,514
from tensorflow.python.ops import state_ops weighted_predictions = predictions * weights weighted_labels = labels * weights update_count = state_ops.assign_add(count, batch_count) # n_AB in eqn prev_count = update_count - batch_count # n_A in update equation # We update the means by Delta=Error*BatchCount/(BatchCount+PrevCount) # batch_mean_prediction is E[x_B] in the update equation batch_mean_prediction = _safe_div( math_ops.reduce_sum(weighted_predictions), batch_count, 'batch_mean_prediction') delta_mean_prediction = _safe_div( (batch_mean_prediction - mean_prediction) * batch_count, update_count, 'delta_mean_prediction') update_mean_prediction = state_ops.assign_add(mean_prediction, delta_mean_prediction) # prev_mean_prediction is E[x_A] in the update equation prev_mean_prediction = update_mean_prediction - delta_mean_prediction # batch_mean_label is E[y_B] in the update equation batch_mean_label = _safe_div( math_ops.reduce_sum(weighted_labels), batch_count, 'batch_mean_label') delta_mean_label = _safe_div((batch_mean_label - mean_label) * batch_count, update_count, 'delta_mean_label') update_mean_label = state_ops.assign_add(mean_label, delta_mean_label) # prev_mean_label is E[y_A] in the update equation prev_mean_label = update_mean_label - delta_mean_label
tensorflow.python.ops.state_ops.assign_add
1,515
import tensorflow as tf initializer=tf.truncated_normal_initializer(stddev=stddev)) self.b = tf.get_variable('b',[output_dim], initializer=tf.constant_initializer(0.0)) self.strides = [1,1,1] self.dilates = [d_t, d_h, d_w] def __call__(self,input_var,name=None) : k_t,k_h,k_w,_,_ = self.w.get_shape().as_list() _t = tf.pad(input_var, [[0,0],[0,0],[k_h//2,k_h//2],[k_w//2,k_w//2],[0,0]], "SYMMETRIC") return tf.nn.bias_add( tf.nn.convolution(_t, self.w, strides=self.strides, dilation_rate=self.dilates, padding='VALID'), self.b,name=name)
tensorflow.pad
1,516
import tensorflow as tf with tf.variable_scope(scope): V = tf.get_variable('V', shape=list(filter_size) + [int(x.get_shape()[-1]), num_filters], dtype=tf.float32, initializer=tf.random_normal_initializer(0, 0.05), trainable=True) g = tf.get_variable('g', shape=[num_filters], dtype=tf.float32, initializer=tf.constant_initializer(1.), trainable=True) b = tf.get_variable('b', shape=[num_filters], dtype=tf.float32, initializer=bias_initializer, trainable=True) def maybe_avg(v): if ema is not None and not init: v = tf.cond(training, lambda: v, lambda: ema.average(v))
tensorflow.get_variable
1,517
import tensorflow as tf d['surface_point_samples']) def parse_example(filename): """A tensorflow function to return a dataset element when mapped""" return tf.py_func(_example_dict_tf_func_wrapper, [filename], [ tf.float32, tf.float32, tf.string, tf.float32, tf.float32, tf.float32, tf.float32])
tensorflow.py_func
1,518
import tensorflow as tf # labels=tf.squeeze(annotation, squeeze_dims=[3]), # name="entropy"))) mask_ = tf.ones([FLAGS.batch_size,64,64,3]) mask = tf.pad(mask_, [[0,0],[32,32],[32,32],[0,0]]) mask2__ = tf.ones([FLAGS.batch_size,78,78,3]) mask2_ = tf.pad(mask2__, [[0,0],[25,25],[25,25],[0,0]]) mask2 = mask2_ - mask pred_annotation, logits = inference((1-mask)*image + mask*255, keep_probability,z) tf.summary.image("input_image", image, max_outputs=2) tf.summary.image("ground_truth", tf.cast(annotation, tf.uint8), max_outputs=2) tf.summary.image("pred_annotation", tf.cast(pred_annotation, tf.uint8), max_outputs=2) # loss0 = tf.reduce_mean(tf.abs(z)) loss = tf.reduce_mean(tf.sqrt(tf.reduce_sum(tf.square((image - logits)),[1,2,3]))) # loss2 = tf.reduce_mean(tf.square((image - logits)*mask2)) # loss = loss1 + loss2 + loss0 # loss = tf.reduce_mean(tf.squared_difference(logits ,annotation )) loss_summary = tf.summary.scalar("entropy", loss) grads = train_z(loss,z) trainable_var = tf.trainable_variables() if FLAGS.debug:
tensorflow.cast
1,519
from tensorflow.python.framework import ops @ops.RegisterShape("SoftsignGrad") def _BinaryElementwiseShape(op): """Returns same shape as both inputs to op. Args: op: Input operation. Returns: Shape of both inputs to `op`. """ return [op.inputs[0].get_shape().merge_with(op.inputs[1].get_shape())] ops.RegisterShape("L2Loss")(common_shapes.scalar_shape) ops.RegisterShape("LRN")(common_shapes.unchanged_shape_with_rank(4)) @ops.RegisterShape("LRNGrad") def _LRNGradShape(op): """Shape function for LRNGrad op.""" in_grads_shape = op.inputs[0].get_shape().with_rank(4) in_image_shape = op.inputs[1].get_shape().with_rank(4) out_image_shape = op.inputs[2].get_shape().with_rank(4) return [in_grads_shape.merge_with(in_image_shape).merge_with(out_image_shape)]
tensorflow.python.framework.ops.RegisterShape
1,520
import tensorflow as tf print('Num of sample per eps is %d' % (num_sample)) # Construct predictions image = tf.placeholder(tf.float32, shape=[hps.batch_size, image_size, image_size, num_channel]) ############MNIST and CIFAR10 are different ar here adv_image = tf.placeholder(tf.float32, shape=[hps.batch_size, image_size, image_size, num_channel]) ############MNIST and CIFAR10 are different ar here predict = tf.placeholder(tf.float32, shape=[hps.batch_size, 10]) predict_nor, tsne_logit_nor = models(hps, image, FLAGS.RCE_train, logits=False, tsne_logits=True) predict_adv, tsne_logit_adv = models(hps, adv_image, FLAGS.RCE_train, logits=False, tsne_logits=True) # Calculate entropy argmax_y_onehot = tf.one_hot(tf.argmax(predict, 1), 10, on_value=0.0, off_value=1.0, axis=-1) normalized_y_nonmaximal = tf.reduce_sum(predict * argmax_y_onehot, 1) entropy = tf.reduce_sum(-tf.log(predict) * predict * argmax_y_onehot, 1) / normalized_y_nonmaximal + tf.log( normalized_y_nonmaximal) for k in range(10): adv_image_craft = adv_craft_func(hps, image, FLAGS.attack_method, eps=0.02 * k + 0.02, RCE_train=FLAGS.RCE_train) #adv_image_craft = adv_craft_func(hps, image, FLAGS.attack_method, eps=0.04,RCE_train=FLAGS.RCE_train) sess.run(tf.global_variables_initializer()) saver.restore(sess, ckpt_state.model_checkpoint_path) for i in six.moves.range(FLAGS.eval_batch_count): time_start = time.time() (nor_img,true_label) = sess.run([images,labels]) adv_img = sess.run(adv_image_craft,feed_dict={image:nor_img})
tensorflow.log
1,521
import tensorflow as tf initializer=tf.constant_initializer(1.), trainable=True) b = tf.get_variable('b', shape=[num_filters], dtype=tf.float32, initializer=bias_initializer, trainable=True) def maybe_avg(v): if ema is not None and not init: v = tf.cond(training, lambda: v, lambda: ema.average(v)) return v if init: x = tf.nn.conv2d(x, tf.nn.l2_normalize(V.initialized_value(), [0, 1, 2]), [1] + list(stride) + [1], pad) init_scale=.01 m_init, v_init = tf.nn.moments(x, [0,1,2]) scale_init = init_scale / tf.sqrt(v_init + 1e-10) with tf.control_dependencies([g.assign(g * scale_init), b.assign_add(-m_init * scale_init)]): x = tf.reshape(scale_init, [1, 1, 1, num_filters]) * (x - tf.reshape(m_init, [1, 1, 1, num_filters])) else: V = maybe_avg(V) g = maybe_avg(g) b = maybe_avg(b) # use weight normalization (Salimans & Kingma, 2016) W = tf.reshape(g, [1, 1, 1, num_filters]) * tf.nn.l2_normalize(V, [0, 1, 2]) # calculate convolutional layer output
tensorflow.nn.moments
1,522
import tensorflow as tf a = 2 values = interpolated inter = tf.reshape(values, [self.resolution, self.resolution,
tensorflow.reshape
1,523
import tensorflow as tf frame_history_len: int How many past frames to include as input to the model. target_update_freq: int How many experience replay rounds (not steps!) to perform between each update to the target Q network grad_norm_clipping: float or None If not None gradients' norms are clipped to this value. """ assert type(env.observation_space) == gym.spaces.Box assert type(env.action_space) == gym.spaces.Discrete ############### # BUILD MODEL # ############### if not out_dir: out_dir = os.path.join(os.getcwd(),'results',env.unwrapped.spec.id +'_' + time.strftime("%d-%m-%Y_%H-%M-%S")) writer = tf.summary.FileWriter(out_dir) if len(env.observation_space.shape) == 1: # This means we are running on low-dimensional observations (e.g. RAM) input_shape = env.observation_space.shape else: img_h, img_w, img_c = env.observation_space.shape input_shape = (img_h, img_w, frame_history_len * img_c) num_actions = env.action_space.n # set up placeholders # placeholder for current observation (or state) obs_t_ph = tf.placeholder(tf.uint8, [None] + list(input_shape)) # placeholder for current action act_t_ph = tf.placeholder(tf.int32, [None])
tensorflow.summary.FileWriter
1,524
import tensorflow as tf return new_dropout_masks def placeholder(dim=None): return tf.placeholder(dtype=tf.float32, shape=(None,dim) if dim else (None,)) def placeholders(*args):
tensorflow.placeholder
1,525
import tensorflow as tf def cross_entropy_layer(tensor, target, **opts): if _rank(tensor) > 1: target = tf.reshape(target, shape=(-1, ))
tensorflow.reshape
1,526
import tensorflow as tf this file.""") tf.flags.DEFINE_string('graph_file', None, """Write the model's graph definition to this file. Defaults to binary format unless filename ends in 'txt'.""") tf.flags.DEFINE_string('optimizer', 'sgd', 'Optimizer to use: momentum or sgd or rmsprop') tf.flags.DEFINE_float('learning_rate', None, """Initial learning rate for training.""") tf.flags.DEFINE_float('num_epochs_per_decay', 0,
tensorflow.flags.DEFINE_string
1,527
import tensorflow as tf p.transformer_tpl.tr_atten_tpl.num_attention_heads = 8 p.transformer_tpl.tr_fflayer_tpl.hidden_dim = 8192 return p @base_layer.initializer def __init__(self, params): super(TransformerStack, self).__init__(params) p = self.params with tf.variable_scope(p.name): # Add transformer layers. transformer_layer_params = [] for i in range(p.num_transformer_layers): params = p.transformer_tpl.Copy() params.name = 'trans_%d' % (i) params.source_dim = p.model_dim params.packed_input = p.packed_input params.has_aux_atten = p.has_aux_attention
tensorflow.variable_scope
1,528
import tensorflow as tf return_dict = {} # invalid position mask such as query and special symbols (PAD, SEP, CLS) p_mask = features["p_mask"] # logit of the start position with tf.variable_scope("start_logits"): start_logits = tf.layers.dense( output, 1, kernel_initializer=initializer) start_logits = tf.transpose(tf.squeeze(start_logits, -1), [1, 0]) start_logits_masked = start_logits * (1 - p_mask) - 1e30 * p_mask
tensorflow.variable_scope
1,529
import tensorflow as tf assert tag != None # handle most of the regularizer here weights_regularizer = tf.contrib.layers.l2_regularizer(cfg.FLAGS.weight_decay) if cfg.FLAGS.bias_decay: biases_regularizer = weights_regularizer
tensorflow.contrib.layers.l2_regularizer
1,530
import tensorflow as tf 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) block_uses = tf.add_n(block_uses) unused_indices = tf.reshape(tf.cast(tf.where(tf.equal(block_uses, 0)), tf.int32), [-1]) num_out_blocks = tf.size(unused_indices) # Select only unused blocks with tf.variable_scope('select'): stacked_blocks = tf.stack(cell_inputs + blocks) out_blocks = tf.gather(stacked_blocks, unused_indices, axis=0) out_blocks = tf.transpose(out_blocks, (1, 2, 3, 0, 4)) # Combine to constant channels with tf.variable_scope('combine'):
tensorflow.one_hot
1,531
import tensorflow as tf 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))
tensorflow.variable_scope
1,532
import tensorflow as tf with tf.Session( target="", config=tf.ConfigProto(device_count={"CPU": 2})) as sess: with sess.graph.device("/cpu:0"): v0 = tf.Variable(10, name="v0") with sess.graph.device("/cpu:1"): v1 = tf.Variable(20, name="v1") save = tf.train.Saver({"v0": v0, "v1": v1}, sharded=True) tf.initialize_all_variables().run() val = save.save(sess, save_path) self.assertEqual(save_path + "-?????-of-00002", val) meta_graph_filename = save._MetaGraphFilename(val) self.assertEqual(save_path + ".meta", meta_graph_filename)
tensorflow.train.Saver
1,533
import tensorflow as tf return [L_, tf.transpose(L_)] tmp = tf.scan(fn, L_flat, initializer=init) if isinstance(tmp, (list, tuple)):
tensorflow.scan
1,534
import tensorflow as tf if do_dnn: last_layer = rnn_output last_layer_size = rnn_output_size for i, layer_size in enumerate(dnn_sizes): layer_name = 'dnn_{}'.format(i) with tf.variable_scope(layer_name): dnn_w = tf.get_variable('W', shape=[last_layer_size, layer_size], initializer=dnn_init, dtype=dtype) dnn_b = tf.get_variable('b', shape=[layer_size], initializer=tf.constant_initializer(0.0), dtype=dtype) projected = tf.nn.bias_add(tf.matmul(last_layer, dnn_w), dnn_b) # TODO: argument nonlinearity, change bias to 0.1 if relu
tensorflow.variable_scope
1,535
import tensorflow as tf session_config=config) if FLAGS.use_hvd and hvd.rank() != 0 and not FLAGS.auto_recover: run_config = tf.estimator.RunConfig( model_dir=FLAGS.output_dir, keep_checkpoint_max=FLAGS.keep_checkpoint_max,
tensorflow.estimator.RunConfig
1,536
import tensorflow as tf def dice_loss(predictions, targets, weights=1., name='dice_loss'): with tf.name_scope(name): # predictions = tf.to_float(predictions) targets = tf.to_float(targets) intersection = 2 * tf.reduce_sum(predictions * targets) + weights union = weights + tf.reduce_sum(predictions) + tf.reduce_sum(targets) loss = -(intersection / (union)) return loss
tensorflow.reduce_sum
1,537
from tensorflow.contrib.distributions.python.ops import distribution_util @distribution_util.AppendDocstring(_poisson_sample_note) def _log_prob(self, x): return self._log_unnormalized_prob(x) - self._log_normalization() @distribution_util.AppendDocstring(_poisson_sample_note) def _prob(self, x): return math_ops.exp(self._log_prob(x))
tensorflow.contrib.distributions.python.ops.distribution_util.AppendDocstring
1,538
import tensorflow as tf k = dense_layer_3d(to_tensor, num_attention_heads, size_per_head, create_initializer(initializer_range), key_act, "key") # `value_layer` = [B, T, N, H] v = dense_layer_3d(to_tensor, num_attention_heads, size_per_head, create_initializer(initializer_range), value_act, "value") q = tf.transpose(q, [0, 2, 1, 3]) k = tf.transpose(k, [0, 2, 1, 3]) v = tf.transpose(v, [0, 2, 1, 3]) if attention_mask is not None: attention_mask = tf.reshape(
tensorflow.transpose
1,539
import tensorflow as tf batch_size_val = self.cnf['batch_size_test'] self.end_points_G = self.model.generator([batch_size_train, 100], True, None, batch_size_val) if gpu_idx == 0: G_means = tf.reduce_mean(self.end_points_G['softmax'], 0, keep_dims=True) G_vars = tf.reduce_mean(tf.square(self.end_points_G['softmax'] - G_means), 0, keep_dims=True) G = tf.Print( self.end_points_G['softmax'], [tf.reduce_mean(G_means), tf.reduce_mean(G_vars)], "generator mean and average var", first_n=1) inputs_means = tf.reduce_mean(inputs, 0, keep_dims=True) inputs_vars = tf.reduce_mean(tf.square(inputs - inputs_means), 0, keep_dims=True) inputs = tf.Print( inputs, [tf.reduce_mean(inputs_means), tf.reduce_mean(inputs_vars)], "image mean and average var", first_n=1) joint = tf.concat([inputs, G], 0) log.info('Input size of unlabelled and generated %s' % (joint.get_shape())) self.end_points_D = self.model.discriminator( joint, True, None, num_classes=num_classes, batch_size=batch_size_train) self.end_points_D_val = self.model.discriminator(
tensorflow.square
1,540
import tensorflow as tf """ # size: num_priors x num_targets ious = iou_of(tf.expand_dims(gt_boxes, axis=0), tf.expand_dims(corner_form_priors, axis=1)) # size: num_priors best_target_per_prior = tf.math.reduce_max(ious, axis=1) best_target_per_prior_index = tf.math.argmax(ious, axis=1) # size: num_targets best_prior_per_target = tf.math.reduce_max(ious, axis=0) best_prior_per_target_index = tf.math.argmax(ious, axis=0)
tensorflow.math.reduce_max
1,541
import tensorflow as tf name='loss_logits_rl_w', initializer=tf.initializers.zeros(), shape=[ FLAGS.num_choices, ], dtype=tf.float32) dist = tfp.distributions.Categorical(logits=logits) dist_entropy = tf.reduce_sum(dist.entropy()) sample = dist.sample() sample_masks = 1. * tf.cast(sample, tf.float32) / FLAGS.loss_weight_scale sample_log_prob = tf.reduce_mean(dist.log_prob(sample)) return (dist_entropy, sample_masks, sample_log_prob) def main(unused_argv): tf.set_random_seed(FLAGS.random_seed) run_config_args = {
tensorflow.cast
1,542
import tensorflow as tf cnn_output = tf.slice(cnn_output, [0, zack_hack_div_2, 0, 0], [-1, rnn_nunroll, -1, -1]) nfeats_conv = reduce(lambda x, y: x * y, [int(x) for x in cnn_output.get_shape()[-2:]]) else: nfeats_conv = reduce(lambda x, y: x * y, [int(x) for x in cnn_output.get_shape()[-3:]]) feats_conv = tf.reshape(cnn_output, [batch_size * rnn_nunroll, nfeats_conv]) nfeats_tot = nfeats_conv + nfeats feats_all = tf.concat(1, [feats_conv, feats_other]) print('feats_cnn: {}'.format(feats_conv.get_shape())) print('feats_all: {}'.format(feats_all.get_shape())) # Project to RNN size rnn_output = feats_all rnn_output_size = nfeats_tot if do_rnn: with tf.variable_scope('rnn_proj'): rnn_proj_w = tf.get_variable('W', [nfeats_tot, rnn_size], initializer=tf.uniform_unit_scaling_initializer(factor=1.0, dtype=dtype), dtype=dtype) rnn_proj_b = tf.get_variable('b', [rnn_size], initializer=tf.constant_initializer(0.0), dtype=dtype) rnn_inputs = tf.nn.bias_add(tf.matmul(feats_all, rnn_proj_w), rnn_proj_b) rnn_inputs = tf.reshape(rnn_inputs, [batch_size, rnn_nunroll, rnn_size]) rnn_inputs = tf.split(rnn_inputs, rnn_nunroll, axis=1) rnn_inputs = [tf.squeeze(input_, [1]) for input_ in rnn_inputs] if rnn_cell_type == 'rnn': cell_fn = tf.nn.rnn_cell.BasicRNNCell elif rnn_cell_type == 'gru': cell_fn = tf.nn.rnn_cell.GRUCell elif rnn_cell_type == 'lstm':
tensorflow.variable_scope
1,543
from tensorflow.python.ops import array_ops ValueError: If `weights` is not `None` and has an incomptable shape. """ default_name = _at_k_name('true_positive', k, class_id=class_id) with ops.name_scope(name, default_name, (predictions_idx, labels)) as scope: tp = _sparse_true_positive_at_k( predictions_idx=predictions_idx, labels=labels, class_id=class_id, weights=weights) batch_total_tp = math_ops.to_double(math_ops.reduce_sum(tp)) var = contrib_variables.local_variable( array_ops.zeros([], dtype=dtypes.float64), name=scope) return var, state_ops.assign_add(var, batch_total_tp, name='update') def _sparse_false_positive_at_k(predictions_idx, labels, class_id=None, weights=None): """Calculates false positives for precision@k.
tensorflow.python.ops.array_ops.zeros
1,544
import tensorflow as tf }) if FLAGS.contrast_norm == 'areafactor': image = tf.decode_raw(features['image_raw'], tf.float32) else: image = tf.decode_raw(features['image_raw'], tf.uint8) image = tf.cast(image, tf.float32) * (1. / 255) image.set_shape(np.prod([FLAGS.num_scales, FLAGS.crop_size, FLAGS.crop_size])) image = tf.reshape(image, [FLAGS.num_scales, FLAGS.crop_size, FLAGS.crop_size, 1]) image = image - 0.5 # Convert label from a scalar uint8 tensor to an int32 scalar. label = tf.cast(features['label'], tf.int32) return image, label def inputs(name, batch_size, num_epochs): """Reads input data num_epochs times. Args: train: Selects between the training (True) and test (False) data. batch_size: Number of examples per returned batch. num_epochs: Number of times to read the input data, or 0/None to train forever.
tensorflow.cast
1,545
import tensorflow as tf FLAGS.save_summaries_steps > 0): summary_writer = tf.summary.FileWriter(FLAGS.train_dir, tf.get_default_graph())
tensorflow.get_default_graph
1,546
import tensorflow as tf return out def deconv2d(x, dim=(32, [3, 3], [1, 1]), pad='SAME', scope="deconv2d", training=True, ema=None, init=False, bias_initializer=tf.constant_initializer(0.)): num_filters, filter_size, stride = dim xs = x.get_shape().as_list() if pad=='SAME': target_shape = [tf.shape(x)[0], xs[1]*stride[0], xs[2]*stride[1], num_filters] else: target_shape = [tf.shape(x)[0], xs[1]*stride[0] + filter_size[0]-1, xs[2]*stride[1] + filter_size[1]-1, num_filters] with tf.variable_scope(scope): V = tf.get_variable("V", shape=list(filter_size) + [num_filters, int(x.get_shape()[-1])], dtype=tf.float32, initializer=tf.random_normal_initializer(0, 0.05), trainable=True) g = tf.get_variable("g", shape=[num_filters], dtype=tf.float32, initializer=tf.constant_initializer(1.), trainable=True) b = tf.get_variable("b", shape=[num_filters], dtype=tf.float32, initializer=bias_initializer, trainable=True) def maybe_avg(v): if ema is not None and not init: v = tf.cond(training, lambda: v, lambda: ema.average(v)) return v if init: x = tf.nn.conv2d_transpose(x, tf.nn.l2_normalize(V.initialized_value(), [0, 1, 3]), target_shape, [1] + list(stride) + [1], padding=pad) init_scale = .01 m_init, v_init = tf.nn.moments(x, [0, 1, 2]) scale_init = init_scale / tf.sqrt(v_init + 1e-10) with tf.control_dependencies([g.assign(g * scale_init), b.assign_add(-m_init * scale_init)]):
tensorflow.constant_initializer
1,547
import tensorflow as tf optimiser = tf.train.AdamOptimizer(decayed_learning_rate, name="Adam").minimize(cross_entropy) # calculate the prediction and the accuracy accuracy, acc_op = tf.metrics.accuracy(labels=tf.argmax(y_, axis=1), predictions=tf.argmax(y_conv, axis=1)) loss_summary = tf.summary.scalar('Loss', cross_entropy) acc_summary = tf.summary.scalar('Accuracy', accuracy) # summaries for TensorBoard visualisation validation_summary = tf.summary.merge([img_summary, acc_summary])
tensorflow.summary.scalar
1,548
import tensorflow as tf if distributional_size > 1: target_value_shape_suffix = [num_target_frames, distributional_size] features = { "inputs": observations, "epoch": tf.constant(epoch + 1), "input_action": tf.zeros(obs_shape[:2] + [1], dtype=tf.int32), "input_reward": tf.zeros(obs_shape[:2] + [1], dtype=tf.int32), "targets": tf.zeros(obs_shape[:1] + [num_target_frames] + obs_shape[2:]), "target_action": tf.zeros( obs_shape[:1] + [num_target_frames, 1], dtype=tf.int32),
tensorflow.zeros
1,549
import tensorflow as tf latent_variable = dense(e_dense_2, n_l2, z_dim, 'e_latent_variable') cat_op = dense(e_dense_2, n_l2, n_labels, 'e_label') if not supervised: softmax_label = tf.nn.softmax(logits=cat_op, name='e_softmax_label') else: softmax_label = cat_op
tensorflow.nn.softmax
1,550
import tensorflow as tf layers_ratio = (l + 1) / (L + 2) drop_path_keep_prob = self._get_drop_path_keep_prob(layers_ratio, step, is_train, **knobs) # Either add a reduction cell or normal cell if l in reduction_layers: block_ch *= 2 w >>= 1 h >>= 1 with tf.variable_scope('reduction_cell'): if use_dynamic_arch: self._add_dynamic_cell(reduction_arch, layers, w, h, block_ch, drop_path_keep_prob, is_train) else: self._add_static_cell(reduction_arch, layers, w, h, block_ch, drop_path_keep_prob, is_train, is_reduction=True) else: with tf.variable_scope('normal_cell'): if use_dynamic_arch:
tensorflow.variable_scope
1,551
from tensorflow.python.platform import gfile # Check that s1 is still here, but s2 is gone. self.assertTrue(gfile.Exists(s1)) self.assertFalse(gfile.Exists(s2)) self.assertTrue(gfile.Exists(s3))
tensorflow.python.platform.gfile.Exists
1,552
import tensorflow as tf avg_norm_k_dot_g = tf.reduce_mean(tf.abs(k_dot_g)) avg_norm_adj = tf.reduce_mean(tf.abs(adj))
tensorflow.abs
1,553
import tensorflow as tf # inputs=embedding_output, # sequence_lengths=_true_length, # rnn_size=config.lstm_size, # dropout=config.bilstm_dropout_rate, # is_training=is_training, # num_layers=config.num_bilstm, # direction='bidirectional') # first_token_tensor = tf.squeeze(sequence_output[:, -1:, :], axis=1) last_token_tensor = tf.squeeze(sequence_output[:, -1:, :], axis=1) output_layer = tf.layers.dense( last_token_tensor, config.hidden_size, activation=tf.tanh, kernel_initializer=modeling.create_initializer(config.initializer_range)) hidden_size = output_layer.shape[-1].value
tensorflow.squeeze
1,554
import tensorflow as tf intermediate_size, create_initializer(initializer_range), intermediate_act_fn, num_attention_heads=num_attention_heads, name="dense") with tf.variable_scope("output"): ffn_output = dense_layer_2d( intermediate_output, hidden_size, create_initializer(initializer_range),
tensorflow.variable_scope
1,555
import tensorflow as tf eval_examples.append(classifier_utils.PaddingInputExample()) cached_dir = FLAGS.cached_dir if not cached_dir: cached_dir = FLAGS.output_dir eval_file = os.path.join(cached_dir, task_name + "_eval.tf_record") if not tf.gfile.Exists(eval_file): classifier_utils.file_based_convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file, task_name) tf.logging.info("***** Running evaluation *****")
tensorflow.gfile.Exists
1,556
from tensorflow.python.framework import ops predictions_idx=top_k_idx, labels=labels, k=k, class_id=class_id, weights=weights) fp, fp_update = _streaming_sparse_false_positive_at_k( predictions_idx=top_k_idx, labels=labels, k=k, class_id=class_id, weights=weights) metric = math_ops.div(tp, math_ops.add(tp, fp), name=name) update = math_ops.div( tp_update, math_ops.add(tp_update, fp_update), name='update') if metrics_collections: ops.add_to_collections(metrics_collections, metric) if updates_collections: ops.add_to_collections(updates_collections, update) return metric, update # TODO(ptucker): Validate range of values in labels? @deprecated_args(IGNORE_MASK_DATE, IGNORE_MASK_INSTRUCTIONS, 'ignore_mask') def streaming_sparse_precision_at_k(predictions, labels,
tensorflow.python.framework.ops.add_to_collections
1,557
import tensorflow as tf i = tf.nn.sigmoid(i) f = tf.nn.sigmoid(f) o = tf.nn.sigmoid(o) u = tf.tanh(u) c = f*c + i*u h = o*tf.tanh(c) xs[idx] = h s = tf.concat(axis=1, values=[c, h]) return xs, s def _ln(x, g, b, e=1e-5, axes=[1]): u, s = tf.nn.moments(x, axes=axes, keep_dims=True) x = (x-u)/tf.sqrt(s+e) x = x*g+b
tensorflow.concat
1,558
import tensorflow as tf self.image_real_A = self.images_real[:,:,:,:self.input_dim] self.image_real_B = self.images_real[:,:,:,self.input_dim:self.input_dim + self.output_dim] self.images_fake_B = self.build_generator(self.image_real_A,reuse=False,name='generator_AB') self.images_fake_A = self.build_generator(self.images_fake_B,reuse=False,name='generator_BA') self.images_fake_A_ = self.build_generator(self.image_real_B,reuse=True,name='generator_BA') self.images_fake_B_ = self.build_generator(self.images_fake_A_,reuse=True,name='generator_AB') self.D_B_fake = self.build_discriminator(self.images_fake_B ,reuse=False, name="discriminatorB") self.D_A_fake = self.build_discriminator(self.images_fake_A_,reuse=False, name="discriminatorA") self.D_B_real = self.build_discriminator(self.image_real_B,reuse=True, name="discriminatorB") self.D_A_real = self.build_discriminator(self.image_real_A,reuse=True, name="discriminatorA") self.loss_GABA = self.lambda_l2*squared_loss(self.images_fake_A,self.image_real_A) + binary_cross_entropy_loss(labels=tf.ones_like(self.D_B_fake),logits=self.D_B_fake) self.loss_GBAB = self.lambda_l2*squared_loss(self.images_fake_B_,self.image_real_B) + binary_cross_entropy_loss(labels=tf.ones_like(self.D_A_fake),logits=self.D_A_fake) self.generator_loss = self.loss_GABA + self.loss_GBAB self.D_B_loss_real = binary_cross_entropy_loss(tf.ones_like(self.D_B_real),self.D_B_real) self.D_B_loss_fake = binary_cross_entropy_loss(tf.zeros_like(self.D_B_fake),self.D_B_fake) self.D_B_loss = (self.D_B_loss_real + self.D_B_loss_fake) / 2.0 self.D_A_loss_real = binary_cross_entropy_loss(tf.ones_like(self.D_A_real),self.D_A_real) self.D_A_loss_fake = binary_cross_entropy_loss(tf.zeros_like(self.D_A_fake),self.D_A_fake) self.D_A_loss = (self.D_A_loss_real + self.D_A_loss_fake) / 2.0 self.discriminator_loss = self.D_B_loss + self.D_A_loss
tensorflow.ones_like
1,559
import tensorflow as tf d_fake_logits=d_fake_logits) penalty_loss = penalty_lib.get_penalty_loss( x=images, x_fake=generated, y=y, is_training=is_training, discriminator=self.discriminator, architecture=self._architecture) self.d_loss += self._lambda * penalty_loss z_projs = tf.concat([z_projs_real, z_projs_fake], 0) z_aug_projs = tf.concat([z_aug_projs_real, z_aug_projs_fake], 0) sims_logits = tf.matmul(z_projs, z_aug_projs, transpose_b=True) logits_max = tf.reduce_max(sims_logits,1) sims_logits = sims_logits - tf.reshape(logits_max, [-1, 1]) sims_probs = tf.nn.softmax(sims_logits) sim_labels = tf.constant(np.arange(bs * 2, dtype=np.int32)) sims_onehot = tf.one_hot(sim_labels, bs * 2) c_real_loss = - tf.reduce_mean( tf.reduce_sum(sims_onehot * tf.log(sims_probs + 1e-10), 1)) self.d_loss += c_real_loss * self._weight_contrastive_loss_d self._tpu_summary.scalar("loss/c_real_loss", c_real_loss) self._tpu_summary.scalar("loss/penalty", penalty_loss)
tensorflow.nn.softmax
1,560
import tensorflow as tf def deconv_bn_relu(self, bottom, name, kernel_size, output_channels, initializer, stride = 1, bn=False, training=False, relu=True): input_shape = bottom.get_shape().as_list() input_channels = input_shape[-1] output_shape = [input_shape[0], input_shape[1]*stride, input_shape[2]*stride, output_channels] with tf.variable_scope(name) as scope: kernel = self.variable('weights', [kernel_size, kernel_size, output_channels, input_channels], initializer, regularizer=tf.contrib.layers.l2_regularizer(0.0005)) deconv = tf.nn.conv2d_transpose(bottom, kernel, output_shape, [1, stride, stride, 1], padding='SAME') biases = self.variable('biases', [output_channels], tf.constant_initializer(0.0)) deconv_layer = tf.nn.bias_add(deconv, biases) if bn: deconv_layer = self.batch_norm_layer('batch_norm_layer',deconv_layer,training) if relu: deconv_layer = tf.nn.relu(deconv_layer, name=scope.name) print('Deconv layer {0} -> {1}'.format(bottom.get_shape().as_list(),deconv_layer.get_shape().as_list())) return deconv_layer
tensorflow.nn.bias_add
1,561
import tensorflow as tf 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) flat_x = tf.nn.dropout(flat_x, rate=dropout)
tensorflow.layers.conv2d
1,562
import tensorflow as tf """ with tf.name_scope('Encode'): return self._encode(boxes, anchors) def decode(self, rel_codes, anchors): """Decode boxes that are encoded relative to an anchor collection. Args: rel_codes: a tensor representing N relative-encoded boxes anchors: BoxList of anchors Returns: boxlist: BoxList holding N boxes encoded in the ordinary way (i.e., with corners y_min, x_min, y_max, x_max) """ with tf.name_scope('Decode'): return self._decode(rel_codes, anchors) @abstractmethod def _encode(self, boxes, anchors): """Method to be overriden by implementations. Args: boxes: BoxList holding N boxes to be encoded anchors: BoxList of N anchors Returns: a tensor representing N relative-encoded boxes """ pass
tensorflow.name_scope
1,563
import tensorflow as tf :, :-1], labels=gtboxes_and_label_r[ :, -1], method=1) tf.summary.image('Compare/gtboxes_h_gpu:%d' % i, gtboxes_in_img_h) tf.summary.image('Compare/gtboxes_r_gpu:%d' % i, gtboxes_in_img_r) if cfgs.ADD_BOX_IN_TENSORBOARD:
tensorflow.summary.image
1,564
import tensorflow as tf 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 if self.trust_region: # [n_envs * n_steps, n_act] grad = tf.gradients(- (loss_policy - self.ent_coef * entropy) * self.n_steps * self.n_envs, phi_i) # [n_envs * n_steps, n_act] # Directly computed gradient of KL divergence wrt f kl_grad = - f_polyak_i / (f_i_ + eps) k_dot_g = tf.reduce_sum(kl_grad * grad, axis=-1) adj = tf.maximum(0.0, (tf.reduce_sum(kl_grad * grad, axis=-1) - self.delta) / (
tensorflow.gradients
1,565
import tensorflow as tf with tf.control_dependencies([layer_output]): # update the initial states for i in range(2): new_state = tf.concat( [final_state[i][:batch_size, :], init_states[i][batch_size:, :]], axis=0) state_update_op = tf.assign(init_states[i], new_state) update_ops.append(state_update_op) layer_input = layer_output self.mask = mask self.sequence_lengths = sequence_lengths self.update_state_op = tf.group(*update_ops) def dump_token_embeddings(vocab_file, options_file, weight_file, outfile): ''' Given an input vocabulary file, dump all the token embeddings to the outfile. The result can be used as the embedding_weight_file when constructing a BidirectionalLanguageModel. ''' with open(options_file, 'r') as fin: options = json.load(fin) max_word_length = options['char_cnn']['max_characters_per_token'] vocab = UnicodeCharsVocabulary(vocab_file, max_word_length)
tensorflow.group
1,566
import tensorflow as tf log_probs = tf.nn.log_softmax(logits, axis=-1) label_ids = tf.reshape(label_ids, [-1]) label_weights = tf.reshape(label_weights, [-1]) one_hot_labels = tf.one_hot(
tensorflow.reshape
1,567
from tensorflow.python.summary import summary """ def gradient_clipping(grads_and_vars): """Internal function for adaptive clipping.""" grads, variables = zip(*grads_and_vars) norm = clip_ops.global_norm(grads) max_norm, log_mean = _adaptive_max_norm(norm, std_factor, decay, global_step, epsilon, name) # reports the max gradient norm for debugging if report_summary: summary.scalar("global_norm/adaptive_max_gradient_norm", max_norm) # factor will be 1. if norm is smaller than max_norm factor = array_ops.where(norm < max_norm, array_ops.ones_like(norm), math_ops.exp(log_mean) / norm) if static_max_norm is not None: factor = math_ops.minimum(static_max_norm / norm, factor) # apply factor clipped_grads = [] for grad in grads: if grad is None:
tensorflow.python.summary.summary.scalar
1,568
import tensorflow as tf if not FLAGS.restore: tf.gfile.DeleteRecursively(FLAGS.checkpoint_path) tf.gfile.MkDir(FLAGS.checkpoint_path) input_images = tf.placeholder(tf.float32, shape=[None, None, None, 3], name='input_images') input_score_maps = tf.placeholder(tf.float32, shape=[None, None, None, 1], name='input_score_maps') if FLAGS.geometry == 'RBOX': input_geo_maps = tf.placeholder(tf.float32, shape=[None, None, None, 5], name='input_geo_maps') else: input_geo_maps = tf.placeholder(tf.float32, shape=[None, None, None, 8], name='input_geo_maps') input_training_masks = tf.placeholder(tf.float32, shape=[None, None, None, 1], name='input_training_masks') global_step = tf.get_variable('global_step', [], initializer=tf.constant_initializer(0), trainable=False) learning_rate = tf.train.exponential_decay(FLAGS.learning_rate, global_step, decay_steps=10000, decay_rate=0.94, staircase=True) # add summary tf.summary.scalar('learning_rate', learning_rate) opt = tf.train.AdamOptimizer(learning_rate) opt = MixedPrecisionOptimizer(opt, scale=FLAGS.loss_scale) from npu_bridge.estimator.npu.npu_optimizer import NPUDistributedOptimizer opt = NPUDistributedOptimizer(opt) # split input_images_split = tf.split(input_images, len(gpus)) input_score_maps_split = tf.split(input_score_maps, len(gpus)) input_geo_maps_split = tf.split(input_geo_maps, len(gpus)) input_training_masks_split = tf.split(input_training_masks, len(gpus))
tensorflow.train.exponential_decay
1,569
import tensorflow as tf theta: A tensor of size [num_batch, 16]. It is the inverse camera transformation matrix (tf.float32). out_size: A tuple representing the size of output of transformer layer (float). z_near: A number representing the near clipping plane (float). z_far: A number representing the far clipping plane (float). Returns: A transformed tensor (tf.float32). """ def _repeat(x, n_repeats): with tf.variable_scope('_repeat'): rep = tf.transpose( tf.expand_dims(tf.ones(shape=tf.stack([ n_repeats, ])), 1), [1, 0]) rep = tf.to_int32(rep) x = tf.matmul(tf.reshape(x, (-1, 1)), rep) return tf.reshape(x, [-1]) def _interpolate(im, x, y, z, out_size): """Bilinear interploation layer.
tensorflow.variable_scope
1,570
import tensorflow as tf cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv)) # Define your AdamOptimiser, using FLAGS.learning_rate to minimixe the loss function decayed_learning_rate = tf.train.exponential_decay(FLAGS.learning_rate, tf.Variable(0, trainable=False), 1000, 0.8) update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) with tf.control_dependencies(update_ops):
tensorflow.Variable
1,571
import tensorflow as tf attn_dists.append(attn_dist_t) p_gens.append(p_gen_t) vocab_scores.append(output_t) # The vocabulary distributions. state_t_1 = state_t context_t_1 = context_t coverage_t_1 = coverage_t if mode_gen == 'greedy': wordidx_t = tf.argmax(output_t, 1) # [batch_size] wordidx_t = tf.reshape(wordidx_t, [-1]) # [batch_size] elif mode_gen == 'sample': log_score_t = tf.log(output_t) # [batch_size, vsize] wordidx_t = tf.multinomial(log_score_t, 1) # [batch_size, 1] wordidx_t = tf.reshape(wordidx_t, [-1]) # [batch_size] elif mode_gen in ('ce_train', 'loss',): wordidx_t = answer_batch_unstack[i] else: assert False, 'unknown generating mode %s' % mode_gen sampled_words.append(wordidx_t) if len(sampled_words)!=0: sampled_words = tf.stack(sampled_words, axis=1) # [batch_size, max_dec_steps]
tensorflow.log
1,572
import tensorflow as tf # Transform the input features for key, input_modality in six.iteritems( self._problem_hparams.input_modality): if key not in features: tf.logging.warning("Missing feature %s - ignoring." % key) continue do_reuse = input_modality.name in all_previous_modalities with tf.variable_scope(input_modality.name, reuse=do_reuse): log_info("Transforming feature '%s' with %s.bottom", key, input_modality.name) transformed_features[key] = input_modality.bottom(features[key]) all_previous_modalities.append(input_modality.name) # Transform the targets (for autoregressive models)
tensorflow.variable_scope
1,573
import tensorflow as tf x = tf.logical_not(tf.nn.in_top_k(logits, label, topk)) return tf.cast(x, tf.float32, name=name) wrong = prediction_incorrect(logits, label, 1, name='wrong-top1') add_moving_summary(tf.reduce_mean(wrong, name='train-error-top1')) wrong = prediction_incorrect(logits, label, 5, name='wrong-top5') add_moving_summary(tf.reduce_mean(wrong, name='train-error-top5'))
tensorflow.reduce_mean
1,574
import tensorflow as tf 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"} if custom_regularizers: custom_regularizers_names = [r.name for r in custom_regularizers] else: custom_regularizers = [tf.zeros([1])] custom_regularizers_names = ["none"] custom_regularizers_fileNames = {"fileName": "custom_regularizers"} # logging hooks tensors_to_average = [[wb_regularizers], [ac_regularizers, custom_regularizers]] tensors_to_average_names = [[wb_regularizers_names], [ac_regularizers_names, custom_regularizers_names]] tensors_to_average_plots = [[wb_regularizers_fileNames], [ac_regularizers_fileNames, custom_regularizers_fileNames]]
tensorflow.zeros
1,575
import tensorflow as tf dataset.training_X, dataset.training_y, dataset.validation_X, dataset.validation_y if not os.path.exists(weights_dir): os.mkdir(weights_dir) if not os.path.exists(weights_dir + '/best_models'): os.mkdir(weights_dir + '/best_models') # Create a saver. saver = tf.train.Saver(max_to_keep=None) if self.is_summary: training_batch_summary_op = tf.merge_all_summaries(key=TRAINING_BATCH_SUMMARIES) training_epoch_summary_op = tf.merge_all_summaries(key=TRAINING_EPOCH_SUMMARIES) validation_batch_summary_op = tf.merge_all_summaries(key=VALIDATION_BATCH_SUMMARIES) validation_epoch_summary_op = tf.merge_all_summaries(key=VALIDATION_EPOCH_SUMMARIES) # Build an initialization operation to run below. init = tf.global_variables_initializer() gpu_options = tf.GPUOptions( per_process_gpu_memory_fraction=self.cnf.get('gpu_memory_fraction', 0.9)) sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True, gpu_options=gpu_options)) sess.run(init) if start_epoch > 1: weights_from = "weights/model-epoch-%d.ckpt" % (start_epoch - 1) if weights_from: self._load_weights(sess, saver, weights_from) learning_rate_value = self.lr_policy.initial_lr log.info("Initial learning rate: %f " % learning_rate_value) if self.is_summary:
tensorflow.global_variables_initializer
1,576
import tensorflow as tf 'Conv2d_10_depthwise', 'Conv2d_10_pointwise', 'Conv2d_11_depthwise', 'Conv2d_11_pointwise', 'Conv2d_12_depthwise', 'Conv2d_12_pointwise', 'Conv2d_13_depthwise', 'Conv2d_13_pointwise'] for index, endpoint in enumerate(endpoints): with tf.Graph().as_default(): inputs = tf.random_uniform((batch_size, height, width, 3)) out_tensor, end_points = mobilenet_v1.mobilenet_v1_base( inputs, final_endpoint=endpoint) self.assertTrue(out_tensor.op.name.startswith( 'MobilenetV1/' + endpoint)) self.assertItemsEqual(endpoints[:index + 1], end_points.keys())
tensorflow.random_uniform
1,577
import tensorflow as tf # initial_state=self._initial_state) outputs = [] with tf.variable_scope("RNN"): for time_step in range(self.num_steps):
tensorflow.variable_scope
1,578
import tensorflow as tf orig_is_opt = opt_indices == orig_indices orig_opt_frac = tf.reduce_mean(tf.cast(orig_is_opt, tf.float32)) tf.compat.v2.summary.scalar( name="orig_task_optimal", data=orig_opt_frac, step=global_step) # How often is the relabelled goal optimal? # The relabel_indices are [B, 1], so we need to remove the extra dim. relabel_is_opt = tf.squeeze(relabel_indices) == orig_indices relabel_opt_frac = tf.reduce_mean(tf.cast(relabel_is_opt, tf.float32)) tf.compat.v2.summary.scalar( name="relabel_task_optimal", data=relabel_opt_frac, step=global_step) # What are the average Q values of the original tasks? if batch_size == num_tasks: indices = tf.transpose(tf.stack([orig_indices, orig_indices], axis=0)) orig_q_vals = tf.gather_nd(logits_vec, indices)
tensorflow.cast
1,579
import tensorflow as tf attention_head_size: int. Size of attention head. attention_probs_dropout_prob: float. dropout probability for attention_layer intermediate_size: int. Size of intermediate hidden layer. intermediate_act_fn: (optional) Activation function for the intermediate layer. initializer_range: float. Range of the weight initializer. hidden_dropout_prob: (optional) float. Dropout probability of the hidden layer. Returns: layer output """ with tf.variable_scope("attention_1"): with tf.variable_scope("self"): attention_output = attention_layer( from_tensor=layer_input, to_tensor=layer_input, attention_mask=attention_mask, num_attention_heads=num_attention_heads, attention_probs_dropout_prob=attention_probs_dropout_prob, initializer_range=initializer_range) # Run a linear projection of `hidden_size` then add a residual # with `layer_input`. with tf.variable_scope("output"): attention_output = dense_layer_3d_proj( attention_output,
tensorflow.variable_scope
1,580
import tensorflow as tf u = tf.contrib.layers.batch_norm(u) u = tf.nn.relu(u)
tensorflow.nn.relu
1,581
import tensorflow as tf # Decoder definition o_d1 = self.general_deconv2d(o_c5, self.base_number_of_features * 8, 3, stride = 2, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_deconv2d_1') o_me1 = tf.concat([o_d1, o_c4], 3) # Skip connection o_d2 = self.general_deconv2d(o_me1, self.base_number_of_features * 4, 3, stride = 2, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_deconv2d_2') o_me2 = tf.concat([o_d2, o_c3], 3) # Skip connection o_d3 = self.general_deconv2d(o_me2, self.base_number_of_features * 2, 3, stride = 2, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_deconv2d_3') o_me3 = tf.concat([o_d3, o_c2], 3) # Skip connection o_d4 = self.general_deconv2d(o_me3, self.base_number_of_features, 3, stride = 2, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_deconv2d_4') o_me4 = tf.concat([o_d4, o_c1], 3) # Skip connection logits = tf.layers.conv2d(o_me4, self.args.num_classes, 1, 1, 'SAME', activation = None) prediction = tf.nn.softmax(logits, name = name + '_softmax') 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.concat
1,582
import tensorflow as tf marker='.', c=sdf_values.numpy()[:, 0]) plt.colorbar() if not tf.math.is_nan(iou): self.iou_per_class[class_id].append(iou)
tensorflow.math.is_nan
1,583
import tensorflow as tf dataset = tf.data.TFRecordDataset(["./data/train.tfrecord"]) dataset = dataset.map(decode) dataset = dataset.map(normalize) dataset = dataset.batch(50) dataset = dataset.take(1) # keep validating on the same items dataset = dataset.repeat() iterator = dataset.make_one_shot_iterator() return iterator.get_next() def update_model(self, *grads): params = [self.w0, self.b0, self.w1, self.b1] grads = [tf.cast(grad, tf.float32) for grad in grads] with tf.name_scope('update'): update_op = tf.group(*[ param.assign(param - grad * self.LEARNING_RATE) for param, grad in zip(params, grads) ]) # return update_op with tf.name_scope('validate'): x, y = self._build_data_pipeline() y_hat, loss = self._build_validation_model(x, y)
tensorflow.cast
1,584
from tensorflow.python.platform import gfile # Created by the first helper. self.assertTrue(gfile.Exists(s1)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s1))) # Deleted by the first helper. self.assertFalse(gfile.Exists(s3)) self.assertFalse(gfile.Exists(save._MetaGraphFilename(s3))) self.assertTrue(gfile.Exists(s2)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s2))) # Adding s1 (s3 should not be deleted because helper is unaware of it) s1 = save3.save(sess, os.path.join(save_dir, "s1")) self.assertEqual([s2, s1], save3.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))) def testSharded(self): save_dir = os.path.join(self.get_temp_dir(), "max_to_keep_sharded") try: gfile.DeleteRecursively(save_dir) except OSError: pass # Ignore gfile.MakeDirs(save_dir) with tf.Session(
tensorflow.python.platform.gfile.Exists
1,585
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") @ops.RegisterShape("Sub") def _BroadcastShape(op): """Common shape function for binary operators that broadcast their inputs.""" shape_x = op.inputs[0].get_shape() shape_y = op.inputs[1].get_shape() if shape_x.ndims is None or shape_y.ndims is None:
tensorflow.python.framework.ops.RegisterShape
1,586
import tensorflow as tf h = x_shape[1] w = x_shape[2] pad_h1 = tf.mod(-h + bsize[1], bstrides[1]) pad_w1 = tf.mod(-w + bsize[2], bstrides[2])
tensorflow.mod
1,587
import tensorflow as tf """ with tf.variable_scope(name): inputdata = tf.transpose(inputdata, [0, 3, 1, 2]) n, c, h, w = inputdata.get_shape().as_list()
tensorflow.transpose
1,588
import tensorflow as tf init_bw = tf.tile(tf.Variable( tf.zeros([1, num_units])), [batch_size, 1]) mask_fw = dropout(tf.ones([batch_size, 1, input_size_], dtype=tf.float32), keep_prob=keep_prob, is_train=is_train, mode=None) mask_bw = dropout(tf.ones([batch_size, 1, input_size_], dtype=tf.float32), keep_prob=keep_prob, is_train=is_train, mode=None) self.grus.append((gru_fw, gru_bw, )) self.inits.append((init_fw, init_bw, ))
tensorflow.ones
1,589
import tensorflow as tf def net_U1(self, x): lambda_1 = self.lambda_1 lambda_2 = tf.exp(self.lambda_2) U = self.neural_net(x, self.weights, self.biases) U_x = self.fwd_gradients_1(U, x) U_xx = self.fwd_gradients_1(U_x, x) F = -lambda_1*U*U_x + lambda_2*U_xx U1 = U + self.dt*tf.matmul(F, (self.IRK_beta - self.IRK_alpha).T) return U1 def callback(self, loss): print('Loss:', loss) def train(self, nIter):
tensorflow.matmul
1,590
import tensorflow as tf images = tf.image.random_contrast(images, 0.6, 1.5) images = tf.image.random_flip_left_right(images)
tensorflow.image.random_flip_left_right
1,591
import tensorflow as tf config.gpu_options.allow_growth = True config.gpu_options.per_process_gpu_memory_fraction = 0.5 # Placeholders 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], 'rewards') self.keep_prob = tf.placeholder(tf.float32, name='dropout_keep_prob') # 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.batch(self.MINIBATCH, drop_remainder=True) self.data_iter = self.dataset.make_initializable_iterator() batch = self.data_iter.get_next() # Call ppo net pi_old, pi_old_params, _, _ = self.build_anet(batch['state'], 'oldpi') pi, pi_params, self.pi_state_init, self.pi_state_final = self.build_anet(batch['state'], 'pi')
tensorflow.placeholder
1,592
import tensorflow as tf # KL Divergence beta = 4 rho = 0.15 p_hat = tf.reduce_mean(activation_out, 0) # theano: p_hat = T.mean( self.a[i], axis=0 ) try: # TF1.0 KLD = beta * tf.reduce_sum(rho * tf.log(tf.divide(rho, p_hat)) + (1 - rho) * tf.log((1 - rho) / (tf.subtract(float(1), p_hat)))) except Exception: # TF0.12 KLD = beta * tf.reduce_sum(rho * tf.log(tf.div(rho, p_hat)) + (1 - rho) * tf.log((1 - rho) / (tf.sub(float(1), p_hat)))) # KLD = beta * tf.reduce_sum( rho * tf.log(rho/ p_hat) + (1- rho) * tf.log((1- rho)/(1- p_hat)) ) # theano: L1_a = l1_a[i] * T.sum( rho[i] * T.log(rho[i]/ p_hat) + (1- rho[i]) * T.log((1- rho[i])/(1- p_hat)) ) # Total cost if act == tf.nn.softplus: logging.info(' use: mse, L2_w, L1_a') self.cost = mse + L1_a + L2_w
tensorflow.div
1,593
import tensorflow as tf major, minor, _ = tf.version.VERSION.split('.') if not (int(major) >= 2 and tf2.enabled()): tf.compat.v1.logging.warning( 'Tensorflow version (%s) found. TransformFeaturesLayer is supported ' 'only for TF 2.x with TF 2.x behaviors enabled and may not work as ' 'intended.', tf.version.VERSION) elif int(major) == 2 and int(minor) < 3: # TODO(varshaan): Log a more specific warning. tf.compat.v1.logging.warning( 'Tensorflow version (%s) found. TransformFeaturesLayer may not work ' 'as intended if the SavedModel contains an initialization op.', tf.version.VERSION) # TODO(b/162055065): Possibly switch back to inherit from Layer when possible. @_maybe_register_keras_serializable(package='TensorFlowTransform')
tensorflow.compat.v1.logging.warning
1,594
import tensorflow as tf A dictionary of the initial values of the cluster centroids, cluster indices, original weights, the pretrained flag for marking the first training epoch, and weight name. """ result = {} weights = getattr(layer.layer, name) if self.preserve_sparsity and not tf.reduce_any(weights == 0): self.preserve_sparsity = False logging.warning( 'Input layer does not contain zero weights, so apply CQAT instead.') centroids_mask = None centroids, lookup = get_unique(weights) num_centroids = tf.size(centroids)
tensorflow.reduce_any
1,595
from tensorflow.contrib.layers.python.layers import feature_column self._assertSingleClassMetrics(metrics) def benchmarkCustomOptimizer(self): iris = test_data.prepare_iris_data_for_logistic_regression() cont_feature = feature_column.real_valued_column('feature', dimension=4) bucketized_feature = feature_column.bucketized_column( cont_feature, test_data.get_quantile_based_buckets(iris.data, 10))
tensorflow.contrib.layers.python.layers.feature_column.real_valued_column
1,596
from tensorflow.python.ops import math_ops A [D1, ... DN] `Tensor` of false positive counts. """ with ops.name_scope(None, 'false_positives', (predictions_idx, labels)): labels, predictions_idx = _maybe_select_class_id(labels, predictions_idx, class_id) fp = set_ops.set_size(set_ops.set_difference( predictions_idx, labels, aminusb=True)) fp = math_ops.to_double(fp) if weights is not None: weights = math_ops.to_double(weights) fp = math_ops.mul(fp, weights) return fp def _streaming_sparse_false_positive_at_k(predictions_idx, labels, k=None, class_id=None, weights=None, name=None): """Calculates weighted per step false positives for precision@k.
tensorflow.python.ops.math_ops.mul
1,597
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])
tensorflow.reshape
1,598
import tensorflow as tf wordidx_t = tf.multinomial(log_score_t, 1) # [batch_size, 1] wordidx_t = tf.reshape(wordidx_t, [-1]) # [batch_size] elif mode_gen in ('ce_train', 'loss',): wordidx_t = answer_batch_unstack[i] else: assert False, 'unknown generating mode %s' % mode_gen sampled_words.append(wordidx_t) if len(sampled_words)!=0: sampled_words = tf.stack(sampled_words, axis=1) # [batch_size, max_dec_steps] vocab_scores = tf.stack(vocab_scores, axis=1) # [batch_size, max_dec_steps, vocab] # calculating loss self._loss = None if mode_gen in ('ce_train', 'loss', ): xent = CE_loss(vocab_scores, answer_batch, loss_weights) # [batch_size] if mode_gen == 'loss': xent *= self.placeholders.reward # multiply with rewards self._loss = tf.reduce_mean(xent)
tensorflow.stack
1,599