seed
stringlengths
25
2.89k
seed_api
stringlengths
14
102
index
int64
0
14.8k
import tensorflow as tf return X def conv(self, id, input, channels, size=3, stride=1, use_bias=True, padding="SAME", init_stddev=-1.0, dilation=1): assert padding in ["SAME", "VALID", "REFLECT", "PARTIAL"], 'valid paddings: "SAME", "VALID", "REFLECT", "PARTIAL"' if type(size) == int: size = [size, size] if init_stddev <= 0.0: init = tf.contrib.layers.variance_scaling_initializer(dtype=tf.float32) else: init = tf.truncated_normal_initializer(stddev=init_stddev) if padding == "PARTIAL": with tf.variable_scope('mask'): _, h, w, _ = input.get_shape().as_list()
tensorflow.contrib.layers.variance_scaling_initializer
9,700
import tensorflow as tf loss_weights: tensor shape (batch_size, max_dec_steps) containing 1s and 0s. Returns: a scalar """ if loss_weights == None: return tf.reduce_mean(tf.stack(values, axis=0)) dec_lens = tf.reduce_sum(loss_weights, axis=1) # shape batch_size. float32 values_per_step = [v * loss_weights[:,dec_step] for dec_step,v in enumerate(values)] values_per_ex = sum(values_per_step)/dec_lens # shape (batch_size); normalized value for each batch member return tf.reduce_mean(values_per_ex) # overall average
tensorflow.stack
9,701
import tensorflow as tf 'image/source_id': tf.io.FixedLenFeature((), tf.string), 'image/height': tf.io.FixedLenFeature((), tf.int64), 'image/width': tf.io.FixedLenFeature((), tf.int64), 'image/object/bbox/xmin': tf.io.VarLenFeature(tf.float32), 'image/object/bbox/xmax': tf.io.VarLenFeature(tf.float32), 'image/object/bbox/ymin': tf.io.VarLenFeature(tf.float32), 'image/object/bbox/ymax': tf.io.VarLenFeature(tf.float32), 'image/object/class/label': tf.io.VarLenFeature(tf.int64), 'image/object/area': tf.io.VarLenFeature(tf.float32), 'image/object/is_crowd': tf.io.VarLenFeature(tf.int64), } if include_mask: self._keys_to_features.update({ 'image/object/mask': tf.io.VarLenFeature(tf.string), }) def _decode_image(self, parsed_tensors): """Decodes the image and set its static shape.""" image = tf.io.decode_image(parsed_tensors['image/encoded'], channels=3)
tensorflow.io.VarLenFeature
9,702
import tensorflow as tf with tf.device("/cpu:0"): val_summaries.append(self._add_image_summary(self._image, self._gt_boxes)) for key, var in self._event_summaries.items(): #添加self._losses val_summaries.append(tf.summary.scalar(key, var)) for key, var in self._score_summaries.items(): #self._score_summaries.update(self._anchor_targets) self._score_summaries.update(self._proposal_targets) self._add_score_summary(key, var)
tensorflow.summary.scalar
9,703
import tensorflow as tf # have not been initialized either. with self.test_session() as sess: v0 = tf.Variable(-1.0, name="v0") v1 = tf.Variable(-1.0, name="v1") save = tf.train.Saver({"v0": v0, "v1": v1}) with self.assertRaisesWithPredicateMatch( tf.OpError, lambda e: "uninitialized value v0" in e.message):
tensorflow.train.Saver
9,704
import tensorflow as tf with tf.variable_scope(layer_name): w = tf.get_variable(name='weight', shape=[size, out_nodes], initializer=tf.constant_initializer(0.0)) b = tf.get_variable(name='bias', shape=[out_nodes], initializer=tf.constant_initializer(0.0)) # batch? flat_x = tf.reshape(x, [-1,size]) x = tf.nn.bias_add(tf.matmul(flat_x,w), b) x = tf.nn.relu(x) return x def lstm(): ''' Build LSTM cell ''' pass
tensorflow.matmul
9,705
import tensorflow as tf 'end_learning_rate': FLAGS.end_learning_rate, 'warmup_learning_rate': FLAGS.warmup_learning_rate, 'warmup_steps': FLAGS.warmup_steps, 'decay_boundaries': parse_comma_list(decay_boundaries), 'lr_decay_factors': parse_comma_list(lr_decay_factors), }) tf.gfile.MakeDirs(model_dir) tf.logging.info('Starting to train model {}.'.format(model_scope)) for _ in range(train_epochs // epochs_per_eval): tensors_to_log = { 'lr': 'learning_rate', 'loss': 'total_loss', 'mse': 'mse_loss',
tensorflow.gfile.MakeDirs
9,706
import tensorflow as tf flattened_inputs = tf.contrib.layers.flatten(preprocessed_inputs) class_prediction = tf.contrib.layers.fully_connected(
tensorflow.contrib.layers.fully_connected
9,707
import tensorflow as tf return output @staticmethod def lrelu(inputdata, name, alpha=0.2): """ :param inputdata: :param alpha: :param name: :return: """ with tf.variable_scope(name): return tf.nn.relu(inputdata) - alpha * tf.nn.relu(-inputdata)
tensorflow.nn.relu
9,708
from tensorflow.python.framework import constant_op """Tests only dense inputs. """ op = sparse_feature_cross_op.sparse_feature_cross([ constant_op.constant([['batch1-FC1-F1', 'batch1-FC1-F2'], ['batch2-FC1-F1', 'batch2-FC1-F2']], dtypes.string),
tensorflow.python.framework.constant_op.constant
9,709
import tensorflow as tf return cand_features, n_cands_per_sample, cand_choices, cand_scoress def padding(output, n_vars_per_sample, fill=-1e8): n_vars_max = tf.reduce_max(n_vars_per_sample) output = tf.split( value=output, num_or_size_splits=n_vars_per_sample, axis=1, ) output = tf.concat([ tf.pad( x, paddings=[[0, 0], [0, n_vars_max - tf.shape(x)[1]]], mode='CONSTANT', constant_values=fill) for x in output ], axis=0) return output def process(policy, dataloader, top_k): mean_kacc = np.zeros(len(top_k)) n_samples_processed = 0 for batch in dataloader:
tensorflow.shape
9,710
import tensorflow as tf else: saver.restore(sess, args.model_path) for i in range(max_train_step): batch_x, batch_gt = mnist.train.next_batch(batch_size) sess.run(train_op, feed_dict={x: batch_x, gt: batch_gt}) if i % 100 == 0: correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(gt, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print('=> accuracy: {}'.format(sess.run(accuracy, feed_dict={x: mnist.test.images, gt: mnist.test.labels}))) saver.save(sess, 'mnist/mnist_{:02d}.ckpt'.format(int(i / 100) + 1))
tensorflow.cast
9,711
import tensorflow as tf from model_io import model_io from task_module import classifier import tensorflow as tf from metric import tf_metrics from optimizer import distributed_optimizer as optimizer from model_io import model_io from distillation import knowledge_distillation as distill def correlation(x, y): x = x - tf.reduce_mean(x, axis=-1, keepdims=True) y = y - tf.reduce_mean(y, axis=-1, keepdims=True) x = tf.nn.l2_normalize(x, -1) y = tf.nn.l2_normalize(y, -1) return -tf.reduce_sum(x*y, axis=-1) # higher the better def kd(x, y): x_prob = tf.nn.softmax(x) print(x_prob.get_shape(), y.get_shape(), tf.reduce_sum(x_prob * y, axis=-1).get_shape()) return -tf.reduce_sum(x_prob * y, axis=-1) # higher the better def mse(x, y): x = x - tf.reduce_mean(x, axis=-1, keepdims=True) y = y - tf.reduce_mean(y, axis=-1, keepdims=True)
tensorflow.reduce_mean
9,712
import tensorflow as tf with slim.arg_scope(self._conv_hyperparams): net = slim.conv2d(net, self._depth, [1, 1], scope='reduce_depth') # Location predictions. location_feature_map_depth = (self._num_spatial_bins[0] * self._num_spatial_bins[1] * self.num_classes * self._box_code_size) location_feature_map = slim.conv2d(net, location_feature_map_depth, [1, 1], activation_fn=None, scope='refined_locations') box_encodings = ops.position_sensitive_crop_regions( location_feature_map, boxes=tf.reshape(proposal_boxes, [-1, self._box_code_size]), box_ind=get_box_indices(proposal_boxes), crop_size=self._crop_size, num_spatial_bins=self._num_spatial_bins, global_pool=True) box_encodings = tf.squeeze(box_encodings, squeeze_dims=[1, 2]) box_encodings = tf.reshape(box_encodings, [batch_size * num_boxes, 1, self.num_classes, self._box_code_size]) # Class predictions. total_classes = self.num_classes + 1 # Account for background class.
tensorflow.reshape
9,713
import tensorflow as tf initializer=modeling.create_initializer(bert_config.initializer_range)) output_bias = tf.get_variable( "output_bias", shape=[2], initializer=tf.zeros_initializer()) logits = tf.matmul(input_tensor, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias) log_probs = tf.nn.log_softmax(logits, axis=-1) labels = tf.reshape(labels, [-1]) one_hot_labels = tf.one_hot(labels, depth=2, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1) loss = tf.reduce_mean(per_example_loss) return (loss, per_example_loss, log_probs)
tensorflow.reshape
9,714
import tensorflow as tf normalized_grad = old_div(grad, avoid_nan_norm) elif ord == 2: red_ind = list(range(1, len(x.get_shape()))) avoid_zero_div = 1e-8 square = tf.maximum(avoid_zero_div, reduce_sum(tf.square(grad), reduction_indices=red_ind, keepdims=True)) normalized_grad = old_div(grad, tf.sqrt(square)) else: normalized_grad = tf.sign(grad) normalized_grad = tf.stop_gradient(normalized_grad) scaled_grad = eps * normalized_grad #目标是让loss下降 adv_x = x - scaled_grad if (clip_min is not None) and (clip_max is not None): adv_x = tf.clip_by_value(adv_x, clip_min, clip_max)
tensorflow.sign
9,715
import tensorflow as tf import tensorflow.contrib.layers as layers import dqn from dqn_utils import * from atari_wrappers import * def atari_model(img_in, num_actions, scope, reuse=False): # as described in https://storage.googleapis.com/deepmind-data/assets/papers/DeepMindNature14236Paper.pdf with tf.variable_scope(scope, reuse=reuse): out = img_in with tf.variable_scope("convnet"): # original architecture out = layers.convolution2d(out, num_outputs=32, kernel_size=8, stride=4, activation_fn=tf.nn.relu) out = layers.convolution2d(out, num_outputs=64, kernel_size=4, stride=2, activation_fn=tf.nn.relu) out = layers.convolution2d(out, num_outputs=64, kernel_size=3, stride=1, activation_fn=tf.nn.relu) out = layers.flatten(out) with tf.variable_scope("action_value"): out = layers.fully_connected(out, num_outputs=512, activation_fn=tf.nn.relu) out = layers.fully_connected(out, num_outputs=num_actions, activation_fn=None) return out
tensorflow.variable_scope
9,716
import tensorflow as tf [FLAGS.learning_rate, FLAGS.learning_rate * 0.1]) optimizer = tf.train.MomentumOptimizer(
tensorflow.train.MomentumOptimizer
9,717
import tensorflow as tf inputdata = tf.reshape(inputdata, [-1, group_size, c // group_size, h, w]) mean, var = tf.nn.moments(inputdata, [2, 3, 4], keep_dims=True) inputdata = (inputdata - mean) / tf.sqrt(var + esp) # 每个通道的gamma和beta gamma = tf.Variable(tf.constant(1.0, shape=[c]), dtype=tf.float32, name='gamma') beta = tf.Variable(tf.constant(0.0, shape=[c]), dtype=tf.float32, name='beta') gamma = tf.reshape(gamma, [1, c, 1, 1]) beta = tf.reshape(beta, [1, c, 1, 1]) # 根据论文进行转换 [n, c, h, w, c] 到 [n, h, w, c] output = tf.reshape(inputdata, [-1, c, h, w])
tensorflow.constant
9,718
import tensorflow as tf if i > 0 and i % save_step == 0: tf.train.Saver().save(sess, path) tf.train.Saver().save(sess, path) coord.request_stop() coord.join(threads) def test_and_valid(test_loop=1,valid_loop=1,test_num=64,valid_num=64): feed_dict={ testnum: test_num, validnum: valid_num } with tf.Session(config=config) as sess: sess.run(init) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) tf.train.Saver().restore(sess,path) #test test_acc_avg = 0.0 test_true_total=np.array([]) test_pre_total=np.array([]) for i in range(0, test_loop): accuracy_np = sess.run([accuracy],feed_dict=feed_dict) test_pre_1, test_true_1 = sess.run([test_pre, test_true],feed_dict=feed_dict)
tensorflow.Session
9,719
import tensorflow as tf observations_ph = make_obs_ph("observation") stochastic_ph = tf.placeholder(tf.bool, (), name="stochastic") update_eps_ph = tf.placeholder(tf.float32, (), name="update_eps") eps = tf.get_variable("eps", (), initializer=tf.constant_initializer(0)) q_values = q_func(observations_ph.get(), num_actions, scope="q_func") deterministic_actions = tf.argmax(q_values, 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)
tensorflow.argmax
9,720
import tensorflow as tf encoder_outputs_, encoder_states_ = auto_reuse(tf.nn.dynamic_rnn)(cell=cell, initial_state=initial_state, **parameters) if encoder.time_pooling: for stride in encoder.time_pooling[:encoder.layers - 1]: encoder_input_length_ = (encoder_input_length_ + stride - 1) // stride # rounding up last_backward = encoder_outputs_[:, 0, cell_output_size:] indices = tf.stack([tf.range(batch_size), encoder_input_length_ - 1], axis=1) last_forward = tf.gather_nd(encoder_outputs_[:, :, :cell_output_size], indices) last_forward.set_shape([None, cell_output_size]) if encoder.final_state == 'concat_last': # concats last states of all backward layers (full LSTM states) encoder_state_ = tf.concat(encoder_states_, axis=1) elif encoder.final_state == 'average': mask = tf.sequence_mask(encoder_input_length_, maxlen=tf.shape(encoder_outputs_)[1], dtype=tf.float32) mask = tf.expand_dims(mask, axis=2)
tensorflow.range
9,721
import tensorflow as tf return in_length/stride + 1 def build(self, x): """Run the backprop version of the Circuit.""" self.prepare_tensors() i0 = tf.constant(0) # Calculate l2 hidden state size x_shape = x.get_shape().as_list() if self.include_pooling and len(self.ff_conv_k):
tensorflow.constant
9,722
import tensorflow as tf with self.session(): tf.global_variables_initializer().run() with self.assertRaisesRegexp(tf.errors.InvalidArgumentError,
tensorflow.global_variables_initializer
9,723
import tensorflow as tf scale = keep_prob if mode == "recurrent" and len(args.get_shape().as_list()) == 3: noise_shape = [shape[0], 1, shape[-1]] args = tf.cond(is_train, lambda: tf.nn.dropout( args, keep_prob, noise_shape=noise_shape) * scale, lambda: args) return args
tensorflow.nn.dropout
9,724
import tensorflow as tf print('Creating networks and loading parameters') with tf.Graph().as_default(): gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction) sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False)) with sess.as_default(): pnet, rnet, onet = align.detect_face.create_mtcnn(sess, None)
tensorflow.GPUOptions
9,725
import tensorflow as tf def _decode_masks(self, parsed_tensors): """Decode a set of PNG masks to the tf.float32 tensors.""" def _decode_png_mask(png_bytes): mask = tf.squeeze( tf.io.decode_png(png_bytes, channels=1, dtype=tf.uint8), axis=-1) mask = tf.cast(mask, dtype=tf.float32) mask.set_shape([None, None]) return mask height = parsed_tensors['image/height'] width = parsed_tensors['image/width'] masks = parsed_tensors['image/object/mask'] return tf.cond( pred=tf.greater(tf.size(input=masks), 0), true_fn=lambda: tf.map_fn(_decode_png_mask, masks, dtype=tf.float32), false_fn=lambda: tf.zeros([0, height, width], dtype=tf.float32)) def _decode_areas(self, parsed_tensors): xmin = parsed_tensors['image/object/bbox/xmin'] xmax = parsed_tensors['image/object/bbox/xmax'] ymin = parsed_tensors['image/object/bbox/ymin'] ymax = parsed_tensors['image/object/bbox/ymax'] return tf.cond( tf.greater(tf.shape(parsed_tensors['image/object/area'])[0], 0), lambda: parsed_tensors['image/object/area'], lambda: (xmax - xmin) * (ymax - ymin))
tensorflow.size
9,726
import tensorflow as tf i, f, o, u = tf.split(axis=1, num_or_size_splits=4, value=z) i = tf.nn.sigmoid(i)
tensorflow.nn.sigmoid
9,727
import tensorflow as tf name="batch_norm_ss") mean, variance = tf.nn.normalize_moments(counts, shifted_sum_x,
tensorflow.nn.normalize_moments
9,728
import tensorflow as tf @dynamic_batching.batch_fn def f(a, b): return a + b outputs = [] for _ in xrange(1000): outputs.append(f(tf.ones([1, 10]), tf.ones([1, 10]))) op_to_benchmark = tf.group(*outputs) tf.train.start_queue_runners() self.run_op_benchmark( name='batching_many_small', sess=session, op_or_tensor=op_to_benchmark, burn_iters=10, min_iters=50)
tensorflow.train.start_queue_runners
9,729
import tensorflow as tf train_op = tf.train.AdamOptimizer(learning_rate=lr).minimize(loss_total, global_step=global_step) with tf.variable_scope("summary"): summary_loss_total = tf.summary.scalar("loss_total", loss_total) summary_accuracy_test = tf.summary.scalar("accuracy_test", accuracy) summary_accuracy_train = tf.summary.scalar("accuracy_train", accuracy) # standardization train_X_reshaped = train_X.reshape([train_X.shape[0], -1]) train_X_means = np.mean(train_X_reshaped, axis=0, keepdims=True)
tensorflow.summary.scalar
9,730
import tensorflow as tf last_c = loop_outputs[-7] last_h = loop_outputs[-6] return arc_seq, entropy, log_prob, last_c, last_h def build_trainer(self, child_model): child_model.build_valid_rl() self.valid_acc = (tf.to_float(child_model.valid_shuffle_acc) / tf.to_float(child_model.batch_size)) self.reward = self.valid_acc if self.entropy_weight is not None: self.reward += self.entropy_weight * self.sample_entropy self.sample_log_prob = tf.reduce_sum(self.sample_log_prob) self.baseline = tf.Variable(0.0, dtype=tf.float32, trainable=False)
tensorflow.to_float
9,731
import tensorflow as tf tf.trainable_variables() + tf.get_collection(tf.GraphKeys.TRAINABLE_RESOURCE_VARIABLES))
tensorflow.get_collection
9,732
import tensorflow as tf q_tp1_best = tf.reduce_sum(target_policy.q_values * tf.one_hot(q_tp1_best_using_online_net, n_actions), axis=1) else: q_tp1_best = tf.reduce_max(target_policy.q_values, axis=1) q_tp1_best_masked = (1.0 - done_mask_ph) * q_tp1_best # compute RHS of bellman equation q_t_selected_target = rew_t_ph + gamma * q_tp1_best_masked # compute the error (potentially clipped) td_error = q_t_selected - tf.stop_gradient(q_t_selected_target) errors = tf_util.huber_loss(td_error) weighted_error = tf.reduce_mean(importance_weights_ph * errors) tf.summary.scalar("td_error", tf.reduce_mean(td_error)) tf.summary.scalar("loss", weighted_error) if full_tensorboard_log: tf.summary.histogram("td_error", td_error) # update_target_fn will be called periodically to copy Q network to target Q network update_target_expr = [] for var, var_target in zip(sorted(q_func_vars, key=lambda v: v.name), sorted(target_q_func_vars, key=lambda v: v.name)): update_target_expr.append(var_target.assign(var)) update_target_expr = tf.group(*update_target_expr) # compute optimization op (potentially with gradient clipping) gradients = optimizer.compute_gradients(weighted_error, var_list=q_func_vars)
tensorflow.summary.scalar
9,733
import tensorflow as tf trainable_var = tf.trainable_variables() if FLAGS.debug: for var in trainable_var: utils.add_to_regularization_and_summary(var) train_op = train(loss, trainable_var) print("Setting up summary op...") summary_op = tf.summary.merge_all() print("Setting up image reader...") train_records, valid_records = scene_parsing.read_dataset(FLAGS.data_dir) print(len(train_records)) print(len(valid_records))
tensorflow.summary.merge_all
9,734
import tensorflow as tf num_samples = self.num_samples.value() deltas, perturbations = self.while_loop( cond=util.tf_always_true, body=body, loop_vars=(deltas, previous_perturbations), maximum_iterations=num_samples ) with tf.control_dependencies(control_inputs=deltas): num_samples = tf.dtypes.cast(x=num_samples, dtype=util.tf_dtype(dtype='float')) deltas = [delta / num_samples for delta in deltas] perturbation_deltas = [delta - pert for delta, pert in zip(deltas, perturbations)] applied = self.apply_step(variables=variables, deltas=perturbation_deltas)
tensorflow.control_dependencies
9,735
import tensorflow as tf variable_summaries(w) if dilation > 1: conv = tf.nn.atrous_conv2d(x, w, dilation, padding) else: if type(padding)==type(''): conv = tf.nn.conv2d(x, w, stride, padding) else: conv = tf.pad(x, padding, "CONSTANT") conv = tf.nn.conv2d(conv, w, stride, padding='VALID') if bias != -1: bias = tf.get_variable('biases', [num_filters], initializer=tf.constant_initializer(bias)) variable_summaries(bias)
tensorflow.pad
9,736
import tensorflow as tf import datetime import BatchDatsetReader as dataset from six.moves import xrange 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")
tensorflow.flags.DEFINE_integer
9,737
import tensorflow as tf def run(dataset_dir): """Runs the download and conversion operation. Args: dataset_dir: The dataset directory where the dataset is stored. """ if not tf.gfile.Exists(dataset_dir): tf.gfile.MakeDirs(dataset_dir) dataset_utils.download_and_uncompress_tarball(_DATA_URL, dataset_dir) # First, process the training data: #with tf.python_io.TFRecordWriter(training_filename) as tfrecord_writer: filenames = []
tensorflow.gfile.Exists
9,738
import tensorflow as tf return x, regularization def mlp_dropout(x, hidden_sizes=(32,), activation=tf.tanh, output_activation=None, dropout_rate=0): for h in hidden_sizes[:-1]: x = tf.layers.dense(x, units=h, activation=activation) x = tf.layers.dropout(x, rate=dropout_rate, training=True) x = tf.layers.dropout(x, rate=dropout_rate, training=True) return tf.layers.dense(x, units=hidden_sizes[-1], activation=output_activation) def mlp(x, hidden_sizes=(32,), activation=tf.tanh, output_activation=None): for h in hidden_sizes[:-1]: x = tf.layers.dense(x, units=h, activation=activation) return tf.layers.dense(x, units=hidden_sizes[-1], activation=output_activation) def get_vars(scope): return [x for x in tf.global_variables() if scope in x.name] def count_vars(scope): v = get_vars(scope) return sum([np.prod(var.shape.as_list()) for var in v]) # """ # Random Network Distillation # """ # def random_net_distill(x_ph, a_ph, hidden_sizes=(400,300), activation=tf.nn.relu, # output_activation=tf.tanh, action_space=None): # act_dim = a_ph.shape.as_list()[-1] # act_limit = action_space.high[0] # with tf.variable_scope('rnd_targ_act'): # rnd_targ_act = act_limit * mlp(x_ph, list(hidden_sizes) + [act_dim], activation, output_activation)
tensorflow.global_variables
9,739
import tensorflow as tf self.dlatent_variable = next(v for v in tf.global_variables() if 'learnable_dlatents' in v.name) self.set_dlatents(self.initial_dlatents) self.generator_output = self.graph.get_tensor_by_name('G_synthesis_1/_Run/concat/concat:0') self.generated_image = tflib.convert_images_to_uint8(self.generator_output, nchw_to_nhwc=True, uint8_cast=False) self.generated_image_uint8 = tf.saturate_cast(self.generated_image, tf.uint8) def reset_dlatents(self): self.set_dlatents(self.initial_dlatents) def set_dlatents(self, dlatents): assert (dlatents.shape == (self.batch_size, 18, 512)) self.sess.run(tf.assign(self.dlatent_variable, dlatents)) def get_dlatents(self): return self.sess.run(self.dlatent_variable) def generate_images(self, dlatents=None): if dlatents: self.set_dlatents(dlatents) return self.sess.run(self.generated_image_uint8)
tensorflow.assign
9,740
import tensorflow as tf with sess.graph.device("/gpu:0"): v0_1 = tf.Variable(123.45)
tensorflow.Variable
9,741
import tensorflow as tf K.zeros((self.nb_actions, self.nb_actions)), K.zeros((self.nb_actions, self.nb_actions)), ] def fn(a, x): # Exponentiate everything. This is much easier than only exponentiating # the diagonal elements, and, usually, the action space is relatively low. x_ = K.exp(x) + K.epsilon() # Only keep the diagonal elements. x_ *= diag_mask # Add the original, non-diagonal elements. x_ += x * (1. - diag_mask) # Finally, gather everything into a lower triangular matrix. L_ = tf.gather(x_, tril_mask) return [L_, tf.transpose(L_)] tmp = tf.scan(fn, L_flat, initializer=init) if isinstance(tmp, (list, tuple)): # TensorFlow 0.10 now returns a tuple of tensors. L, LT = tmp else: # Old TensorFlow < 0.10 returns a shared tensor. L = tmp[:, 0, :, :] LT = tmp[:, 1, :, :] else: raise RuntimeError('Unknown Keras backend "{}".'.format(K.backend()))
tensorflow.gather
9,742
import tensorflow as tf # limitations under the License. import time import numpy as np import tensorflow as tf import random from tensorflow.contrib import slim from npu_bridge.estimator import npu_ops from tensorflow.core.protobuf.rewriter_config_pb2 import RewriterConfig tf.app.flags.DEFINE_integer('input_size', 512, '') tf.app.flags.DEFINE_integer('batch_size_per_gpu', 14, '') tf.app.flags.DEFINE_integer('num_readers', 16, '') tf.app.flags.DEFINE_float('learning_rate', 0.0001, '') tf.app.flags.DEFINE_integer('max_steps', 100000, '') tf.app.flags.DEFINE_integer('loss_scale', 1024, '') tf.app.flags.DEFINE_float('moving_average_decay', 0.997, '') tf.app.flags.DEFINE_string('gpu_list', '1', '') tf.app.flags.DEFINE_string('checkpoint_path', '/tmp/east_resnet_v1_50_rbox/', '') tf.app.flags.DEFINE_boolean('restore', False, 'whether to resotre from checkpoint') tf.app.flags.DEFINE_integer('save_checkpoint_steps', 1000, '') tf.app.flags.DEFINE_integer('save_summary_steps', 100, '') tf.app.flags.DEFINE_string('pretrained_model_path', None, '') tf.app.flags.DEFINE_boolean('allow_mix_precision', False, 'whether to allow mix precision') tf.app.flags.DEFINE_boolean('auto_tune', False, 'whether to autotune') tf.app.flags.DEFINE_boolean('use_processed_data', False, 'whether to use processed data') tf.app.flags.DEFINE_string('processed_data', './processed_dataset/', 'where to save preprocessed datasets')
tensorflow.app.flags.DEFINE_float
9,743
import tensorflow as tf optimize.get_variable_initializer(self.hparams)) with self._eager_var_store.as_default(): self._fill_problem_hparams_features(features) sharded_features = self._shard_features(features) sharded_logits, losses = self.model_fn_sharded(sharded_features) if isinstance(sharded_logits, dict): concat_logits = {} for k, v in sharded_logits.iteritems(): concat_logits[k] = tf.concat(v, 0) return concat_logits, losses else: return tf.concat(sharded_logits, 0), losses @property def use_body_sharded(self): return False
tensorflow.concat
9,744
from tensorflow.python.framework import ops range `[1,k]`, as documented above. Returns: `float64` `Tensor` of shape [D1, ... DN], where each value is the average precision for that row. Raises: ValueError: if k is invalid. """ if k < 1: raise ValueError('Invalid k=%s.' % k) with ops.name_scope( None, 'average_precision', (predictions, labels, k)) as scope: # Calculate top k indices to produce [D1, ... DN, k] tensor. _, predictions_idx = nn.top_k(predictions, k) predictions_idx = math_ops.to_int64(predictions_idx, name='predictions_idx') # Expand dims to produce [D1, ... DN, k, 1] tensor. This gives us a separate # prediction for each k, so we can calculate separate true positive values # for each k. predictions_idx_per_k = array_ops.expand_dims( predictions_idx, -1, name='predictions_idx_per_k')
tensorflow.python.framework.ops.name_scope
9,745
import tensorflow as tf elif params.initializer == "uniform_unit_scaling": return tf.variance_scaling_initializer(params.initializer_gain, mode="fan_avg", distribution="uniform") else: raise ValueError("Unrecognized initializer: %s" % params.initializer) def get_learning_rate_decay(learning_rate, global_step, params): if params.learning_rate_decay == "noam": step = tf.to_float(global_step) warmup_steps = tf.to_float(params.warmup_steps) multiplier = params.hidden_size ** -0.5 decay = multiplier * tf.minimum((step + 1) * (warmup_steps ** -1.5), (step + 1) ** -0.5) return learning_rate * decay elif params.learning_rate_decay == "new_warmup_rsqrt_decay": step = tf.to_float(global_step) warmup_steps = tf.to_float(params.warmup_steps) multiplier = params.hidden_size ** -0.5 decay = params.r0 * multiplier * tf.minimum((step + 1) * (warmup_steps ** -1.0) * (warmup_steps ** -0.5),
tensorflow.to_float
9,746
import tensorflow as tf accuracy_1 = tf.reduce_mean(tf.cast(tf.equal( tf.argmax(output_1, axis=-1), tf.argmax(y_1, axis=-1)), tf.float32), name="accuracy_1") accuracy_2 = tf.reduce_mean(tf.cast(tf.equal( tf.argmax(output_2, axis=-1), tf.argmax(y_2, axis=-1)), tf.float32), name="accuracy_2") accuracy = tf.divide(accuracy_1 + accuracy_2, 2.0, name="accuracy") with tf.variable_scope("train"): global_step = tf.get_variable("global_step", shape=(), dtype=tf.int32, trainable=False) train_op = tf.train.AdamOptimizer(learning_rate=lr).minimize(loss_total, global_step=global_step)
tensorflow.divide
9,747
import tensorflow as tf if not is_training: config.hidden_dropout_prob = 0.0 config.attention_probs_dropout_prob = 0.0 input_shape = get_shape_list(input_ids, expected_rank=2) batch_size = input_shape[0] seq_length = input_shape[1] if input_mask is None: input_mask = tf.ones(shape=[batch_size, seq_length], dtype=tf.int32) if token_type_ids is None: token_type_ids = tf.zeros(shape=[batch_size, seq_length], dtype=tf.int32) with tf.variable_scope(scope, default_name="bert"): with tf.variable_scope("embeddings"): # Perform embedding lookup on the word ids. (self.word_embedding_output, self.output_embedding_table) = embedding_lookup( input_ids=input_ids, vocab_size=config.vocab_size, embedding_size=config.embedding_size, initializer_range=config.initializer_range, word_embedding_name="word_embeddings", use_one_hot_embeddings=use_one_hot_embeddings) # Add positional embeddings and token type embeddings, then layer # normalize and perform dropout.
tensorflow.variable_scope
9,748
import tensorflow as tf return update_mean_op, update_second_moment_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.
tensorflow.no_op
9,749
import tensorflow as tf """ batch_size = y_pred.shape[0] num_of_joints = y_pred.shape[-1] # 有多少个关键点 y_pred = tf.reshape(y_pred, shape=(batch_size, -1, num_of_joints)) # 合并宽和高 heatmap_pred_list = tf.split(value=y_pred, num_or_size_splits=num_of_joints, axis=-1) # 拆分每一个关键点的特征图 [batch_size, -1, 1] y_true = tf.reshape(y_true, shape=(batch_size, -1, num_of_joints)) heatmap_true_list = tf.split(value=y_true, # y_true执行与y_pred相同的操作 num_or_size_splits=num_of_joints, axis=-1) losses = [] # 计算每一个关键点的损失值,并累加求平均 for i in range(num_of_joints): heatmap_pred = tf.squeeze(heatmap_pred_list[i])
tensorflow.reshape
9,750
import tensorflow as tf else: print(f'EPOCH: {epoch}, real_rot_loss: {round(epoch_real_rot_loss, 3)}, fake_rot_loss: {round(epoch_fake_rot_loss, 3)}, loss_d_rot: {round(epoch_loss_d, 3)}, loss_g_rot: {round(epoch_loss_g, 3)}, real_rot_acc: {round(real_rot_acc, 3)}, fake_rot_acc: {round(fake_rot_acc, 3)}') return dict, duration def _add_summaries(self, writer, names, values): for name, value in zip(names, values): summary = tf.Summary(value=[ tf.Summary.Value(tag=name, simple_value=value), ]) writer.add_summary(summary, self.step_count) def eval_rot(self, batch_data): feed_dict = {self.real_pc: batch_data, self.is_training_pl: False} _, rot_loss = self.sess.run([self.opt_pred, self.real_pc_rot_loss], feed_dict=feed_dict) return rot_loss
tensorflow.Summary.Value
9,751
import tensorflow as tf task_name = FLAGS.task_name.lower() if task_name not in processors: raise ValueError("Task not found: %s" % (task_name)) processor = processors[task_name]() label_list = processor.get_labels() tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) 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 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( iterations_per_loop=FLAGS.iterations_per_loop, num_shards=FLAGS.num_tpu_cores, per_host_input_for_training=is_per_host))
tensorflow.contrib.cluster_resolver.TPUClusterResolver
9,752
import tensorflow as tf #he_normal = tf.contrib.layers.variance_scaling_initializer() 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 # Three types of downsampling methods described by paper def downsampling(inputs, downsampling_type, name, optional_shortcut=False, shortcut=None): # k-maxpooling
tensorflow.layers.batch_normalization
9,753
import tensorflow as tf N = tf.cast(tf.shape(X)[0], tf.float32) D_int = tf.cast(D, tf.int32) N_int = tf.cast(N, tf.int32) if y is None: y = silverman_rule_of_thumb(N) YDistr = tf.contrib.distributions.MultivariateNormalDiag(loc=tf.zeros(D_int, tf.float32), scale_diag=tf.ones(D_int, tf.float32)) Y = YDistr.sample(N_int) T = 1.0/(2.0*N*tf.sqrt(m.pi*y)) A0 = euclidean_norm_squared(tf.subtract(tf.expand_dims(X, 0), tf.expand_dims(X, 1)), axis=2) A = tf.reduce_sum(phi_sampling(A0/(4*y), D)) B0 = euclidean_norm_squared(tf.subtract(tf.expand_dims(Y, 0), tf.expand_dims(Y, 1)), axis=2) B = tf.reduce_sum(phi_sampling(B0/(4*y), D)) C0 = euclidean_norm_squared(tf.subtract(tf.expand_dims(X, 0), tf.expand_dims(Y, 1)), axis=2) C = tf.reduce_sum(phi_sampling(C0/(4*y), D)) return T*(A + B - 2*C)
tensorflow.expand_dims
9,754
import tensorflow as tf name='H') T = tf.layers.dense( inputs, units=depth, activation=tf.nn.sigmoid, name='T', bias_initializer=tf.constant_initializer(-1.0)) return H * T + inputs * (1.0 - T) def conv1d(inputs, kernel_size, channels, activation, is_training, scope): with tf.variable_scope(scope):
tensorflow.constant_initializer
9,755
import tensorflow as tf case where IoU of a box with any groundtruth box is greater than `background_iou_low_threshold` and less than `background_iou_low_threshold`. ignored_matches: a bool tensor of shape of [batch, N], representing whether each box is an ignored matches or not. An ignored matches is the match that is neither positive or negative. """ matched_gt_boxes, matched_gt_classes, matched_gt_indices, matched_iou, _ = ( box_ops.box_matching(boxes, gt_boxes, gt_classes)) positive_matches = tf.greater( matched_iou, self._config_dict['foreground_iou_threshold']) negative_matches = tf.logical_and( tf.greater_equal( matched_iou, self._config_dict['background_iou_low_threshold']), tf.less( matched_iou, self._config_dict['background_iou_high_threshold'])) ignored_matches = tf.logical_and( tf.less(matched_iou, 0.0), tf.greater_equal( matched_iou, self._config_dict['background_iou_high_threshold'])) ignored_matches = tf.logical_and( ignored_matches, tf.less( matched_iou, self._config_dict['foreground_iou_threshold']))
tensorflow.greater_equal
9,756
import tensorflow as tf # To find out where placement occurs, set 'log_device_placement' sess = tf.Session(config=tf.ConfigProto(log_device_placement=True)) a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a') b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b') c = tf.matmul(a, b) # Runs the op. print(sess.run(c)) # If we load a graph and want device placement to be forgotten, # we set a parameter in our session: config = tf.ConfigProto() config.allow_soft_placement = True sess_soft = tf.Session(config=config) # GPUs #--------------------------------- # Note that the GPU must have a compute capability > 3.5 for TF to use. # http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#compute-capability # Careful with GPU memory allocation, TF never releases it. TF starts with almost # all of the GPU memory allocated. We can slowly grow to that limit with an # option setting: config.gpu_options.allow_growth = True sess_grow = tf.Session(config=config)
tensorflow.Session
9,757
import tensorflow as tf " event_shape=()" " dtype=float32>") # There's no notion of partially known shapes in eager mode, so exit # early. if tf.executing_eagerly(): return exp = tfd.Exponential(rate=tf.placeholder_with_default( input=1., shape=None)) self.assertEqual( repr(exp), "<tfp.distributions.Exponential" " 'Exponential/'" " batch_shape=<unknown>" " event_shape=()"
tensorflow.placeholder_with_default
9,758
from tensorflow.python.framework import ops returned_shape.append(dim) return [tensor_shape.TensorShape(returned_shape)] else: raise ValueError( "dimension (%d) must be in the range [0, %d), where %d is the number " "of dimensions in the input" % (dimension, input_shape.ndims, input_shape.ndims)) @ops.RegisterShape("All") @ops.RegisterShape("Any") @ops.RegisterShape("Max") @ops.RegisterShape("Mean") @ops.RegisterShape("Min") @ops.RegisterShape("Prod") @ops.RegisterShape("Sum") def _ReductionShape(op): """Common shape function for reduction ops.""" input_shape = op.inputs[0].get_shape() reduction_indices = tensor_util.ConstantValue(op.inputs[1]) keep_dims = op.get_attr("keep_dims") if reduction_indices is None or input_shape.ndims is None: if keep_dims: return [tensor_shape.unknown_shape(ndims=input_shape.ndims)] else: return [tensor_shape.unknown_shape()] # Turn reduction_indices from scalar to vector if necessary reduction_indices = np.ravel(reduction_indices)
tensorflow.python.framework.ops.RegisterShape
9,759
import tensorflow as tf def main(args): with tf.Graph().as_default(): config = tf.ConfigProto(inter_op_parallelism_threads=args.num_inter_threads, intra_op_parallelism_threads=args.num_intra_threads) with tf.Session(config = config) as sess: # Read the file containing the pairs used for testing pairs = lfw.read_pairs(os.path.expanduser(args.lfw_pairs)) # Get the paths for the corresponding images
tensorflow.Session
9,760
import tensorflow as tf k = tf.to_int32(tf.ceil(time_steps / stride) * stride) - time_steps # TODO: simpler pad = tf.zeros([batch_size, k, tf.shape(encoder_inputs_)[2]]) encoder_inputs_ = tf.concat([encoder_inputs_, pad], axis=1) encoder_inputs_ = tf.nn.pool(encoder_inputs_, window_shape=[stride], pooling_type='MAX', padding='VALID', strides=[stride]) encoder_input_length_ = tf.to_int32(tf.ceil(encoder_input_length_ / stride)) if encoder.highway_layers: x = encoder_inputs_ for j in range(encoder.highway_layers): size = x.shape[2].value with tf.variable_scope('highway_{}'.format(j + 1)): g = tf.layers.dense(x, size, activation=tf.nn.sigmoid, use_bias=True, name='g') y = tf.layers.dense(x, size, activation=tf.nn.relu, use_bias=True, name='y') x = g * y + (1 - g) * x encoder_inputs_ = x # Contrary to Theano's RNN implementation, states after the sequence length are zero # (while Theano repeats last state) inter_layer_keep_prob = None if not encoder.use_dropout else encoder.inter_layer_keep_prob parameters = dict( inputs=encoder_inputs_, sequence_length=encoder_input_length_, dtype=tf.float32, parallel_iterations=encoder.parallel_iterations,
tensorflow.layers.dense
9,761
import tensorflow as tf def main(_): tf.logging.set_verbosity(tf.logging.INFO) if FLAGS.use_hvd: hvd.init() if FLAGS.reduce_log and (hvd.rank() != 0): tf.logging.set_verbosity(tf.logging.ERROR) FLAGS.output_dir = FLAGS.output_dir if hvd.rank() == 0 else os.path.join(FLAGS.output_dir, str(hvd.rank())) if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_train_eval: raise ValueError("At least one of `do_train` or `do_eval` must be True.")
tensorflow.logging.set_verbosity
9,762
import tensorflow as tf log("Loading training data from: {}".format(metadat_fpath)) log("Using model: Tacotron") log(hparams_debug_string()) # Start by setting a seed for repeatability tf.set_random_seed(hparams.tacotron_random_seed) # Set up data feeder coord = tf.train.Coordinator() with tf.variable_scope("datafeeder") as scope: feeder = Feeder(coord, metadat_fpath, hparams) # Set up model: global_step = tf.Variable(0, name="global_step", trainable=False) model, stats = model_train_mode(args, feeder, hparams, global_step) eval_model = model_test_mode(args, feeder, hparams, global_step) # Embeddings metadata
tensorflow.variable_scope
9,763
from tensorflow.python.ops import array_ops 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) zeros = array_ops.zeros_like(logits, dtype=logits.dtype) pos_p_sub = array_ops.where(labels > zeros, labels - logits, zeros) neg_p_sub = array_ops.where(labels > zeros, zeros, logits) cross_ent = - alpha * (pos_p_sub ** gamma) * tf.log(tf.clip_by_value(logits, 1e-8, 1.0)) \ - (1 - alpha) * (neg_p_sub ** gamma) * tf.log(tf.clip_by_value(1.0 - logits, 1e-8, 1.0)) return tf.reduce_sum(cross_ent, 1) start_label = tf.one_hot(self.start_label, tf.shape(self.logits1)[1], axis=1) end_label = tf.one_hot(self.end_label, tf.shape(self.logits2)[1], axis=1)
tensorflow.python.ops.array_ops.where
9,764
from tensorflow.python.framework import ops # TODO(mrry): Move this to where it is used, so we can get rid of this op # wrapper? if set_shape: ret.set_shape(shape) return ret # NOTE(mrry): Shapes are conditionally set in the Python wrapper. ops.RegisterShape("Variable")(common_shapes.unknown_shape) @ops.RegisterShape("TemporaryVariable") def _TemporaryVariableShape(op): """Shape function for the TemporaryVariable op.""" shape = tensor_util.TensorShapeProtoToList(op.get_attr("shape")) return [tensor_shape.TensorShape(shape)]
tensorflow.python.framework.ops.RegisterShape
9,765
import tensorflow as tf processed_l2_h2 = self.ff_nl(processed_l2_h2) if self.batch_norm: with tf.variable_scope( 'l3_h2_bn_ff_%s' % idx, reuse=self.scope_reuse) as scope: processed_l2_h2 = tf.contrib.layers.batch_norm( inputs=processed_l2_h2, scale=True, center=True, fused=True,
tensorflow.contrib.layers.batch_norm
9,766
import tensorflow as tf ret = ops return ret def _build_ops(self, lm_graph): with tf.control_dependencies([lm_graph.update_state_op]): # get the LM embeddings token_embeddings = lm_graph.embedding layers = [ tf.concat([token_embeddings, token_embeddings], axis=2) ] n_lm_layers = len(lm_graph.lstm_outputs['forward']) for i in range(n_lm_layers): layers.append( tf.concat( [lm_graph.lstm_outputs['forward'][i], lm_graph.lstm_outputs['backward'][i]],
tensorflow.concat
9,767
import tensorflow as tf dc_g_loss_fake = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.zeros_like(d_g_fake), logits=d_g_fake)) dc_g_loss = dc_g_loss_fake + dc_g_loss_real # Categorical Discrimminator Loss dc_c_loss_real = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones_like(d_c_real), logits=d_c_real)) dc_c_loss_fake = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.zeros_like(d_c_fake), logits=d_c_fake)) dc_c_loss = dc_c_loss_fake + dc_c_loss_real # Generator loss generator_g_loss = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones_like(d_g_fake), logits=d_g_fake)) generator_c_loss = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones_like(d_c_fake), logits=d_c_fake))
tensorflow.zeros_like
9,768
import tensorflow as tf with tf.variable_scope('target_q'): self.target_q = R + self.gamma * self.q_ with tf.variable_scope('abs_TD'): self.abs_td = tf.abs(self.target_q - self.q) self.ISWeights = tf.placeholder(tf.float32, [None, 1], name='IS_weights') with tf.variable_scope('TD_error'): self.loss = tf.reduce_mean(self.ISWeights * tf.squared_difference(self.target_q, self.q)) with tf.variable_scope('C_train'): self.train_op = tf.train.AdamOptimizer(self.lr).minimize(self.loss, global_step=GLOBAL_STEP) with tf.variable_scope('a_grad'): self.a_grads = tf.gradients(self.q, a)[0] # tensor of gradients of each sample (None, a_dim) def _build_net(self, s, a, scope, trainable): with tf.variable_scope(scope): init_w = tf.random_normal_initializer(0., 0.01) init_b = tf.constant_initializer(0.01) with tf.variable_scope('l1'): n_l1 = 700 # combine the action and states together in this way w1_s = tf.get_variable('w1_s', [self.s_dim, n_l1], initializer=init_w, trainable=trainable)
tensorflow.variable_scope
9,769
import tensorflow as tf def _testGraphExtensionRestore(self): test_dir = os.path.join(self.get_temp_dir(), "graph_extension") filename = os.path.join(test_dir, "metafile") saver0_ckpt = os.path.join(test_dir, "saver0.ckpt") with self.test_session(graph=tf.Graph()) as sess: # Restores from MetaGraphDef. new_saver = tf.train.import_meta_graph(filename) # Generates a new MetaGraphDef. new_saver.export_meta_graph()
tensorflow.Graph
9,770
import tensorflow as tf gfile.MakeDirs(save_dir) with tf.Session( target="", config=tf.ConfigProto(device_count={"CPU": 2})) as sess: with sess.graph.device("/cpu:0"): v0 = tf.Variable(111, name="v0") with sess.graph.device("/cpu:1"): v1 = tf.Variable(222, name="v1") save = tf.train.Saver({"v0": v0, "v1": v1}, sharded=True, 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) self.assertEqual(2, len(gfile.Glob(s1))) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s1)))
tensorflow.train.Saver
9,771
import tensorflow as tf 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))
tensorflow.div
9,772
import tensorflow as tf @classmethod def from_tfrecord_files(cls, input_files, **kwargs) -> tf.data.Dataset: dataset = utils.read_tfrecord_files(input_files, **kwargs) d = cls(examples=None, **kwargs) # parse example features = { d.input_ids: tf.io.VarLenFeature(tf.int64), d.token_type_ids: tf.io.VarLenFeature(tf.int64), d.attention_mask: tf.io.VarLenFeature(tf.int64), d.labels: tf.io.VarLenFeature(tf.int64), } dataset = dataset.map( lambda x: tf.io.parse_example(x, features), num_parallel_calls=utils.AUTOTUNE,
tensorflow.io.VarLenFeature
9,773
import tensorflow as tf observations_ph = U.ensure_tf_input(make_obs_ph("observation")) stochastic_ph = tf.placeholder(tf.bool, (), name="stochastic") update_eps_ph = tf.placeholder(tf.float32, (), name="update_eps") eps = tf.get_variable("eps", (), initializer=tf.constant_initializer(0.0)) q_func_results = q_func(observations_ph.get(), num_actions, scope="q_func") q_values = q_func_results['q']
tensorflow.constant_initializer
9,774
import tensorflow as tf w2 = tf.get_variable('weight2', [1024, 1024], initializer=tf.random_normal_initializer()) b2 = tf.get_variable('bias2', [1024], initializer=tf.constant_initializer(0.0)) h2 = tf.nn.relu(tf.matmul(h1, w2) + b2) with tf.variable_scope('layer3'): w3 = tf.get_variable('weight3', [1024, 10], initializer=tf.random_normal_initializer()) b3 = tf.get_variable('bias3', [10], initializer=tf.constant_initializer(0.0)) y = tf.matmul(h2, w3) + b3 # losses cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=gt, logits=y)) # optimizer optimizer = tf.train.GradientDescentOptimizer(args.lr) # define one-step train ops
tensorflow.matmul
9,775
import tensorflow as tf with tf.name_scope('AccumGradOptimizer'): ops = [] for s, gv in zip(slots, grads_and_vars): g, v = gv ops.append(s.assign_add(g)) update_counter = tf.assign_add(counter, 1, name='update_counter') update_slot_op = tf.group(update_counter, *ops, name='update_slot') def update_grad(): update_op = self._opt.apply_gradients(slots_and_vars)
tensorflow.assign_add
9,776
import tensorflow as tf Returns: Tensor with nearest element in mean encoded in one-hot notation. """ x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keep_dims=True) means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keep_dims=True) scalar_prod = tf.matmul( tf.transpose(x, perm=[1, 0, 2]), tf.transpose(means, perm=[0, 2, 1])) scalar_prod = tf.transpose(scalar_prod, perm=[1, 0, 2]) dist = x_norm_sq + tf.transpose( means_norm_sq, perm=[2, 0, 1]) - 2 * scalar_prod if self.hparams.soft_em: nearest_idx = tf.stack( [ tf.multinomial( -dist[:, i, :], num_samples=self.hparams.num_samples) for i in range(self.hparams.num_blocks)
tensorflow.transpose
9,777
import tensorflow as tf target_samples: a tensor of shape [num_samples, num_features]. weight: the weight of the MMD loss. scope: optional name scope for summary tags. Returns: a scalar tensor representing the MMD loss value. """ with tf.name_scope(name): sigmas = [ 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1, 5, 10, 15, 20, 25, 30, 35, 100, 1e3, 1e4, 1e5, 1e6 ] gaussian_kernel = partial(util.gaussian_kernel_matrix, sigmas=tf.constant(sigmas)) loss_value = maximum_mean_discrepancy(source_samples, target_samples, kernel=gaussian_kernel) loss_value = tf.maximum(1e-4, loss_value) * weight assert_op = tf.Assert(tf.is_finite(loss_value), [loss_value]) with tf.control_dependencies([assert_op]): tag = 'MMD_Loss' barrier = tf.no_op(tag) return loss_value
tensorflow.constant
9,778
import tensorflow as tf tf.split(1, max_sequence_len, embeddings)] # Need to prepare a mask to zero out the padding symbols. # Make a batch_size x max_sequence_len matrix where each # row contains the length repeated max_sequence_len times. lengths_transposed = tf.expand_dims(tf.to_int32(self.seq_lens), 1) lengths_tiled = tf.tile(lengths_transposed, [1, max_sequence_len]) # Make a matrix where each row contains [0, 1, ..., max_sequence_len] r = tf.range(0, max_sequence_len, 1) range_row = tf.expand_dims(r, 0) range_tiled = tf.tile(range_row, [batch_size, 1]) self.lengths_transposed = lengths_transposed self.lengths_tiled = lengths_tiled self.range_row = range_row self.range_tiled = range_tiled # Use the logical operations to create a mask
tensorflow.range
9,779
import tensorflow as tf sliced_propensity = tf.unstack(propensity_weights, axis=1) for i in range(len(sliced_output)): for j in range(i+1, len(sliced_output)): cur_label_weight = tf.math.sign(sliced_label[i] - sliced_label[j]) cur_propensity = sliced_propensity[i] * sliced_label[i] + sliced_propensity[j] * sliced_label[j] cur_pair_loss = -tf.exp(sliced_output[i]) / (tf.exp(sliced_output[i]) + tf.exp(sliced_output[j])) if loss == None: loss = cur_label_weight * cur_pair_loss * cur_propensity loss += cur_label_weight * cur_pair_loss * cur_propensity batch_size = tf.shape(labels[0])[0] return tf.reduce_sum(loss) / tf.cast(batch_size, dtypes.float32) #/ (tf.reduce_sum(propensity_weights)+1) def click_weighted_log_loss(self, output, labels, propensity_weights, name=None): """Computes pointwise sigmoid loss with propensity weighting. Args: output: (tf.Tensor) A tensor with shape [batch_size, list_size]. Each value is the ranking score of the corresponding example. labels: (tf.Tensor) A tensor of the same shape as `output`. A value >= 1 means a
tensorflow.cast
9,780
import tensorflow as tf feature_loss = tf.reduce_mean(tf.abs(tf.subtract(real_data_mean, fake_data_mean))) return feature_loss def _tower_loss_semi_supervised(self, inputs, targets, gpu_idx=0, num_classes=11, is_fm_loss=False): with tf.variable_scope("train_specific"): avg_error_rate = tf.get_variable( 'avg_error_rate', [], initializer=tf.constant_initializer(0.), trainable=False) num_error_rate = tf.get_variable( 'num_error_rate', [], initializer=tf.constant_initializer(0.), trainable=False)
tensorflow.variable_scope
9,781
import tensorflow as tf Returns: a tensor with shape [N, M] representing pairwise iou scores. """ intersections = pairwise_intersection(boxlist1, boxlist2) areas1 = area(boxlist1) areas2 = area(boxlist2) unions = ( tf.expand_dims(areas1, 1) + tf.expand_dims(areas2, 0) - intersections) return tf.where( tf.equal(intersections, 0.0), tf.zeros_like(intersections), tf.truediv(intersections, unions)) @under_name_scope() def pairwise_iou_batch(proposal_boxes, gt_boxes, orig_gt_counts, batch_size): """Computes pairwise intersection-over-union between box collections. Args: proposal_boxes: K x 5 (batch_index, x1, y1, x2, y2) gt_boxes: BS x MaxNumGTs x 4 orig_gt_counts: BS
tensorflow.truediv
9,782
import tensorflow as tf # Use indices to lookup pixels in the flat image and restore # 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)
tensorflow.to_float
9,783
import tensorflow as tf with tf.control_dependencies(None): slots = self._create_accum_slots(vs) slots_and_vars = [(s, gv[1]) for s, gv in zip(slots, grads_and_vars)] # Create the counter on the same device as the first variable. with tf.variable_scope(self._name), \ vs[0].graph.colocate_with(vs[0]): counter = tf.Variable( 0, name="counter", trainable=False, dtype=tf.int32) with tf.name_scope('AccumGradOptimizer'):
tensorflow.variable_scope
9,784
import tensorflow as tf log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1) loss = tf.reduce_mean(per_example_loss) return (loss, per_example_loss, logits, probabilities)
tensorflow.reduce_mean
9,785
import tensorflow as tf b1 = tf.get_variable('bias1', [1024], initializer=tf.constant_initializer(0.0)) h1 = tf.nn.relu(tf.matmul(x, w1) + b1) with tf.variable_scope('layer2'): w2 = tf.get_variable('weight2', [1024, 1024], initializer=tf.random_normal_initializer()) b2 = tf.get_variable('bias2', [1024], initializer=tf.constant_initializer(0.0)) h2 = tf.nn.relu(tf.matmul(h1, w2) + b2) with tf.variable_scope('layer3'): w3 = tf.get_variable('weight3', [1024, 10], initializer=tf.random_normal_initializer())
tensorflow.constant_initializer
9,786
import tensorflow as tf return tf.squeeze((y_max - y_min) * (x_max - x_min), [1]) @under_name_scope() def pairwise_intersection(boxlist1, boxlist2): """Compute pairwise intersection areas between boxes. Args: boxlist1: Nx4 floatbox boxlist2: Mx4 Returns: a tensor with shape [N, M] representing pairwise intersections """ x_min1, y_min1, x_max1, y_max1 = tf.split(boxlist1, 4, axis=1) x_min2, y_min2, x_max2, y_max2 = tf.split(boxlist2, 4, axis=1) all_pairs_min_ymax = tf.minimum(y_max1, tf.transpose(y_max2)) all_pairs_max_ymin = tf.maximum(y_min1, tf.transpose(y_min2)) intersect_heights = tf.maximum(0.0, all_pairs_min_ymax - all_pairs_max_ymin) all_pairs_min_xmax = tf.minimum(x_max1, tf.transpose(x_max2)) all_pairs_max_xmin = tf.maximum(x_min1, tf.transpose(x_min2)) intersect_widths = tf.maximum(0.0, all_pairs_min_xmax - all_pairs_max_xmin) return intersect_heights * intersect_widths @under_name_scope() def pairwise_iou(boxlist1, boxlist2): """Computes pairwise intersection-over-union between box collections. Args:
tensorflow.split
9,787
import tensorflow as tf num_attention_heads= input_shape[2] with tf.variable_scope(name): w = tf.get_variable( name="kernel",
tensorflow.get_variable
9,788
import tensorflow as tf with tf.device(worker_device): with tf.variable_scope("local"): self.local_network = pi = LSTMPolicy(env.observation_space.shape, env.action_space.n) pi.global_step = self.global_step self.ac = tf.placeholder(tf.float32, [None, env.action_space.n], name="ac") self.adv = tf.placeholder(tf.float32, [None], name="adv") self.r = tf.placeholder(tf.float32, [None], name="r") log_prob_tf = tf.nn.log_softmax(pi.logits) prob_tf = tf.nn.softmax(pi.logits) # the "policy gradients" loss: its derivative is precisely the policy gradient
tensorflow.placeholder
9,789
import tensorflow as tf if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions) # Calculate loss, which includes softmax cross entropy and L2 regularization. cross_entropy = tf.cond(n_positives > 0., lambda: tf.losses.sparse_softmax_cross_entropy(labels=glabels, logits=cls_pred), lambda: 0.) #cross_entropy = tf.losses.sparse_softmax_cross_entropy(labels=glabels, logits=cls_pred) # Create a tensor named cross_entropy for logging purposes. tf.identity(cross_entropy, name='cross_entropy_loss') tf.summary.scalar('cross_entropy_loss', cross_entropy) loc_loss = tf.cond(n_positives > 0., lambda: modified_smooth_l1(location_pred, tf.stop_gradient(gtargets), sigma=1.), lambda: tf.zeros_like(location_pred)) #loc_loss = modified_smooth_l1(location_pred, tf.stop_gradient(gtargets)) loc_loss = tf.reduce_mean(tf.reduce_sum(loc_loss, axis=-1)) loc_loss = tf.identity(loc_loss, name='location_loss') tf.summary.scalar('location_loss', loc_loss) tf.losses.add_loss(loc_loss) # Add weight decay to the loss. We exclude the batch norm variables because # doing so leads to a small improvement in accuracy. loss = cross_entropy + loc_loss + params['weight_decay'] * tf.add_n( [tf.nn.l2_loss(v) for v in tf.trainable_variables() if 'batch_normalization' not in v.name]) total_loss = tf.identity(loss, name='total_loss') if mode == tf.estimator.ModeKeys.TRAIN: global_step = tf.train.get_or_create_global_step() lr_values = [params['learning_rate'] * decay for decay in params['lr_decay_factors']]
tensorflow.identity
9,790
import tensorflow.contrib.layers as layers with tf.variable_scope("convnet"): # original architecture out = layers.convolution2d(out, num_outputs=32, kernel_size=8, stride=4, activation_fn=tf.nn.relu) out = layers.convolution2d(out, num_outputs=64, kernel_size=4, stride=2, activation_fn=tf.nn.relu) out = layers.convolution2d(out, num_outputs=64, kernel_size=3, stride=1, activation_fn=tf.nn.relu) out = layers.flatten(out) with tf.variable_scope("action_value"): out = layers.fully_connected(out, num_outputs=512, activation_fn=tf.nn.relu) out = layers.fully_connected(out, num_outputs=num_actions, activation_fn=None) return out def simple_model(img_in, num_actions, scope, reuse=False, num_filters=64):
tensorflow.contrib.layers.fully_connected
9,791
import tensorflow as tf # Trainable variables: # Weight matrices and bias weights # ------------------------------------------------ # Input weight matrix: # (uniform initialization as in pycog) self.W_in = \ tf.get_variable('W_in', [N_rec, N_in], initializer=W_in_initializer, trainable=self.W_in_train) # Recurrent weight matrix: # (gamma (Dale) or normal (non-Dale) initialization) self.W_rec = \ tf.get_variable( 'W_rec', [N_rec, N_rec], initializer=W_rec_initializer, trainable=self.W_rec_train) # Output weight matrix: # (uniform initialization as in pycog) self.W_out = tf.get_variable('W_out', [N_out, N_rec], initializer=W_out_initializer, trainable=self.W_out_train) # Recurrent bias: self.b_rec = tf.get_variable('b_rec', [N_rec], initializer=b_rec_initializer,
tensorflow.get_variable
9,792
import tensorflow as tf regularizer=l2_regularizer, dtype=inpOp.dtype) cnv = tf.nn.conv2d(inpOp, kernel, [1, dH, dW, 1], padding=padType) if use_batch_norm: conv_bn = batch_norm(cnv, phase_train) else: conv_bn = cnv biases = tf.get_variable("biases", [nOut], initializer=tf.constant_initializer(), dtype=inpOp.dtype) bias = tf.nn.bias_add(conv_bn, biases) conv1 = tf.nn.relu(bias) return conv1 def convLinear(inpOp, nIn, nOut, kH, kW, dH, dW, padType, name, phase_train=True, use_batch_norm=True, weight_decay=0.0): with tf.variable_scope(name): l2_regularizer = lambda t: l2_loss(t, weight=weight_decay) kernel = tf.get_variable("weights", [kH, kW, nIn, nOut],
tensorflow.nn.bias_add
9,793
import tensorflow as tf # Bidaf style conv-highway encoder ch_emb = conv(ch_emb, d, bias = True, activation = tf.nn.relu, kernel_size = 5, name = "char_conv", reuse = None) qh_emb = conv(qh_emb, d, bias = True, activation = tf.nn.relu, kernel_size = 5, name = "char_conv", reuse = True) ch_emb = tf.reduce_max(ch_emb, axis = 1) qh_emb = tf.reduce_max(qh_emb, axis = 1) ch_emb = tf.reshape(ch_emb, [N, PL, ch_emb.shape[-1]]) qh_emb = tf.reshape(qh_emb, [N, QL, ch_emb.shape[-1]]) c_emb = tf.nn.dropout(tf.nn.embedding_lookup(self.word_mat, self.c), 1.0 - self.dropout) q_emb = tf.nn.dropout(tf.nn.embedding_lookup(self.word_mat, self.q), 1.0 - self.dropout) c_emb = tf.concat([c_emb, ch_emb], axis=2) q_emb = tf.concat([q_emb, qh_emb], axis=2) c_emb = highway(c_emb, size = d, scope = "highway", dropout = self.dropout, reuse = None) q_emb = highway(q_emb, size = d, scope = "highway", dropout = self.dropout, reuse = True) with tf.variable_scope("Embedding_Encoder_Layer"): c = residual_block(c_emb, num_blocks = 1, num_conv_layers = 4, kernel_size = 7,
tensorflow.nn.embedding_lookup
9,794
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" # Use a variable name map to set the saved tensor names val = save.save(sess, save_path) self.assertTrue(isinstance(val, six.string_types)) self.assertEqual(save_path, val) # Verify that the original names are not in the Saved file save = tf.train.Saver({"v0": v0, "v1": v1}) with self.assertRaisesOpError("not found in checkpoint"): save.restore(sess, save_path) # Verify that the mapped names are present in the Saved file and can be # Restored using remapped names. with self.test_session() as sess: v0 = tf.Variable(-1.0, name="v0") v1 = tf.Variable(-1.0, name="v1") with self.assertRaisesOpError("uninitialized value v0"): sess.run(v0)
tensorflow.train.Saver
9,795
from tensorflow.python.ops import variable_scope Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ with variable_scope.variable_scope(name, 'precision_at_thresholds', [predictions, labels]): # TODO(nsilberman): Replace with only tp and fp, this results in unnecessary # variable creation. b/30842882 (true_positives, _, _, false_positives, true_positives_compute_op, _, _,
tensorflow.python.ops.variable_scope.variable_scope
9,796
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(_ln(c, gc, bc)) xs[idx] = h s = tf.concat(axis=1, values=[c, h]) return xs, s def conv_to_fc(x): nh = np.prod([v.value for v in x.get_shape()[1:]]) x = tf.reshape(x, [-1, nh])
tensorflow.concat
9,797
import tensorflow as tf def pad_or_clip_tensor(t, length): """Pad or clip the input tensor along the first dimension. Args: t: the input tensor, assuming the rank is at least 1. length: a tensor of shape [1] or an integer, indicating the first dimension of the input tensor t after processing. Returns: processed_t: the processed tensor, whose first dimension is length. If the length is an integer, the first dimension of the processed tensor is set to length statically. """ processed_t = tf.cond( tf.greater(tf.shape(t)[0], length), lambda: clip_tensor(t, length), lambda: pad_tensor(t, length)) if not _is_tensor(length): processed_t = _set_dim_0(processed_t, length) return processed_t def combined_static_and_dynamic_shape(tensor): """Returns a list containing static and dynamic values for the dimensions. Returns a list of static and dynamic values for shape dimensions. This is useful to preserve static shapes when available in reshape operation. Args:
tensorflow.shape
9,798
import tensorflow as tf maybe_log2 = tf.log(2.0) if surrogate_type == 'xent' else 1.0 maybe_log2 = tf.cast(maybe_log2, logits.dtype.base_dtype)
tensorflow.cast
9,799