seed
stringlengths
25
2.89k
seed_api
stringlengths
14
102
index
int64
0
14.8k
import tensorflow as tf tf.summary.scalar('Loss/Policy', loss_pg) tf.summary.scalar('Loss/Value', loss_vf) tf.summary.scalar('Loss/Entropy', loss_entropy) tf.summary.scalar('Loss/Total', loss) tf.summary.scalar('Var/Epsilon', epsilon_decay) tf.summary.scalar('Var/Policy Mode', tf.reduce_mean(pi.mode())) tf.summary.scalar('Var/Policy Sigma', tf.reduce_mean(pi.stddev())) tf.summary.scalar('Var/Value', tf.reduce_mean(self.vf)) self.summarise = tf.summary.merge(tf.get_collection(tf.GraphKeys.SUMMARIES)) # AC net def build_anet(self, state_in, name, reuse=False, batch_size=64): reg = None 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) lstm_a = tf.nn.rnn_cell.LSTMCell(num_units=256) lstm_a = tf.nn.rnn_cell.DropoutWrapper(lstm_a, output_keep_prob=self.keep_prob) state_init_a = lstm_a.zero_state(batch_size=batch_size, dtype=tf.float32) lstm_ain = tf.expand_dims(layer_a2, axis=1) out_a, state_final_a = tf.nn.dynamic_rnn(cell=lstm_a, inputs=lstm_ain, initial_state=state_init_a) cell_out_a = tf.reshape(out_a, [-1, 256]) mu = tf.layers.dense(cell_out_a, self.a_dim, tf.nn.tanh, kernel_regularizer=reg) sigma = tf.layers.dense(cell_out_a, 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)
tensorflow.variable_scope
14,300
import tensorflow as tf class PPO(Base): def __init__(self, env, summary_dir='./', gpu=False): self.LR = 1e-4 self.MINIBATCH = 64 self.EPOCHS = 8 self.EPSILON = 0.2 self.EPS_LEN = 100000 # GPU setup os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False, device_count={'GPU': gpu}) config.gpu_options.allow_growth = True config.gpu_options.per_process_gpu_memory_fraction = 0.5 # Placeholders self.sess = tf.Session(config=config) self.s_dim, self.a_dim = env.observation_space.shape, env.action_space.shape[0] self.a_bound = (env.action_space.high - env.action_space.low) / 2 self.actions = tf.placeholder(tf.float32, [None, self.a_dim], 'action') self.state = tf.placeholder(tf.float32, [None, self.s_dim[0]], 'state') self.advantage = tf.placeholder(tf.float32, [None, 1], 'advantage') self.rewards = tf.placeholder(tf.float32, [None, 1], 'discounted_r') # Dateset with experiennce replay self.dataset = tf.data.Dataset.from_tensor_slices({'state': self.state, 'actions': self.actions, 'rewards': self.rewards, 'advantage': self.advantage}) self.dataset = self.dataset.shuffle(buffer_size=10000) self.dataset = self.dataset.batch(self.MINIBATCH) self.dataset = self.dataset.cache() self.dataset = self.dataset.repeat(self.EPOCHS)
tensorflow.Session
14,301
from tensorflow.python.framework import ops def register_gradient(): if "GuidedBackProp" not in ops._gradient_registry._registry: @ops.RegisterGradient("GuidedBackProp") def _GuidedBackProp(op, grad):
tensorflow.python.framework.ops.RegisterGradient
14,302
import tensorflow as tf def batch_to_seq(h, nbatch, nsteps, flat=False): if flat: h = tf.reshape(h, [nbatch, nsteps]) else: h = tf.reshape(h, [nbatch, nsteps, -1]) return [tf.squeeze(v, [1]) for v in tf.split(axis=1, num_or_size_splits=nsteps, value=h)] def seq_to_batch(h, flat = False): shape = h[0].get_shape().as_list()
tensorflow.split
14,303
import tensorflow as tf one_hot_labels = tf.one_hot( label_ids, depth=bert_config.vocab_size, dtype=tf.float32) # 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 return (loss, per_example_loss, log_probs)
tensorflow.reduce_sum
14,304
import tensorflow as tf is_training=False, drop_remainder=eval_drop_remainder) result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps) output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt") with open(output_eval_file, "w") as writer: tf.logging.info("***** Eval results *****") for key in sorted(result.keys()): tf.logging.info(" %s = %s", key, str(result[key])) writer.write("%s = %s\n" % (key, str(result[key])))
tensorflow.logging.info
14,305
import tensorflow as tf cell = tf.contrib.rnn.MultiRNNCell( [make_cell() for _ in range(config.num_layers)], state_is_tuple=True) self._initial_state = cell.zero_state(config.batch_size, tf.float32) state = self._initial_state outputs = [] with tf.variable_scope('RNN'): for time_step in range(self.num_steps): if time_step > 0: tf.get_variable_scope().reuse_variables() (cell_output, state) = cell(inputs[:, time_step, :], state) outputs.append(cell_output) output = tf.reshape(tf.concat(outputs, 1), [-1, config.hidden_size]) return output, state
tensorflow.variable_scope
14,306
import tensorflow as tf with tf.name_scope('Train'): train_input = DataInput(config=config, data=train_data, name='TrainInput') with tf.variable_scope('Model', reuse=None, initializer=initializer): m = Model(is_training=True, config=config, input_=train_input, graph=train_graph) tf.summary.scalar('Training Loss', m.cost) tf.summary.scalar('Learning rate', m.lr) latest_ckpt = tf.train.latest_checkpoint(FLAGS.save_path) with train_graph.as_default(): sv = tf.train.Supervisor(logdir=FLAGS.save_path) config_proto = tf.ConfigProto(log_device_placement=False, allow_soft_placement=True) with sv.managed_session(config=config_proto) as train_sess: #with tf.Session(config=config_proto) as train_sess: train_sess.run(tf.global_variables_initializer()) for i in range(config.max_max_epoch): lr_decay = config.lr_decay ** max(i + 1 - config.max_epoch, 0.) m.assign_lr(train_sess, config.learning_rate * lr_decay) train_perplexity = run_epoch(train_sess, m, #eval_op=m.train_op, verbose=True) print('Epoch {} Train Perplexity: {:.3f}'.format(i + 1,
tensorflow.ConfigProto
14,307
from tensorflow.contrib.metrics.python.ops import metric_ops metric_ops.streaming_precision_at_thresholds, threshold) # Recall for positive examples. metrics[_MetricKeys.RECALL_MEAN % threshold] = _streaming_at_threshold( metric_ops.streaming_recall_at_thresholds, threshold) return metrics def _float_weights_or_none(weights): if weights is None: return None return math_ops.to_float(weights) def _labels_streaming_mean(unused_predictions, labels, weights=None): return metric_ops.streaming_mean(labels, weights=weights) def _predictions_streaming_mean(predictions, unused_labels, weights=None): return metric_ops.streaming_mean(predictions, weights=weights) def _streaming_auc(predictions, labels, weights=None): return metric_ops.streaming_auc( predictions, labels, weights=_float_weights_or_none(weights)) def _accuracy_at_threshold(threshold): def _accuracy_metric(predictions, labels, weights=None):
tensorflow.contrib.metrics.python.ops.metric_ops.streaming_mean
14,308
from tensorflow.python.framework import ops num_units = config["num_units"] batch_size = config["batch_size"] seq_length = config["seq_length"] with ops.Graph().as_default(), ops.device("/device:GPU:0"): model = cudnn_rnn_ops.CudnnLSTM(num_layers, num_units, num_units) params_size_t = model.params_size() input_data = variables.Variable(
tensorflow.python.framework.ops.device
14,309
import tensorflow as tf # tgt1, tgt2 = tf.split(horizon_tgt, 2, axis=0) even = [2 * i for i in range(25)] odd = [2 * i + 1 for i in range(25)] pred1 = tf.gather(horizon_pred, even) pred2 = tf.gather(horizon_pred, odd) tgt1 = tf.gather(horizon_tgt, even) tgt2 = tf.gather(horizon_tgt, odd) geq = tf.cast((tgt1 - tgt2) > 0, tf.bool) tgt_larg = tf.where(geq, tgt1, tgt2) tgt_small = tf.where(geq, tgt2, tgt1) pred_larg = tf.where(geq, pred1, pred2) pred_small = tf.where(geq, pred2, pred1) loss = tf.maximum(0.0, ((tgt_larg - tgt_small) - (pred_larg - pred_small))) loss = tf.reduce_mean(loss) return loss
tensorflow.cast
14,310
import tensorflow as tf if single_file: dataset_path = os.path.join(dataset_path, 'train_annotated.json') else: dataset_path = os.path.join(dataset_path, 'dev_annotated.json') def load_dataset(): dataset = [] if single_file: # Opening with GFile allows to use remotely stored files, e.g. # in a gs bucket. dataset_handle = tf.io.gfile.GFile(dataset_path, 'r') for line in dataset_handle: dataset.append(json.loads(line)) else: all_files = tf.io.gfile.listdir(dataset_path) for filename in all_files: if 'json' in filename: print('Loading data from file {}'.format(filename)) with tf.io.gfile.GFile(os.path.join(dataset_path, filename)) as f: for line in f: dataset.append(json.loads(line)) print('The total size of the dataset {}'.format(len(dataset))) return dataset[:int(len(dataset) * percentile)] def drop_annotated_yield_examples(generator=None): del generator while True: passages = set()
tensorflow.io.gfile.listdir
14,311
import tensorflow as tf summaries = { 'triplet_loss/Margin': tf.constant(margin), 'triplet_loss/Anchor/Positive/Distance/Mean': tf.math.reduce_mean(anchor_positive_distances), 'triplet_mining/Anchor/Positive/Distance/Mean': tf.math.reduce_mean(anchor_positive_mining_distances), }
tensorflow.math.reduce_mean
14,312
import tensorflow as tf dropout=self.dropout) def _fuse(self): with tf.variable_scope("Context_to_Query_Attention_Layer"): C = tf.tile(tf.expand_dims(self.c_embed_encoding, 2), [1, 1, self.max_q_len, 1]) Q = tf.tile(tf.expand_dims(self.q_embed_encoding, 1), [1, self.max_p_len, 1, 1]) S = trilinear([C, Q, C * Q], input_keep_prob=1.0 - self.dropout)
tensorflow.variable_scope
14,313
import tensorflow as tf num_layers = [16,16,10,6] else: raise ValueError('depth=%g is a not a valid setting!' % depth) # input tensors self.input_x = tf.placeholder(tf.int32, [None, sequence_max_length], name="input_x") self.input_tags = tf.placeholder(tf.int32, [None, sequence_max_length], name="input_tags") self.input_deps = tf.placeholder(tf.int32, [None, sequence_max_length], name="input_dependency") self.input_head = tf.placeholder(tf.int32, [None, sequence_max_length], name="input_head") self.input_y = tf.placeholder(tf.float32, [None, num_classes], name="input_y") self.is_training = tf.placeholder(tf.bool) initializer = tf.contrib.layers.variance_scaling_initializer() # Embedding Lookup 16 with tf.device('/cpu:0'), tf.name_scope("embedding"):
tensorflow.placeholder
14,314
import tensorflow as tf Args: variables: List of variables. deltas: List of deltas of same length. Returns: The step-applied operation. A tf.group of tf.assign_add ops. """ if len(variables) != len(deltas): raise TensorforceError("Invalid variables and deltas lists.") assignments = list() for variable, delta in zip(variables, deltas): assignments.append(tf.assign_add(ref=variable, value=delta)) with tf.control_dependencies(control_inputs=assignments): return util.no_operation() def tf_minimize(self, variables, **kwargs): """ Performs an optimization step. Args: variables: List of variables to optimize. **kwargs: Additional optimizer-specific arguments. The following arguments are used by some optimizers:
tensorflow.assign_add
14,315
import tensorflow as tf 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): """Build the inference graph using CUDNN cell.""" inputs = tf.transpose(inputs, [1, 0, 2]) self._cell = tf.contrib.cudnn_rnn.CudnnLSTM( num_layers=config.num_layers, num_units=config.hidden_size, input_size=config.hidden_size, dropout=1 - config.keep_prob if is_training else 0) params_size_t = self._cell.params_size() self._rnn_params = tf.get_variable( "lstm_params", initializer=tf.random_uniform( [params_size_t], -config.init_scale, config.init_scale), validate_shape=False) c = tf.zeros([config.num_layers, self.batch_size, config.hidden_size],
tensorflow.contrib.cudnn_rnn.CudnnLSTM
14,316
import tensorflow as tf tmp_bboxes = _calc_bounding_boxes() bboxes = np.vstack((bboxes, tmp_bboxes)) # <class 'tuple'>: (5265, 5) # non maximum suppression # refind_idx = util.nms(bboxes, nms_thresh) refind_idx = tf.image.non_max_suppression(tf.convert_to_tensor(bboxes[:, :4], dtype=tf.float32), tf.convert_to_tensor(bboxes[:, 4], dtype=tf.float32), max_output_size=bboxes.shape[0], iou_threshold=nms_thresh) refind_idx = sess.run(refind_idx) refined_bboxes = bboxes[refind_idx] overlay_bounding_boxes(raw_img, refined_bboxes, lw) if display:
tensorflow.convert_to_tensor
14,317
import tensorflow as tf ref=self.episode_indices[-1], value=tf.where(self.memory_index + num_instances > self.capacity, self.episode_indices[self.episode_count - 1], self.capacity - 1) ) with tf.control_dependencies(control_inputs=(assignment,)): assignment = tf.assign(ref=self.memory_index, value=((self.memory_index + num_instances) % self.capacity)) with tf.control_dependencies(control_inputs=(assignment,)): return tf.no_op() def tf_retrieve_indices(self, indices): """ Fetches experiences for given indices. Args:
tensorflow.control_dependencies
14,318
import tensorflow as tf vocab = UnicodeCharsVocabulary(vocab_file, max_word_length) batcher = Batcher(vocab_file, max_word_length) ids_placeholder = tf.placeholder('int32', shape=(None, None, max_word_length) ) model = BidirectionalLanguageModel(options_file, weight_file) ops = model(ids_placeholder) config = tf.ConfigProto(allow_soft_placement=True) with tf.Session(config=config) as sess: sess.run(tf.global_variables_initializer()) sentence_id = 0 with open(dataset_file, 'r') as fin, h5py.File(outfile, 'w') as fout: for line in fin: sentence = line.strip().split() char_ids = batcher.batch_sentences([sentence]) embeddings = sess.run( ops['lm_embeddings'], feed_dict={ids_placeholder: char_ids} )
tensorflow.Session
14,319
from tensorflow.contrib import tpu as contrib_tpu total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu, optimizer) output_spec = contrib_tpu.TPUEstimatorSpec( mode=mode, loss=total_loss,
tensorflow.contrib.tpu.TPUEstimatorSpec
14,320
import tensorflow as tf vocab = data.frequent_vocab_list embed = wv.load_matrix(args.embedding_size, vocab) embed = np.array(embed, dtype = np.float32) with tf.Session(config=config) as sess: model = create_model(sess, data, args, embed) if args.mode == "train": model.train_process(sess, data, args) else:
tensorflow.Session
14,321
import tensorflow as tf weight_decay = 1e-4 momentum = 0.9 total_epochs = 30 iteration = 14089 // 1 # 128 * 14089 ~ 1,803,460 test_iteration = 10 def center_loss(features, label, alfa, nrof_classes): """Center loss based on the paper "A Discriminative Feature Learning Approach for Deep Face Recognition" (http://ydwen.github.io/papers/WenECCV16.pdf) """ nrof_features = features.get_shape()[1] centers = tf.get_variable('centers', [nrof_classes, nrof_features], dtype=tf.float32, initializer=tf.constant_initializer(0), trainable=False) label = tf.reshape(label, [-1]) centers_batch = tf.gather(centers, label) diff = (1 - alfa) * (centers_batch - features) centers = tf.scatter_sub(centers, label, diff) # centers = tf.nn.l2_normalize(centers, 1, 1e-10, name='centers_norm') loss = tf.reduce_mean(tf.square(features - centers_batch)) return loss, centers def focal_loss(onehot_labels, cls_preds, alpha=0.25, gamma=2.0, name=None, scope=None): """Compute softmax focal loss between logits and onehot labels logits and onehot_labels must have same shape [batchsize, num_classes] and the same data type (float16, 32, 64) Args: onehot_labels: Each row labels[i] must be a valid probability distribution
tensorflow.reshape
14,322
import tensorflow as tf x0 = tf.to_int32(tf.floor(x)) x1 = x0 + 1 y0 = tf.to_int32(tf.floor(y)) y1 = y0 + 1 z0 = tf.to_int32(tf.floor(z)) z1 = z0 + 1 x0_clip = tf.clip_by_value(x0, zero, max_x) x1_clip = tf.clip_by_value(x1, zero, max_x) y0_clip = tf.clip_by_value(y0, zero, max_y) y1_clip = tf.clip_by_value(y1, zero, max_y) z0_clip = tf.clip_by_value(z0, zero, max_z) z1_clip = tf.clip_by_value(z1, zero, max_z) dim3 = width dim2 = width * height dim1 = width * height * depth base = _repeat(
tensorflow.clip_by_value
14,323
import tensorflow as tf Sets: feedable placeholders with general purpose """ self.is_training = tf.placeholder_with_default(False, shape=(), name="is_training") #def create_is_training_node(self): # self._is_training = tf.placeholder_with_default(False, shape=(), name="is_training")
tensorflow.placeholder_with_default
14,324
import tensorflow as tf self.placeholders = placeholders with tf.variable_scope("embedding"), tf.device('/cpu:0'): self.embedding = tf.get_variable('word_embedding', trainable=(options.fix_word_vec==False),
tensorflow.variable_scope
14,325
import tensorflow as tf # the shape of `tmp` is (B,T,D)*(D,A)=(B,T,A), where A=attention_size tmp1 = tf.tensordot(facts, w1, axes=1) tmp2 = tf.tensordot(query, w2, axes=1) tmp2 = tf.reshape(tmp2, [-1, 1, tf.shape(tmp2)[-1]]) tmp = tf.tanh((tmp1 + tmp2) + b) # For each of the timestamps its vector of size A from `tmp` is reduced with `v` vector v_dot_tmp = tf.tensordot(tmp, v, axes=1, name='v_dot_tmp') # (B,T) shape key_masks = mask # [B, 1, T] # key_masks = tf.expand_dims(mask, 1) # [B, 1, T] paddings = tf.ones_like(v_dot_tmp) * (-2 ** 32 + 1) v_dot_tmp = tf.where(key_masks, v_dot_tmp, paddings) # [B, 1, T] alphas = tf.nn.softmax(v_dot_tmp, name='alphas') # (B,T) shape # Output of (Bi-)RNN is reduced with attention vector; the result has (B,D) shape #output = tf.reduce_sum(facts * tf.expand_dims(alphas, -1), 1) output = facts * tf.expand_dims(alphas, -1) output = tf.reshape(output, tf.shape(facts)) # output = output / (facts.get_shape().as_list()[-1] ** 0.5) if not return_alphas: return output else: return output, alphas
tensorflow.nn.softmax
14,326
import tensorflow as tf ''' if is_max_pool: # May Name Conflict x = tf.nn.max_pool(x,kernel_size,strides=strides,padding='SAME',name=layer_name) else: x = tf.nn.avg_pool(x,kernel_size,strides=strides,padding='SAME',name=layer_name) return x def pool3d(layer_name, x, kernel_size=[1,1,2,2,1], strides=[1,1,2,2,1], is_max_pool=True): '''
tensorflow.nn.avg_pool
14,327
import tensorflow as tf 1. / model_options.output_stride) resize_width = scale_dimension( model_options.crop_size[1], 1. / model_options.output_stride) else: # If crop_size is None, we simply do global pooling. pool_height = tf.shape(features)[1] pool_width = tf.shape(features)[2] image_feature = tf.reduce_mean( features, axis=[1, 2], keepdims=True) resize_height = pool_height resize_width = pool_width image_feature_activation_fn = tf.nn.relu image_feature_normalizer_fn = batch_norm if model_options.aspp_with_squeeze_and_excitation: image_feature_activation_fn = tf.nn.sigmoid
tensorflow.reduce_mean
14,328
import tensorflow as tf tvars = tf.trainable_variables() initialized_variable_names = {} scaffold_fn = None if init_checkpoint: (assignment_map, initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) if use_tpu: def tpu_scaffold(): tf.train.init_from_checkpoint(init_checkpoint, assignment_map) return tf.train.Scaffold() scaffold_fn = tpu_scaffold else: tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf.logging.info("**** Trainable Variables ****") for var in tvars: init_string = "" if var.name in initialized_variable_names: init_string = ", *INIT_FROM_CKPT*"
tensorflow.train.Scaffold
14,329
import tensorflow as tf if nn_type == 'mlp': with tf.variable_scope('pi'): pi = act_limit * mlp(x, list(hidden_sizes) + [act_dim], activation, output_activation) with tf.variable_scope('q1'): q1 = tf.squeeze(mlp(tf.concat([x, a], axis=-1), list(hidden_sizes) + [1], activation, None), axis=1) with tf.variable_scope('q2'): q2 = tf.squeeze(mlp(tf.concat([x, a], axis=-1), list(hidden_sizes) + [1], activation, None), axis=1) with tf.variable_scope('q1', reuse=True): q1_pi = tf.squeeze(mlp(tf.concat([x, pi], axis=-1), list(hidden_sizes) + [1], activation, None), axis=1) elif nn_type == 'mlp_dropout': with tf.variable_scope('pi'): pi = act_limit * mlp_dropout(x, list(hidden_sizes)+[act_dim], activation, output_activation) with tf.variable_scope('q'): q = tf.squeeze(mlp_dropout(tf.concat([x,a], axis=-1), list(hidden_sizes)+[1], activation, None, dropout_rate), axis=1) with tf.variable_scope('q', reuse=True): q_pi = tf.squeeze(mlp_dropout(tf.concat([x,pi], axis=-1), list(hidden_sizes)+[1], activation, None, dropout_rate), axis=1) elif nn_type == 'mlp_variational': with tf.variable_scope('pi'): pi_in_dim = x.shape.as_list()[1] pi_dropout_mask_generator = DropoutMaskGenerator(pi_in_dim, hidden_sizes, model_prob=1.0 - dropout_rate) pi_dropout_mask_phs = pi_dropout_mask_generator.generate_dropout_mask_placeholders() pi, pi_reg = mlp_variational(x, pi_dropout_mask_phs, list(hidden_sizes) + [act_dim], activation, output_activation, dropout_rate) pi = act_limit * pi with tf.variable_scope('q1'): q1_in_ph = tf.concat([x, a], axis=-1) q1_in_dim = q1_in_ph.shape.as_list()[1] q1_dropout_mask_generator = DropoutMaskGenerator(q1_in_dim, hidden_sizes, model_prob=1.0 - dropout_rate)
tensorflow.variable_scope
14,330
import tensorflow as tf # Setup Index Matrix for one-hot-encoding identity_mat = tf.diag(tf.ones(shape=[embedding_size]))
tensorflow.ones
14,331
import tensorflow as tf images=tf.cast(images,tf.float32)/255.0 l1 = tf.matmul(images, self.w1)+self.b1 l1=tf.nn.relu(l1) l2 = tf.matmul(l1, self.w2)+self.b2 l2=tf.nn.relu(l2) l3=tf.matmul(l2, self.w3)+self.b3 l3=tf.nn.relu(l3) out=tf.matmul(l3, self.w4)+self.b4 return out def test_inference(self,images): images=tf.cast(images,tf.float32)/255.0
tensorflow.nn.relu
14,332
import tensorflow as tf if isinstance(facts, tuple): # In case of Bi-RNN, concatenate the forward and the backward RNN outputs. facts = tf.concat(facts, 2) print ("querry_size mismatch") query = tf.concat(values = [ query, query, ], axis=1) if time_major: # (T,B,D) => (B,T,D) facts = tf.array_ops.transpose(facts, [1, 0, 2]) mask = tf.equal(mask, tf.ones_like(mask)) facts_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer querry_size = query.get_shape().as_list()[-1] queries = tf.tile(query, [1, tf.shape(facts)[1]]) queries = tf.reshape(queries, tf.shape(facts)) din_all = tf.concat([queries, facts, queries-facts, queries*facts], axis=-1) d_layer_1_all = tf.layers.dense(din_all, 80, activation=tf.nn.sigmoid, name='f1_att' + stag) d_layer_2_all = tf.layers.dense(d_layer_1_all, 40, activation=tf.nn.sigmoid, name='f2_att' + stag) d_layer_3_all = tf.layers.dense(d_layer_2_all, 1, activation=None, name='f3_att' + stag) d_layer_3_all = tf.reshape(d_layer_3_all, [-1, 1, tf.shape(facts)[1]])
tensorflow.array_ops.transpose
14,333
import tensorflow as tf Valid values: `detection`, `classification`. Default 'detection'. Returns: A dict mapping variable names to variables. """ return {var.op.name: var for var in tf.global_variables()} def updates(self): """Returns a list of update operators for this model.
tensorflow.global_variables
14,334
import tensorflow as tf :param name: [string] Name of the variable scope. :param x: [Tensor] Tensor to apply BN on. :param is_training [bool] Whether in training mode. :return: [Tensor] Normalized activation. """ bn = tf.contrib.layers.batch_norm( x, fused=True, scale=True, data_format=data_format, is_training=is_training, scope=name) return bn # log.warning('Not using BN to test performance at inference time') # return x
tensorflow.contrib.layers.batch_norm
14,335
import tensorflow as tf def _init(): v_norm = tf.nn.l2_normalize(self.v,axis=[0,1,2]) t = tf.nn.conv2d(input_var,v_norm,self.strides,self.padding,data_format='NHWC') mu,var = tf.nn.moments(t,axes=[0,1,2]) std = tf.sqrt(var+self.epsilon) return [tf.assign(self.g,1/std),tf.assign(self.b,-1.*mu/std)] require_init = tf.reduce_any(tf.is_nan(self.g)) init_ops = tf.cond(require_init,_init,lambda : [self.g,self.b])
tensorflow.assign
14,336
import tensorflow as tf tf.summary.scalar('ent_coef', self.ent_coef) tf.summary.scalar('learning_rate', tf.reduce_mean(self.learning_rate_ph)) # Retrieve parameters that must be saved self.params = tf_util.get_trainable_vars("model") self.target_params = tf_util.get_trainable_vars("target/values_fn/vf") # Initialize Variables and target network with self.sess.as_default(): self.sess.run(tf.global_variables_initializer()) self.sess.run(target_init_op) self.summary = tf.summary.merge_all() def pretrain_sac(self,pretrain_steps): print("=====SAC Pretraining=====") for step in range(pretrain_steps): # Compute current learning_rate frac = 1.0 - step / pretrain_steps current_lr = self.learning_rate(frac) # Update policy and critics (q functions) policy_loss, qf1_loss, qf2_loss, value_loss,*entropy =self._train_step(step, writer=None,learning_rate=current_lr,pretrain=True) if step % 50==0: print("** Pretraining step: |",step/pretrain_steps," Actor loss: |",policy_loss, "Critic loss|",value_loss," Actor expert loss|",entropy[-1] ) # Update target network
tensorflow.summary.merge_all
14,337
import tensorflow as tf params = { self.SEED_PARAM_KEY: tf.random.uniform((), maxval=tf.int32.max, dtype=tf.int32) }
tensorflow.random.uniform
14,338
import tensorflow as tf tf.compat.v2.summary.scalar( name="relabel_q_vals", data=tf.reduce_mean(relabel_q_vals), step=global_step, ) max_q = tf.reduce_max(logits_vec, axis=1) tf.compat.v2.summary.scalar( name="max_q", data=tf.reduce_mean(max_q), step=global_step) ### End metrics
tensorflow.reduce_max
14,339
import tensorflow as tf loop_vars=[n, result, two]) return result def factorial(n: TensorLike) -> TensorLike: n = tf.convert_to_tensor(value=n) return tf.exp(tf.math.lgamma(n + 1)) def generate_l_m_permutations( max_band: int, name: str = "spherical_harmonics_generate_l_m_permutations") -> Tuple[TensorLike, TensorLike]: with tf.name_scope(name):
tensorflow.math.lgamma
14,340
import tensorflow as tf with tf.variable_scope(scope, reuse=reuse): # set up placeholders obs_t_input = make_obs_ph("obs_t") act_t_ph = tf.placeholder(tf.int32, [None], name="action") rew_t_ph = tf.placeholder(tf.float32, [None], name="reward") obs_tp1_input = make_obs_ph("obs_tp1") done_mask_ph = tf.placeholder(tf.float32, [None], name="done") importance_weights_ph = tf.placeholder(tf.float32, [None], name="weight") # q network evaluation q_t = q_func(obs_t_input.get(), num_actions, scope="q_func", reuse=True) # reuse parameters from act q_func_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=tf.get_variable_scope().name + "/q_func")
tensorflow.placeholder
14,341
from tensorflow.python.framework import ops rank = array_ops.rank(top_k_predictions) check_rank_op = control_flow_ops.Assert( math_ops.greater_equal(rank, 2), ['top_k_predictions must have rank 2 or higher, e.g. [batch_size, k].']) with ops.control_dependencies([check_rank_op]): return _streaming_sparse_precision_at_k( top_k_idx=top_k_predictions, labels=labels,
tensorflow.python.framework.ops.control_dependencies
14,342
import tensorflow as tf boxes (num_priors, 4): real values for priors. labels (num_priors): labels for priors. """ # size: num_priors x num_targets ious = iou_of(tf.expand_dims(gt_boxes, axis=0), tf.expand_dims(corner_form_priors, axis=1)) # size: num_priors best_target_per_prior = tf.math.reduce_max(ious, axis=1)
tensorflow.expand_dims
14,343
import tensorflow as tf n = tf.random_normal(shape=shape, dtype=tf.float32) n = tf.reshape(n, shape=(int(shape[0]), -1)) n = tf.nn.l2_normalize(n, dim=1) n = tf.reshape(n, shape) return n
tensorflow.reshape
14,344
import tensorflow as tf [None, num_classes]) images = tf.random_uniform((batch_size, height, width, 3)) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(logits, {inputs: images.eval()}) self.assertEqual(output.shape, (batch_size, num_classes)) def testEvaluation(self): batch_size = 2 height, width = 224, 224 num_classes = 1000 eval_inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = mobilenet_v1.mobilenet_v1(eval_inputs, num_classes, is_training=False) predictions = tf.argmax(logits, 1) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(predictions) self.assertEqual(output.shape, (batch_size,)) def testTrainEvalWithReuse(self): train_batch_size = 5 eval_batch_size = 2
tensorflow.random_uniform
14,345
from tensorflow.python.ops import array_ops """ with self._name_scope(name, values=[x]): x = ops.convert_to_tensor(x, name="x") sample_shape, batch_shape, event_shape = self.get_shape(x) event_shape = distribution_util.pick_vector( self._event_ndims_is_0, (1,), event_shape) batch_shape = distribution_util.pick_vector( self._batch_ndims_is_0, (1,), batch_shape) 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 def undo_make_batch_of_event_sample_matrices( self, x, sample_shape, name="undo_make_batch_of_event_sample_matrices"): """Reshapes/transposes `Distribution` `Tensor` from B_+E_+S_ to S+B+E.
tensorflow.python.ops.array_ops.concat
14,346
import tensorflow as tf # Classification accuracy of encoder correct_pred = tf.equal(tf.argmax(encoder_output_label_, 1), tf.argmax(y_input, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
tensorflow.argmax
14,347
import tensorflow as tf h, w, _ = image.shape grid = 8 image = image[:h // grid * grid, :w // grid * grid, :] mask = mask[:h // grid * grid, :w // grid * grid, :] image = np.expand_dims(image, 0) mask = np.expand_dims(mask, 0) input_image = np.concatenate([image, mask], axis=2) sess_config = tf.ConfigProto() sess_config.gpu_options.allow_growth = True with tf.Session(config=sess_config) as sess: input_image = tf.constant(input_image, dtype=tf.float32) output = model.build_server_graph(FLAGS, input_image) output = (output + 1.) * 127.5 output = tf.reverse(output, [-1]) output = tf.saturate_cast(output, tf.uint8) # load pretrained model
tensorflow.ConfigProto
14,348
import tensorflow as tf l3=tf.matmul(l2, self.w3)+self.b3 l3=tf.nn.relu(l3) out=tf.matmul(l3, self.w4)+self.b4 return out def valid_inference(self,images): images=tf.cast(images,tf.float32)/255.0 l1 = tf.matmul(images, self.w1)+self.b1 l1=tf.nn.relu(l1) l2 = tf.matmul(l1, self.w2)+self.b2 l2=tf.nn.relu(l2) l3=tf.matmul(l2, self.w3)+self.b3 l3=tf.nn.relu(l3) out=tf.matmul(l3, self.w4)+self.b4 return out def softmax_loss(self,predicts,labels): predicts=tf.nn.softmax(predicts) labels=tf.one_hot(labels,classnum) loss=-tf.reduce_sum(labels*tf.log(predicts)) return loss def optimer(self,loss,lr=0.001): train_step=tf.train.GradientDescentOptimizer(lr).minimize(loss) return train_step
tensorflow.matmul
14,349
import tensorflow as tf def train_z(loss,Z): return tf.gradients(ys = loss, xs = Z)
tensorflow.gradients
14,350
import tensorflow as tf sample: the ground truth information detections: the predicted detections Returns: dict of intermediate results. """ result_dict = {'iou_mean': -1, 'iou_min': -1, 'collisions': 0, 'collision_intersection': 0, 'collision_iou': 0} num_boxes = sample['num_boxes'].numpy() labeled_boxes_init = tf.gather( sample['groundtruth_boxes'], axis=1, indices=[1, 0, 3, 2]) * 256.0 for _, metric in self.metrics.items(): if isinstance(metric, ShapeAccuracyMetric): labels = sample['shapes'] weights = tf.math.sign(labels + 1) # -1 is mapped to zero, else 1 metric.update(labels, detections['shapes_logits'], weights) elif isinstance(metric, BoxIoUMetric): scene_id = str(sample['scene_filename'].numpy(), 'utf-8')
tensorflow.gather
14,351
import tensorflow as tf 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., margin-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
tensorflow.maximum
14,352
import tensorflow as tf # List of dicts to dict of lists metrics = dict(zip(metrics[0], zip(*[m.values() for m in metrics]))) metrics = {m: np.nanmean(metrics[m], axis=0) for m in metrics} return metrics def _checkpoint_var_search(self, checkpoint_path): reader = tf.train.NewCheckpointReader(checkpoint_path) saved_shapes = reader.get_variable_to_shape_map() model_names = tf.model_variables() # Used by tf.slim layers if not len(tf.model_variables()): model_names = tf.global_variables() # Fallback when slim is not used model_names = set([v.name.split(':')[0] for v in model_names]) checkpoint_names = set(saved_shapes.keys()) found_names = model_names & checkpoint_names missing_names = model_names - checkpoint_names shape_conflicts = set()
tensorflow.model_variables
14,353
import tensorflow as tf return tf.layers.conv2d(input, channels, kernel_size=size, strides=[stride, stride], padding=padding, kernel_initializer=init, name='conv' + id, use_bias=use_bias, dilation_rate=(dilation, dilation)) def z_conv(self, id, input, channels, size, stride=1, padding="SAME", use_bias=False, dilation=1): # zero mean conv if type(size) == int: size = [size, size] in_ch = input.get_shape().as_list()[-1] # init = tf.contrib.layers.variance_scaling_initializer(dtype=tf.float32) init = tf.truncated_normal_initializer(mean=0.0, stddev=0.02) filters = tf.get_variable('zero_conv_weights' + id, initializer=init, shape=[size[0], size[1], in_ch, channels]) filters = filters - tf.reduce_mean(filters, axis=[0, 1, 2], keepdims=True) if padding == "PARTIAL": with tf.variable_scope('mask'): _, h, w, _ = input.get_shape().as_list() slide_window = size[0] * size[1] mask = tf.ones(shape=[1, h, w, 1])
tensorflow.truncated_normal_initializer
14,354
import tensorflow as tf with tf.name_scope('inputs'): noise, one_hot_labels = _get_generator_inputs( FLAGS.num_images_per_class, NUM_CLASSES, FLAGS.noise_dims) # Generate images. with tf.variable_scope('Generator'): # Same scope as in train job. images = networks.conditional_generator( (noise, one_hot_labels), is_training=False) # Visualize images.
tensorflow.variable_scope
14,355
from tensorflow.contrib.metrics.python.ops import set_ops labels, predictions_idx = _maybe_select_class_id(labels, predictions_idx, class_id) fn = set_ops.set_size(set_ops.set_difference(predictions_idx, labels, aminusb=False))
tensorflow.contrib.metrics.python.ops.set_ops.set_difference
14,356
import tensorflow as tf # Convert RGB to BGR red, green, blue = tf.split(axis=3, num_or_size_splits=3, value=rgb_scaled) assert red.get_shape().as_list()[1:] == [224, 224, 1] assert green.get_shape().as_list()[1:] == [224, 224, 1] assert blue.get_shape().as_list()[1:] == [224, 224, 1] bgr = tf.concat(axis=3, values=[ blue - VGG_MEAN[0], green - VGG_MEAN[1], red - VGG_MEAN[2], ]) assert bgr.get_shape().as_list()[1:] == [224, 224, 3]
tensorflow.concat
14,357
import tensorflow as tf h_conv3_flat = tf.reshape(h_conv3, [-1, 1600], 'h_conv3_flat') h_fc1 = tf.nn.relu(tf.add(tf.matmul(h_conv3_flat, W_fc1), b_fc1, 'h_fc1')) readout = tf.add(tf.matmul(h_fc1, W_fc2), b_fc2, 'h_fc2') return s, readout, h_fc1
tensorflow.matmul
14,358
import tensorflow as tf else: print("Created model with fresh parameters.") global_variable = [gv for gv in tf.global_variables() if args.name in gv.name] sess.run(tf.variables_initializer(global_variable)) return model def main(args): if args.debug: debug() if args.cuda: config = tf.ConfigProto() config.gpu_options.allow_growth = True else: config = tf.ConfigProto(device_count={'GPU': 0}) os.environ["CUDA_VISIBLE_DEVICES"] = "-1" data_class = MultiTurnDialog.load_class(args.dataset) wordvec_class = WordVector.load_class(args.wvclass) if wordvec_class == None: wordvec_class = Glove if args.cache: data = try_cache(data_class, (args.datapath,), args.cache_dir) vocab = data.frequent_vocab_list
tensorflow.ConfigProto
14,359
import tensorflow as tf assert n_filters > projection_dim with tf.variable_scope('CNN_proj') as scope: W_proj_cnn = tf.get_variable( "W_proj", [n_filters, projection_dim], initializer=tf.random_normal_initializer( mean=0.0, stddev=np.sqrt(1.0 / n_filters)), dtype=DTYPE) b_proj_cnn = tf.get_variable( "b_proj", [projection_dim], initializer=tf.constant_initializer(0.0), dtype=DTYPE) # apply highways layers def high(x, ww_carry, bb_carry, ww_tr, bb_tr): carry_gate = tf.nn.sigmoid(tf.matmul(x, ww_carry) + bb_carry) transform_gate = tf.nn.relu(tf.matmul(x, ww_tr) + bb_tr) return carry_gate * transform_gate + (1.0 - carry_gate) * x if use_highway: highway_dim = n_filters for i in range(n_highway): with tf.variable_scope('CNN_high_%s' % i) as scope: W_carry = tf.get_variable( 'W_carry', [highway_dim, highway_dim], # glorit init initializer=tf.random_normal_initializer( mean=0.0, stddev=np.sqrt(1.0 / highway_dim)),
tensorflow.matmul
14,360
import tensorflow as tf anchor_match_mining_distance_matrix=( anchor_match_mining_distance_matrix))) negative_distances = tf.boolean_mask( negative_distances, mask=negative_distances < negative_distances.dtype.max) negative_mining_distances = tf.boolean_mask( negative_mining_distances, mask=negative_distances < negative_distances.dtype.max) active_triplet_ratio = ( tf.cast(num_active_triplets, dtype=tf.float32) / num_total_triplets) active_mining_triplet_ratio = ( tf.cast(num_active_mining_triplets, dtype=tf.float32) / num_total_triplets) active_loss = ( loss / tf.math.maximum(1e-12, tf.stop_gradient(active_triplet_ratio))) active_mining_loss = ( mining_loss / tf.math.maximum(1e-12, tf.stop_gradient(active_mining_triplet_ratio))) tag = 'SemiHardNegative' if use_semi_hard else 'HardNegative' summaries = { # Summaries related to triplet loss computation.
tensorflow.cast
14,361
import tensorflow as tf geq = tf.cast((tgt1 - tgt2) > 0, tf.bool) tgt_larg = tf.where(geq, tgt1, tgt2) tgt_small = tf.where(geq, tgt2, tgt1) pred_larg = tf.where(geq, pred1, pred2) pred_small = tf.where(geq, pred2, pred1) loss = tf.maximum(0.0, ((tgt_larg - tgt_small) - (pred_larg - pred_small))) loss = tf.reduce_mean(loss) return loss def apply_optimizers(objectives, trainer, config): # Make sure all losses are computed and apply loss scales. processed = [] values = [ob.value for ob in objectives]
tensorflow.reduce_mean
14,362
import tensorflow as tf M = tf.placeholder(tf.float32, [None, 2, n_ctx]) Y_train = tf.placeholder(tf.int32, [n_batch_train]) Y = tf.placeholder(tf.int32, [None]) train, logits, clf_losses, lm_losses = mgpu_train(X_train, M_train, Y_train) clf_loss = tf.reduce_mean(clf_losses) params = find_trainable_variables('model') sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) sess.run(tf.global_variables_initializer())
tensorflow.reduce_mean
14,363
from tensorflow.contrib.learn.python.learn.estimators import run_config learner_config.num_classes = 2 learner_config.constraints.max_tree_depth = 1 model_dir = tempfile.mkdtemp() config = run_config.RunConfig() classifier = estimator.GradientBoostedDecisionTreeClassifier(
tensorflow.contrib.learn.python.learn.estimators.run_config.RunConfig
14,364
import tensorflow as tf with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): cell = tf.nn.rnn_cell.GRUCell(2) inp = tf.constant(0.5, shape=[2, 2, 2]) enc_outputs, enc_state = tf.nn.dynamic_rnn(cell, inp, dtype=tf.float32) attn_states = enc_outputs dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3
tensorflow.nn.dynamic_rnn
14,365
import tensorflow as tf 1) for i in range(num_boxes)], axis=0) rotations_y = tf.reshape(rotations_y, [-1, 1]) predicted_boxes = tf.concat([detections['translations_3d'], detections['sizes_3d'], rotations_y], axis=1) labeled_classes = tf.cast(sample['groundtruth_valid_classes'], tf.int64) predicted_classes = tf.cast(detections['detection_classes'], tf.int64) confidences = detections['detection_scores'] metric.update(scene_id, labeled_boxes, labeled_classes, predicted_boxes, predicted_classes, confidences) elif isinstance(metric, IoUMetric): classes = sample['classes'] mesh_names = sample['mesh_names']
tensorflow.cast
14,366
import tensorflow as tf U = tf.get_variable(name="attn_U", shape=[2 * self.config.hidden_size, 2 * self.config.hidden_size], initializer=tf.contrib.layers.xavier_initializer(), # initializer=tf.truncated_normal_initializer(), # initializer=tf.keras.initializers.lecun_normal(), dtype=tf.float32) self.position_emb = tf.reshape(self.position_emb, [-1, 2 * self.config.hidden_size]) shape = tf.shape(output) output = tf.reshape(output, [-1, 2 * self.config.hidden_size]) atten_hidden = tf.tanh( tf.add( tf.matmul(self.position_emb, W), tf.matmul(output, U))) alpha = tf.nn.softmax( tf.reshape(tf.matmul(atten_hidden, V), [-1, shape[1], 1]), axis=1) output = tf.reshape(output, [-1, shape[1], 2 * self.config.hidden_size]) C = tf.multiply(alpha, output) return tf.concat([output, C], axis=-1) def _train_epoch(self, train_batches, dropout): """ :param train_batches: :param dropout:
tensorflow.matmul
14,367
import tensorflow as tf predictions = tf.reshape(predictions, [1, -1, heatmap_size*heatmap_size]) pred_max = tf.reduce_max(predictions, axis=-1) pred_indices = tf.argmax(predictions, axis=-1) pred_x, pred_y = tf.cast(tf.floormod(pred_indices, heatmap_size), tf.float32), tf.cast(tf.floordiv(pred_indices, heatmap_size), tf.float32) width, height = tf.cast(width, tf.float32), tf.cast(height, tf.float32) pred_x, pred_y = pred_x * width / tf.cast(heatmap_size, tf.float32), pred_y * height / tf.cast(heatmap_size, tf.float32) if clip_at_zero: pred_x, pred_y = pred_x * tf.cast(pred_max>0, tf.float32), pred_y * tf.cast(pred_max>0, tf.float32) pred_x = pred_x * tf.cast(pred_max>0, tf.float32) + tf.cast(pred_max<=0, tf.float32) * (width / 2.) pred_y = pred_y * tf.cast(pred_max>0, tf.float32) + tf.cast(pred_max<=0, tf.float32) * (height / 2.) if config.PRED_DEBUG: pred_indices_ = tf.squeeze(pred_indices) image_ = tf.squeeze(image) * 255. pred_heatmap = tf.one_hot(pred_indices_, heatmap_size*heatmap_size, on_value=1., off_value=0., axis=-1, dtype=tf.float32) pred_heatmap = tf.reshape(pred_heatmap, [-1, heatmap_size, heatmap_size]) if data_format == 'channels_first': image_ = tf.transpose(image_, perm=(1, 2, 0))
tensorflow.cast
14,368
import tensorflow as tf feed_previous=True) res1 = sess.run(d1) res2 = sess.run(d2) res3 = sess.run(d3) self.assertAllClose(res1, res2) self.assertAllClose(res1, res3) def testAttentionDecoder1(self): with self.test_session() as sess: with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): cell = tf.nn.rnn_cell.GRUCell(2) inp = [tf.constant(0.5, shape=[2, 2])] * 2 enc_outputs, enc_state = tf.nn.rnn(cell, inp, dtype=tf.float32) attn_states = tf.concat(1, [tf.reshape(e, [-1, 1, cell.output_size]) for e in enc_outputs]) dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3 dec, mem = tf.nn.seq2seq.attention_decoder( dec_inp, enc_state, attn_states, cell, output_size=4) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res))
tensorflow.constant
14,369
import tensorflow as tf i, f, o, u = tf.split(axis=1, num_or_size_splits=4, value=z) i = tf.nn.sigmoid(i) f = tf.nn.sigmoid(f) o = tf.nn.sigmoid(o) u = tf.tanh(u) c = f*c + i*u h = o*tf.tanh(c) xs[idx] = h s = tf.concat(axis=1, values=[c, h]) return xs, s def _ln(x, g, b, e=1e-5, axes=[1]): u, s = tf.nn.moments(x, axes=axes, keep_dims=True) x = (x-u)/tf.sqrt(s+e) x = x*g+b return x
tensorflow.concat
14,370
import tensorflow as tf margin: Margin of the contrastive loss Returns: loss: scalar float Tensor """ ######################## # PUT YOUR CODE HERE # ######################## D = (tf.reduce_sum((channel_1 - channel_2)**2, reduction_indices=1))**0.5 zeros = tf.fill(tf.shape(D), 0.0) # loss = 0.5*(label*(D**2.) + (1-label) * (tf.reduce_max([zeros, margin - D], reduction_indices=0))**2) loss = label*(D**2) + (1-label) * (tf.reduce_max([zeros, margin - D**2], 0)) ######################## # END OF YOUR CODE # ########################
tensorflow.reduce_sum
14,371
import tensorflow as tf Returns ------- A tensor. """ res = tf.nn.elu(x) if alpha == 1: return res else: return tf.where(x > 0, res, alpha * res)
tensorflow.nn.elu
14,372
import tensorflow as tf wrong = tf.to_float(tf.logical_not(tf.nn.in_top_k(logits, label, 1)), name='incorrect_vector') summary.add_moving_summary(tf.reduce_mean(wrong, name='train_error')) wd_cost = tf.multiply(1e-5, regularize_cost('fc.*/W', tf.nn.l2_loss), name='regularize_loss') summary.add_moving_summary(cost, wd_cost) self.cost = tf.add_n([wd_cost, cost], name='cost') def _get_optimizer(self): lr = tf.get_variable('learning_rate', initializer=5e-4, trainable=False) opt = tf.train.AdamOptimizer(lr, epsilon=1e-3) return optimizer.apply_grad_processors(
tensorflow.add_n
14,373
from tensorflow.contrib.eager.python.examples.revnet import config as config_ for grad, var in zip(grads, vars_): if grad is not None: self.assertEqual(grad.shape, var.shape) def test_training_graph(self): """Test model training in graph mode.""" with tf.Graph().as_default(): config = config_.get_hparams_cifar_38() config.add_hparam("n_classes", 10) config.add_hparam("dataset", "cifar-10") x = tf.random_normal( shape=(self.config.batch_size,) + self.config.input_shape) t = tf.random_uniform(
tensorflow.contrib.eager.python.examples.revnet.config.get_hparams_cifar_38
14,374
import tensorflow as tf return img_h0, img_h1, img_h2, img_h3, img_h4, img_z with tf.variable_scope("conv") as scope: srcimg_h0, srcimg_h1, srcimg_h2, srcimg_h3, srcimg_h4, srcimg_z = encode(srcimg) scope.reuse_variables() tgtimg_h0, tgtimg_h1, tgtimg_h2, tgtimg_h3, tgtimg_h4, tgtimg_z = encode(tgtimg) tgtctx_h0, tgtctx_h1, tgtctx_h2, tgtctx_h3, tgtctx_h4, tgtctx_z = encode(tgtctx) with tf.variable_scope("translate") as scope: trans_h0 = lrelu(linear(tf.nn.dropout(tf.concat([srcimg_z, tgtctx_z], 1), keep_prob), featsize, 'trans_h0')) trans_z = linear(tf.nn.dropout(trans_h0, keep_prob), featsize, 'trans_z') self.translated_z = trans_z s_h, s_w = self.output_height, self.output_width s_h0, s_h1, s_h2, s_h3 = \ int(s_h/ns0), int(s_h/ns0/ns1), int(s_h/ns0/ns1/ns2), int(s_h/ns0/ns1/ns2/ns3) s_w0, s_w1, s_w2, s_w3 = \ int(s_w/ns0), int(s_w/ns0/ns1), int(s_w/ns0/ns1/ns2), int(s_w/ns0/ns1/ns2/ns3)
tensorflow.concat
14,375
import tensorflow as tf def _add_train_summary(self, var): tf.summary.histogram('TRAIN/' + var.op.name, var) # Custom Layers # def _reshape_layer(self, bottom, num_dim, name): input_shape = tf.shape(bottom) with tf.variable_scope(name): # change the channel to the caffe format # 18个通道[,18,none,none],分别显示得分,前9个为前景得分,后9个为背景得分 # 第二次[1,2,none,none] to_caffe = tf.transpose(bottom, [0, 3, 1, 2]) # then force it to have channel 2 #[1,2,none.none],将9个anchor的前景得分和背景得分分开 # 第二次[1,18,none,none] reshaped = tf.reshape(to_caffe, tf.concat(axis=0, values=[[self._batch_size], [num_dim, -1], [input_shape[2]]])) # then swap the channel back # [1,none,none,2], 第一个none应该为(行*9) # 第二次[1,none,none,18] to_tf = tf.transpose(reshaped, [0, 2, 3, 1]) return to_tf
tensorflow.transpose
14,376
from tensorflow.python.framework import tensor_shape """Common shape function for binary operators that broadcast their inputs.""" shape_x = op.inputs[0].get_shape() shape_y = op.inputs[1].get_shape() if shape_x.ndims is None or shape_y.ndims is None: return [tensor_shape.unknown_shape()] # To compute the broadcasted dimensions, we zip together shape_x and shape_y, # and pad with 1 to make them the same length. broadcasted_dims = reversed(list(six.moves.zip_longest( reversed(shape_x.dims), reversed(shape_y.dims), fillvalue=tensor_shape.Dimension(1)))) # Next we combine the dimensions according to the numpy broadcasting rules. # http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html return_dims = [] for (dim_x, dim_y) in broadcasted_dims: if dim_x.value is None or dim_y.value is None: # One or both dimensions is unknown. If either dimension is greater than # 1, we assume that the program is correct, and the other dimension will # be broadcast to match it. # TODO(mrry): If we eliminate the shape checks in C++, we must still # assert that the unknown dim is either 1 or the same as the known dim.
tensorflow.python.framework.tensor_shape.Dimension
14,377
import tensorflow as tf with tf.variable_scope(scope, reuse=reuse): observations_ph = make_obs_ph("observation") stochastic_ph = tf.placeholder(tf.bool, (), name="stochastic") update_eps_ph = tf.placeholder(tf.float32, (), name="update_eps")
tensorflow.placeholder
14,378
import tensorflow as tf tf.app.flags.DEFINE_float( 'neg_threshold', 0.4, 'Matching threshold for the negtive examples in the loss function.') # optimizer related configuration tf.app.flags.DEFINE_float( 'weight_decay', 0.0005, 'The weight decay on the model weights.') tf.app.flags.DEFINE_float( 'momentum', 0.9, 'The momentum for the MomentumOptimizer and RMSPropOptimizer.') tf.app.flags.DEFINE_float('learning_rate', 0.001, 'Initial learning rate.') tf.app.flags.DEFINE_float( 'end_learning_rate', 0.00005, 'The minimal end learning rate used by a polynomial decay learning rate.') # for learning rate exponential_decay tf.app.flags.DEFINE_float( 'learning_rate_decay_factor', 0.96, 'Learning rate decay factor.') tf.app.flags.DEFINE_float( 'decay_steps', 1000, 'Number of epochs after which learning rate decays.') # for learning rate piecewise_constant decay tf.app.flags.DEFINE_string( 'decay_boundaries', '60000, 800000', 'Learning rate decay boundaries by global_step (comma-separated list).') tf.app.flags.DEFINE_string( 'lr_decay_factors', '1, 0.6, 0.1', 'The values of learning_rate decay factor for each segment between boundaries (comma-separated list).') # checkpoint related configuration tf.app.flags.DEFINE_string( 'checkpoint_path', './model/resnet50',#None, 'The path to a checkpoint from which to fine-tune.') tf.app.flags.DEFINE_string(
tensorflow.app.flags.DEFINE_float
14,379
import tensorflow as tf z = tf.math.exp(log_sigmas)*x ldj = tf.math.reduce_sum(log_sigmas, axis=[1,2,3]) else: z = x*tf.math.exp(-log_sigmas) ldj = -tf.math.reduce_sum(log_sigmas, axis=[1,2,3]) return z, ldj class HalfGaussianize(Parameterize):
tensorflow.math.reduce_sum
14,380
import tensorflow as tf for (name, value) in monitored_values.items(): tf.summary.scalar(name, value) summary_op = tf.summary.merge_all() return (summary_op, monitored_values) def _make_var(self, name, shape, dtype=None, no_reg=False, initializer=None, init_constant=None, trainable=True): if initializer is None: if init_constant is not None: initializer = tf.constant_initializer(init_constant, dtype=tf.float32) else: initializer = tf.contrib.keras.initializers.he_normal() # Ensure that name is unique by shape too name += '-shape-{}'.format('x'.join([str(x) for x in shape])) var = tf.get_variable(name, shape=shape, dtype=dtype, initializer=initializer, trainable=trainable) # Add L2 regularization node for trainable var if trainable and not no_reg: l2_loss = tf.nn.l2_loss(var) tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES, l2_loss)
tensorflow.contrib.keras.initializers.he_normal
14,381
import tensorflow as tf LR = 0.001 def main(unused_argv): tf.compat.v1.enable_v2_behavior() # The trainer only runs with V2 enabled. with tf.device('/CPU:0'): # due to b/128333994 if FLAGS.normalize_reward_fns: action_reward_fns = ( environment_utilities.normalized_sliding_linear_reward_fn_generator( CONTEXT_DIM, NUM_ACTIONS, REWARD_NOISE_VARIANCE)) else:
tensorflow.device
14,382
import tensorflow as tf tpu_cluster_resolver = None if FLAGS.use_tpu and FLAGS.tpu_name: tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver( FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
tensorflow.contrib.cluster_resolver.TPUClusterResolver
14,383
import tensorflow as tf Of shape (n_test, n_support) """ rnorm_test = tf.rsqrt( tf.reduce_sum(tf.square(test), 1, keep_dims=True)) + 1e-7 rnorm_support = tf.rsqrt( tf.reduce_sum(tf.square(support), 1, keep_dims=True)) + 1e-7 test_normalized = test * rnorm_test support_normalized = support * rnorm_support # Transpose for mul support_normalized_t = tf.transpose(support_normalized, perm=[1, 0]) g = tf.matmul(test_normalized, support_normalized_t) # Gram matrix return g def elu(x, alpha=1.): """Exponential linear unit. Parameters ---------- x: A tensor or variable to compute the activation function for. alpha: A scalar, slope of positive section.
tensorflow.matmul
14,384
import tensorflow as tf update_mask = tf.layers.conv2d(mask, filters=1, dilation_rate=(dilation, dilation), name='mask' + id, kernel_size=size, kernel_initializer=tf.constant_initializer(1.0),
tensorflow.constant_initializer
14,385
import tensorflow as tf x_duplicate_sample = x_duplicate.sample(name="custom_sample") self.assertEqual(x.name, "x/") self.assertEqual(y.name, "y/") # There's no notion of graph, hence the same name will be reused. # Tensors also do not have names in eager mode, so exit early. if tf.executing_eagerly(): return self.assertTrue(x_sample.name.startswith("x/custom_sample")) self.assertTrue(x_log_prob.name.startswith("x/custom_log_prob")) self.assertEqual(x_duplicate.name, "x_1/") self.assertTrue(x_duplicate_sample.name.startswith(
tensorflow.executing_eagerly
14,386
import tensorflow as tf 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.less
14,387
import tensorflow as tf # Init dual param values self.param_eta = init_eta self.param_omega = init_omega self.param_eta_non_lin = init_eta self.param_omega_non_lin = init_omega param_eta = tf.placeholder(dtype=tf.float32, shape=[], name="param_eta") param_omega = tf.placeholder(dtype=tf.float32, shape=[], name="param_omega") old_entropy = tf.placeholder(dtype=tf.float32, shape=[], name="old_entropy") varphis = tf.placeholder(dtype=tf.float32, shape=[None, None], name="varphis") Kt = tf.placeholder(dtype=tf.float32, shape=[None, None], name="Kt") prec = tf.placeholder(dtype=tf.float32, shape=[None, None], name="prec") Waa = tf.placeholder(dtype=tf.float32, shape=[None, None], name="Waa") Wsa = tf.placeholder(dtype=tf.float32, shape=[None, None], name="Wsa") wa = tf.placeholder(dtype=tf.float32, shape=[None, None], name="wa")
tensorflow.placeholder
14,388
import tensorflow as tf 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
tensorflow.ConfigProto
14,389
import tensorflow as tf def variational_expectations( Fmu, Fvar, phi, num_gauss_hermite_points=20): """ Compute the expected value of a function phi, given a Gaussian distribution for the input values. if q(f) = N(Fmu, Fvar) then this method computes \int phi(f) q(f) df. Here, we implement a default Gauss-Hermite quadrature routine """ gh_x, gh_w = hermgauss(num_gauss_hermite_points) gh_x = gh_x.reshape(1, -1) gh_w = gh_w.reshape(-1, 1) / np.sqrt(np.pi) shape = tf.shape(Fmu) Fmu, Fvar = [tf.reshape(e, (-1, 1)) for e in (Fmu, Fvar)] X = gh_x * tf.sqrt(2.0 * Fvar) + Fmu logp = phi(X) return tf.reshape(tf.matmul(logp, gh_w), shape) import tensorflow as tf def block_diagonal(matrices, dtype=tf.float32): """Constructs block-diagonal matrices from a list of batched 2D tensors. Args: matrices: A list of Tensors with shape [..., N_i, M_i] (i.e. a list of matrices with the same batch dimension). dtype: Data type to use. The Tensors in `matrices` must match this dtype.
tensorflow.reshape
14,390
import tensorflow as tf self.b,data_format='NHWC',name=name) def get_variables(self): return {'w':self.w,'b':self.b} class WeightNormSymPadConv2d(object): #Resize and Convolution(upsacle by 2) def __init__(self,name,input_dim,output_dim, k_h=3,k_w=3,stddev=0.02) : assert k_h%2==1 and k_w%2==1, 'kernel size should be odd numbers to ensure exact size' with tf.variable_scope(name) : self.conv2d = WeightNormConv2d('conv',input_dim,output_dim,k_h,k_w,1,1,data_format='NHWC',padding='VALID') self.padding = [ [0,0],[k_h//2,k_h//2],[k_w//2,k_w//2],[0,0] ] def __call__(self,input_var,name=None,**kwargs): _,h,w,c = input_var.shape.as_list() _t = tf.image.resize_nearest_neighbor(input_var, [h*2, w*2]) _t = tf.pad(_t,self.padding, mode='SYMMETRIC')
tensorflow.variable_scope
14,391
import tensorflow as tf np.log(1. - sm_normal.cdf(1)), qdist.log_prob(2.).eval(), atol=0) def test_log_prob_and_grad_gives_finite_results(self): with self.test_session(): for dtype in [np.float32, np.float64]: mu = tf.Variable(0., name="mu", dtype=dtype) sigma = tf.Variable(1., name="sigma", dtype=dtype) qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, mu=mu, sigma=sigma) x = np.arange(-100, 100, 2).astype(dtype) tf.initialize_all_variables().run()
tensorflow.Variable
14,392
import tensorflow as tf x = tf.to_float(x) y = tf.to_float(y) z = tf.to_float(z) depth_f = tf.to_float(depth) height_f = tf.to_float(height) width_f = tf.to_float(width)
tensorflow.to_float
14,393
from tensorflow.python.framework import ops """Moves a list of tensors to a device by concatenating/splitting them.""" # Reset the device setting to avoid weird interactions with device merging # logic. with ops.device(None): if all(tensor.shape == tensor_shape.scalar() for tensor in tensors): with ops.device(tensors[0].device):
tensorflow.python.framework.ops.device
14,394
import tensorflow as tf ema = tf.train.ExponentialMovingAverage(decay=0.9) def mean_var_with_update(): ema_apply_op = ema.apply([batch_mean, batch_var]) with tf.control_dependencies([ema_apply_op]): return tf.identity(batch_mean), tf.identity(batch_var) mean, var = tf.cond(b_train,
tensorflow.control_dependencies
14,395
import tensorflow as tf num_decoder_symbols=5, embedding_size=2, output_projection=(w, b)) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 2), res[0].shape) # Test that previous-feeding model ignores inputs after the first. dec_inp2 = [tf.constant(0, tf.int32, shape=[2]) for _ in range(3)] with tf.variable_scope("other"): d3, _ = tf.nn.seq2seq.embedding_attention_seq2seq( enc_inp, dec_inp2, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, feed_previous=tf.constant(True)) sess.run([tf.global_variables_initializer()]) tf.get_variable_scope().reuse_variables() d1, _ = tf.nn.seq2seq.embedding_attention_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, feed_previous=True) d2, _ = tf.nn.seq2seq.embedding_attention_seq2seq( enc_inp, dec_inp2, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, feed_previous=True) res1 = sess.run(d1) res2 = sess.run(d2) res3 = sess.run(d3) self.assertAllClose(res1, res2) self.assertAllClose(res1, res3)
tensorflow.global_variables_initializer
14,396
import tensorflow as tf word_t_representation = self.embedding_lookup(word_t) (state_t, context_t, coverage_t, attn_dist_t, p_gen_t, output_t) = self.one_step_decoder( state_t_1, context_t_1, coverage_t_1, word_t_representation, encoder_states, encoder_features, passage_word_idx, passage_mask, v, w_c, word_vocab) vocab_scores = tf.log(output_t) greedy_prediction = tf.reshape(tf.argmax(output_t, 1),[-1]) # calcualte greedy multinomial_prediction = tf.reshape(tf.multinomial(vocab_scores, 1),[-1]) # calculate multinomial topk_log_probs, topk_ids = tf.nn.top_k(vocab_scores, beam_size) # calculate topK return (state_t, context_t, coverage_t, attn_dist_t, p_gen_t, output_t, topk_log_probs, topk_ids,
tensorflow.log
14,397
import tensorflow as tf @dynamic_batching.batch_fn def f(a): return a f(tf.constant([1])) # Intentionally using tf.Session() instead of self.test_session() to have # control over closing the session. test_session() is a cached session. with tf.Session(): coord = tf.train.Coordinator() tf.train.start_queue_runners(coord=coord) time.sleep(_SLEEP_TIME) coord.request_stop() # Calls close operation. coord.join() # Session closed. def test_minimum_batch_size(self): with self.test_session() as session: @dynamic_batching.batch_fn_with_options( minimum_batch_size=2, timeout_ms=1000)
tensorflow.train.start_queue_runners
14,398
import tensorflow as tf except ValueError: # auto_reuse doesn't work with LSTM cells output, new_state = get_cell(input_size, reuse=True)(input_, state) if decoder.skip_update and decoder.pred_edits and symbol is not None: is_del = tf.equal(symbol, utils.DEL_ID) new_state = tf.where(is_del, state, new_state) if decoder.cell_type.lower() == 'lstm' and decoder.use_lstm_full_state: output = new_state
tensorflow.where
14,399