seed
stringlengths
25
2.89k
seed_api
stringlengths
14
102
index
int64
0
14.8k
import tensorflow as tf # We now test every codepath within the underlying is_scalar_helper # function. # Test case 1, 2. x = tf.placeholder(dtype=tf.int32, shape=[]) # None would fire an exception were it actually executed. self.assertTrue(normal._is_scalar_helper(x.get_shape, lambda: None)) self.assertTrue(normal._is_scalar_helper(lambda: tf.TensorShape(None), lambda: tf.shape(x))) x = tf.placeholder(dtype=tf.int32, shape=[1]) # None would fire an exception were it actually executed. self.assertFalse(normal._is_scalar_helper(x.get_shape, lambda: None)) self.assertFalse(normal._is_scalar_helper(lambda: tf.TensorShape(None), lambda: tf.shape(x))) # Test case 3. x = tf.placeholder(dtype=tf.int32) is_scalar = normal._is_scalar_helper(x.get_shape, lambda: tf.shape(x)) self.assertTrue(is_scalar.eval(feed_dict={x: 1})) self.assertFalse(is_scalar.eval(feed_dict={x: [1]})) if __name__ == '__main__': tf.test.main()
tensorflow.TensorShape
8,100
import tensorflow as tf inputs = tf.random.uniform( [100, 8], minval=-10, maxval=10.0, dtype=tf.float32) centers = tf.random.uniform( [5, 8], minval=-10, maxval=10.0, dtype=tf.float32) distances1 = isu.inputs_distances_to_centers(inputs, centers) num_centers = tf.shape(centers)[0] inputs_reshaped = tf.tile(tf.expand_dims(inputs, axis=1), tf.stack([1, num_centers, 1])) distances2 = tf.reduce_sum(tf.square(inputs_reshaped - centers), axis=2) self.assertAllClose(distances1.numpy(), distances2.numpy(), atol=0.001) def test_pairwise_iou_matrix(self): mask0 = tf.constant([[1, 0], [0, 1]], dtype=tf.float32) mask1 = tf.constant([[1, 1], [0, 1]], dtype=tf.float32) mask2 = tf.constant([[1, 0], [1, 1]], dtype=tf.float32) mask3 = tf.constant([[1, 1], [1, 1]], dtype=tf.float32) mask4 = tf.constant([[0, 0], [0, 0]], dtype=tf.float32) mask5 = tf.constant([[1, 0], [1, 0]], dtype=tf.float32)
tensorflow.constant
8,101
import tensorflow as tf # `attention_mask` = [B, T] from_shape = get_shape_list(q) if len(from_shape) == 4: broadcast_ones = tf.ones([from_shape[0], 1, from_shape[2], 1], tf.float32) elif len(from_shape) == 5: # from_shape = [B, N, Block_num, block_size, depth]# broadcast_ones = tf.ones([from_shape[0], 1, from_shape[2], from_shape[3], 1], tf.float32) bias = tf.matmul(broadcast_ones, tf.cast(bias, tf.float32), transpose_b=True) # Since attention_mask is 1.0 for positions we want to attend and 0.0 for # masked positions, this operation will create a tensor which is 0.0 for # positions we want to attend and -10000.0 for masked positions. adder = (1.0 - bias) * -10000.0 # Since we are adding it to the raw scores before the softmax, this is # effectively the same as removing these entirely. logits += adder
tensorflow.cast
8,102
import tensorflow as tf input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, label_id=label_id, is_real_example=True) return feature def file_based_convert_examples_to_features( examples, label_list, max_seq_length, tokenizer, output_file): """Convert a set of `InputExample`s to a TFRecord file.""" writer = tf.python_io.TFRecordWriter(output_file) for (ex_index, example) in enumerate(examples): if ex_index % 10000 == 0: tf.logging.info("Writing example %d of %d" % (ex_index, len(examples))) feature = convert_single_example(ex_index, example, label_list, max_seq_length, tokenizer) def create_int_feature(values): f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values))) return f
tensorflow.python_io.TFRecordWriter
8,103
import tensorflow as tf return pt_loss def log_sum_exp(x): """numerically stable log_sum_exp implementation that prevents overflow.""" axis = len(x.get_shape()) - 1 m = tf.reduce_max(x, axis) m2 = tf.reduce_max(x, axis, keep_dims=True) return m + tf.log(tf.reduce_sum(tf.exp(x - m2), axis)) def log_prob_from_logits(x): """numerically stable log_softmax implementation that prevents overflow.""" axis = len(x.get_shape()) - 1 m = tf.reduce_max(x, axis, keep_dims=True) return x - m - tf.log(tf.reduce_sum(tf.exp(x - m), axis, keep_dims=True)) def segment_loss(logits, labels, num_classes, head=None): """Calculate the loss from the logits and the labels. Args: logits: tensor, float - [batch_size * width * height, num_classes]. Use vgg_fcn.up as logits. labels: Labels tensor, int32 - [batch_size * width * height, num_classes]. The ground truth of your data. head: numpy array - [num_classes] Weighting the loss of each class Optional: Prioritize some classes
tensorflow.exp
8,104
import tensorflow as tf classification_for_object = tf.gather_nd(classification, indices_for_object) cls_loss_for_object = keras.backend.binary_crossentropy(labels_for_object, classification_for_object) # 找出实际上为背景的先验框 indices_for_back = tf.where(keras.backend.equal(anchor_state, 0)) labels_for_back = tf.gather_nd(labels, indices_for_back) classification_for_back = tf.gather_nd(classification, indices_for_back) # 计算每一个先验框应该有的权重 cls_loss_for_back = keras.backend.binary_crossentropy(labels_for_back, classification_for_back) # 标准化,实际上是正样本的数量 normalizer_pos = tf.where(keras.backend.equal(anchor_state, 1))
tensorflow.gather_nd
8,105
from tensorflow.python.ops import array_ops var = contrib_variables.local_variable( array_ops.zeros([], dtype=dtypes.float64), name=scope)
tensorflow.python.ops.array_ops.zeros
8,106
import tensorflow as tf with tf.Graph().as_default():
tensorflow.Graph
8,107
import tensorflow.contrib.slim as slim def get_gtboxes_and_label(self, gtboxes_and_label_h, gtboxes_and_label_r, num_objects): return gtboxes_and_label_h[:int(num_objects), :].astype(np.float32), \ gtboxes_and_label_r[:int(num_objects), :].astype(np.float32) def main(self): with tf.Graph().as_default() as graph, tf.device('/cpu:0'): num_gpu = len(cfgs.GPU_GROUP.strip().split(',')) global_step = slim.get_or_create_global_step() lr = self.warmup_lr(cfgs.LR, global_step, cfgs.WARM_SETP, num_gpu) tf.summary.scalar('lr', lr) optimizer = tf.train.MomentumOptimizer(lr, momentum=cfgs.MOMENTUM) r3det_gwd = build_whole_network.DetectionNetworkR3DetGWD(cfgs=self.cfgs, is_training=True) with tf.name_scope('get_batch'):
tensorflow.contrib.slim.get_or_create_global_step
8,108
import tensorflow as tf kernel_size=[5, 5], padding="same", activation=tf.nn.relu) pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2) conv2 = tf.layers.conv2d( inputs=pool1, filters=filter_list[1], kernel_size=[5, 5], padding="same", activation=tf.nn.relu) pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2) # return int(np.prod(pool2.get_shape().as_list()[1:])) return pool2.get_shape().as_list() if __name__ == "__main__": tf.autograph.set_verbosity(0) print(get_conv_dimension([32, 64]))
tensorflow.layers.max_pooling2d
8,109
import tensorflow as tf return update_scale_expr # Functionality to update the threshold for parameter space noise. update_param_noise_threshold_expr = param_noise_threshold.assign(tf.cond(update_param_noise_threshold_ph >= 0, lambda: update_param_noise_threshold_ph, lambda: param_noise_threshold)) # Put everything together. deterministic_actions = tf.argmax(q_values_perturbed, axis=1) batch_size = tf.shape(observations_ph.get())[0] random_actions = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=num_actions, dtype=tf.int64) chose_random = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=1, dtype=tf.float32) < eps stochastic_actions = tf.where(chose_random, random_actions, deterministic_actions) output_actions = tf.cond(stochastic_ph, lambda: stochastic_actions, lambda: deterministic_actions) update_eps_expr = eps.assign(tf.cond(update_eps_ph >= 0, lambda: update_eps_ph, lambda: eps)) updates = [ update_eps_expr, tf.cond(reset_ph, lambda: perturb_vars(original_scope="q_func", perturbed_scope="perturbed_q_func"), lambda: tf.group(*[])), tf.cond(update_param_noise_scale_ph, lambda: update_scale(), lambda: tf.Variable(0., trainable=False)), update_param_noise_threshold_expr,
tensorflow.stack
8,110
from tensorflow.python.training import summary_io output_dir: `string`, the directory to save the summaries to. Only used if no `summary_writer` is supplied. summary_writer: `SummaryWriter`. If `None` and an `output_dir` was passed, one will be created accordingly. scaffold: `Scaffold` to get summary_op if it's not provided. """ # TODO(ipolosukhin): Implement every N seconds. super(SummarySaver, self).__init__(every_n_steps=save_steps) self._summary_op = summary_op self._summary_writer = summary_writer if summary_writer is None and output_dir: self._summary_writer = summary_io.SummaryWriter(output_dir) self._scaffold = scaffold # TODO(mdan): Throw an error if output_dir and summary_writer are None. def set_estimator(self, estimator): super(SummarySaver, self).set_estimator(estimator) # TODO(mdan): This line looks redundant. if self._summary_writer is None: self._summary_writer = summary_io.SummaryWriter(estimator.model_dir) def every_n_step_begin(self, step):
tensorflow.python.training.summary_io.SummaryWriter
8,111
import tensorflow as tf 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.placeholder
8,112
import tensorflow as tf for i in range(new_w): weights[i:i + h, i] = 1.0 weights_list += [weights] weights_tensors = tf.stack([tf.convert_to_tensor(weights, dtype=tf.float32) for weights in weights_list]) rand_horizon = tf.random_uniform((), 0, horizon, dtype=tf.int32) new_w = epi_len - rand_horizon cur_weights = tf.slice(weights_tensors[tf.cast(rand_horizon, tf.int32)], [0, 0], [epi_len, new_w]) # cur_weights = tf.slice(weights_tensors, [tf.cast(rand_horizon, tf.int32), 0, 0], [1, epi_len, new_w]) horizon_pred = tf.matmul(pred, cur_weights) horizon_tgt = tf.matmul(tgt, cur_weights) return horizon_pred, horizon_tgt
tensorflow.cast
8,113
from tensorflow.python.framework import ops if input_shape is not None: return [tensor_shape.TensorShape(input_shape.tolist())] else: return [tensor_shape.unknown_shape(ndims=4)] @ops.RegisterShape("MaxPoolGrad") @ops.RegisterShape("MaxPoolGradWithArgmax") def _MaxPoolGradShape(op): """Shape function for the MaxPoolGrad op.""" orig_input_shape = op.inputs[0].get_shape().with_rank(4) return [orig_input_shape]
tensorflow.python.framework.ops.RegisterShape
8,114
import tensorflow as tf gtboxes_and_label_r = tf.reshape(gtboxes_and_label_r, [-1, 6]) if cfgs.ANGLE_RANGE == 180: gtboxes_and_label_r_ = tf.py_func(coordinate_present_convert, inp=[gtboxes_and_label_r, -1], Tout=tf.float32)
tensorflow.py_func
8,115
import tensorflow as tf return self._lr = tf.Variable(0.0, trainable=False) tvars = tf.trainable_variables() grads, _ = tf.clip_by_global_norm(tf.gradients(self._cost, tvars), config.max_grad_norm) optimizer = tf.train.GradientDescentOptimizer(self._lr) self._train_op = optimizer.apply_gradients( zip(grads, tvars), global_step=tf.contrib.framework.get_or_create_global_step()) self._new_lr = tf.placeholder( tf.float32, shape=[], name="new_learning_rate") self._lr_update = tf.assign(self._lr, self._new_lr) def _build_rnn_graph(self, inputs, config, is_training): if config.rnn_mode == CUDNN: return self._build_rnn_graph_cudnn(inputs, config, is_training) else: return self._build_rnn_graph_lstm(inputs, config, is_training) def _build_rnn_graph_cudnn(self, inputs, config, is_training):
tensorflow.placeholder
8,116
import tensorflow as tf # TODO(zoyahav): Use register_keras_serializable directly once we no longer support # TF<2.1. def _maybe_register_keras_serializable(package): if hasattr(tf.keras.utils, 'register_keras_serializable'): return tf.keras.utils.register_keras_serializable(package=package) else: return lambda cls: cls def _check_tensorflow_version():
tensorflow.keras.utils.register_keras_serializable
8,117
import tensorflow as tf features_nonzero) else: raise ValueError('Undefined model!') # Optimizer pos_weight = float(adj.shape[0] * adj.shape[0] - adj.sum()) / adj.sum() norm = adj.shape[0] * adj.shape[0] / float((adj.shape[0] * adj.shape[0] - adj.sum()) * 2) with tf.name_scope('optimizer'): # Optimizer for Non-Variational Autoencoders if model_name in ('gcn_ae', 'linear_ae', 'deep_gcn_ae'): opt = OptimizerAE(preds = model.reconstructions, labels = tf.reshape(tf.sparse_tensor_to_dense(placeholders['adj_orig'], validate_indices = False), [-1]), pos_weight = pos_weight, norm = norm)
tensorflow.name_scope
8,118
import tensorflow as tf for x in checkpoints: if x.op and x.op.name is not None: grad_node = tf.stop_gradient(x, name=x.op.name+"_sg") else:
tensorflow.stop_gradient
8,119
import tensorflow as tf loss_entropy = - 0.01 * tf.reduce_mean(pi.entropy()) loss = loss_pg + loss_vf + loss_entropy opt = tf.train.AdamOptimizer(self.LR) self.train_op = opt.minimize(loss, global_step=self.global_step, var_list=pi_params + vf_params) self.pi_new_params = [oldp.assign(p) for p, oldp in zip(pi_params, pi_old_params)] self.vf_new_params = [oldp.assign(p) for p, oldp in zip(vf_params, vf_old_params)] self.sess.run(tf.global_variables_initializer()) # Tensorboard if summary_dir is not None: self.writer = tf.summary.FileWriter(summary_dir) tf.summary.scalar('Loss/Policy', loss_pg) tf.summary.scalar('Loss/Value', loss_vf)
tensorflow.global_variables_initializer
8,120
from tensorflow.python.platform import gfile self.assertFalse(gfile.Exists(save._MetaGraphFilename(s1))) self.assertEqual(2, len(gfile.Glob(s2)))
tensorflow.python.platform.gfile.Glob
8,121
import tensorflow as tf #print(image.shape) #print(label.shape) images,labels=tf.train.shuffle_batch([image,label], batch_size=batch_size,num_threads=10,capacity=10000,min_after_dequeue=200) return tf.reshape(images,[batch_size,4096]),tf.reshape(labels,[batch_size]) def get_test_batch(image,label,batch_size): images,labels=tf.train.batch([image,label],batch_size=batch_size) return tf.reshape(images,[batch_size,4096]),tf.reshape(labels,[batch_size]) def get_valid_batch(image,label,batch_size): images,labels=tf.train.batch([image,label],batch_size=batch_size) return tf.reshape(images,[batch_size,4096]),tf.reshape(labels,[batch_size]) class trainwork(object): def __init__(self): with tf.variable_scope('scop'): self.w1=tf.get_variable('w1', [4096,2048],initializer=tf.contrib.layers.xavier_initializer_conv2d()) self.w2=tf.get_variable('w2', [2048,3072],initializer=tf.contrib.layers.xavier_initializer_conv2d()) self.w3=tf.get_variable('w3', [3072,512],initializer=tf.contrib.layers.xavier_initializer_conv2d()) self.w4=tf.get_variable('w4', [512,classnum],initializer=tf.contrib.layers.xavier_initializer_conv2d()) self.b1 = tf.get_variable('b1', [2048],initializer=tf.constant_initializer(0.0)) self.b2 = tf.get_variable('b2', [3072],initializer=tf.constant_initializer(0.0)) self.b3 = tf.get_variable('b3', [512],initializer=tf.constant_initializer(0.0))
tensorflow.reshape
8,122
import tensorflow as tf stddev=np.sqrt(1.0 / (width * char_embed_dim)) ) w = tf.get_variable( "W_cnn_%s" % i, [1, width, char_embed_dim, num], initializer=w_init, dtype=DTYPE) b = tf.get_variable( "b_cnn_%s" % i, [num], dtype=DTYPE, initializer=tf.constant_initializer(0.0)) conv = tf.nn.conv2d( inp, w, strides=[1, 1, 1, 1], padding="VALID") + b # now max pool conv = tf.nn.max_pool( conv, [1, 1, max_chars-width+1, 1],
tensorflow.constant_initializer
8,123
import tensorflow as tf candidate_starts = tf.tile(tf.expand_dims(tf.range(num_words), 1), [1, self.max_span_width]) # [num_words, max_span_width]
tensorflow.range
8,124
import tensorflow as tf [None, None, 3]) def test_images_and_additional_channels(self): input_tensor_dict = { fields.InputDataFields.image: tf.placeholder(tf.float32, [None, None, 5]), fields.InputDataFields.image_additional_channels: tf.placeholder(tf.float32, [None, None, 2]), } padded_tensor_dict = inputs.pad_input_data_to_static_shapes( tensor_dict=input_tensor_dict, max_num_boxes=3, num_classes=3, spatial_image_shape=[5, 6])
tensorflow.placeholder
8,125
import tensorflow as tf pred_posi_dif = tf.where(geq, pred_dif, -pred_dif) loss = tf.maximum(0., tgt_posi_dif - pred_posi_dif) cstr_pct = tf.math.count_nonzero(loss, dtype=tf.float32) / tf.cast(tf.reduce_prod(tf.shape(loss)), tf.float32) final_loss = tf.reduce_mean(loss) return final_loss, cstr_pct def contra_traj_lossV7(pred, tgt, horizon=12, temp=100): 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]) tgt_dif = tgt_flat1 - tgt_flat2 pred_dif = pred_flat1 - pred_flat2 geq = tf.cast(tgt_dif > 0, tf.bool) tgt_posi_dif = tf.where(geq, tgt_dif, -tgt_dif) pred_posi_dif = tf.where(geq, pred_dif, -pred_dif) loss = tf.maximum(0., tgt_posi_dif - pred_posi_dif) cstr_pct = tf.math.count_nonzero(loss, dtype=tf.float32) / tf.cast(tf.reduce_prod(tf.shape(loss)), tf.float32) unorm_w = tf.exp((tgt_flat1 + tgt_flat2)/temp) loss = unorm_w * loss / (tf.reduce_sum(unorm_w)) a = tf.print(tf.reduce_sum(unorm_w)) with tf.control_dependencies([a]): final_loss = tf.reduce_sum(loss) return final_loss, cstr_pct def contra_traj_lossV8(pred, tgt, horizon=12):
tensorflow.cast
8,126
import tensorflow as tf return tf.reduce_mean(tf.square(uP)) def conv2d(img, w, b, strides=[1, 1, 1, 1], is_dilated=False): if is_dilated: layer = tf.nn.atrous_conv2d(img, w, rate=2, padding='SAME') + b else: layer = tf.nn.conv2d(img, w, strides=strides, padding='SAME') + b return layer def dropout(layer, keep_prob=0.9, is_training=True, name=None, selu=False): if selu: return dropout_selu(layer, 1.0 - keep_prob, name=name, training=is_training) if is_training: return tf.nn.dropout(layer, keep_prob=keep_prob, name=name) else: return tf.add(layer, 0, name=name) def norm(layer, norm_type='batch_norm', decay=0.9, id=0, is_training=True, activation_fn=tf.nn.relu, prefix='conv_'): if norm_type != 'batch_norm' and norm_type != 'layer_norm': return tf.nn.relu(layer) with tf.variable_scope('norm_layer_%s%d' % (prefix, id)) as vs: if norm_type == 'batch_norm': if is_training: try: layer = tf.contrib.layers.batch_norm(layer, is_training=True, center=True, scale=False, decay=decay, activation_fn=activation_fn, updates_collections=None, scope=vs) # updates_collections=None except ValueError: layer = tf.contrib.layers.batch_norm(layer, is_training=True, center=True, scale=False, decay=decay, activation_fn=activation_fn, updates_collections=None, scope=vs, reuse=True) # updates_collections=None else:
tensorflow.add
8,127
import tensorflow as tf m.ph.train_images: np.zeros((1, w, h, in_ch)), m.ph.train_classes: np.zeros((1,)), m.ph.pred_images: np.zeros((1, w, h, in_ch)), m.ph.pred_classes: np.zeros((1,)) }) def _make_session(self): config = tf.ConfigProto(allow_soft_placement=True) config.gpu_options.allow_growth = True sess = tf.Session(config=config) return sess def _feed_dataset_to_model(self, images, classes=None, is_train=False): m = self._model utils.logger.log('Feeding dataset to model...') # Mock classes if required classes = classes or [0 for _ in range(len(images))]
tensorflow.Session
8,128
from tensorflow.python.ops import gradients_impl inputs = seq_length * [ array_ops.zeros([batch_size, num_units], dtypes.float32) ] cell = lambda: lstm_ops.LSTMBlockCell(num_units=num_units) # pylint: disable=cell-var-from-loop multi_cell = rnn_cell.MultiRNNCell( [cell() for _ in range(num_layers)]) outputs, final_state = core_rnn.static_rnn( multi_cell, inputs, dtype=dtypes.float32) trainable_variables = ops.get_collection( ops.GraphKeys.TRAINABLE_VARIABLES) gradients = gradients_impl.gradients([outputs, final_state], trainable_variables) training_op = control_flow_ops.group(*gradients) self._BenchmarkOp(training_op, "tf_rnn_lstm_block_cell %s %s" % (config_name, self._GetConfigDesc(config))) if __name__ == "__main__": test.main()
tensorflow.python.ops.gradients_impl.gradients
8,129
import tensorflow as tf "student_label":tf.ones_like(label_ids, dtype=tf.int32), "teacher_label":tf.zeros_like(label_ids, dtype=tf.int32),
tensorflow.zeros_like
8,130
import tensorflow as tf self.sample_action = tf.squeeze(pi_eval.sample(1), axis=0) self.eval_action = pi_eval.mode() self.global_step = tf.train.get_or_create_global_step() self.saver = tf.train.Saver() # Loss functions and training loss_pg = - tf.reduce_mean(pi.log_prob(batch['actions']) * batch['advantage']) - 0.01 * tf.reduce_mean(pi.entropy()) loss_vf = 0.5 * tf.reduce_mean(tf.square(batch['rewards'] - self.vf)) self.a_grads = tf.gradients(loss_pg, self.pi_params) self.c_grads = tf.gradients(loss_vf, self.vf_params) self.a_grads, _ = tf.clip_by_global_norm(self.a_grads, 20.0) self.c_grads, _ = tf.clip_by_global_norm(self.c_grads, 20.0) opt = tf.train.AdamOptimizer(self.LR) self.update_a_op = opt.apply_gradients(zip(self.a_grads, self.pi_params))
tensorflow.square
8,131
import tensorflow as tf mean, var = tf.nn.moments(inputdata, list(range(1, len(shape))), keep_dims=True) if data_format == 'NCHW': channnel = shape[1] new_shape = [1, channnel, 1, 1] else: channnel = shape[-1] new_shape = [1, 1, 1, channnel] if ndims == 2: new_shape = [1, channnel] if use_bias: beta = tf.get_variable('beta', [channnel], initializer=tf.constant_initializer()) beta = tf.reshape(beta, new_shape) else: beta = tf.zeros([1] * ndims, name='beta') if use_scale: gamma = tf.get_variable('gamma', [channnel], initializer=tf.constant_initializer(1.0)) gamma = tf.reshape(gamma, new_shape) else: gamma = tf.ones([1] * ndims, name='gamma') return tf.nn.batch_normalization(inputdata, mean, var, beta, gamma, epsilon, name=name) @staticmethod
tensorflow.constant_initializer
8,132
import tensorflow as tf # Build an initialization operation to run below. init = tf.global_variables_initializer() # Start running operations on the Graph. allow_soft_placement must be set to # True to build towers on GPU, as some of the ops do not have GPU # implementations. sess = tf.Session(config=tf.ConfigProto( allow_soft_placement=True, log_device_placement=FLAGS.log_device_placement)) sess.run(init) # Start the queue runners. tf.train.start_queue_runners(sess=sess) summary_writer = tf.summary.FileWriter(FLAGS.train_dir, sess.graph) for step in xrange(FLAGS.max_steps): start_time = time.time() _, loss_value = sess.run([train_op, loss]) duration = time.time() - start_time assert not np.isnan(loss_value), 'Model diverged with loss = NaN' if step % 10 == 0:
tensorflow.train.start_queue_runners
8,133
import tensorflow as tf input_size = inputs.get_shape()[2].value dtype = inputs.dtype x = inputs x0 = tf.transpose(x, perm=[1, 2,0]) # (num_nodes, total_arg_size, batch_size) x0 = tf.reshape(x0, shape=[self._num_nodes, input_size * batch_size]) x = tf.expand_dims(x0, axis=0)
tensorflow.transpose
8,134
import tensorflow as tf @pytest.fixture def sqrt(session_tf): return tf.convert_to_tensor(Datum.sqrt_data) @pytest.fixture() def I(session_tf): return tf.convert_to_tensor(Datum.I) @pytest.mark.parametrize('white', [True, False]) def test_diags(session_tf, white, mu, sqrt_diag, K): """ The covariance of q(x) can be Cholesky matrices or diagonal matrices. Here we make sure the behaviours overlap.
tensorflow.convert_to_tensor
8,135
from tensorflow.keras.layers import Dense, Conv2D, MaxPool2D, Flatten # Block 3 conv3a = Conv2D(padding="same", filters=RNN_SIZE//2, kernel_size=[3, 3], strides=1, data_format='channels_last', kernel_initializer=w_init,activation=tf.nn.relu)(pool2) conv3b = Conv2D(padding="same", filters=RNN_SIZE//2, kernel_size=[3, 3], strides=1, data_format='channels_last', kernel_initializer=w_init,activation=tf.nn.relu)(conv3a) conv3c = Conv2D(padding="same", filters=RNN_SIZE//2, kernel_size=[3, 3], strides=1, data_format='channels_last', kernel_initializer=w_init,activation=tf.nn.relu)(conv3b) pool3 = MaxPool2D(pool_size=[2,2])(conv3c) # final convolutional layer
tensorflow.keras.layers.Conv2D
8,136
import tensorflow as tf scores = d_layer_3_all # Mask # key_masks = tf.sequence_mask(facts_length, tf.shape(facts)[1]) # [B, T] key_masks = tf.expand_dims(mask, 1) # [B, 1, T] paddings = tf.ones_like(scores) * (-2 ** 32 + 1) scores = tf.where(key_masks, scores, paddings) # [B, 1, T] # Scale
tensorflow.ones_like
8,137
import tensorflow as tf import numpy as np from datetime import datetime from sklearn.metrics import confusion_matrix from sklearn.metrics import classification_report slim = tf.contrib.slim global first first = True classnum=12 testnum = tf.placeholder(tf.int32) trainnum = tf.placeholder(tf.int32) validnum = tf.placeholder(tf.int32) learnrate = tf.placeholder(tf.float32) def getinputs(path): filename_queue=tf.train.string_input_producer([path]) reader=tf.TFRecordReader() _,serialized_example=reader.read(filename_queue) features=tf.parse_single_example(serialized_example, features={ 'label':tf.FixedLenFeature([], tf.int64), 'img_raw' : tf.FixedLenFeature([], tf.string), }) image=tf.decode_raw(features['img_raw'],tf.uint8) label=tf.cast(features['label'],tf.int32) image=tf.reshape(image,[4096,1])
tensorflow.placeholder
8,138
import tensorflow as tf def make_cell(): cell = self._get_lstm_cell(config, is_training) if is_training and config.keep_prob < 1: cell = tf.contrib.rnn.DropoutWrapper( cell, output_keep_prob=config.keep_prob) return cell
tensorflow.contrib.rnn.DropoutWrapper
8,139
import tensorflow as tf img = tf.expand_dims(img_batch[i], axis=0) pretrain_zoo = PretrainModelZoo() if self.cfgs.NET_NAME in pretrain_zoo.pth_zoo or self.cfgs.NET_NAME in pretrain_zoo.mxnet_zoo: img = img / tf.constant([cfgs.PIXEL_STD]) gtboxes_and_label_r = tf.py_func(backward_convert, inp=[gtboxes_and_label_batch[i]], Tout=tf.float32) gtboxes_and_label_r = tf.reshape(gtboxes_and_label_r, [-1, 6]) gtboxes_and_label_h = get_horizen_minAreaRectangle(gtboxes_and_label_batch[i]) gtboxes_and_label_h = tf.reshape(gtboxes_and_label_h, [-1, 5]) num_objects = num_objects_batch[i] num_objects = tf.cast(tf.reshape(num_objects, [-1, ]), tf.float32) img_h = img_h_batch[i] img_w = img_w_batch[i] inputs_list.append([img, gtboxes_and_label_h, gtboxes_and_label_r, num_objects, img_h, img_w]) tower_grads = []
tensorflow.reshape
8,140
import tensorflow as tf # Concat both halves across channels X = tf.concat([X_half_1, X_half_2], axis=3) # Apply batch normalization X = self._add_batch_norm(X, out_ch, is_train=is_train) X = tf.reshape(X, (-1, in_w // 2, in_h // 2, out_ch)) # Sanity shape check return X def _add_batch_norm(self, X, in_ch, decay=0.9, epsilon=1e-5, offset=None, scale=None, is_train=False, no_moving_average=False): with tf.variable_scope('batch_norm'):
tensorflow.reshape
8,141
import tensorflow as tf result = estimator.predict( input_fn=predict_input_fn, checkpoint_path=checkpoint_path) output_predict_file = os.path.join(FLAGS.output_dir, "test_results.tsv") output_submit_file = os.path.join(FLAGS.output_dir, "submit_results.tsv") with tf.gfile.GFile(output_predict_file, "w") as pred_writer,\ tf.gfile.GFile(output_submit_file, "w") as sub_writer: sub_writer.write("index" + "\t" + "prediction\n") num_written_lines = 0 tf.logging.info("***** Predict results *****") for (i, (example, prediction)) in\ enumerate(zip(predict_examples, result)): probabilities = prediction["probabilities"] if i >= num_actual_predict_examples: break output_line = "\t".join( str(class_probability) for class_probability in probabilities) + "\n" pred_writer.write(output_line)
tensorflow.logging.info
8,142
from tensorflow.python.ops import math_ops @distribution_util.AppendDocstring( """This is defined to be ``` entropy = alpha - log(beta) + log(Gamma(alpha)) + (1-alpha)digamma(alpha) ``` where digamma(alpha) is the digamma function.""") def _entropy(self): return (self.alpha + math_ops.log(self.beta) + math_ops.lgamma(self.alpha) - (1. + self.alpha) * math_ops.digamma(self.alpha)) @distribution_util.AppendDocstring( """The mean of an inverse gamma distribution is `beta / (alpha - 1)`, when `alpha > 1`, and `NaN` otherwise. If `self.allow_nan_stats` is `False`, an exception will be raised rather than returning `NaN`""") def _mean(self): mean = self.beta / (self.alpha - 1.) if self.allow_nan_stats: nan = np.array(np.nan, dtype=self.dtype.as_numpy_dtype()) return array_ops.where(
tensorflow.python.ops.math_ops.lgamma
8,143
import tensorflow as tf gsum = tf.reduce_sum(gstack, axis=1) phi = tf.get_variable("phi", (self.g_dim, self.k)) w = tf.matmul(gsum, phi) w = tf.expand_dims(w, [2]) # Calculate policy and sample logits = tf.reshape(tf.matmul(U, w), [-1, num_acts]) self.pi = tf.nn.softmax(logits) self.log_pi = tf.nn.log_softmax(logits) self.sample = policy_utils.categorical_sample( tf.reshape(logits, [-1, num_acts]), num_acts)[0, :] def build_value(self, _input): with tf.variable_scope('VF'): hidden = tf.layers.dense(inputs=_input, units=self.vf_hidden_size, activation=tf.nn.elu) w = tf.get_variable("weights", (self.vf_hidden_size, 1))
tensorflow.reshape
8,144
import tensorflow as tf import os.path as osp FLAGS = tf.flags.FLAGS tf.flags.DEFINE_integer("batch_size", "2", "batch size for training") tf.flags.DEFINE_string("logs_dir", r"E:\work\01-Myproject\imag_division\FCN.tensorflow-master\logs", "path to logs directory") tf.flags.DEFINE_string("data_dir", r"E:\work\01-Myproject\imag_division\FCN.tensorflow-master\Data_zoo\STEM", "path to dataset") tf.flags.DEFINE_float("learning_rate", "1e-4", "Learning rate for Adam Optimizer") tf.flags.DEFINE_string("model_dir", r"E:\work\01-Myproject\imag_division\FCN.tensorflow-master\Model_zoo", "Path to vgg model mat") tf.flags.DEFINE_bool('debug', "False", "Debug mode: True/ False") tf.flags.DEFINE_string('mode', "train", "Mode train/ test/ visualize") MODEL_URL = 'http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat' MAX_ITERATION = 100 #最大步数
tensorflow.flags.DEFINE_string
8,145
import tensorflow as tf qh_emb = tf.reshape(tf.nn.embedding_lookup( self.char_mat, self.qh), [N * QL * self.max_p_num, CL, dc]) ch_emb = tf.nn.dropout(ch_emb, 1.0 - 0.5 * self.dropout) qh_emb = tf.nn.dropout(qh_emb, 1.0 - 0.5 * self.dropout)
tensorflow.nn.dropout
8,146
import tensorflow as tf pooling_result = tf.cond( tf.equal(sl_unhead, 0), lambda: tf.zeros([bs, 0, hn], tf.float32), lambda: mean_pooling_for_unselected_head( unhead_org_idx, sl_unhead, rep_unhead_mask, input_idx, sl, rep_mask, rep_map, None) # todo: point ! ) with tf.variable_scope('output'): if keep_unselected: range_head = tf.tile(tf.expand_dims(tf.range(bs), -1), [1, sl_head]) scatter_attn = tf.cond( tf.equal(sl_head, 0), 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])
tensorflow.variable_scope
8,147
from tensorflow.contrib import metrics as metrics_lib label_name=label_name, weight_column_name=weight_column_name) def logits_to_predictions(self, logits, proba=False): if self.num_label_columns == 1: return array_ops.squeeze(logits, squeeze_dims=[1]) return logits def get_eval_ops(self, features, logits, targets, metrics=None): loss = self.loss(logits, targets, features) result = {"loss": metrics_lib.streaming_mean(loss)} if metrics: predictions = self.logits_to_predictions(logits, proba=False) result.update(_run_metrics(predictions, targets, metrics, self.get_weight_tensor(features))) return result class _MultiClassTargetColumn(_TargetColumn): """_TargetColumn for classification."""
tensorflow.contrib.metrics.streaming_mean
8,148
import tensorflow as tf labels=label_ids, predictions=predictions, weights=is_real_example) loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example)
tensorflow.metrics.mean
8,149
import tensorflow as tf max_output = K.max(layer_output, axis=3) saliency = K.gradients(K.sum(max_output), input_img)[0] return K.function([input_img, K.learning_phase()], [saliency]) def modify_backprop(model, name): g = tf.get_default_graph() with g.gradient_override_map({'Relu': name}): # get layers that have an activation layer_dict = [layer for layer in model.layers[1:]
tensorflow.get_default_graph
8,150
import tensorflow as tf 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 # Three types of downsampling methods described by paper def downsampling(inputs, downsampling_type, name, optional_shortcut=False, shortcut=None): # k-maxpooling
tensorflow.nn.relu
8,151
import tensorflow as tf https://arxiv.org/abs/1712.04851. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import i3d_utils trunc_normal = lambda stddev: tf.truncated_normal_initializer(0.0, stddev) conv3d_spatiotemporal = i3d_utils.conv3d_spatiotemporal inception_block_v1_3d = i3d_utils.inception_block_v1_3d # Orignaly, arg_scope = slim.arg_scope and layers = slim, now switch to more # update-to-date tf.contrib.* API. arg_scope = tf.contrib.framework.arg_scope layers = tf.contrib.layers def s3dg_arg_scope(weight_decay=1e-7,
tensorflow.truncated_normal_initializer
8,152
import tensorflow as tf if add_flipped_images: scales_to_logits_reversed = ( outputs_to_scales_to_logits_reversed[output]) logits_reversed = _resize_bilinear( tf.reverse_v2(scales_to_logits_reversed[MERGED_LOGITS_SCOPE], [2]), tf.shape(images)[1:3], scales_to_logits_reversed[MERGED_LOGITS_SCOPE].dtype) outputs_to_predictions[output].append( tf.expand_dims(tf.nn.softmax(logits_reversed), 4))
tensorflow.shape
8,153
import tensorflow as tf tf.summary.scalar('lr', lr) optimizer = tf.train.MomentumOptimizer(lr, momentum=cfgs.MOMENTUM) fcos = build_whole_network_batch_quad.DetectionNetworkFCOS(cfgs=self.cfgs, is_training=True) with tf.name_scope('get_batch'): if cfgs.IMAGE_PYRAMID: shortside_len_list = tf.constant(cfgs.IMG_SHORT_SIDE_LEN) shortside_len = tf.random_shuffle(shortside_len_list)[0] else: shortside_len = cfgs.IMG_SHORT_SIDE_LEN img_name_batch, img_batch, gtboxes_and_label_batch, num_objects_batch, img_h_batch, img_w_batch = \ self.reader.next_batch(dataset_name=cfgs.DATASET_NAME,
tensorflow.constant
8,154
import tensorflow as tf # Check that the parameter nodes have been initialized. self.assertEqual(10.0, v0.eval()) self.assertEqual(20.0, v1.eval()) # Save the initialized values in the file at "save_path" val = save.save(sess, save_path) self.assertTrue(isinstance(val, six.string_types)) self.assertEqual(save_path, val) # Start a second session. In that session the variables # have not been initialized either. with self.test_session(graph=tf.Graph()) as sess: v0 = tf.Variable(-1.0, name="v0") v1 = tf.Variable(-1.0, name="v1") save = tf.train.Saver([v0, v1]) with self.assertRaisesWithPredicateMatch( tf.OpError, lambda e: "uninitialized value v0" in e.message): sess.run(v0) with self.assertRaisesWithPredicateMatch( tf.OpError, lambda e: "uninitialized value v1" in e.message): sess.run(v1) # Restore the saved values in the parameter nodes. save.restore(sess, save_path) # Check that the parameter nodes have been restored.
tensorflow.Variable
8,155
import tensorflow as tf """Layers used during upsampling""" with tf.variable_scope(name): if reuse: tf.get_variable_scope().reuse_variables() else: assert tf.get_variable_scope().reuse is False u = tf.contrib.layers.conv2d_transpose(layer_input,filters,f_size,stride=stride,padding=padding) if dropout_rate: u = tf.contrib.layers.dropout(u,keep_prob=dropout_rate) u = tf.contrib.layers.batch_norm(u) u = tf.nn.relu(u) # u = tf.contrib.keras.layers.concatenate([skip_input,u]) return u # Downsampling dwn1 = common_conv2d(image,self.gf,stride=2,norm=False,name='dwn1') # 64x64 -> 32x32 #print('dwn1',np.shape(dwn1))
tensorflow.contrib.layers.dropout
8,156
import tensorflow as tf if FLAGS.do_train: tf.logging.info("***** Running training *****")
tensorflow.logging.info
8,157
import tensorflow as tf if lm_coef > 0: train_loss = tf.reduce_mean(clf_losses) + lm_coef*tf.reduce_mean(lm_losses) else: train_loss = tf.reduce_mean(clf_losses) params = find_trainable_variables("model") grads = tf.gradients(train_loss, params) grads = list(zip(grads, params)) gpu_grads.append(grads) gpu_ops.append([clf_logits, clf_losses, lm_losses]) ops = [tf.concat(op, 0) for op in zip(*gpu_ops)] grads = average_grads(gpu_grads) grads = [g for g, p in grads] train = opt_fns[opt](params, grads, lr, partial(lr_schedules[lr_schedule], warmup=lr_warmup), n_updates_total, l2=l2, max_grad_norm=max_grad_norm, vector_l2=vector_l2, b1=b1, b2=b2, e=e) return [train]+ops def mgpu_predict(*xs): gpu_ops = [] xs = (tf.split(x, n_gpu, 0) for x in xs)
tensorflow.concat
8,158
import tensorflow as tf def train_right_length(example, target): l = tf.maximum(tf.shape(example['inputs'])[0], tf.shape(target)[0]) return tf.less(l, max_length + 1)
tensorflow.shape
8,159
import tensorflow as tf self.summarise = tf.summary.merge(tf.get_collection(tf.GraphKeys.SUMMARIES)) # AC net def build_anet(self, state_in, name, reuse=False): reg = tf.contrib.layers.l2_regularizer(1e-3) with tf.variable_scope(name, reuse=reuse): layer_a1 = tf.layers.dense(state_in, 512, tf.nn.relu, kernel_regularizer=reg) 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)
tensorflow.constant_initializer
8,160
import tensorflow as tf model = revnet.RevNet(config=config) if defun: # TODO(apassos): reenable after cond lets you return None model.call = tfe.defun(model.call) batch_size = 64 num_burn = 5 num_iters = 10 with tf.device(device): images, _ = random_batch(batch_size, config) for _ in range(num_burn): model(images, training=False) if execution_mode: tfe.async_wait() gc.collect()
tensorflow.device
8,161
import tensorflow as tf # logit of the end position with tf.variable_scope("end_logits"): if is_training: # during training, compute the end logits based on the # ground truth of the start position start_positions = tf.reshape(features["start_positions"], [-1]) start_index = tf.one_hot(start_positions, depth=seq_len, axis=-1, dtype=tf.float32) start_features = tf.einsum("lbh,bl->bh", output, start_index) start_features = tf.tile(start_features[None], [seq_len, 1, 1]) end_logits = tf.layers.dense( tf.concat([output, start_features], axis=-1), xlnet_config.d_model, kernel_initializer=initializer, activation=tf.tanh, name="dense_0") end_logits = tf.contrib.layers.layer_norm( end_logits, begin_norm_axis=-1) end_logits = tf.layers.dense(
tensorflow.einsum
8,162
import tensorflow as tf improvement = (mean_dist-mean_pred_error)/mean_dist pairwise_improvement = tf.nn.relu(dists[1:] - pred_error) pairwise_improvement_bool = tf.cast(pairwise_improvement > 0, pairwise_improvement.dtype) self.pairwise_improvement_bool = pairwise_improvement_bool metrics.append(tf.summary.scalar('training/avg_dist', mean_dist)) metrics.append(tf.summary.scalar('training/pred_dist', mean_pred_error)) metrics.append(tf.summary.scalar('training/improvement', improvement)) metrics.append(tf.summary.scalar('training/improvement_abs', tf.nn.relu(improvement))) metrics.append(tf.summary.histogram('training/improvement_abs_hist', nut.nan_to_zero(improvement))) metrics.append(tf.summary.scalar('training/improvement_pairwise', tf.reduce_mean(pairwise_improvement_bool))) metrics.append(tf.summary.histogram('training/improvement_pairwise_hist', pairwise_improvement_bool)) self.eval_summs = tf.summary.merge(metrics) def _build_embedding_saver(self, sess): """To use embedding visualizer data has to be stored in variable
tensorflow.nn.relu
8,163
import tensorflow as tf tf.gfile.MakeDirs(FLAGS.output_dir) input_files = [] for input_pattern in FLAGS.input_file.split(","): input_files.extend(tf.gfile.Glob(input_pattern)) tf.logging.info("*** Input Files ***") for input_file in input_files: tf.logging.info(" %s" % input_file) tpu_cluster_resolver = None if FLAGS.use_tpu and FLAGS.tpu_name: tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver( FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project ) is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2 if FLAGS.use_tpu: run_config = tf.contrib.tpu.RunConfig( cluster=tpu_cluster_resolver, master=FLAGS.master, model_dir=FLAGS.output_dir, save_checkpoints_steps=FLAGS.save_checkpoints_steps, tpu_config=tf.contrib.tpu.TPUConfig(
tensorflow.contrib.cluster_resolver.TPUClusterResolver
8,164
import tensorflow as tf from tensorflow.python.ops import array_ops from tensorflow.python.ops import variable_scope as vs from tensorflow.keras import backend as K def dice(_x, axis=-1, epsilon=0.000000001, name=''): with tf.variable_scope(name, reuse=tf.AUTO_REUSE): alphas = tf.get_variable('alpha'+name, _x.get_shape()[-1], initializer=tf.constant_initializer(0.0), dtype=_x.dtype) input_shape = list(_x.get_shape())
tensorflow.variable_scope
8,165
import tensorflow as tf def __init__(self,name,input_dim,output_dim,k_t=2,k_h=3,k_w=3,d_t=2,d_h=1,d_w=1, stddev=0.02, data_format='NDHWC') : with tf.variable_scope(name) : assert(data_format == 'NDHWC') self.w = tf.get_variable('w', [k_t, k_h, k_w, input_dim, output_dim], 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) class Linear(object) : def __init__(self,name,input_dim,output_dim,stddev=0.02) : with tf.variable_scope(name) : self.w = tf.get_variable('w',[input_dim, output_dim], initializer=tf.random_normal_initializer(stddev=stddev)) self.b = tf.get_variable('b',[output_dim], initializer=tf.constant_initializer(0.0))
tensorflow.nn.convolution
8,166
import tensorflow as tf pattern = files[0].name[:pos] + 'AB%sDEF.GH*' self.assertEqual(set(tf.matching_files(pattern % 'z').eval()), self._subset(files, [1])) self.assertEqual(set(tf.matching_files(pattern % '?').eval()), self._subset(files, [0, 1, 3, 4])) self.assertEqual(set(tf.matching_files(pattern % '*').eval()), self._subset(files, [0, 1, 2, 3, 4, 5])) self.assertEqual(set(tf.matching_files(pattern % '[cxz]').eval()), self._subset(files, [0, 1])) self.assertEqual(set(tf.matching_files(pattern % '[0-9]').eval()), self._subset(files, [3, 4]))
tensorflow.matching_files
8,167
from tensorflow.python.framework import ops mean, tf.check_numerics( decay * (mean - cur_mean), "NaN in moving mean.")) with tf.name_scope(name, "AssignMovingAvg", [var, cur_var, decay]): with ops.colocate_with(var): new_var = tf.assign_sub( var, tf.check_numerics(decay * (var - cur_var), "NaN in moving variance.")) with tf.name_scope(name, "IncrementTime", [step]): with ops.colocate_with(step): new_step = tf.assign_add(step, 1.) used_var += 0. * new_mean * new_var * new_step used_var += epsilon return used_mean, used_var def convnet(input_, dim_in,
tensorflow.python.framework.ops.colocate_with
8,168
import tensorflow as tf def _evaluate_spherical_harmonics_branch(degree, order, theta, phi, sign_order, var_type=tf.float64): sqrt_2 = tf.constant(1.41421356237, dtype=var_type) order_float = tf.cast(order, dtype=var_type) tmp = sqrt_2 * _spherical_harmonics_normalization( degree, order, var_type) * evaluate_legendre_polynomial( degree, order, tf.cos(theta)) positive = tmp * tf.cos(order_float * phi) negative = tmp * tf.sin(order_float * phi) return tf.where(tf.greater(sign_order, 0), positive, negative) def evaluate_spherical_harmonics( degree_l: TensorLike, order_m: TensorLike, theta: TensorLike, phi: TensorLike, name: str = "spherical_harmonics_evaluate_spherical_harmonics") -> TensorLike: # pylint: disable=line-too-long with tf.name_scope(name):
tensorflow.sin
8,169
from tensorflow.python.framework import ops * `optimizer` has the wrong type. * `clip_gradients` is neither float nor callable. * `learning_rate` and `learning_rate_decay_fn` are supplied, but no `global_step` is available. * `gradients` is empty. """ loss = ops.convert_to_tensor(loss) contrib_framework.assert_scalar(loss) if global_step is None: global_step = train.get_global_step() else: train.assert_global_step(global_step) with vs.variable_scope(name, "OptimizeLoss", [loss, global_step]): # Update ops take UPDATE_OPS collection if not provided. if update_ops is None: update_ops = set(ops.get_collection(ops.GraphKeys.UPDATE_OPS)) # Make sure update ops are ran before computing loss. if update_ops: loss = control_flow_ops.with_dependencies(list(update_ops), loss) # Learning rate variable, with possible decay. lr = None if learning_rate is not None: if (isinstance(learning_rate, ops.Tensor) and learning_rate.get_shape().ndims == 0): lr = learning_rate elif isinstance(learning_rate, float): if learning_rate < 0.0: raise ValueError("Invalid learning_rate %s.", learning_rate) lr = vs.get_variable(
tensorflow.python.framework.ops.get_collection
8,170
import tensorflow as tf dxt = tf.stack(dxt_list) xt = tf.stack(states) num = (1 - self.alpha) * dxt + tf.tensordot(self.alpha * dxt , tf.transpose( tf.matmul(tf.abs(self.W_rec) * self.rec_Connectivity,self.Dale_rec)), axes=1) * \ tf.where(tf.greater(xt, 0), tf.ones_like(xt), tf.zeros_like(xt)) denom = dxt # sum over hidden units num = tf.reduce_sum(tf.square(num), axis=2) denom = tf.reduce_sum(tf.square(denom), axis=2) bounded = tf.where(tf.greater(denom, 1e-20), tf.div(num, 1.0 * denom), tf.ones_like(num)) nelems = tf.reduce_mean(tf.where(tf.greater(denom, 1e-20), 1.0 * tf.ones_like(num), 1.0 * tf.zeros_like(num)), axis=1) # sum mean over each batch by time steps Omega = tf.square(bounded - 1.0) Omega = tf.reduce_sum(tf.reduce_mean(Omega, axis=1)) / (1.0 * tf.reduce_sum(nelems)) out = tf.gradients(Omega, self.W_rec) out[0] = tf.Print(out[0], [out[0], self.W_rec, Omega], "omega grads")
tensorflow.square
8,171
import tensorflow as tf q_vals, _ = self._critic(critic_input, training=False) q_vals_vec = tf.reshape(q_vals, (batch_size, num_tasks)) rewards, dones = self._task_distribution.evaluate(states_tiled, actions_tiled, tasks_tiled) dones = tf.cast(dones, tf.float32) rewards_vec = tf.reshape(rewards, (batch_size, num_tasks)) dones_vec = tf.reshape(dones, (batch_size, num_tasks)) relabelled_obs = self._task_distribution.combine(states_tiled, tasks_tiled) action_distribution = self._actor( relabelled_obs, step_type=(), network_state=())[0] log_pi = common.log_probability(action_distribution, actions_tiled,
tensorflow.reshape
8,172
import tensorflow as tf weights_list = [] type_list = [] for hop_edge_types, count in zip(edge_types, counts): neighbors, weights, types = sample_neighbor( neighbors_list[-1], hop_edge_types, count, default_node=default_node) neighbors_list.append(tf.reshape(neighbors, [-1])) weights_list.append(tf.reshape(weights, [-1])) type_list.append(tf.reshape(types, [-1])) return neighbors_list, weights_list, type_list def get_multi_hop_neighbor(nodes, edge_types): """ Get multi-hop neighbors with adjacent matrix.
tensorflow.reshape
8,173
import tensorflow as tf def _tf_multi_index(t, indices): """Partial TensorFlow implementation of Theano t[indices].""" # Note: this is far from a full implementation of Theano fancy # indexing, use with care. assert K._BACKEND == 'tensorflow' from collections import Sequence import tensorflow as tf if not isinstance(indices, Sequence): raise ValueError(indices) if len(indices) == 1: return tf.gather(t, indices[0]) # gather() suffices for 1d if K.ndim(t) == len(indices): # Index n-dimensional tensor with n indices: pack the indices # from e.g. [[i_0, i_1, ...] [j_0, j_1, ...]] to [[i_0, j_0], # [i_1, j_1], ...] and use gather_nd() # (https://www.tensorflow.org/api_docs/python/array_ops.html#gather_nd) # TODO: check that all i in indices have ndim n-1 # TODO: support broadcasting for numpy arrays with np.broadcast_to() #indices = tf.pack(list(indices), axis=len(indices)-1) indices = tf.pack(list(indices), axis=-1) # indices = tf.Print(indices, [indices], 'indices', summarize=100) return tf.gather_nd(t, indices) else:
tensorflow.gather
8,174
import tensorflow as tf Q_filter = tf.cast((qf1 > min_q)|(qf2 > min_q),tf.float32) #Q_filter_1 = tf.cast(qf1 > min_q,tf.float32) #Q_filter_2 = tf.cast(qf2 > min_q,tf.float32) im_loss1 = tf.square(self.actions_ph - self.deterministic_actions_ph)*Q_filter*self.is_demo_ph #im_loss2 = tf.square(self.actions_ph - self.deterministic_actions_ph)*Q_filter_2*self.is_demo_ph #actor_loss_di1 = tf.reduce_mean(im_loss1) #actor_loss_di2 = tf.reduce_mean(im_loss2) self.actor_loss_di = tf.reduce_mean(im_loss1) imitation_for_priority = tf.reduce_mean(im_loss1,axis=1) regularizerpi = tf.contrib.layers.l1_l2_regularizer(scale_l1=0.0, scale_l2=1e-5, scope="model/pi") all_trainable_weights_pi = tf.trainable_variables('model/pi') regularization_penalty_pi = tf.contrib.layers.apply_regularization(regularizerpi, all_trainable_weights_pi) policy_loss = policy_kl_loss + regularization_penalty_pi + self.actor_loss_di
tensorflow.reduce_mean
8,175
import tensorflow as tf rnn_outputs, final_state = tf.nn.dynamic_rnn(cell, rnn_inputs, initial_state=init_state) '''预测,损失,优化''' with tf.variable_scope('softmax'): W = tf.get_variable('W', [state_size, num_classes]) b = tf.get_variable('b', [num_classes], initializer=tf.constant_initializer(0.0)) '''因为rnn_outputs是三维的,这里需要将其转成2维的, 矩阵运算后再转换回来[batch_size, num_steps, num_classes]''' logits = tf.reshape(tf.matmul(tf.reshape(rnn_outputs, [-1, state_size]), W) +b, \ shape=[batch_size, num_steps, num_classes]) predictions = tf.nn.softmax(logits) y_as_list = tf.unstack(y, num=num_steps, axis=1) losses = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y,logits=logits) total_loss = tf.reduce_mean(losses) train_step = tf.train.AdagradOptimizer(learning_rate).minimize(total_loss) '''训练网络''' def train_rnn(num_epochs, num_steps, state_size=4, verbose=True): with tf.Session() as sess: sess.run(tf.global_variables_initializer()) #sess = tf_debug.LocalCLIDebugWrapperSession(sess) training_losses = []
tensorflow.unstack
8,176
import tensorflow as tf feature_emb = tf.concat(feature_emb_list, 2) # [k, c, emb] feature_emb = tf.nn.dropout(feature_emb, self.dropout) # [k, c, emb] target_emb = tf.expand_dims(top_span_emb, 1) # [k, 1, emb] similarity_emb = top_antecedent_emb * target_emb # [k, c, emb] target_emb = tf.tile(target_emb, [1, c, 1]) # [k, c, emb] pair_emb = tf.concat([target_emb, top_antecedent_emb, similarity_emb, feature_emb], 2) # [k, c, emb] with tf.variable_scope("slow_antecedent_scores"): slow_antecedent_scores = util.ffnn(pair_emb, self.config["ffnn_depth"], self.config["ffnn_size"], 1, self.dropout) # [k, c, 1] slow_antecedent_scores = tf.squeeze(slow_antecedent_scores, 2) # [k, c] return slow_antecedent_scores # [k, c]
tensorflow.concat
8,177
import tensorflow as tf # channels dim im_flat = tf.reshape(im, tf.stack([-1, channels])) im_flat = tf.to_float(im_flat) i_z0_y0_x0 = tf.gather(im_flat, idx_z0_y0_x0) i_z0_y0_x1 = tf.gather(im_flat, idx_z0_y0_x1) i_z0_y1_x0 = tf.gather(im_flat, idx_z0_y1_x0) i_z0_y1_x1 = tf.gather(im_flat, idx_z0_y1_x1) i_z1_y0_x0 = tf.gather(im_flat, idx_z1_y0_x0) i_z1_y0_x1 = tf.gather(im_flat, idx_z1_y0_x1) i_z1_y1_x0 = tf.gather(im_flat, idx_z1_y1_x0) i_z1_y1_x1 = tf.gather(im_flat, idx_z1_y1_x1) # Finally calculate interpolated values. x0_f = tf.to_float(x0) x1_f = tf.to_float(x1) y0_f = tf.to_float(y0) y1_f = tf.to_float(y1) z0_f = tf.to_float(z0) z1_f = tf.to_float(z1) # Check the out-of-boundary case. x0_valid = tf.to_float( tf.less_equal(x0, max_x) & tf.greater_equal(x0, 0)) x1_valid = tf.to_float( tf.less_equal(x1, max_x) & tf.greater_equal(x1, 0)) y0_valid = tf.to_float( tf.less_equal(y0, max_y) & tf.greater_equal(y0, 0))
tensorflow.to_float
8,178
import tensorflow as tf # Set up optional scale and offset factors. if self._offset: self._set_default_initializer(self.BETA) self._beta = tf.get_variable( self.BETA, shape=self._mean_shape, initializer=self._initializers[self.BETA])
tensorflow.get_variable
8,179
import tensorflow as tf 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)
tensorflow.contrib.tpu.TPUEstimatorSpec
8,180
import tensorflow as tf generator_target_prob) self.g_loss = tf.reduce_mean(self.g_loss)
tensorflow.reduce_mean
8,181
import tensorflow as tf # Compute the policy loss # Alternative: policy_kl_loss = tf.reduce_mean(logp_pi - min_qf_pi) policy_kl_loss = tf.reduce_mean((self.ent_coef * logp_pi - min_qf_pi)*self.weight_ph) actor_for_priority = tf.reduce_mean(self.ent_coef * logp_pi - min_qf_pi,1) # NOTE: in the original implementation, they have an additional # regularization loss for the Gaussian parameters # this is not used for now # policy_loss = (policy_kl_loss + policy_regularization_loss) min_q = tf.minimum(dtm_qf1,dtm_qf2) Q_filter = tf.cast((qf1 > min_q)|(qf2 > min_q),tf.float32) #Q_filter_1 = tf.cast(qf1 > min_q,tf.float32) #Q_filter_2 = tf.cast(qf2 > min_q,tf.float32) im_loss1 = tf.square(self.actions_ph - self.deterministic_actions_ph)*Q_filter*self.is_demo_ph #im_loss2 = tf.square(self.actions_ph - self.deterministic_actions_ph)*Q_filter_2*self.is_demo_ph #actor_loss_di1 = tf.reduce_mean(im_loss1) #actor_loss_di2 = tf.reduce_mean(im_loss2) self.actor_loss_di = tf.reduce_mean(im_loss1) imitation_for_priority = tf.reduce_mean(im_loss1,axis=1) regularizerpi = tf.contrib.layers.l1_l2_regularizer(scale_l1=0.0, scale_l2=1e-5, scope="model/pi") all_trainable_weights_pi = tf.trainable_variables('model/pi')
tensorflow.cast
8,182
import tensorflow as tf print() net = [] with tf.variable_scope(name): with tf.variable_scope('branch1_1x1'): if o1s>0: conv1 = conv(inp, inSize, o1s, 1, 1, 1, 1, 'SAME', 'conv1x1', phase_train=phase_train, use_batch_norm=use_batch_norm, weight_decay=weight_decay) net.append(conv1)
tensorflow.variable_scope
8,183
from tensorflow.python.framework import ops grad, use_locking=self._use_locking).op def _apply_sparse(self, grad, var): delta = ops.IndexedSlices(grad.values * self._learning_rate_tensor, grad.indices, grad.dense_shape) return var.scatter_sub(delta, use_locking=self._use_locking)
tensorflow.python.framework.ops.IndexedSlices
8,184
from tensorflow.contrib.distributions.python.ops import distribution_util new_shape = array_ops.concat(0, ((-1,), batch_shape, event_shape)) x = array_ops.reshape(x, shape=new_shape) x = distribution_util.rotate_transpose(x, shift=-1) return x, sample_shape
tensorflow.contrib.distributions.python.ops.distribution_util.rotate_transpose
8,185
from tensorflow.python.ops import variables update_op = clip_opt.apply_gradients( list(zip([grads, grads], [var0, var1]))) variables.global_variables_initializer().run() return var0, var1, update_op
tensorflow.python.ops.variables.global_variables_initializer
8,186
import tensorflow as tf def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_tpu, use_one_hot_embeddings): """Returns `model_fn` closure for TPUEstimator.""" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument """The `model_fn` for TPUEstimator.""" tf.logging.info("*** Features ***") for name in sorted(features.keys()): tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape)) input_ids = features["input_ids"] input_mask = features["input_mask"] segment_ids = features["segment_ids"] label_ids = features["label_ids"] is_real_example = None
tensorflow.logging.info
8,187
import tensorflow as tf def attention(query, facts, attention_size, mask, stag='null', mode='LIST', softmax_stag=1, time_major=False, return_alphas=False): if isinstance(facts, tuple): # In case of Bi-RNN, concatenate the forward and the backward RNN outputs. facts = tf.concat(facts, 2) if time_major:
tensorflow.concat
8,188
import tensorflow as tf self.batch_pos_cnt = batch_pos_cnt self.max_iter = max_iter self.model_type = model_type self.add_bias = add_bias if opt is None: opt = tf.train.AdagradOptimizer(1.0) self.opt = opt self.sess = None self.train_step = None self.post_step = None self.graph = tf.Graph() with self.graph.as_default(): self.head_input = tf.placeholder(tf.int32, shape=[None]) self.rel_input = tf.placeholder(tf.int32, shape=[None]) self.tail_input = tf.placeholder(tf.int32, shape=[None]) self.target = tf.placeholder(tf.float32, shape=[None]) def _create_model(self, train_triples): ''' Subclasses must build Graph and set self.train_step ''' raise Exception('subclass must implement') def _create_batch_provider(self, train_triples): ''' Default implementation ''' return ContrastiveTrainingProvider(train_triples, self.batch_pos_cnt) def _create_output_and_loss(self, raw_output):
tensorflow.placeholder
8,189
import tensorflow as tf soft_placement = True util.auto_parallel(metagraph, m) with tf.Graph().as_default(): tf.train.import_meta_graph(metagraph) for model in models.values(): model.import_ops() sv = tf.train.Supervisor(logdir=FLAGS.save_path) config_proto = tf.ConfigProto(allow_soft_placement=soft_placement) with sv.managed_session(config=config_proto) as session: for i in range(config.max_max_epoch): lr_decay = config.lr_decay ** max(i + 1 - config.max_epoch, 0.0) m.assign_lr(session, config.learning_rate * lr_decay)
tensorflow.train.Supervisor
8,190
import tensorflow as tf self.param_initializer = { 'moving_mean': tf.constant_initializer(0., dtype=self.dtype), 'moving_variance': tf.constant_initializer(1., dtype=self.dtype), 'gamma': tf.constant_initializer(0.1, dtype=self.dtype) } self.param_trainable = {
tensorflow.constant_initializer
8,191
import tensorflow as tf conv2_bn = tf.nn.relu(tf.layers.batch_normalization(conv2, training=train)) pool2 = tf.layers.max_pooling2d( inputs=conv2_bn, pool_size=[2, 2], strides=2, name='pool2' ) v = tf.reshape(pool2, [-1, 4096]) fc1 = tf.layers.dense( inputs=v, units=1024, activation=tf.nn.relu, use_bias=True, name='fc1' ) fc2 = tf.layers.dense( inputs=fc1,
tensorflow.layers.dense
8,192
import tensorflow as tf 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) pairwise_improvement_bool = tf.cast(pairwise_improvement > 0, pairwise_improvement.dtype) self.pairwise_improvement_bool = pairwise_improvement_bool metrics.append(tf.summary.scalar('training/avg_dist', mean_dist))
tensorflow.reduce_mean
8,193
import tensorflow as tf x_batch_minus_min, x_batch_max = tf_utils.reduce_batch_minus_min_and_max( x, reduce_instance_dims) minus_x_min, x_max = _numeric_combine( # pylint: disable=unbalanced-tuple-unpacking inputs=[x_batch_minus_min, x_batch_max], fn=combine_fn, default_accumulator_value=default_accumulator_value, reduce_instance_dims=reduce_instance_dims) return tf.cast(0 - minus_x_min, output_dtype), tf.cast(x_max, output_dtype) def _min_and_max_per_key( x: common_types.TensorType, key: common_types.TensorType, reduce_instance_dims: bool = True, key_vocabulary_filename: Optional[str] = None,
tensorflow.cast
8,194
import tensorflow as tf sigma2 = 1.0 / 0.26 f1 = 'CE' def models(hps, images, RCE_train, logits=False, tsne_logits=False): model = model_name.ResNet(hps, images, FLAGS.mode, Reuse=True) model.build_graph() op = model.predictions.op logit, = op.inputs if RCE_train==True: logit = -logit if tsne_logits==True: return tf.nn.softmax(logit), model.t_SNE_logits if logits==True: return tf.nn.softmax(logit), logit return tf.nn.softmax(logit) class models_carlini: def __init__(self,hps): self.image_size = image_size self.num_channels = num_channel############MNIST and CIFAR10 are different ar here self.num_labels = num_classes self.hps = hps
tensorflow.nn.softmax
8,195
import tensorflow as tf to_seq = mask.shape.dims + [1] * (sequence.shape.ndims - mask.shape.ndims) sequence *= tf.reshape(mask, to_seq) to_decay = mask.shape.dims + [1] * (decay.shape.ndims - mask.shape.ndims) decay *= tf.reshape(mask, to_decay) sequences = [sequence, decay]
tensorflow.reshape
8,196
import tensorflow as tf if self.mode == tf.estimator.ModeKeys.EVAL: return tf.estimator.EstimatorSpec( self.mode, loss=loss, eval_metric_ops=metrics ) elif self.mode == tf.estimator.ModeKeys.TRAIN: optimizer_params = self.params.get("optimizer_params", {}) global_step = tf.train.get_or_create_global_step() # apply learning rate decay if it's setup already. lr_decay_params = optimizer_params.pop("learning_rate_exp_decay", {}) # learning_rate = tf.train.exponential_decay( # self.params["learning_rate"], # global_step, # decay_steps=self.params["lr_decay_steps"],
tensorflow.train.get_or_create_global_step
8,197
import tensorflow as tf def testParetoPDFGradientZeroOutsideSupport(self): scale = tf.constant(1.) concentration = tf.constant(3.) # Check the gradient on the undefined portion. x = scale - 1 pareto = tfd.Pareto(concentration, scale) compute_pdf = lambda x: pareto.prob(x) # pylint:disable=unnecessary-lambda self.assertAlmostEqual(self.compute_gradients( compute_pdf, args=[x])[0], 0.) def testParetoCDFGradientZeroOutsideSupport(self): scale = tf.constant(1.) concentration = tf.constant(3.) # Check the gradient on the undefined portion. x = scale - 1 pareto = tfd.Pareto(concentration, scale) compute_cdf = lambda x: pareto.cdf(x) # pylint:disable=unnecessary-lambda self.assertAlmostEqual( self.compute_gradients( compute_cdf, args=[x])[0], 0.) def testParetoMean(self): scale = [1.4, 2., 2.5] concentration = [2., 3., 2.5] pareto = tfd.Pareto(concentration, scale)
tensorflow.constant
8,198
import tensorflow as tf # The `positions` tensor might be zero-padded (if the sequence is too # short to have the maximum number of predictions). The `label_weights` # tensor has a value of 1.0 for every real prediction and 0.0 for the # padding predictions. per_example_loss = -tf.reduce_sum(log_probs * one_hot_labels, axis=[-1]) numerator = tf.reduce_sum(label_weights * per_example_loss) denominator = tf.reduce_sum(label_weights) + 1e-5 loss = numerator / denominator
tensorflow.reduce_sum
8,199