seed
stringlengths
25
2.89k
seed_api
stringlengths
14
102
index
int64
0
14.8k
import tensorflow as tf mask_shape = list(map(int, self.mask.shape)) graph_typecheck.assert_shape(expanded_tensor, mask_shape + expected_extra_dims) value_if_masked = expanded_tensor.dtype.as_numpy_dtype(value_if_masked) if_masked_tensor = tf.fill(expanded_tensor.shape, value_if_masked) mask = self.mask for i in range(2, 2 + len(expected_extra_dims)): mask = tf.expand_dims(mask, axis=i)
tensorflow.fill
11,600
import tensorflow as tf if os.path.isdir(DATA_PATH): shutil.rmtree(DATA_PATH) os.mkdir(DATA_PATH) sess.run(tf.global_variables_initializer())
tensorflow.global_variables_initializer
11,601
import tensorflow as tf
tensorflow.Session
11,602
import tensorflow as tf if self.config.use_position_attn: start_logits = tf.squeeze( conv(self._attention(tf.concat([self.enc[1], self.enc[2]], axis=-1), name="attn1"), 1, bias=False, name="start_pointer"), -1) end_logits = tf.squeeze( conv(self._attention(tf.concat([self.enc[1], self.enc[3]], axis=-1), name="attn2"), 1, bias=False, name="end_pointer"), -1) else: start_logits = tf.squeeze( conv(tf.concat([self.enc[1], self.enc[2]], axis=-1), 1, bias=False, name="start_pointer"), -1) end_logits = tf.squeeze( conv(tf.concat([self.enc[1], self.enc[3]], axis=-1), 1, bias=False, name="end_pointer"), -1) self.logits = [mask_logits(start_logits, mask=tf.reshape(self.c_mask, [N, -1])), mask_logits(end_logits, mask=tf.reshape(self.c_mask, [N, -1]))] self.logits1, self.logits2 = [l for l in self.logits] outer = tf.matmul(tf.expand_dims(tf.nn.softmax(self.logits1), axis=2), tf.expand_dims(tf.nn.softmax(self.logits2), axis=1)) outer = tf.matrix_band_part(outer, 0, self.max_a_len) self.yp1 = tf.argmax(tf.reduce_max(outer, axis=2), axis=1) self.yp2 = tf.argmax(tf.reduce_max(outer, axis=1), axis=1) def _compute_loss(self): def focal_loss(logits, labels, weights=None, alpha=0.25, gamma=2): logits = tf.nn.sigmoid(logits)
tensorflow.reshape
11,603
import tensorflow as tf padding='same', activation=tf.nn.relu) self.drop3 = tf.layers.dropout(self.conv4, self.config.cifar10_cnn["keep_prob"], training=self.train) # b. Flatten input data self.flatten = tf.reshape(self.drop3, [-1, self.config.cifar10_cnn["fc1_nb_units"]]) # Create connected layers: fc1, fc2 with tf.contrib.framework.arg_scope([tf.contrib.layers.fully_connected], normalizer_fn=tf.contrib.layers.batch_norm, normalizer_params={"is_training": self.train}): self.fc1 = tf.contrib.layers.fully_connected(self.flatten, self.config.cifar10_cnn["fc1_nb_units"]) self.fc2 = tf.contrib.layers.fully_connected(self.fc1, self.config.data["num_categories"], activation_fn=None) # Compute loss with tf.name_scope("loss"): self.loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=self.fc2, labels=self.y)) # Optimizer with tf.name_scope("training_op"): self.training_op = tf.compat.v1.train.AdamOptimizer(self.learning_rate).minimize(self.loss)
tensorflow.contrib.layers.fully_connected
11,604
import tensorflow as tf regularizer = tf.contrib.layers.l2_regularizer(1e-4) def Convolutional_Block(inputs, shortcut, num_filters, name, is_training): print("-"*20) print("Convolutional Block", str(num_filters), name) print("-"*20) with tf.variable_scope("conv_block_" + str(num_filters) + "_" + name): for i in range(2): with tf.variable_scope("conv1d_%s" % str(i)): filter_shape = [3, inputs.get_shape()[2], num_filters] W = tf.get_variable(name='W', shape=filter_shape, initializer=he_normal, regularizer=regularizer) inputs = tf.nn.conv1d(inputs, W, stride=1, padding="SAME") inputs = tf.layers.batch_normalization(inputs=inputs, momentum=0.997, epsilon=1e-5, center=True, scale=True, training=is_training) inputs = tf.nn.relu(inputs) print("Conv1D:", inputs.get_shape()) print("-"*20) if shortcut is not None: print("-"*5) print("Optional Shortcut:", shortcut.get_shape()) print("-"*5) return inputs + shortcut return inputs
tensorflow.nn.conv1d
11,605
import tensorflow as tf return output def layer_normalization_layer(self, data): output = tf.contrib.layers.layer_norm(data) return output
tensorflow.contrib.layers.layer_norm
11,606
import tensorflow as tf def variable(self, name, shape, initializer,regularizer=None): with tf.device('/cpu:0'): return tf.get_variable(name, shape, initializer=initializer, regularizer=regularizer, trainable=True) def fc_layer(self, bottom, in_size, out_size, name): with tf.variable_scope(name): weights, biases = self.get_fc_var(in_size, out_size, name) x = tf.reshape(bottom, [-1, in_size]) fc = tf.nn.bias_add(tf.matmul(x, weights), biases) tf.summary.histogram('weight', weights) tf.summary.histogram('bias', biases) return fc def get_conv_var(self, filter_size, in_channels, out_channels, name): initial_value = tf.truncated_normal([filter_size, filter_size, in_channels, out_channels], 0.0, stddev = 1 / math.sqrt(float(filter_size * filter_size))) filters = self.get_var(initial_value = initial_value, name = name, idx = 'weights', var_name = "_filters") initial_value = tf.truncated_normal([out_channels], 0.0, 1.0) biases = self.get_var(initial_value = initial_value, name = name, idx = 'biases', var_name = "_biases") return filters, biases
tensorflow.summary.histogram
11,607
import tensorflow as tf inter = tf.reshape(values, [self.resolution, self.resolution, self.resolution]) inter = tf.transpose(tf.reduce_max(inter, axis=a)) im = axs[fig_obj_count, 4].matshow(inter.numpy()) plt.colorbar(im, ax=axs[fig_obj_count, 4]) print(mtype, fig_obj_count, 2) fig_obj_count += 1 intersection = tf.reduce_sum(tf.math.sign(tf.nn.relu(sdf_values - 1))) union = tf.reduce_sum(tf.math.sign(sdf_values)) iou = intersection / union if not tf.math.is_nan(iou): ious.append(iou) status3 = False if status3: _ = plt.figure(figsize=(5, 5)) plt.clf()
tensorflow.nn.relu
11,608
from tensorflow.python.framework import ops Args: x: `Tensor` numerator of numeric type. y: `Tensor` denominator of numeric type. name: A name for the operation (optional). Returns: `x / y` evaluated in floating point. Raises: TypeError: If `x` and `y` have different dtypes. """ with ops.op_scope([x, y], name, "truediv") as name: x = ops.convert_to_tensor(x, name="x") y = ops.convert_to_tensor(y, name="y") x_dtype = x.dtype.base_dtype y_dtype = y.dtype.base_dtype if x_dtype != y_dtype: raise TypeError("x and y must have the same dtype, got %r != %r" % (x_dtype, y_dtype)) try: dtype = _TRUEDIV_TABLE[x_dtype] except KeyError: raise TypeError("Invalid dtype %r in __truediv__" % x_dtype) if dtype is not None:
tensorflow.python.framework.ops.convert_to_tensor
11,609
import tensorflow as tf filename = os.path.join(test_dir, "metafile") with self.test_session(): # Creates a graph. v0 = tf.Variable(10.0, name="v0") var = tf.Variable(tf.constant(0, dtype=tf.int64)) count_up_to = var.count_up_to(3) input_queue = tf.FIFOQueue(30, tf.float32, shared_name="collection_queue") qr = tf.train.QueueRunner(input_queue, [count_up_to]) tf.initialize_all_variables() # Creates a saver. save = tf.train.Saver({"v0": v0}) # Adds a set of collections. tf.add_to_collection("int_collection", 3) tf.add_to_collection("float_collection", 3.5) tf.add_to_collection("string_collection", "hello") tf.add_to_collection("variable_collection", v0) # Add QueueRunners. tf.train.add_queue_runner(qr) # Adds user_defined proto in three formats: string, bytes and Any. queue_runner = queue_runner_pb2.QueueRunnerDef(queue_name="test_queue") tf.add_to_collection("user_defined_string_collection", str(queue_runner)) tf.add_to_collection("user_defined_bytes_collection", queue_runner.SerializeToString()) any_buf = Any() any_buf.Pack(queue_runner) tf.add_to_collection("user_defined_any_collection", any_buf)
tensorflow.add_to_collection
11,610
from tensorflow.python.ops import variable_scope ValueError: If `weights` is not `None` and its shape doesn't match `values`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ with variable_scope.variable_scope(name, 'mean', [values, weights]): values = math_ops.to_float(values) total = _create_local('total', shape=[])
tensorflow.python.ops.variable_scope.variable_scope
11,611
import tensorflow as tf enc_inp, dec_inp, cell, num_symbols=5, embedding_size=2, output_projection=(w, b)) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 2), res[0].shape) # Test that previous-feeding model ignores inputs after the first. dec_inp2 = [tf.constant(0, tf.int32, shape=[2])] * 3 with tf.variable_scope("other"): d3, _ = tf.nn.seq2seq.embedding_tied_rnn_seq2seq( enc_inp, dec_inp2, cell, num_symbols=5, embedding_size=2, feed_previous=tf.constant(True)) sess.run([tf.global_variables_initializer()]) tf.get_variable_scope().reuse_variables() d1, _ = tf.nn.seq2seq.embedding_tied_rnn_seq2seq(
tensorflow.constant
11,612
import tensorflow as tf def center_crop(image, size): image_height = tf.shape(image)[0] image_width = tf.shape(image)[1] offset_height = (image_height - size) // 2 offset_width = (image_width - size) // 2 image = tf.slice(image, [offset_height, offset_width, 0], [size, size, -1]) return image def lighting(image, std, eigval, eigvec): v = tf.random_normal(shape=[3], stddev=std) * eigval inc = tf.matmul(eigvec, tf.reshape(v, [3, 1])) image = tf.cast(tf.cast(image, tf.float32) + tf.reshape(inc, [3]), image.dtype) return image def validation_mapper(byte): image = tf.image.decode_jpeg( tf.reshape(byte, shape=[]), 3, **JPEG_OPT) image = resize_shortest_edge(image, tf.shape(image), 256) image = center_crop(image, 224)
tensorflow.random_normal
11,613
import tensorflow as tf if full_tensorboard_log: tf.summary.histogram('rewards', rew_t_ph) tf.summary.histogram('importance_weights', importance_weights_ph) if tf_util.is_image(obs_phs[0]): tf.summary.image('observation', obs_phs[0])
tensorflow.summary.histogram
11,614
import tensorflow as tf 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 def build_cnet(self, state_in, name, reuse=False): reg = tf.contrib.layers.l2_regularizer(1e-3) with tf.variable_scope(name, reuse=reuse): layer_c1 = tf.layers.dense(state_in, 512, tf.nn.relu, kernel_regularizer=reg) layer_c2 = tf.layers.dense(layer_c1, 256, tf.nn.relu, kernel_regularizer=reg) vf = tf.layers.dense(layer_c2, 1, kernel_regularizer=reg) params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=name) return vf, params # Update the network def train(self, s, a, r, adv): start = time()
tensorflow.contrib.layers.l2_regularizer
11,615
import tensorflow as tf with tf.control_dependencies(init_ops):
tensorflow.control_dependencies
11,616
import tensorflow as tf a scalar tensor representing the correlation loss value. """ with tf.variable_scope(name): batch_size = tf.shape(source_samples)[0] samples = tf.concat(values=[source_samples, target_samples], axis=0) samples = flatten(samples) domain_selection_mask = tf.concat(
tensorflow.concat
11,617
import tensorflow as tf self.assertEqual(output.shape, (batch_size,)) def testTrainEvalWithReuse(self): train_batch_size = 5 eval_batch_size = 2 height, width = 150, 150 num_classes = 1000 train_inputs = tf.random_uniform((train_batch_size, height, width, 3)) mobilenet_v1.mobilenet_v1(train_inputs, num_classes) eval_inputs = tf.random_uniform((eval_batch_size, height, width, 3)) logits, _ = mobilenet_v1.mobilenet_v1(eval_inputs, num_classes, reuse=True) predictions = tf.argmax(logits, 1) with self.test_session() as sess:
tensorflow.random_uniform
11,618
import tensorflow as tf relevant example. propensity_weights: (tf.Tensor) A tensor of the same shape as `output` containing the weight of each element. name: A string used as the name for this variable scope. Returns: (tf.Tensor) A single value tensor containing the loss. """ # loss = None with tf.name_scope(name, "click_loglikelihood"): ob_prob=tf.nn.softmax(propensity) rel_prob=tf.nn.softmax(train_output) click_prob=ob_prob*rel_prob click_prob_norm=click_prob/tf.reduce_sum(click_prob,axis=1,keep_dims=True) label_dis = labels/ tf.reduce_sum(labels, 1, keep_dims=True) entropy = tf.reduce_sum(tf.math.log(click_prob_norm)*label_dis,1) return tf.reduce_mean(entropy) def click_weighted_pairwise_loss(self, output, labels, propensity_weights, name=None): """Computes pairwise entropy loss with propensity weighting.
tensorflow.nn.softmax
11,619
from tensorflow.python.framework import ops def _define_vars(self, params): pass def inference_graph(self, data): with ops.device(self.device_assigner): # Compute activations for the neural network. nn_activations = [layers.fully_connected(data, self.params.layer_size)] for _ in range(1, self.params.num_layers):
tensorflow.python.framework.ops.device
11,620
import tensorflow as tf ) self.assertAllClose( augmented_tensor_dict_out[fields.InputDataFields.groundtruth_boxes], [[10, 10, 20, 20]] ) self.assertAllClose( augmented_tensor_dict_out[fields.InputDataFields.groundtruth_keypoints], [[[10, 20], [10, 10]]] ) def _fake_model_preprocessor_fn(image): return (image, tf.expand_dims(tf.shape(image)[1:], axis=0)) def _fake_image_resizer_fn(image, mask): return (image, mask, tf.shape(image)) class DataTransformationFnTest(test_case.TestCase): def test_combine_additional_channels_if_present(self): image = np.random.rand(4, 4, 3).astype(np.float32) additional_channels = np.random.rand(4, 4, 2).astype(np.float32)
tensorflow.shape
11,621
import tensorflow as tf output = run_node(node_def, []) np.testing.assert_equal(output["Y"].shape, shape) np.testing.assert_almost_equal(output["Y"].flatten(), values) # test sparse tensor if not legacy_opset_pre_ver(11): expected = np.array([[1, 0, 0, 0], [0, 0, 2, 0], [0, 0, 0, 0]]) x = np.array([[0, 0], [1, 2]]).flatten().astype(np.int64) values = helper.make_tensor("values", TensorProto.INT32, [2], [1, 2]) indices = helper.make_tensor("indices", TensorProto.INT64, [2, 2], x) a = helper.make_sparse_tensor(values, indices,[3, 4]) node_def = helper.make_node("Constant", [], ["Y"], sparse_value=a) output = run_node(node_def, []) b = tf.sparse_to_dense(output["Y"].indices, output["Y"].dense_shape, output["Y"].values) result = b.eval(session=tf.Session()) np.testing.assert_equal(result, expected) def test_constant_fill(self): if not legacy_opset_pre_ver(9): raise unittest.SkipTest( "ONNX version {} doesn't support ConstantFill.".format( defs.onnx_opset_version())) shape = [1, 2, 3, 4] extra_shape = [5, 6] value = 3. node_def = helper.make_node( "ConstantFill", ["X"],
tensorflow.Session
11,622
import tensorflow as tf def build_batch_stats(): """Builds the batch statistics calculation ops.""" # We use the moving mean as an estimate of the mean in order to perform # a more numerically stable calculation of the batch mean. # Copy for better stability. shift = tf.add(self._moving_mean, 0) counts, shifted_sum_x, shifted_sum_x2, _ = tf.nn.sufficient_statistics( input_batch, reduction_indices, keep_dims=True, shift=shift, name="batch_norm_ss")
tensorflow.nn.sufficient_statistics
11,623
import tensorflow as tf print(" [*] Reading checkpoint...") model_dir = "%s_%s" % (self.dataset_dir, self.image_size) checkpoint_dir = os.path.join(checkpoint_dir, model_dir) ckpt = tf.train.get_checkpoint_state(checkpoint_dir) if ckpt and ckpt.model_checkpoint_path: ckpt_name = os.path.basename(ckpt.model_checkpoint_path) self.saver.restore(self.sess, os.path.join(checkpoint_dir, ckpt_name)) return True
tensorflow.train.get_checkpoint_state
11,624
import tensorflow as tf vat_loss, ul_u_updated = vat.virtual_adversarial_loss(ul_x, ul_u, ul_logit) ent_loss = L.entropy_y_x(ul_logit) additional_loss = vat_loss + ent_loss elif FLAGS.method == 'baseline': additional_loss = 0 else: raise NotImplementedError loss = nll_loss + additional_loss opt = tf.train.AdamOptimizer(learning_rate=lr, beta1=mom) tvars = tf.trainable_variables() grads_and_vars = opt.compute_gradients(loss, tvars) train_op = opt.apply_gradients(grads_and_vars, global_step=global_step) return loss, train_op, global_step, ul_u_updated def build_eval_graph(x, y, ul_x, ul_u): losses = {}
tensorflow.train.AdamOptimizer
11,625
import tensorflow.contrib.graph_editor as ge bottleneck_ts = [] for t in ts: b = set(ge.get_backward_walk_ops(t.op, inclusive=True, within_ops=fwd_ops)) f = set(ge.get_forward_walk_ops(t.op, inclusive=False, within_ops=fwd_ops))
tensorflow.contrib.graph_editor.get_backward_walk_ops
11,626
from tensorflow.python.framework import ops with ops.control_dependencies([train_step]): with ops.get_default_graph().colocate_with(global_step):
tensorflow.python.framework.ops.get_default_graph
11,627
import tensorflow as tf batch_size = tf.shape(attention_weights)[0] src_len = tf.shape(attention_weights)[2] trg_len = tf.shape(attention_weights)[1] src_indices = tf.tile(tf.reshape(tf.range(src_len), shape=[1, 1, src_len]), [batch_size, trg_len, 1]) trg_indices = tf.tile(tf.reshape(tf.range(trg_len), shape=[1, trg_len, 1]), [batch_size, 1, src_len]) source_length = encoder_input_length[0] target_length = tf.to_int32(tf.reduce_sum(trg_mask, axis=1)) true_src_len = tf.reshape(source_length, shape=[batch_size, 1, 1]) - 1 true_trg_len = tf.reshape(target_length, shape=[batch_size, 1, 1]) - 1 src_mask = tf.to_float(tf.sequence_mask(source_length, maxlen=src_len)) mask = tf.matmul(tf.expand_dims(trg_mask, axis=2), tf.expand_dims(src_mask, axis=1)) monotonous = tf.sqrt(((true_trg_len * src_indices - true_src_len * trg_indices) ** 2)
tensorflow.reduce_sum
11,628
import tensorflow as tf def stable_var(input_, mean=None, axes=[0]): """Numerically more stable variance computation.""" if mean is None: mean = tf.reduce_mean(input_, axes) res = tf.square(input_ - mean) max_sqr = tf.reduce_max(res, axes) res /= max_sqr res = tf.reduce_mean(res, axes) res *= max_sqr
tensorflow.square
11,629
import tensorflow as tf 'Could not compute vocabulary size for {}, does not exist'.format( vocab_filename)) elif vocab_path.endswith('tfrecord.gz'): dataset = tf.data.TFRecordDataset(vocab_path, compression_type='GZIP') def reduce_fn(accum, elem): return tf.size(elem, out_type=tf.int64, name='vocabulary_size') + accum return _get_tensor_value( dataset.batch(tf.int32.max).reduce( tf.constant(0, tf.int64), reduce_fn)) else: with tf.io.gfile.GFile(vocab_path, 'rb') as f: return sum(1 for _ in f) def vocabulary_by_name(self, vocab_filename: str) -> List[bytes]: """Like vocabulary_file_by_name but returns a list.""" vocab_path = self.vocabulary_file_by_name(vocab_filename) if not vocab_path: raise ValueError('Could not read vocabulary: {}, does not exist'.format(
tensorflow.constant
11,630
import tensorflow as tf print(v.op.name + " - loaded successfully") print("All pretrained weights of resnet18 is loaded") def _residual_block(self, name, x, filters, pool_first=False, strides=1, dilation=1): print('Building residual unit: %s' % name) with tf.variable_scope(name): # get input channels in_channel = x.shape.as_list()[-1] # Shortcut connection shortcut = tf.identity(x) if pool_first: if in_channel == filters: if strides == 1: shortcut = tf.identity(x) else: shortcut= tf.pad(x, tf.constant([[0,0],[1,1],[1,1],[0,0]]), "CONSTANT") shortcut = tf.nn.max_pool(shortcut, [1, strides, strides, 1], [1, strides, strides, 1], 'VALID') else: shortcut = self._conv('shortcut_conv', x, padding='VALID', num_filters=filters, kernel_size=(1, 1), stride=(strides, strides), bias=self.bias) else: if dilation != 1: shortcut = self._conv('shortcut_conv', x, padding='VALID', num_filters=filters, kernel_size=(1, 1), dilation=dilation, bias=self.bias) # Residual x = self._conv('conv_1', x, padding=[[0,0],[1,1],[1,1],[0,0]],
tensorflow.identity
11,631
import tensorflow as tf elif args.experiment_type == "sweep": test = ContextAESweep() test.build(tfinput, args.ablation_type) config = tf.ConfigProto() config.gpu_options.allow_growth=True sess = tf.Session(config=config) learning_rate = tf.placeholder(tf.float32, shape=[]) optimizer = tf.train.AdamOptimizer(learning_rate).minimize(test.loss) sess.run(tf.global_variables_initializer()) allloss = [] validloss = [] itr = 0 saver = tf.train.Saver()
tensorflow.Session
11,632
import tensorflow as tf bounds=bounds, var_list=variables, # supply with bounds to match order! tol=1e-14, ) tf.scalar_summary('nll', nll) init_op = tf.initialize_all_variables() # from http://stackoverflow.com/a/35907755/1199693
tensorflow.scalar_summary
11,633
import tensorflow as tf ])), 1), [1, 0]) rep = tf.to_int32(rep) x = tf.matmul(tf.reshape(x, (-1, 1)), rep) return tf.reshape(x, [-1])
tensorflow.reshape
11,634
import tensorflow as tf head_init = dense_maxnorm(head_init, self.maxnorm) rel_init = dense_maxnorm(rel_init, self.maxnorm) tail_init = dense_maxnorm(tail_init, self.maxnorm) self.head_embedding_vars = tf.Variable(head_init) self.rel_embedding_vars = tf.Variable(rel_init) self.tail_embedding_vars = tf.Variable(tail_init) # Embedding layer for each (head, rel, tail) triple being fed in as input head_embed = tf.nn.embedding_lookup(self.head_embedding_vars, self.head_input) rel_embed = tf.nn.embedding_lookup(self.rel_embedding_vars, self.rel_input) tail_embed = tf.nn.embedding_lookup(self.tail_embedding_vars, self.tail_input) # Model output raw_output = tf.reduce_sum(tf.mul(tf.mul(head_embed, rel_embed), tail_embed), 1) self.output, self.loss = self._create_output_and_loss(raw_output) # Optimization self.train_step = self.opt.minimize(self.loss) if self.maxnorm is not None: # Post-processing to limit embedding vars to L2 ball head_constraint = self._norm_constraint_op(self.head_embedding_vars,
tensorflow.nn.embedding_lookup
11,635
import tensorflow as tf output_spec = None if mode == tf.estimator.ModeKeys.TRAIN: train_op = optimization.create_optimizer( total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu) output_spec = tf.contrib.tpu.TPUEstimatorSpec( mode=mode, loss=total_loss, train_op=train_op, scaffold_fn=scaffold_fn) elif mode == tf.estimator.ModeKeys.EVAL:
tensorflow.contrib.tpu.TPUEstimatorSpec
11,636
import tensorflow as tf [1, 1, 1, 1, 0, 0, 0, 0]], dtype=tf.float32) mask1 = tf.constant([[1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], dtype=tf.float32) mask2 = tf.constant([[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1, 1]], dtype=tf.float32) masks = tf.stack([mask0, mask1, mask2]) return masks
tensorflow.constant
11,637
import tensorflow as tf trainable=False) def build_batch_stats(): """Builds the batch statistics calculation ops.""" # We use the moving mean as an estimate of the mean in order to perform # a more numerically stable calculation of the batch mean. # Copy for better stability. shift = tf.add(self._moving_mean, 0) counts, shifted_sum_x, shifted_sum_x2, _ = tf.nn.sufficient_statistics( input_batch, reduction_indices, keep_dims=True, shift=shift, name="batch_norm_ss")
tensorflow.add
11,638
import tensorflow as tf ema = tf.train.ExponentialMovingAverage(decay=0.9) def mean_var_with_update(): ema_apply_op = ema.apply([batch_mean, batch_var]) with tf.control_dependencies([ema_apply_op]): return tf.identity(batch_mean), tf.identity(batch_var) mean, var = tf.cond(b_train, mean_var_with_update, lambda: (ema.average(batch_mean), ema.average(batch_var)))
tensorflow.identity
11,639
import tensorflow as tf 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 ortho_init(scale=1.0): def _ortho_init(shape, dtype, partition_info=None):
tensorflow.concat
11,640
import tensorflow as tf grads = tf.gradients(loss, self.params) norm_grads = None if self.max_grad_norm is not None: grads, norm_grads = tf.clip_by_global_norm(grads, self.max_grad_norm) grads = list(zip(grads, self.params)) with tf.variable_scope("input_info", reuse=False): tf.summary.scalar('rewards', tf.reduce_mean(self.reward_ph)) tf.summary.scalar('learning_rate', tf.reduce_mean(self.learning_rate)) tf.summary.scalar('advantage', tf.reduce_mean(adv)) tf.summary.scalar('action_probability', tf.reduce_mean(self.mu_ph)) if self.full_tensorboard_log: tf.summary.histogram('rewards', self.reward_ph) tf.summary.histogram('learning_rate', self.learning_rate) tf.summary.histogram('advantage', adv) tf.summary.histogram('action_probability', self.mu_ph) if tf_util.is_image(self.observation_space): tf.summary.image('observation', train_model.obs_ph) else: tf.summary.histogram('observation', train_model.obs_ph) trainer = tf.train.RMSPropOptimizer(learning_rate=self.learning_rate_ph, decay=self.rprop_alpha, epsilon=self.rprop_epsilon) _opt_op = trainer.apply_gradients(grads) # so when you call _train, you first do the gradient step, then you apply ema
tensorflow.summary.histogram
11,641
import tensorflow as tf while True: random.shuffle(train_examples) for example in train_examples: tensorized_example = self.tensorize_example(example, is_training=True) feed_dict = dict(zip(self.queue_input_tensors, tensorized_example)) session.run(self.enqueue_op, feed_dict=feed_dict) enqueue_thread = threading.Thread(target=_enqueue_loop) enqueue_thread.daemon = True enqueue_thread.start() def restore(self, session): # Don't try to restore unused variables from the TF-Hub ELMo module. vars_to_restore = [v for v in tf.global_variables() if "module/" not in v.name] saver = tf.train.Saver(vars_to_restore) checkpoint_path = os.path.join(self.config["log_dir"], "model.max.ckpt") print("Restoring from {}".format(checkpoint_path)) session.run(tf.global_variables_initializer()) saver.restore(session, checkpoint_path) def load_lm_embeddings(self, doc_key): if self.lm_file is None: return np.zeros([0, 0, self.lm_size, self.lm_layers]) file_key = doc_key.replace("/", ":") group = self.lm_file[file_key]
tensorflow.global_variables
11,642
import tensorflow as tf assert len(input_ids) == max_seq_length assert len(input_mask) == max_seq_length assert len(segment_ids) == max_seq_length if ex_index < 5: tf.logging.info("*** Example ***") tf.logging.info("id: %s" % (example.unique_id)) tf.logging.info("tokens: %s" % " ".join( [tokenization.printable_text(x) for x in input_tokens])) tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids])) tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
tensorflow.logging.info
11,643
import tensorflow as tf "input_ids": tf.FixedLenFeature([max_seq_length], tf.int64), "input_mask": tf.FixedLenFeature([max_seq_length], tf.int64), "segment_ids": tf.FixedLenFeature([max_seq_length], tf.int64), "masked_lm_positions": tf.FixedLenFeature( [max_predictions_per_seq], tf.int64 ), "masked_lm_ids": tf.FixedLenFeature([max_predictions_per_seq], tf.int64), "masked_lm_weights": tf.FixedLenFeature( [max_predictions_per_seq], tf.float32 ), "next_sentence_labels": tf.FixedLenFeature([1], tf.int64), }
tensorflow.FixedLenFeature
11,644
import tensorflow as tf # Construct predictions image = tf.placeholder(tf.float32, shape=[hps.batch_size, image_size, image_size, num_channel]) ############MNIST and CIFAR10 are different ar here
tensorflow.placeholder
11,645
from tensorflow.contrib.learn.python.learn.datasets import base train_path = os.path.join(module_path, 'data', 'text_train.csv') test_path = os.path.join(module_path, 'data', 'text_test.csv') train = base.load_csv_without_header( train_path, target_dtype=np.int32, features_dtype=np.str, target_column=0) test = base.load_csv_without_header(
tensorflow.contrib.learn.python.learn.datasets.base.load_csv_without_header
11,646
import tensorflow as tf images = tf.constant(1.2, tf.float32, shape=[100, 28]) with tf.name_scope("hidden1"):
tensorflow.name_scope
11,647
import tensorflow as tf elif activation == "elu": new_context_act = tf.nn.elu(new_context) elif activation == "linear": new_context_act = tf.identity(new_context) else: raise RuntimeError gate_sig = tf.nn.sigmoid(gate) combination_res = gate_sig * new_context_act + (1 - gate_sig) * rep_map # bs,bn,bl,vec with tf.variable_scope('restore_original_length'): combination_res_reshape = tf.reshape(combination_res, [bs, bn * bl, ivec]) # bs,bn*bl,vec output = combination_res_reshape[:, :sl, :]
tensorflow.nn.sigmoid
11,648
import tensorflow as tf output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt") with open(output_eval_file, "w") as writer: tf.logging.info("***** Eval results *****") for key in sorted(result.keys()): tf.logging.info(" %s = %s", key, str(result[key])) writer.write("%s = %s\n" % (key, str(result[key]))) if __name__ == "__main__": tf.app.run()
tensorflow.app.run
11,649
from tensorflow.python.framework import ops return [op.inputs[1].get_shape()] @ops.RegisterShape("AssignAdd") @ops.RegisterShape("AssignSub") def _AssignUpdateShape(op): """Shape function for the AssignAdd and AssignSub dense update ops.""" return [op.inputs[0].get_shape().merge_with(op.inputs[1].get_shape())]
tensorflow.python.framework.ops.RegisterShape
11,650
import tensorflow as tf if hparams.predict_linear: tf.summary.scalar("linear_loss", model.linear_loss) for i in range(hparams.tacotron_num_gpus): tf.summary.histogram("mel_outputs %d" % i, model.tower_linear_outputs[i]) tf.summary.histogram("mel_targets %d" % i, model.tower_linear_targets[i]) tf.summary.scalar("regularization_loss", model.regularization_loss) tf.summary.scalar("stop_token_loss", model.stop_token_loss) tf.summary.scalar("loss", model.loss) tf.summary.scalar("learning_rate", model.learning_rate) # Control learning rate decay speed if hparams.tacotron_teacher_forcing_mode == "scheduled": tf.summary.scalar("teacher_forcing_ratio", model.ratio) # Control teacher forcing # ratio decay when mode = "scheduled" gradient_norms = [tf.norm(grad) for grad in model.gradients] tf.summary.histogram("gradient_norm", gradient_norms) tf.summary.scalar("max_gradient_norm", tf.reduce_max(gradient_norms)) # visualize # gradients (in case of explosion) return tf.summary.merge_all()
tensorflow.summary.scalar
11,651
from tensorflow.contrib import framework as contrib_framework build model. Args: features: `Tensor` or `dict` of `Tensor` objects. targets: `Tensor` or `dict` of `Tensor` objects. Returns: Tuple of train `Operation` and loss `Tensor`. """ _, loss = self._model_fn(features, targets, ModeKeys.TRAIN) train_op = layers.optimize_loss( loss, contrib_framework.get_global_step(), learning_rate=self.learning_rate, optimizer=self.optimizer, clip_gradients=self.clip_gradients) return train_op, loss def _get_eval_ops(self, features, targets, metrics): """Method that builds model graph and returns evaluation ops. Expected to be overriden by sub-classes that require custom support. This implementation uses `model_fn` passed as parameter to constructor to build model.
tensorflow.contrib.framework.get_global_step
11,652
import tensorflow as tf (common_image_attention.DistributionType.CAT, None, 256), ) def testPostProcessImageInferMode(self, likelihood, num_mixtures, depth): 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], )
tensorflow.contrib.training.HParams
11,653
import tensorflow as tf horizon_tgt = horizon_sumV1(tgt, horizon) pred_flat = tf.reshape(horizon_pred, [-1]) tgt_flat = tf.reshape(horizon_tgt, [-1]) batch = tf.stack([pred_flat, tgt_flat], 1) sample_func = sample_pair(batch) def sample_compute(_): pairs = sample_func() loss = compute_contra_loss(*pairs, hard_ratio=hard_ratio) pct = tf.math.count_nonzero(loss, dtype=tf.float32) / tf.size(loss, out_type=tf.float32) p = tf.cond(tf.random_uniform((), dtype=tf.float32) < 1e-4, lambda: tf.print('csrt acc ', [pct]), lambda: tf.no_op()) with tf.control_dependencies([p]): return tf.reduce_mean(loss) loss = tf.map_fn(fn=lambda inp: sample_compute(inp), elems=tf.range(resample), dtype=tf.float32, parallel_iterations=32) final_loss = tf.reduce_mean(loss) return final_loss def contra_traj_lossV6(pred, tgt, horizon=12): horizon_pred, horizon_tgt = horizon_sumV1(pred, horizon), horizon_sumV1(tgt, horizon) # horizon_pred, horizon_tgt = horizon_sumV2(pred, tgt, horizon) pred_flat1, pred_flat2 = tf.reshape(horizon_pred, [-1, 1]), tf.reshape(horizon_pred, [1, -1]) tgt_flat1, tgt_flat2 = tf.reshape(horizon_tgt, [-1, 1]), tf.reshape(horizon_tgt, [1, -1])
tensorflow.control_dependencies
11,654
import tensorflow as tf # pre-calculate cumsum cumsum_y_pred = tf.cumsum(y_pred) hazard_ratio = tf.exp(y_pred) cumsum_hazard_ratio = tf.cumsum(hazard_ratio)
tensorflow.exp
11,655
import tensorflow as tf values = [] bleu = 100 * bleu_hook.bleu_wrapper( decode_hparams.decode_reference, decode_hparams.decode_to_file) values.append(tf.Summary.Value(tag="BLEU", simple_value=bleu)) tf.logging.info("%s: BLEU = %6.2f" % (decode_hparams.decode_to_file, bleu)) if hook_args.hparams.mlperf_mode: current_step = decode_hparams.mlperf_decode_step
tensorflow.Summary.Value
11,656
import tensorflow as tf output_weights = tf.get_variable( "output_weights", shape=[2, bert_config.hidden_size], initializer=modeling.create_initializer(bert_config.initializer_range)) output_bias = tf.get_variable( "output_bias", shape=[2], initializer=tf.zeros_initializer()) logits = tf.matmul(input_tensor, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias) if clip: log_probs = tf.log(tf.clip_by_value(tf.nn.softmax(logits, axis=-1), 1e-6, 1.0 - 1e-6)) else: log_probs = tf.nn.log_softmax(logits, axis=-1) labels = tf.reshape(labels, [-1])
tensorflow.matmul
11,657
import tensorflow as tf initializer=tf.constant_initializer(0), trainable=False) label = tf.reshape(label, [-1]) centers_batch = tf.gather(centers, label) diff = (1 - alfa) * (centers_batch - features) centers = tf.scatter_sub(centers, label, diff) # centers = tf.nn.l2_normalize(centers, 1, 1e-10, name='centers_norm') loss = tf.reduce_mean(tf.square(features - centers_batch)) return loss, centers
tensorflow.scatter_sub
11,658
import tensorflow as tf outputs = tf.matmul(inputs_, tf.transpose( memory_, [0, 2, 1])) / (hidden ** 0.5) mask = tf.tile(tf.expand_dims(mask, axis=1), [1, JX, 1]) logits = tf.nn.softmax(softmax_mask(outputs, mask)) outputs = tf.matmul(logits, memory) res = tf.concat([inputs, outputs], axis=2) with tf.variable_scope("gate"): dim = res.get_shape().as_list()[-1] d_res = dropout(res, keep_prob=keep_prob, is_train=is_train)
tensorflow.concat
11,659
import tensorflow as tf name="update_moving_variance").op return update_mean_op, update_variance_op def build_no_ops(): return (tf.no_op(), tf.no_op()) # Only make the ops if we know that `is_training=True`, or the value of # `is_training` is unknown. is_training_const = utils.constant_value(is_training)
tensorflow.no_op
11,660
import tensorflow as tf # Pad mask. mask_ = tf.expand_dims(mask, 3) mask_ = _pad_input(mask_, ksize, strides, padding, bsize=bsize, bstrides=bstrides)
tensorflow.expand_dims
11,661
import tensorflow as tf Can be empty. """ sum_loss = _gather_clone_loss(clone, num_clones, regularization_losses) clone_grad = None if sum_loss is not None: with tf.device(clone.device): clone_grad = optimizer.compute_gradients(sum_loss, **kwargs) return sum_loss, clone_grad
tensorflow.device
11,662
import tensorflow as tf regularization_loss = tf.losses.get_regularization_loss() # create localization and classification losses losses = ssd.loss(labels, params) tf.losses.add_loss(params['localization_loss_weight'] * losses['localization_loss']) tf.losses.add_loss(params['classification_loss_weight'] * losses['classification_loss']) tf.summary.scalar('regularization_loss', regularization_loss) tf.summary.scalar('localization_loss', losses['localization_loss']) tf.summary.scalar('classification_loss', losses['classification_loss']) total_loss = tf.losses.get_total_loss(add_regularization_losses=True) if mode == tf.estimator.ModeKeys.EVAL: batch_size = features['images'].shape[0].value assert batch_size == 1
tensorflow.summary.scalar
11,663
import tensorflow as tf vz = tf.contrib.lookup.MutableHashTable(key_dtype=tf.string, value_dtype=tf.int64, default_value=-1) vx_keys = tf.reshape(tf.Variable([], collections=[], dtype=tf.string), (-1, 1)) vz_keys = tf.reshape(tf.Variable([], collections=[], dtype=tf.string), (-1, 1)) x_t = tf.gather(x, l) x_t_len = tf.strings.length(x_t) x_t = tf.string_split([x_t], delimiter='').values z_t = tf.gather(y, m) z_t_len = tf.strings.length(z_t) z_t = tf.string_split([z_t], delimiter='').values
tensorflow.gather
11,664
import tensorflow as tf perturb_ops.append(operation) 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. with tf.variable_scope("adaptive_model", reuse=False): adaptive_policy = q_func(sess, ob_space, ac_space, 1, 1, None, obs_phs=obs_phs) perturb_for_adaption = perturb_vars(original_scope="model", perturbed_scope="adaptive_model/model") kl_loss = tf.reduce_sum( tf.nn.softmax(policy.q_values) * (tf.log(tf.nn.softmax(policy.q_values)) - tf.log(tf.nn.softmax(adaptive_policy.q_values))), axis=-1) mean_kl = tf.reduce_mean(kl_loss) def update_scale(): """ update the scale expression :return: (TensorFlow Tensor) the updated scale expression """ with tf.control_dependencies([perturb_for_adaption]): update_scale_expr = tf.cond(mean_kl < param_noise_threshold,
tensorflow.nn.softmax
11,665
from tensorflow.python.ops import math_ops target = target[self.name] if isinstance(target, dict) else target loss_unweighted = self._loss_fn(logits, target) weight_tensor = self.get_weight_tensor(features) if weight_tensor is None: return math_ops.reduce_mean(loss_unweighted, name="loss") else: loss_unweighted = array_ops.reshape(loss_unweighted, shape=(-1,)) loss_weighted = math_ops.mul( loss_unweighted,
tensorflow.python.ops.math_ops.reduce_mean
11,666
import tensorflow as tf for pt in [pt_0, pt_1, pt_2, pt_3]: if pt[0] < box_limits_x[0]: box_limits_x[0] = pt[0] if pt[0] > box_limits_x[1]: box_limits_x[1] = pt[0] if pt[1] < box_limits_z[0]: box_limits_z[0] = pt[1] if pt[1] > box_limits_z[1]: box_limits_z[1] = pt[1] mean_x = tf.reduce_mean(box_limits_x) mean_z = tf.reduce_mean(box_limits_z) else: mean_x = tf.reduce_mean(labeled_translations[:, 0]) mean_z = tf.reduce_mean(labeled_translations[:, 2]) samples_world = grid.generate( (mean_x - 0.5, 0.0, mean_z - 0.5), (mean_x + 0.5, 1.0, mean_z + 0.5), [self.resolution, self.resolution, self.resolution]) # samples_world = grid.generate( # (box_limits_x[0][0], box_limits_y[0], box_limits_z[0][0]), # (box_limits_x[1][0], box_limits_y[1], box_limits_z[1][0]), # [self.resolution, self.resolution, self.resolution]) # samples_world = grid.generate( # (-5.0, -5.0, -5.0), # (5.0, 5.0, 5.0), # [self.resolution, self.resolution, self.resolution]) samples_world = tf.reshape(samples_world, [-1, 3]) ious = []
tensorflow.reduce_mean
11,667
from tensorflow.python.platform import test dtypes.int64) return sparse_tensor.SparseTensor( constant_op.constant(indices, dtypes.int64, [len(indices), 2]), constant_op.constant(values, value_type, [len(indices)]), constant_op.constant(shape, dtypes.int64)) if __name__ == '__main__': test.main()
tensorflow.python.platform.test.main
11,668
from tensorflow.python.framework import ops auc = compute_auc(tp, fn, tn, fp, 'value') update_op = compute_auc( tp_update_op, fn_update_op, tn_update_op, fp_update_op, 'update_op') if metrics_collections: ops.add_to_collections(metrics_collections, auc) if updates_collections: ops.add_to_collections(updates_collections, update_op)
tensorflow.python.framework.ops.add_to_collections
11,669
import tensorflow as tf + tf.matmul( rnn_in, self.W_in * self.input_Connectivity, transpose_b=True, name="2") + self.b_rec)\ + np.sqrt(2.0 * self.alpha * self.rec_noise * self.rec_noise)\ * tf.random_normal(state.get_shape(), mean=0.0, stddev=1.0) return new_state def rnn_output(self, new_state): if self.dale_ratio: new_output = tf.matmul(tf.nn.relu(new_state), tf.matmul(tf.abs(self.W_out) * self.output_Connectivity, self.Dale_out, name="in_2"), transpose_b=True, name="3") \ + self.b_out else: new_output = tf.matmul(tf.nn.relu(new_state), self.W_out * self.output_Connectivity, transpose_b=True, name="3") \ + self.b_out return new_output def rnn_step_scan(self, state, rnn_in):
tensorflow.nn.relu
11,670
from tensorflow.python.platform import gfile class BoostedTreeEstimatorTest(test_util.TensorFlowTestCase): def setUp(self): self._export_dir_base = tempfile.mkdtemp() + "export/" gfile.MkDir(self._export_dir_base) def testFitAndEvaluateDontThrowException(self): learner_config = learner_pb2.LearnerConfig()
tensorflow.python.platform.gfile.MkDir
11,671
import tensorflow as tf self.beta = safe_get("beta", [shape[-1]], initializer=tf.constant_initializer(0.)) beta = tf.reshape(self.beta, [1, 1, 1, -1]) assert self.epsilon is not None assert mean_sq is not None assert mean is not None std = tf.sqrt(self.epsilon + mean_sq - tf.square(mean)) out = x - mean out = out / std out = out * gamma out = out + beta return out
tensorflow.square
11,672
import tensorflow as tf batch_size=10, model_params=None, c2v=None, max_sequence_len=None, dropout_keep_prob=None, weights=None): self.params = model_params self._out_vocab_size = out_vocab_size # num. of languages self.weights = tf.constant(weights, dtype=tf.float32, name='class_weights') with tf.variable_scope("tweetff"): hidden = tf.get_variable("ff_hidden", [c2v.embedding_dims, out_vocab_size]) bias = tf.get_variable('ff_bias', [out_vocab_size]) #probably useless. at least I don't want to use it self.seq_lens = tf.placeholder(tf.int64, [batch_size], name='seq_lens') self.x = tf.placeholder(tf.int32, [batch_size, max_sequence_len], name='x') self.y = tf.placeholder(tf.float32, [batch_size, out_vocab_size], name='y') self.example_weights = tf.placeholder(tf.float32, [batch_size], name='example_weights') # get one 'word' embedding for the full tweet tweet_embedding = c2v.GetEmbeddings(self.x)[:,1,:] logits = tf.nn.xw_plus_b(tweet_embedding, hidden, bias) self.probs = tf.nn.softmax(logits)
tensorflow.placeholder
11,673
import tensorflow as tf if decoder.context_mapping: with tf.variable_scope(scope_name):
tensorflow.variable_scope
11,674
import tensorflow as tf return layer def get_weight_initializer(params): initializer = [] scope = tf.get_variable_scope() scope.reuse_variables() for layer, value in params.items(): op = tf.get_variable('%s' % layer).assign(value) initializer.append(op) return initializer def save_model(name, scope, sess): variables = tf.get_collection(tf.GraphKeys.WEIGHTS, scope=scope) d = [(v.name.split(':')[0], sess.run(v)) for v in variables] cPickle.dump(d, open(name, 'wb'))
tensorflow.get_variable
11,675
import tensorflow as tf lstm_c = tf.nn.rnn_cell.DropoutWrapper(lstm_c, output_keep_prob=self.keep_prob) state_init_c = lstm_c.zero_state(batch_size=batch_size, dtype=tf.float32) lstm_cin = tf.expand_dims(layer_c2, axis=1) out_c, state_final_c = tf.nn.dynamic_rnn(cell=lstm_c, inputs=lstm_cin, initial_state=state_init_c) cell_out_c = tf.reshape(out_c, [-1, 256]) vf = tf.layers.dense(cell_out_c, 1, kernel_regularizer=reg) params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=name) return vf, params, state_init_c, state_final_c
tensorflow.reshape
11,676
import tensorflow as tf widths, x_centers = tf.meshgrid(widths, x_centers) heights, y_centers = tf.meshgrid(heights, y_centers) anchor_centers = tf.stack([x_centers, y_centers], axis=2) anchor_centers = tf.reshape(anchor_centers, [-1, 2]) anchor_sizes = tf.stack([widths, heights], axis=2)
tensorflow.stack
11,677
import tensorflow as tf self.loss_db_sum = tf.summary.scalar("db_loss", self.D_B_loss) self.loss_da_sum = tf.summary.scalar("da_loss", self.D_A_loss) self.loss_d_sum = tf.summary.scalar("d_loss",self.discriminator_loss) self.db_loss_real_sum = tf.summary.scalar("db_loss_real", self.D_B_loss_real) self.db_loss_fake_sum = tf.summary.scalar("db_loss_fake", self.D_B_loss_fake) self.da_loss_real_sum = tf.summary.scalar("da_loss_real", self.D_A_loss_real) self.da_loss_fake_sum = tf.summary.scalar("da_loss_fake", self.D_A_loss_fake) self.d_sum = tf.summary.merge( [self.loss_da_sum, self.da_loss_real_sum, self.da_loss_fake_sum,
tensorflow.summary.scalar
11,678
import tensorflow as tf self.vis_summary = tf.summary.image('visualization', self.vis_placeholder) # embedding dists = l2(self.embedding_test[:-1] - self.embedding_test[1:]) self.dist = dists metrics = [] metrics.append(tf.summary.histogram('point_distance', dists)) metrics.append(tf.summary.scalar('training/trajectory_length', tf.reduce_sum(dists))) self.blur_ph = tf.placeholder(dtype=tf.float32) metrics.append(tf.summary.scalar('training/blur_sigma', self.blur_ph)) pred = self.embedding_test[1:-1]*2 - self.embedding_test[0:-2] pred_error = l2(pred - self.embedding_test[2:]) mean_dist, mean_pred_error = tf.reduce_mean(dists), tf.reduce_mean(pred_error) improvement = (mean_dist-mean_pred_error)/mean_dist pairwise_improvement = tf.nn.relu(dists[1:] - pred_error)
tensorflow.summary.scalar
11,679
import tensorflow as tf def input_fn_builder(input_files, max_seq_length, max_predictions_per_seq, is_training, num_cpu_threads=4): """Creates an `input_fn` closure to be passed to TPUEstimator.""" def input_fn(params): """The actual input function.""" batch_size = params["batch_size"] name_to_features = { "input_ids": tf.FixedLenFeature([max_seq_length], tf.int64), "input_mask": tf.FixedLenFeature([max_seq_length], tf.int64), "segment_ids": tf.FixedLenFeature([max_seq_length], tf.int64), "masked_lm_positions": tf.FixedLenFeature([max_predictions_per_seq], tf.int64), "masked_lm_ids": tf.FixedLenFeature([max_predictions_per_seq], tf.int64), "masked_lm_weights": tf.FixedLenFeature([max_predictions_per_seq], tf.float32), "next_sentence_labels": tf.FixedLenFeature([1], tf.int64), }
tensorflow.FixedLenFeature
11,680
import tensorflow as tf for order in range(-degree, degree + 1): degree_l.append(degree) order_m.append(order) return (tf.convert_to_tensor(value=degree_l), tf.convert_to_tensor(value=order_m)) def _evaluate_legendre_polynomial_pmm_eval(m, x): pmm = tf.pow(1.0 - tf.pow(x, 2.0), tf.cast(m, dtype=x.dtype) / 2.0) ones = tf.ones_like(m) pmm *= tf.cast( tf.pow(-ones, m) * double_factorial(2 * m - 1), dtype=pmm.dtype) return pmm
tensorflow.pow
11,681
import tensorflow as tf symbol = "\\s" # For visual purposes, swap space with \s f.write("{}\n".format(symbol)) char_embedding_meta = char_embedding_meta.replace(log_dir, "..") # Book keeping step = 0 time_window = ValueWindow(100) loss_window = ValueWindow(100) saver = tf.train.Saver(max_to_keep=5) log("Tacotron training set to a maximum of {} steps".format(args.tacotron_train_steps)) # Memory allocation on the GPU as needed config = tf.ConfigProto() config.gpu_options.allow_growth = True config.allow_soft_placement = True # Train
tensorflow.train.Saver
11,682
import tensorflow as tf 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. Args: im: A 5D tensor of size [num_batch, depth, height, width, num_channels]. It is the input volume for the transformation layer (tf.float32).
tensorflow.reshape
11,683
import tensorflow as tf criterion_map = { 'L1': nn.L1Loss(), 'L2': nn.L2Loss(), 'MSE': nn.MSELoss(), } criterion = criterion_map[FLAGS.model.loss] loss_mod = MultiStepLoss(model, normalizers, dim_state, dim_action, criterion, FLAGS.model.multi_step) loss_mod.build_backward(FLAGS.model.lr, FLAGS.model.weight_decay) shadow_loss_mods = [MultiStepLoss(shadow_model, normalizers, dim_state, dim_action, criterion, FLAGS.model.multi_step) for shadow_model in shadow_models] for shadow_loss_mod in shadow_loss_mods: shadow_loss_mod.build_backward(FLAGS.model.lr, FLAGS.model.weight_decay) algo = TRPO(vfn=vfn, policy=policy, dim_state=dim_state, dim_action=dim_action, **FLAGS.TRPO.as_dict()) advtask = ADVTASK(dim_state, dim_action, policy, vfn, warmup_policy, warmup_vfn, task, alpha=alpha, beta=beta, nsample=nsample, atype=atype) tf.get_default_session().run(tf.global_variables_initializer()) print ("norm params:", normalizers_parameters) print ("norm_copy params:", normalizers_copy_parameters) norm_before = tf.get_default_session().run(normalizers_parameters) print ("norm_before:", norm_before) assert FLAGS.algorithm != 'MF', "don't support model free for now" print (f"n_envs for task: {nsample}//{FLAGS.plan.max_steps}={nsample//FLAGS.plan.max_steps}") runners = { 'test': make_real_runner(FLAGS.plan.n_envs, task_config=task), 'collect': make_real_runner(FLAGS.plan.n_envs, task_config=task), #1
tensorflow.global_variables_initializer
11,684
import tensorflow as tf + 0.00392377*t**(-8)) a = 7.5 return __phi_f(tf.minimum(x, a)) - __phi_f(a) + __phi_g(tf.maximum(x, a)) N = tf.cast(tf.shape(X)[0], tf.float32) if y is None: y = silverman_rule_of_thumb(N) A = 1/(N*N*tf.sqrt(y)) B = 2.0/(N*tf.sqrt(y+0.5)) A1 = euclidean_norm_squared(tf.subtract(tf.expand_dims(X, 0), tf.expand_dims(X, 1)), axis=2)/(4*y) B1 = euclidean_norm_squared(X, axis=1)/(2+4*y) return 1/tf.sqrt(1+y) + A*tf.reduce_sum(__phi(A1)) - B*tf.reduce_sum(__phi(B1)) def cw(X, y=None): D = tf.cast(tf.shape(X)[1], tf.float32) N = tf.cast(tf.shape(X)[0], tf.float32) if y is None: y = silverman_rule_of_thumb(N) K = 1/(2*D-3)
tensorflow.expand_dims
11,685
import tensorflow as tf y += dense(conv, encoder.attn_size, use_bias=False, name='C_a') v = get_variable('v_a', [encoder.attn_size]) return tf.reduce_sum(v * tf.tanh(y), axis=2) def global_attention(state, hidden_states, encoder, encoder_input_length, scope=None, context=None, **kwargs): with tf.variable_scope(scope or 'attention_{}'.format(encoder.name)): if context is not None and encoder.use_context: state = tf.concat([state, context], axis=1) 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
tensorflow.shape
11,686
import tensorflow.contrib.graph_editor as ge return ops.name if hasattr(ops, "name") else str(ops) def my_add_control_inputs(wait_to_do_ops, inputs_to_do_before): for op in wait_to_do_ops: ci = [i for i in inputs_to_do_before if op.control_inputs is None or i not in op.control_inputs] ge.add_control_inputs(op, ci)
tensorflow.contrib.graph_editor.add_control_inputs
11,687
import tensorflow as tf cast0 = tf.dtypes.as_string(add if not swap else sub, name="TOSTR0") else: cast0 = tf.cast(add if not swap else sub, tf_output0_dtype, "CAST0")
tensorflow.cast
11,688
import tensorflow as tf self.all_params = tf.trainable_variables() if self.config.l2_norm is not None: self.logger.info("applying l2 loss") variables = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) l2_loss = tf.contrib.layers.apply_regularization(regularizer, variables) self.loss += l2_loss if self.config.decay is not None: self.var_ema = tf.train.ExponentialMovingAverage(self.config.decay) ema_op = self.var_ema.apply(tf.trainable_variables()) with tf.control_dependencies([ema_op]): self.loss = tf.identity(self.loss) self.shadow_vars = [] self.global_vars = [] for var in tf.global_variables(): v = self.var_ema.average(var) if v: self.shadow_vars.append(v) self.global_vars.append(var) self.assign_vars = [] for g, v in zip(self.global_vars, self.shadow_vars): self.assign_vars.append(tf.assign(g, v))
tensorflow.identity
11,689
import tensorflow as tf learning_rate """ with tf.name_scope(name): learning_rate = tf.cast(learning_rate, dtype=tf.float32) global_step = tf.cast(global_step, dtype=tf.float32) step_size = tf.cast(step_size, dtype=tf.float32) max_lr = tf.cast(max_lr, dtype=tf.float32) if mode == 'tri': periodic_comp = tf.mod((global_step + step_size / 4) / step_size, 1) first_factor = tf.abs(periodic_comp - 0.5) second_factor = 2 * (max_lr - learning_rate) second_comp = learning_rate elif mode == 'sin': first_factor = (learning_rate - max_lr) / 2. second_factor = tf.sin((pi * global_step) / step_size) second_comp = (learning_rate + max_lr) / 2. elif mode == 'saw': first_factor = max_lr - learning_rate second_factor = tf.mod(global_step / step_size, 1)
tensorflow.abs
11,690
from tensorflow.python.framework import ops def _OverrideBinaryOperatorHelper(func, op_name): """Register operators with different tensor and scalar versions. Args: func: the operator op_name: name of the operator being overridden """ def binary_op_wrapper(x, y): with ops.op_scope([x, y], None, op_name) as name: assert isinstance(x, ops.Tensor) y = ops.convert_to_tensor(y, dtype=x.dtype.base_dtype, name="y") return func(x, y, name=name) ops.Tensor._override_operator("__%s__" % op_name, binary_op_wrapper) del binary_op_wrapper def r_binary_op_wrapper(y, x): with ops.op_scope([x, y], None, op_name) as name:
tensorflow.python.framework.ops.op_scope
11,691
import tensorflow as tf elif norm == 'G': X = tf.contrib.layers.group_norm(X, groups=16, scope=scope, reuse=reuse) if nonlin: X = tf.nn.leaky_relu(X, 0.2) return X with tf.variable_scope('discriminator') as scope: if reuse: scope.reuse_variables() print('D in:', X.get_shape().as_list()) X = self.conv('DZ1', X, 512, 1, 1) X = tf.nn.leaky_relu(X, 0.2) X = self.conv('DZ2', X, 512, 1, 1) X = tf.nn.leaky_relu(X, 0.2) X = self.conv('DZ3', X, 512, 1, 1) X = tf.nn.leaky_relu(X, 0.2) X = self.conv('DZ4', X, 512, 1, 1) X = tf.nn.leaky_relu(X, 0.2) X = discrim_conv('d_out', X, 1, 1, norm=False, nonlin=False, init_stddev=0.02) print('D out:', X.get_shape().as_list()) return X
tensorflow.nn.leaky_relu
11,692
import tensorflow as tf lambda: tf.zeros([bs, sl+1, hn], tf.float32), lambda: tf.scatter_nd( tf.stack([range_head, head_org_idx], -1), attn_result, [bs, sl+1, hn]) ) range_unhead = tf.tile(tf.expand_dims(tf.range(bs), -1), [1, sl_unhead]) scatter_pooling = tf.cond( tf.equal(sl_unhead, 0), lambda: tf.zeros([bs, sl+1, hn], tf.float32), lambda: tf.scatter_nd(
tensorflow.range
11,693
import tensorflow as tf gfile.MakeDirs(save_dir) with self.test_session() as sess: v = tf.Variable(10.0, name="v") save = tf.train.Saver({"v": v}, max_to_keep=2) tf.initialize_all_variables().run() self.assertEqual([], save.last_checkpoints) s1 = save.save(sess, os.path.join(save_dir, "s1")) self.assertEqual([s1], save.last_checkpoints)
tensorflow.initialize_all_variables
11,694
import tensorflow as tf [tf.float32, tf.float32]) rois.set_shape([None, 5]) 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])
tensorflow.variable_scope
11,695
import tensorflow as tf image_width = tf.shape(image)[1] offset_height = (image_height - size) // 2 offset_width = (image_width - size) // 2 image = tf.slice(image, [offset_height, offset_width, 0], [size, size, -1]) return image def lighting(image, std, eigval, eigvec): v = tf.random_normal(shape=[3], stddev=std) * eigval inc = tf.matmul(eigvec, tf.reshape(v, [3, 1])) image = tf.cast(tf.cast(image, tf.float32) + tf.reshape(inc, [3]), image.dtype) return image def validation_mapper(byte): image = tf.image.decode_jpeg( tf.reshape(byte, shape=[]), 3, **JPEG_OPT) image = resize_shortest_edge(image, tf.shape(image), 256) image = center_crop(image, 224) image = tf.reverse(image, axis=[2]) # to BGR return image
tensorflow.cast
11,696
import tensorflow as tf print ("query_size mismatch") query = tf.concat(values = [ query, query, ], axis=1) if time_major: # (T,B,D) => (B,T,D) facts = tf.array_ops.transpose(facts, [1, 0, 2]) facts_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer querry_size = query.get_shape().as_list()[-1] queries = tf.tile(query, [1, tf.shape(facts)[1]]) queries = tf.reshape(queries, tf.shape(facts)) din_all = tf.concat([queries, facts, queries-facts, queries*facts], axis=-1) d_layer_1_all = tf.layers.dense(din_all, 80, activation=tf.nn.sigmoid, name='f1_att' + stag) d_layer_2_all = tf.layers.dense(d_layer_1_all, 40, activation=tf.nn.sigmoid, name='f2_att' + stag)
tensorflow.array_ops.transpose
11,697
import tensorflow as tf def _fixed_padding(self, dataset: tf.data.Dataset, pad_id=0, max_sequence_length=512, **kwargs) -> tf.data.Dataset: maxlen = tf.constant(max_sequence_length, dtype=tf.int32) pad_id = tf.constant(pad_id, dtype=tf.int32) # fmt: off padded_shapes = kwargs.get("padded_shapes", ([maxlen, ], [maxlen, ], [maxlen, ], [maxlen, ]))
tensorflow.constant
11,698
import tensorflow as tf 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), } def _decode_record(record, name_to_features):
tensorflow.FixedLenFeature
11,699