seed
stringlengths
25
2.89k
seed_api
stringlengths
14
102
index
int64
0
14.8k
import tensorflow as tf def testProblemHparamsTargetOnlyModality(self): class TargetOnlyProblem(problem_module.Problem): def hparams(self, defaults, model_hparams): hp = defaults hp.modality = {"targets": modalities.SymbolModality} hp.vocab_size = {"targets": 3} problem = TargetOnlyProblem(False, False) p_hparams = problem.get_hparams() self.assertIsInstance(p_hparams.modality["targets"], modalities.SymbolModality) self.assertLen(p_hparams.modality, 1) if __name__ == "__main__": tf.test.main()
tensorflow.test.main
1,800
import tensorflow as tf with tf.variable_scope(self.name): # ------------------ all inputs ------------------------ self.S = tf.placeholder(tf.float32, [None, self.num_global_s], name='S') # input Global State self.s = tf.placeholder(tf.float32, [None, self.num_s], name='s1') # input state for agent1 self.S_ = tf.placeholder(tf.float32, [None, self.num_global_s], name='S_') # input Next Global State self.s_ = tf.placeholder(tf.float32, [None, self.num_s], name='s1_') # input next state for agent1
tensorflow.placeholder
1,801
from tensorflow.contrib.learn.python.learn.estimators import run_config model.evaluate(input_fn=_ranking_train_input_fn, steps=1) model.predict(input_fn=_infer_ranking_train_input_fn) class CoreGradientBoostedDecisionTreeEstimator(test_util.TensorFlowTestCase): def testTrainEvaluateInferDoesNotThrowError(self): head_fn = head_lib._binary_logistic_head_with_sigmoid_cross_entropy_loss( loss_reduction=losses.Reduction.SUM_OVER_NONZERO_WEIGHTS) learner_config = learner_pb2.LearnerConfig() learner_config.num_classes = 2 learner_config.constraints.max_tree_depth = 1 model_dir = tempfile.mkdtemp() config = run_config.RunConfig() est = estimator.CoreGradientBoostedDecisionTreeEstimator( head=head_fn, learner_config=learner_config, num_trees=1, examples_per_layer=3, model_dir=model_dir, config=config, feature_columns=[core_feature_column.numeric_column("x")]) # Train for a few steps. est.train(input_fn=_train_input_fn, steps=1000) est.evaluate(input_fn=_eval_input_fn, steps=1)
tensorflow.contrib.learn.python.learn.estimators.run_config.RunConfig
1,802
import tensorflow as tf if self.config["use_features"]: span_width_index = span_width - 1 # [k] span_width_emb = tf.gather(tf.get_variable("span_width_embeddings", [self.config["max_span_width"], self.config["feature_size"]]), span_width_index) # [k, emb] span_width_emb = tf.nn.dropout(span_width_emb, self.dropout) span_emb_list.append(span_width_emb) if self.config["model_heads"]: span_indices = tf.expand_dims(tf.range(self.config["max_span_width"]), 0) + tf.expand_dims(span_starts, 1) # [k, max_span_width] span_indices = tf.minimum(util.shape(context_outputs, 0) - 1, span_indices) # [k, max_span_width] span_text_emb = tf.gather(head_emb, span_indices) # [k, max_span_width, emb] with tf.variable_scope("head_scores"): self.head_scores = util.projection(context_outputs, 1) # [num_words, 1] span_head_scores = tf.gather(self.head_scores, span_indices) # [k, max_span_width, 1] span_mask = tf.expand_dims(tf.sequence_mask(span_width, self.config["max_span_width"], dtype=tf.float32), 2) # [k, max_span_width, 1] span_head_scores += tf.log(span_mask) # [k, max_span_width, 1] span_attention = tf.nn.softmax(span_head_scores, 1) # [k, max_span_width, 1] span_head_emb = tf.reduce_sum(span_attention * span_text_emb, 1) # [k, emb] span_emb_list.append(span_head_emb) span_emb = tf.concat(span_emb_list, 1) # [k, emb] return span_emb # [k, emb] def get_mention_scores(self, span_emb): with tf.variable_scope("mention_scores"): return util.ffnn(span_emb, self.config["ffnn_depth"], self.config["ffnn_size"], 1, self.dropout) # [k, 1] def softmax_loss(self, antecedent_scores, antecedent_labels):
tensorflow.sequence_mask
1,803
import tensorflow as tf # Embedding variables entity_var_shape = [entity_cnt, self.embedding_size] rel_var_shape = [rel_cnt, self.embedding_size] entity_init = tf.truncated_normal(entity_var_shape, stddev=init_sd) rel_init = tf.truncated_normal(rel_var_shape, stddev=init_sd) # Ensure maxnorm constraints are initially satisfied
tensorflow.truncated_normal
1,804
import tensorflow as tf 'img_raw' : tf.FixedLenFeature([], tf.string), }) image=tf.decode_raw(features['img_raw'],tf.uint8) label=tf.cast(features['label'],tf.int32) image=tf.reshape(image,[4096,1]) return image,label def get_batch(image,label,batch_size,crop_size): #print(image.shape) #print(label.shape) images,labels=tf.train.shuffle_batch([image,label], batch_size=batch_size,num_threads=10,capacity=10000,min_after_dequeue=200) return tf.reshape(images,[batch_size,4096]),tf.reshape(labels,[batch_size]) def get_test_batch(image,label,batch_size): images,labels=tf.train.batch([image,label],batch_size=batch_size) return tf.reshape(images,[batch_size,4096]),tf.reshape(labels,[batch_size]) def get_valid_batch(image,label,batch_size): images,labels=tf.train.batch([image,label],batch_size=batch_size) return tf.reshape(images,[batch_size,4096]),tf.reshape(labels,[batch_size]) class trainwork(object): def __init__(self):
tensorflow.reshape
1,805
import tensorflow as tf grl = fc(grl, 100, True, None, activation=relu, name='fc1') logits = fc(grl, 1, True, None, activation=None, name='fc2') domain_predictions = tf.sigmoid(logits) domain_loss = tf.losses.log_loss(domain_selection_mask, domain_predictions, weights=weight) domain_accuracy = util.accuracy_tf(domain_selection_mask, tf.round(domain_predictions)) assert_op = tf.Assert(tf.is_finite(domain_loss), [domain_loss]) with tf.control_dependencies([assert_op]): tag_loss = 'losses/domain_loss' barrier = tf.no_op(tag_loss) return domain_loss def difference_loss(private_samples, shared_samples, weight=1.0, name='difference_loss'): """Adds the difference loss between the private and shared representations. Args: private_samples: a tensor of shape [num_samples, num_features]. shared_samples: a tensor of shape [num_samples, num_features]. weight: the weight of the incoherence loss. name: the name of the tf summary.
tensorflow.no_op
1,806
import tensorflow as tf self._subset(files, [1])) self.assertEqual(set(tf.matching_files(pattern % '?').eval()), self._subset(files, [0, 1, 3, 4])) self.assertEqual(set(tf.matching_files(pattern % '*').eval()), self._subset(files, [0, 1, 2, 3, 4, 5])) self.assertEqual(set(tf.matching_files(pattern % '[cxz]').eval()), self._subset(files, [0, 1])) self.assertEqual(set(tf.matching_files(pattern % '[0-9]').eval()), self._subset(files, [3, 4]))
tensorflow.matching_files
1,807
from tensorflow.python.ops import array_ops result is undefined. When `False`, an exception is raised if one or more of the statistic's batch members are undefined. name: `String` name prefixed to Ops created by this class. """ parameters = locals() with ops.name_scope(name, values=[rate]) as ns: with ops.control_dependencies([check_ops.assert_positive(rate)] if validate_args else []): self._rate = array_ops.identity(rate, name="rate") super(Poisson, self).__init__( dtype=self._rate.dtype, is_continuous=False, reparameterization_type=distribution.NOT_REPARAMETERIZED, validate_args=validate_args, allow_nan_stats=allow_nan_stats, parameters=parameters,
tensorflow.python.ops.array_ops.identity
1,808
import tensorflow as tf self.saver = tf.train.Saver() def train_network(self): self.learning_rate = tf.placeholder(tf.float32) self.d_optimizer = tf.train.AdamOptimizer(self.learning_rate,beta1=self.beta1,beta2=self.beta2).minimize(self.discriminator_loss,var_list=self.d_variables) self.g_optimizer = tf.train.AdamOptimizer(self.learning_rate,beta1=self.beta1,beta2=self.beta2).minimize(self.generator_loss,var_list=self.g_variables) self.init_op = tf.global_variables_initializer() self.sess = tf.Session() self.sess.run(self.init_op)
tensorflow.train.AdamOptimizer
1,809
from tensorflow.python.framework import ops ops.RegisterShape("IsInf")(common_shapes.unchanged_shape) ops.RegisterShape("IsNan")(common_shapes.unchanged_shape) ops.RegisterShape("Log")(common_shapes.unchanged_shape) ops.RegisterShape("LogicalNot")(common_shapes.unchanged_shape)
tensorflow.python.framework.ops.RegisterShape
1,810
import tensorflow as tf def assign_lr(self, session, lr_value): session.run(self._lr_update, feed_dict={self._new_lr: lr_value}) def export_ops(self, name): """Exports ops to collections.""" self._name = name ops = {util.with_prefix(self._name, "cost"): self._cost} if self._is_training: ops.update(lr=self._lr, new_lr=self._new_lr, lr_update=self._lr_update) if self._rnn_params: ops.update(rnn_params=self._rnn_params) for name, op in ops.iteritems(): tf.add_to_collection(name, op) self._initial_state_name = util.with_prefix(self._name, "initial") self._final_state_name = util.with_prefix(self._name, "final") util.export_state_tuples(self._initial_state, self._initial_state_name) util.export_state_tuples(self._final_state, self._final_state_name) def import_ops(self): """Imports ops from collections.""" if self._is_training: self._train_op = tf.get_collection_ref("train_op")[0] self._lr = tf.get_collection_ref("lr")[0] self._new_lr = tf.get_collection_ref("new_lr")[0]
tensorflow.add_to_collection
1,811
import tensorflow as tf w_c: [1,1, attention_vec_size] coverage: [batch_size, passage_len] ''' with variable_scope.variable_scope("Attention"): # Equation (11) in the paper state_features = linear(decoder_state, attention_vec_size, True) # [batch_size, attention_vec_size] state_features = tf.expand_dims(state_features, 1) # [batch_size, 1, attention_vec_size] all_features = encoder_features + state_features # [batch_size,passage_len,attention_vec_size] if use_coverage and coverage is not None: coverage_features = tf.expand_dims(coverage, axis=-1) * w_c # [batch_size, passage_len, attention_vec_size] all_features += coverage_features e = tf.reduce_sum(v * tf.tanh(all_features), axis=-1) # [batch_size, passage_len] attn_dist = nn_ops.softmax(e) # [batch_size, passage_len] attn_dist *= passage_mask if coverage is not None: # Update coverage vector coverage += attn_dist else: # first step of training
tensorflow.expand_dims
1,812
import tensorflow as tf masked_lm_positions=masked_lm_positions, masked_lm_ids=masked_lm_labels) features.append(feature) i += mask_count return features def parse_result(result, all_tokens, output_file=None): with tf.gfile.GFile(output_file, "w") as writer: tf.logging.info("***** Predict results *****") i = 0 sentences = [] for word_loss in result: # start of a sentence if all_tokens[i] == "[CLS]": sentence = {}
tensorflow.gfile.GFile
1,813
import tensorflow as tf export_feat_tensors[layer_name] = last_layer dnn_output = last_layer dnn_output_size = last_layer_size # Logistic regression with tf.variable_scope('logit') as scope: logit_w = tf.get_variable('W', shape=[dnn_output_size, 1], initializer=tf.truncated_normal_initializer(stddev=1.0 / dnn_output_size, dtype=dtype), dtype=dtype) logit_b = tf.get_variable('b', shape=[1], initializer=tf.constant_initializer(0.0), dtype=dtype) logits = tf.squeeze(tf.nn.bias_add(tf.matmul(dnn_output, logit_w), logit_b), squeeze_dims=[1]) prediction = tf.nn.sigmoid(logits) prediction_inspect = tf.reshape(prediction, [batch_size, rnn_nunroll]) prediction_final = tf.squeeze(tf.slice(prediction_inspect, [0, rnn_nunroll - 1], [-1, 1]), squeeze_dims=[1]) print('logit: {}'.format(logits.get_shape())) # Compute loss
tensorflow.constant_initializer
1,814
import tensorflow as tf mean, var = tf.nn.moments(x, [1, 2], keep_dims=True) scale = tf.get_variable('scale',[x.get_shape()[-1]], initializer=tf.truncated_normal_initializer(mean=1.0, stddev=0.02)) offset = tf.get_variable('offset',[x.get_shape()[-1]],initializer=tf.constant_initializer(0.0)) out = scale*tf.div(x-mean, tf.sqrt(var+epsilon)) + offset return out def d_layer(layer_input,filters,f_size=4,stride=2,norm=True,name='d_layer'): """Discriminator layer""" with tf.variable_scope(name): if reuse: tf.get_variable_scope().reuse_variables() else: assert tf.get_variable_scope().reuse is False d = tf.contrib.layers.conv2d(layer_input,filters,kernel_size=f_size,stride=2, padding='SAME') if norm: d = tf.contrib.layers.batch_norm(d) d = lrelu(d,alpha=0.2) return d down1 = d_layer(image,self.df, norm=False,name='down1') #256x256 -> 128x128 #rint('down1',np.shape(down1)) down2 = d_layer(down1,self.df*2,name='down2') #128x128 -> 64x64 #rint('down2',np.shape(down2)) down3 = d_layer(down2,self.df*4,name='down3') #64x64 -> 32x32
tensorflow.get_variable_scope
1,815
import tensorflow as tf with tf.device(self._test_device): batch_size = 3 size = 10 tracker_size = 8 reducer = spinn.Reducer(size, tracker_size=tracker_size) left_in = [] right_in = [] tracking = [] for _ in range(batch_size): left_in.append(tf.random_normal((1, size * 2))) right_in.append(tf.random_normal((1, size * 2))) tracking.append(tf.random_normal((1, tracker_size * 2))) out = reducer(left_in, right_in, tracking=tracking) self.assertEqual(batch_size, len(out)) self.assertEqual(tf.float32, out[0].dtype) self.assertEqual((1, size * 2), out[0].shape) def testReduceTreeLSTM(self): with tf.device(self._test_device): size = 10 tracker_size = 8 reducer = spinn.Reducer(size, tracker_size=tracker_size)
tensorflow.random_normal
1,816
import tensorflow as tf # click_feature[list_size:]=[tf.expand_dims(tf.zeros_like(self.labels[i]) , -1) for _ in range(3*list_size)] click_feature[list_size:list_size+i] =[tf.expand_dims(self.labels[k] , -1) for k in range(i-1,-1,-1)] click_feature[2*list_size:2*list_size+i+1]=[tf.expand_dims(self.types[k] , -1) for k in range(i,-1,-1)] click_feature[3*list_size:3*list_size+list_size-i-1]=[tf.expand_dims(self.types[k] , -1) for k in range(i+1,list_size)] # Predict propensity with a simple network output_propensity_list.append(propensity_network(tf.concat(click_feature, 1), i))
tensorflow.expand_dims
1,817
from tensorflow.contrib import framework as contrib_framework time.sleep(sleep_secs) # Device allocation device_fn = device_fn or self._device_fn with ops.Graph().as_default() as g, g.device(device_fn): random_seed.set_random_seed(self._config.tf_random_seed) global_step = contrib_framework.create_global_step(g) features, targets = input_fn() self._check_inputs(features, targets) train_op, loss_op = self._get_train_ops(features, targets) return train( graph=g, output_dir=self._model_dir,
tensorflow.contrib.framework.create_global_step
1,818
import tensorflow as tf out = tf.gradients(Omega, self.W_rec)
tensorflow.gradients
1,819
import tensorflow as tf opti=work.optimer(loss,learnrate) test_image_batch,test_label_batch=get_test_batch(test_image,test_label,testnum) test_inf=work.test_inference(test_image_batch) test_labels=tf.one_hot(test_label_batch,classnum) test_pre = tf.reshape(test_inf, [testnum, classnum]) correct_prediction=tf.equal(tf.argmax(test_inf,1),tf.argmax(test_labels,1)) accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) test_pre = tf.argmax(test_pre, 1) test_true = tf.argmax(test_labels, 1) valid_image_batch,valid_label_batch=get_valid_batch(valid_image,valid_label,validnum) valid_inf=work.valid_inference(valid_image_batch) valid_labels=tf.one_hot(valid_label_batch,classnum) #train_step=tf.train.GradientDescentOptimizer(0.001).minimize(cross_entropy) valid_pre = tf.reshape(valid_inf, [validnum, classnum]) valid_correct_prediction=tf.equal(tf.argmax(valid_inf,1),tf.argmax(valid_labels,1)) valid_accuracy=tf.reduce_mean(tf.cast(valid_correct_prediction,tf.float32))
tensorflow.argmax
1,820
import tensorflow as tf tf.train.Saver().save(sess, path) tf.train.Saver().save(sess, path)
tensorflow.train.Saver
1,821
import tensorflow as tf return True else: return self._optimistic_restore_model(sess) def _optimistic_restore_model(self, sess): """ restore weights of same names with model. :param sess: :return: """ if self.restore_ckpt_file is None: logger.warn(Color.yellow('No ckpt file for restore vars, ckpt file is None')) return False reader = tf.train.NewCheckpointReader(self.restore_ckpt_file) saved_shapes = reader.get_variable_to_shape_map() if self._var_list is None: restore_key2vars = {var.name.split(':')[0]: var for var in tf.global_variables()} elif isinstance(self._var_list, list): restore_key2vars = {var.name.split(':')[0]: var for var in self._var_list} elif isinstance(self._var_list, dict): restore_key2vars = self._var_list else: raise RuntimeError('type error {}'.format(self._var_list)) assert len(restore_key2vars) > 0 restore_key2vars = sorted([(k, v) for k, v in restore_key2vars.items() if k in saved_shapes]) msg = []
tensorflow.train.NewCheckpointReader
1,822
import tensorflow as tf predict = tf.placeholder(tf.float32,shape=[hps.batch_size, 10]) logit_nor,tsne_logit_nor = model_carlini_adv.predict(image,tsne_logits=True) logit_adv,tsne_logit_adv = model_carlini_adv.predict(adv_image,tsne_logits=True) predict_nor = tf.nn.softmax(logit_nor) predict_adv = tf.nn.softmax(logit_adv) # Calculate entropy argmax_y_onehot = tf.one_hot(tf.argmax(predict, 1), 10, on_value=0.0, off_value=1.0, axis=-1) normalized_y_nonmaximal = tf.reduce_sum(predict * argmax_y_onehot, 1) entropy = tf.reduce_sum(-tf.log(predict) * predict * argmax_y_onehot,1) / normalized_y_nonmaximal + tf.log(normalized_y_nonmaximal) for k in range(1): result_dict = loadmat('kernel_para_'+FLAGS.dataset+'/kernel1000_for_attack_' + f1 + '.mat') result_dict_median = loadmat('kernel_para_'+FLAGS.dataset+'/kernel1000_median_for_attack_' + f1 + '.mat')
tensorflow.argmax
1,823
import tensorflow as tf if num_classes == 2: q = tf.nn.sigmoid(q_logits)
tensorflow.nn.sigmoid
1,824
import tensorflow as tf return grid def _transform(theta, input_dim, out_size, z_near, z_far): with tf.variable_scope('_transform'): num_batch = input_dim.get_shape().as_list()[0] num_channels = input_dim.get_shape().as_list()[4] theta = tf.reshape(theta, (-1, 4, 4)) theta = tf.cast(theta, 'float32') out_depth = out_size[0] out_height = out_size[1] out_width = out_size[2] grid = _meshgrid(out_depth, out_height, out_width, z_near, z_far) grid = tf.expand_dims(grid, 0) grid = tf.reshape(grid, [-1]) grid = tf.tile(grid, tf.stack([num_batch])) grid = tf.reshape(grid, tf.stack([num_batch, 4, -1])) # Transform A x (x_t', y_t', 1, d_t)^T -> (x_s, y_s, z_s, 1). t_g = tf.matmul(theta, grid) z_s = tf.slice(t_g, [0, 0, 0], [-1, 1, -1]) y_s = tf.slice(t_g, [0, 1, 0], [-1, 1, -1]) x_s = tf.slice(t_g, [0, 2, 0], [-1, 1, -1]) z_s_flat = tf.reshape(z_s, [-1]) y_s_flat = tf.reshape(y_s, [-1]) x_s_flat = tf.reshape(x_s, [-1])
tensorflow.reshape
1,825
import tensorflow as tf analyzer_nodes.TensorInfo( tf.as_dtype(self._output_numpy_dtype), self._output_shape, None) ] * 2 else: return [ analyzer_nodes.TensorInfo( tf.as_dtype(np.int64), self._output_shape, None), analyzer_nodes.TensorInfo( tf.as_dtype(self._output_numpy_dtype), self._output_shape, None), analyzer_nodes.TensorInfo( tf.as_dtype(self._output_numpy_dtype), self._output_shape, None), analyzer_nodes.TensorInfo( tf.as_dtype(self._output_numpy_dtype), self._output_shape, None) ] def _combine_mean_and_var_accumulators(
tensorflow.as_dtype
1,826
import tensorflow as tf stride=1, init_scale=np.sqrt(2))) nh = np.prod([v.value for v in c3.get_shape()[1:]]) h3 = tf.reshape(c3, [-1, nh]) pre_s = tf.nn.relu(self.fc(h3, 'fc1', nh=512, init_scale=np.sqrt(2))) l1 = tf.layers.dense(inputs=pre_s, units=200, # number of hidden units activation=tf.nn.relu, name='l1', trainable=trainable ) mu = 2 * tf.layers.dense(inputs=l1, units=action_dim, # number of hidden units activation=tf.nn.tanh, name='mu', trainable=trainable ) sigma = tf.layers.dense(inputs=l1, units=action_dim, # output units activation=tf.nn.softplus, # get action probabilities name='sigma', trainable=trainable ) norm_dist = tf.distributions.Normal(loc=mu, scale=sigma) params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=name)
tensorflow.layers.dense
1,827
import tensorflow as tf with tf.device(device): (chars, length) = (tf.identity(chars), tf.identity(length)) chars = tf.expand_dims(chars, 0) length = tf.expand_dims(length, 0) preds = tf.unstack(model((chars, length), training=False)[0])
tensorflow.expand_dims
1,828
from tensorflow.python.framework import tensor_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) for reduction_index in reduction_indices:
tensorflow.python.framework.tensor_shape.unknown_shape
1,829
import tensorflow as tf def construct_placeholders(edge_types): placeholders = { 'batch': tf.placeholder(tf.int32, name='batch'), 'batch_neg': tf.placeholder(tf.int32, name='batch_neg'), 'batch_node':tf.placeholder(tf.int32,name = 'batch_node'), 'adj_min_batch': tf.placeholder(tf.float32,name='adj_min_batch'), 'sim_min_batch': tf.placeholder(tf.float32,name='sim_min_batch'), 'batch_edge_type_idx': tf.placeholder(tf.int32, shape=(), name='batch_edge_type_idx'), 'batch_row_edge_type': tf.placeholder(tf.int32, shape=(), name='batch_row_edge_type'), 'batch_col_edge_type': tf.placeholder(tf.int32, shape=(), name='batch_col_edge_type'), 'degrees': tf.placeholder(tf.int32), 'dropout': tf.placeholder_with_default(0., shape=()), } placeholders.update({ 'adj_mats_%d,%d,%d' % (i, j, k): tf.sparse_placeholder(tf.float32) for i, j in edge_types for k in range(edge_types[i,j])}) placeholders.update({ 'feat_%d' % i: tf.sparse_placeholder(tf.float32) for i, _ in edge_types}) return placeholders ########################################################### test_size = 0.20 val_size = 0.05 num_drugs = 2926 n_drugdrug_rel_types =11
tensorflow.sparse_placeholder
1,830
import tensorflow as tf self.is_training_pl = tf.placeholder(tf.bool, shape=(), name='is_training_pl') self.bn_decay = train_rotation_prediction.get_bn_decay(batch) self.get_pred = partial(self.model_pred.get_model, is_training=self.is_training_pl, bn_decay=self.bn_decay, num_angles=self.num_angles, use_input_trans=self.use_input_trans, use_feature_trans=self.use_feature_trans) self.get_loss = partial(self.model_pred.get_loss, use_trans_loss=self.use_trans_loss) with tf.variable_scope(name): self.noise = tf.placeholder(tf.float32, shape=[self.batch_size, self.noise_dim], name='noise') # Noise vector. self.real_pc = tf.placeholder(tf.float32, shape=[self.batch_size] + self.n_output, name='real_pc') # Ground-truth. with tf.variable_scope('rotation'): self.rot_label_pl = tf.placeholder(tf.int32, shape=self.batch_size, name='rot_label_pl') self.real_pc_rotated = self.rotate_n_angles(self.real_pc, self.rot_label_pl) self.real_pc_pred, real_pc_end_points = self.get_pred(self.real_pc_rotated) self.real_pc_rot_loss = self.get_loss(self.real_pc_pred, self.rot_label_pl, real_pc_end_points) with tf.variable_scope('generator'): self.generator_out = self.generator(self.noise, self.n_output, **gen_kwargs) self.gen_out_rotated = self.rotate_n_angles(self.generator_out, self.rot_label_pl) self.gen_out_pred, gen_out_end_points = self.get_pred(self.gen_out_rotated)
tensorflow.placeholder
1,831
from tensorflow.contrib.rnn import BasicLSTMCell, RNNCell, DropoutWrapper, MultiRNNCell noise_shape = [1, size] if decoder.pervasive_dropout else [tf.shape(input_)[0], size] embedded_input = tf.nn.dropout(embedded_input, keep_prob=decoder.embedding_keep_prob, noise_shape=noise_shape) return embedded_input def get_cell(input_size=None, reuse=False): cells = [] for j in range(decoder.layers): input_size_ = input_size if j == 0 else cell_output_size if decoder.cell_type.lower() == 'lstm': cell = CellWrapper(BasicLSTMCell(decoder.cell_size, reuse=reuse)) elif decoder.cell_type.lower() == 'plstm': cell = PLSTM(decoder.cell_size, reuse=reuse, fact_size=decoder.lstm_fact_size, proj_size=decoder.lstm_proj_size) elif decoder.cell_type.lower() == 'dropoutgru': cell = DropoutGRUCell(decoder.cell_size, reuse=reuse, layer_norm=decoder.layer_norm, input_size=input_size_, input_keep_prob=decoder.rnn_input_keep_prob, state_keep_prob=decoder.rnn_state_keep_prob) else: cell = GRUCell(decoder.cell_size, reuse=reuse, layer_norm=decoder.layer_norm) if decoder.use_dropout and decoder.cell_type.lower() != 'dropoutgru': cell = DropoutWrapper(cell, input_keep_prob=decoder.rnn_input_keep_prob,
tensorflow.contrib.rnn.BasicLSTMCell
1,832
import tensorflow as tf xs = x.get_shape().as_list() if pad=='SAME': target_shape = [tf.shape(x)[0], xs[1]*stride[0], xs[2]*stride[1], num_filters] else: target_shape = [tf.shape(x)[0], xs[1]*stride[0] + filter_size[0]-1, xs[2]*stride[1] + filter_size[1]-1, num_filters] with tf.variable_scope(scope): V = tf.get_variable("V", shape=list(filter_size) + [num_filters, int(x.get_shape()[-1])], dtype=tf.float32, initializer=tf.random_normal_initializer(0, 0.05), trainable=True) g = tf.get_variable("g", shape=[num_filters], dtype=tf.float32, initializer=tf.constant_initializer(1.), trainable=True) b = tf.get_variable("b", shape=[num_filters], dtype=tf.float32, initializer=bias_initializer, trainable=True) def maybe_avg(v): if ema is not None and not init: v = tf.cond(training, lambda: v, lambda: ema.average(v)) return v if init: x = tf.nn.conv2d_transpose(x, tf.nn.l2_normalize(V.initialized_value(), [0, 1, 3]), target_shape, [1] + list(stride) + [1], padding=pad)
tensorflow.get_variable
1,833
import tensorflow as tf # strides = [2, 0, 2, 2, 2] tf.add_to_collection('debug_layers', self.x_preprocessed)
tensorflow.add_to_collection
1,834
import tensorflow as tf outputs = { 'foo': tf.RaggedTensor.from_row_splits( values=tf.constant([3, 1, 4, 1, 5, 9, 2, 6], tf.int64), row_splits=[0, 4, 4, 7, 8, 8]),
tensorflow.constant
1,835
import tensorflow as tf predicts=tf.nn.softmax(predicts) labels=tf.one_hot(labels,classnum) loss=-tf.reduce_sum(labels*tf.log(predicts)) return loss
tensorflow.log
1,836
import tensorflow as tf elif mode == tf.estimator.ModeKeys.PREDICT: print(logits.get_shape(), "===logits shape===") pred_label = tf.argmax(logits, axis=-1, output_type=tf.int32) prob = tf.nn.softmax(logits)
tensorflow.argmax
1,837
import tensorflow as tf stddev=1e-2, strides=[1, 1, 1, 1], padding="SAME", nonlinearity=None, bias=False, weight_norm=False, scale=False): """Convolutional layer.""" with tf.variable_scope(name) as scope: weights = variable_on_cpu( "weights", filter_size + [dim_in, dim_out], tf.random_uniform_initializer( minval=-stddev, maxval=stddev)) # weight normalization if weight_norm: weights /= tf.sqrt(tf.reduce_sum(tf.square(weights), [0, 1, 2])) if scale: magnitude = variable_on_cpu( "magnitude", [dim_out], tf.constant_initializer( stddev * numpy.sqrt(dim_in * numpy.prod(filter_size) / 12.))) weights *= magnitude res = input_
tensorflow.random_uniform_initializer
1,838
import tensorflow as tf filename_queue=tf.train.string_input_producer([path]) reader=tf.TFRecordReader() _,serialized_example=reader.read(filename_queue) features=tf.parse_single_example(serialized_example, features={ 'label':tf.FixedLenFeature([], tf.int64), 'img_raw' : tf.FixedLenFeature([], tf.string), }) image=tf.decode_raw(features['img_raw'],tf.uint8) label=tf.cast(features['label'],tf.int32)
tensorflow.FixedLenFeature
1,839
from tensorflow.python.ops import math_ops Returns: The specificity using the aggregated values. """ sensitivities = math_ops.div(tp, tp + fn + kepsilon) # We'll need to use this trick until tf.argmax allows us to specify # whether we should use the first or last index in case of ties. min_val = math_ops.reduce_min(math_ops.abs(sensitivities - sensitivity)) indices_at_minval = math_ops.equal( math_ops.abs(sensitivities - sensitivity), min_val) indices_at_minval = math_ops.to_int64(indices_at_minval) indices_at_minval = math_ops.cumsum(indices_at_minval) tf_index = math_ops.argmax(indices_at_minval, 0) tf_index = math_ops.cast(tf_index, dtypes.int32) # Now, we have the implicit threshold, so compute the specificity: return math_ops.div(tn[tf_index], tn[tf_index] + fp[tf_index] + kepsilon, name)
tensorflow.python.ops.math_ops.abs
1,840
from tensorflow.python.ops import array_ops 0, (array_ops.slice(tensor.shape, [0], expand_dims), [1], array_ops.slice(tensor.shape, expand_dims, [-1])), name='expanded_shape') expanded = sparse_ops.sparse_reshape( tensor, shape=expanded_shape, name='expand') if multiple == 1: return expanded return sparse_ops.sparse_concat( dim - 1 if dim < 0 else dim, [expanded] * multiple, name=scope) # Dense. expanded = array_ops.expand_dims( tensor, dim if (dim >= 0) else (dim - 1), name='expand') if multiple == 1: return expanded ones = array_ops.ones_like(array_ops.shape(tensor)) tile_multiples = array_ops.concat( 0, (ones[:dim], (multiple,), ones[dim:]), name='multiples') return array_ops.tile(expanded, tile_multiples, name=scope) def sparse_average_precision_at_k(predictions, labels, k):
tensorflow.python.ops.array_ops.expand_dims
1,841
import tensorflow as tf else: act_f = build_act(make_obs_ph, q_func, num_actions, scope=scope, reuse=reuse) with tf.variable_scope(scope, reuse=reuse): # set up placeholders obs_t_input = make_obs_ph("obs_t")
tensorflow.variable_scope
1,842
from tensorflow.contrib.rnn.python.ops import lstm_ops (config_name, self._GetConfigDesc(config))) def benchmarkTfRNNLSTMBlockCellTraining(self): test_configs = self._GetTestConfig() for config_name, config in test_configs.items(): num_layers = config["num_layers"] 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"): inputs = seq_length * [ array_ops.zeros([batch_size, num_units], dtypes.float32) ] cell = lambda: lstm_ops.LSTMBlockCell(num_units=num_units) # pylint: disable=cell-var-from-loop multi_cell = rnn_cell.MultiRNNCell( [cell() for _ in range(num_layers)]) outputs, final_state = core_rnn.static_rnn( multi_cell, inputs, dtype=dtypes.float32) trainable_variables = ops.get_collection( ops.GraphKeys.TRAINABLE_VARIABLES) gradients = gradients_impl.gradients([outputs, final_state], trainable_variables) training_op = control_flow_ops.group(*gradients) self._BenchmarkOp(training_op, "tf_rnn_lstm_block_cell %s %s" % (config_name, self._GetConfigDesc(config)))
tensorflow.contrib.rnn.python.ops.lstm_ops.LSTMBlockCell
1,843
import tensorflow as tf # patches = tf.gather(patches, rand_idx, axis=0) rows = tf.split(patches,n_col//self.size,axis=0) rows = [tf.concat(tf.unstack(x),axis=1) for x in rows] x_aug = tf.concat(rows,axis=0) x_aug = tf.convert_to_tensor(x_aug) return tf.concat([x, x_aug],axis=2) def mix_scramble(self,x): # assume square patch
tensorflow.convert_to_tensor
1,844
import tensorflow as tf """ sum_grads = [] for grad_and_vars in zip(*clone_grads): # Note that each grad_and_vars looks like the following: # ((grad_var0_clone0, var0), ... (grad_varN_cloneN, varN)) grads = [] var = grad_and_vars[0][1] for g, v in grad_and_vars: assert v == var if g is not None: grads.append(g) if grads: if len(grads) > 1: sum_grad = tf.add_n(grads, name=var.op.name + '/sum_grads') else: sum_grad = grads[0] sum_grads.append((sum_grad, var)) return sum_grads def _add_gradients_summaries(grads_and_vars): """Add histogram summaries to gradients. Note: The summaries are also added to the SUMMARIES collection. Args:
tensorflow.add_n
1,845
import tensorflow as tf # First convolutional layer - maps one image to 32 feature maps. with tf.variable_scope('Conv_1'): conv1 = tf.layers.conv2d( inputs=x_image,
tensorflow.layers.conv2d
1,846
import tensorflow as tf print('feats_other: {}'.format(feats_other_nunroll.get_shape())) if mode != 'gen': targets_nunroll = tf.placeholder(dtype, shape=[batch_size, rnn_nunroll]) # TODO: tf.ones acts as an overridable placeholder but this is still awkward target_weights_nunroll = tf.ones([batch_size, rnn_nunroll], dtype) # Reshape input tensors to remove nunroll dim; will briefly restore later during RNN if necessary if cnn_rnn_zack: feats_audio = tf.reshape(feats_audio_nunroll, shape=[batch_size, rnn_nunroll + zack_hack, audio_nbands, audio_nchannels]) else: feats_audio = tf.reshape(feats_audio_nunroll, shape=[batch_size * rnn_nunroll, audio_context_len, audio_nbands, audio_nchannels]) feats_other = tf.reshape(feats_other_nunroll, shape=[batch_size * rnn_nunroll, nfeats]) if mode != 'gen': targets = tf.reshape(targets_nunroll, shape=[batch_size * rnn_nunroll]) target_weights = tf.reshape(target_weights_nunroll, shape=[batch_size * rnn_nunroll]) # CNN cnn_output = feats_audio if do_cnn: layer_last = feats_audio nfilt_last = audio_nchannels for i, ((ntime, nband, nfilt), (ptime, pband)) in enumerate(zip(cnn_filter_shapes, cnn_pool)): layer_name = 'cnn_{}'.format(i) with tf.variable_scope(layer_name): filters = tf.get_variable('filters', [ntime, nband, nfilt_last, nfilt], initializer=cnn_init, dtype=dtype) biases = tf.get_variable('biases', [nfilt], initializer=tf.constant_initializer(0.1), dtype=dtype) if cnn_rnn_zack:
tensorflow.reshape
1,847
import tensorflow as tf tf.summary.scalar('qf2_loss', qf2_loss) tf.summary.scalar('value_loss', value_loss) tf.summary.scalar("Imitation_loss",self.actor_loss_di) tf.summary.scalar('entropy', self.entropy) tf.summary.scalar('importance weight',tf.reduce_mean(self.weight_ph)) if ent_coef_loss is not None: tf.summary.scalar('ent_coef_loss', ent_coef_loss) 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())
tensorflow.reduce_mean
1,848
import tensorflow as tf Yp = tf.greater(an , 0.5) accuracy = tf.reduce_mean(tf.cast(tf.equal(Yp, tf.equal(Y,1.0)), "float")) elif actL == 'esp' or actL == 'relu': #r2 score norm= tf.reduce_mean( tf.squared_difference(Y,tf.reduce_mean(Y)) ) accuracy = 1 - tf.divide( tf.reduce_mean(tf.squared_difference(an, Y)), norm) elif actL == 'softmax': #accuracy score for multiclass classification Yp = tf.sigmoid(betan*hn) correct = tf.equal(tf.argmax(Yp), tf.argmax(Y)) accuracy= tf.reduce_mean(tf.cast(correct, "float")) #-----------------Initialize the graph and start the session------------------------------------------------- init = tf.global_variables_initializer() with tf.Session() as sess: # Run the initialization sess.run(init) jj=0
tensorflow.argmax
1,849
import tensorflow as tf # (T,B,D) => (B,T,D) facts = tf.array_ops.transpose(facts, [1, 0, 2]) # Trainable parameters 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] query = tf.layers.dense(query, facts_size, activation=None, name='f1_trans_shine' + stag) query = prelu(query) 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, facts_size, activation=tf.nn.sigmoid, name='f1_shine_att' + stag) d_layer_2_all = tf.layers.dense(d_layer_1_all, facts_size, activation=tf.nn.sigmoid, name='f2_shine_att' + stag) d_layer_2_all = tf.reshape(d_layer_2_all, tf.shape(facts)) output = d_layer_2_all return output
tensorflow.shape
1,850
import tensorflow as tf tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask])) tf.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids])) tf.logging.info("label: %s (id = %d)" % (example.label, label_id))
tensorflow.logging.info
1,851
from tensorflow.keras.layers import Dense, Conv2D, MaxPool2D, Flatten # FC layers for goal_pos input # goal_layer1 = Dense(units=GOAL_SIZE)(goal_pos) # goal_layer2 = Dense(units=GOAL_SIZE)(goal_layer1) # FC layers to find next location loc_layer1 = Dense(units=loc_layer_size)(prev_loc) loc_layer2 = Dense(units=loc_layer_size)(loc_layer1) # Concatenationation of above layers, followed by FC layer concat = tf.concat([flat1b, loc_layer2],1) # goal_layer2 h1 = Dense(units=RNN_SIZE)(concat) h2 = Dense(units=RNN_SIZE)(h1) self.h3 = tf.nn.relu(h2+concat) #Recurrent network for temporal dependencies lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(RNN_SIZE,state_is_tuple=True) c_init = np.zeros((1, lstm_cell.state_size.c), np.float32) h_init = np.zeros((1, lstm_cell.state_size.h), np.float32) state_init = [c_init, h_init] c_in = tf.placeholder(tf.float32, [1, lstm_cell.state_size.c]) h_in = tf.placeholder(tf.float32, [1, lstm_cell.state_size.h])
tensorflow.keras.layers.Dense
1,852
import tensorflow as tf _,serialized_example=reader.read(filename_queue) features=tf.parse_single_example(serialized_example, features={ 'label':tf.FixedLenFeature([], tf.int64), 'img_raw' : tf.FixedLenFeature([], tf.string), }) image=tf.decode_raw(features['img_raw'],tf.uint8) label=tf.cast(features['label'],tf.int32) image=tf.reshape(image,[4096,1]) return image,label def get_batch(image,label,batch_size,crop_size): #print(image.shape) #print(label.shape)
tensorflow.cast
1,853
import tensorflow as tf min_x = tf.cast(0.0 - labeled_sizes[i][0] / 2.0, dtype=tf.float32) max_x = tf.cast(0.0 + labeled_sizes[i][0] / 2.0, dtype=tf.float32) # min_y = tf.cast(0.0 - labeled_sizes[i][1] / 2.0, dtype=tf.float32) # max_y = tf.cast(0.0 + labeled_sizes[i][1] / 2.0, dtype=tf.float32) min_z = tf.cast(0.0 - labeled_sizes[i][2] / 2.0, dtype=tf.float32) max_z = tf.cast(0.0 + labeled_sizes[i][2] / 2.0, dtype=tf.float32) translation = tf.reshape([labeled_translations[i][0], labeled_translations[i][2]], [2, 1]) pt_0 = rot @ tf.reshape([min_x, min_z], [2, 1]) + translation pt_1 = rot @ tf.reshape([min_x, max_z], [2, 1]) + translation pt_2 = rot @ tf.reshape([max_x, min_z], [2, 1]) + translation pt_3 = rot @ tf.reshape([max_x, max_z], [2, 1]) + translation for pt in [pt_0, pt_1, pt_2, pt_3]: if pt[0] < box_limits_x[0]: box_limits_x[0] = pt[0] if pt[0] > box_limits_x[1]: box_limits_x[1] = pt[0] if pt[1] < box_limits_z[0]:
tensorflow.reshape
1,854
import tensorflow as tf loss_f = -tf.reduce_mean(gain_f) # Bias correction for the truncation adv_bc = (q_value - tf.reshape(value, [self.n_envs * self.n_steps, 1])) # [n_envs * n_steps, n_act] # check_shape([adv_bc, log_f_bc], [[self.n_envs * self.n_steps, self.n_act]] * 2)
tensorflow.reshape
1,855
import tensorflow as tf with tf.name_scope("Test"): test_input = PTBInput( config=eval_config, data=test_data, name="TestInput") with tf.variable_scope("Model", reuse=True, initializer=initializer): mtest = PTBModel(is_training=False, config=eval_config, input_=test_input) models = {"Train": m, "Valid": mvalid, "Test": mtest} for name, model in models.items(): model.export_ops(name) metagraph = tf.train.export_meta_graph() if tf.__version__ < "1.1.0" and FLAGS.num_gpus > 1: raise ValueError("num_gpus > 1 is not supported for TensorFlow versions " "below 1.1.0") soft_placement = False if FLAGS.num_gpus > 1: soft_placement = True util.auto_parallel(metagraph, m) with tf.Graph().as_default():
tensorflow.train.export_meta_graph
1,856
import tensorflow as tf centers = tf.get_variable( 'centers', [num_classes, num_features], dtype=tf.float32, initializer=tf.constant_initializer(0), trainable=False) label = tf.reshape(label, [-1]) centers_batch = tf.gather(centers, label) diff = (1 - alpha) * (centers_batch - features) centers = tf.scatter_sub(centers, label, diff) loss = tf.nn.l2_loss(features - centers_batch)
tensorflow.reshape
1,857
import tensorflow as tf convf = sc_module.direct_sparse_filter_conversion(t2ind, t2val, t2sh, t1sh) with tf.Session(config=config) as sess: pd = sess.run(convd) pf = sess.run(convf) tf.reset_default_graph() ts = 0 with tf.device("/gpu:0"): approx_scskconv = sc_module.direct_sparse_conv_kd(pd.out_indices, pd.out_values, pd.out_shape, pd.out_block_channel_mapping, pf.out_indices, pf.out_values, pf.out_shape, pf.out_channel_mapping, bias, strides, padding, out_entry_count, dim, max_density, filter_type); with tf.Session(config=config) as sess: t6 = time.time() sv3 = sess.run(approx_scskconv) t5 = time.time() for i in range(0, num_trials): sess.run(approx_scskconv) t6 = time.time() ts = abs(t6 - t5) / max(num_trials,1) print("time approx sparse: ", ts) tf.reset_default_graph()
tensorflow.Session
1,858
import tensorflow as tf assert len(input_ids) == max_seq_length assert len(input_mask) == max_seq_length assert len(segment_ids) == max_seq_length label_id = label_map[example.label] if ex_index < 5: tf.logging.info("*** Example ***") tf.logging.info("guid: %s" % (example.guid)) tf.logging.info("tokens: %s" % " ".join( [tokenization.printable_text(x) for x in tokens])) tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids])) tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask])) tf.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids])) tf.logging.info("label: %s (id = %d)" % (example.label, label_id)) feature = InputFeatures( input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, label_id=label_id, is_real_example=True) return feature def file_based_convert_examples_to_features( examples, label_list, max_seq_length, tokenizer, output_file):
tensorflow.logging.info
1,859
import tensorflow as tf correct_prediction = tf.equal(tf.argmax(pred_Y, 1), tf.argmax(Y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, dtype=tf.float32))
tensorflow.cast
1,860
import tensorflow as tf if pairwise_reduction == common.DISTANCE_REDUCTION_NEG_LOG_MEAN: return lambda x: -tf.math.log(tf.math.reduce_mean(x, axis=[-2, -1]))
tensorflow.math.reduce_mean
1,861
import tensorflow as tf class CharSeqModel(object): #formerly TweetSeqModel """ Treats each document (tweet) as a single "word," which is fed through c2v, and the output "embedding" sized to be a vector of language predictions. """ def __init__(self, out_vocab_size=None, batch_size=10, model_params=None, c2v=None, max_sequence_len=None, dropout_keep_prob=None, weights=None): self.params = model_params self._out_vocab_size = out_vocab_size # num. of languages self.weights = tf.constant(weights, dtype=tf.float32, name='class_weights') with tf.variable_scope("tweetff"): hidden = tf.get_variable("ff_hidden", [c2v.embedding_dims, out_vocab_size]) bias = tf.get_variable('ff_bias', [out_vocab_size]) #probably useless. at least I don't want to use it self.seq_lens = tf.placeholder(tf.int64, [batch_size], name='seq_lens') self.x = tf.placeholder(tf.int32, [batch_size, max_sequence_len], name='x')
tensorflow.constant
1,862
import tensorflow as tf output_1 = contrib.layers.fully_connected(dropout3_1, n_output_1, activation_fn=None, scope="output_1") output_2 = contrib.layers.fully_connected(dropout3_2, n_output_2, activation_fn=None, scope="output_2") with tf.variable_scope("loss"): loss_base_1 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_1, logits=output_1)) loss_base_2 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_2, logits=output_2)) reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) loss_total = loss_base_1 + loss_base_2 + tf.reduce_sum(reg_losses) with tf.variable_scope("evaluation"): 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.argmax
1,863
import tensorflow as tf def _do_cutout(self, image, im_width, im_height, cutout_size): mask = tf.ones([cutout_size, cutout_size], dtype=tf.int32) start_x = tf.random.uniform(shape=(1,), minval=0, maxval=im_width, dtype=tf.int32) start_y = tf.random.uniform(shape=(1,), minval=0, maxval=im_height, dtype=tf.int32) mask = tf.pad(mask, [[cutout_size + start_y[0], im_height - start_y[0]], [cutout_size + start_x[0], im_width - start_x[0]]]) mask = mask[cutout_size: cutout_size + im_height, cutout_size: cutout_size + im_width] mask = tf.tile(tf.reshape(mask, (im_height, im_width, 1)), (1, 1, 3)) image = tf.where(tf.equal(mask, 0), x=image, y=tf.zeros_like(image)) return image def _add_drop_path(self, X, keep_prob): with tf.variable_scope('drop_path'): batch_size = tf.shape(X)[0] noise_shape = (batch_size, 1, 1, 1) random_tensor = keep_prob + tf.random_uniform(noise_shape, dtype=tf.float32) binary_tensor = tf.floor(random_tensor) X = (X / keep_prob) * binary_tensor return X def _do_conv(self, X, w, h, in_ch, out_ch, filter_size=1, no_relu=False, no_reg=False, is_train=False): W = self._make_var('W', (filter_size, filter_size, in_ch, out_ch), no_reg=no_reg) if not no_relu: X = tf.nn.relu(X) X = tf.nn.conv2d(X, W, (1, 1, 1, 1), padding='SAME')
tensorflow.variable_scope
1,864
import tensorflow as tf self.assertAllEqual(labels_0_n.numpy(), expected_labels_0_n.numpy()) def test_map_labels_to_0_to_n2(self): labels = tf.constant([[-1, 1, 2], [1, 1, 2]], dtype=tf.int32) labels_0_n = isu.map_labels_to_0_to_n(labels) expected_labels_0_n = tf.constant([[-1, 0, 1], [0, 0, 1]], dtype=tf.int32) self.assertAllEqual(labels_0_n.numpy(), expected_labels_0_n.numpy()) def test_randomly_select_one_point_per_segment(self): instance_labels = tf.constant([[1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 2, 2, 2, 2, 2, 2], [1, 2, 2, 2, 2, 2, 2, 2], [0, 0, 0, 0, 2, 2, 2, 2], [0, 0, 0, 0, 2, 2, 2, 2]], dtype=tf.int32) instance_labels = tf.reshape(instance_labels, [-1]) (indices, masks_t) = isu.randomly_select_one_point_per_segment(instance_labels) masks = tf.transpose(masks_t) masks = tf.reshape(masks, [3, 5, 8])
tensorflow.constant
1,865
import tensorflow as tf else: self.c = tf.placeholder(tf.int32, [self.config.batch_size * self.max_p_num, self.config.max_p_len], "context") self.q = tf.placeholder(tf.int32, [self.config.batch_size * self.max_p_num, self.config.max_q_len], "question") self.ch = tf.placeholder(tf.int32, [self.config.batch_size * self.max_p_num, self.config.max_p_len, self.config.max_ch_len], "context_char") self.qh = tf.placeholder(tf.int32, [self.config.batch_size * self.max_p_num, self.config.max_q_len, self.config.max_ch_len], "question_char") self.start_label = tf.placeholder(tf.int32, [self.config.batch_size], "answer_label1") self.end_label = tf.placeholder(tf.int32, [self.config.batch_size], "answer_label2") self.position_emb = position_embedding(self.c, 2 * self.config.hidden_size) self.c_mask = tf.cast(self.c, tf.bool) # index 0 is padding symbol N x self.max_p_num, max_p_len self.q_mask = tf.cast(self.q, tf.bool) self.c_len = tf.reduce_sum(tf.cast(self.c_mask, tf.int32), axis=1) self.q_len = tf.reduce_sum(tf.cast(self.q_mask, tf.int32), axis=1) self.dropout = tf.placeholder(tf.float32, name="dropout")
tensorflow.placeholder
1,866
import tensorflow as tf - responsible_next_loc is NOW policy ''' self.value, self.next_loc_mean, self.loc_std, self.next_loc, self.state_out, self.state_in, self.state_init = self._build_net(self.inputs, self.prev_loc, RNN_SIZE, TRAINING, a_size) # self.goal_pos if TRAINING: self.target_v = tf.placeholder(tf.float32, [None], 'Vtarget') self.advantages = tf.placeholder(shape=[None], dtype=tf.float32) self.sampled_next_locs = tf.placeholder(tf.float32, [None,2]) # sampled action is stored here self.policy = gaussian_pdf(self.next_loc_mean, self.loc_std, self.sampled_next_locs) # Distribution == Policy # Loss Functions self.value_loss = 0.5*tf.reduce_sum(tf.square(self.target_v - tf.reshape(self.value, shape=[-1]))) # H(x) = Sum[p(x)*log(p(x))] self.entropy = - 0.01 * tf.reduce_sum(self.policy * tf.log(tf.clip_by_value(self.policy,1e-10,1.0))) self.policy_loss = - 0.2 * tf.reduce_sum( tf.log(tf.clip_by_value(self.policy[:,0],1e-15,1.0)) * self.advantages + tf.log(tf.clip_by_value(self.policy[:,1],1e-15,1.0)) * self.advantages) #For Normal RL Part self.loss = self.value_loss + self.policy_loss - self.entropy # removed self.blocking_loss, valid_loss, discrete_policy _loss #+ 0.5*self.mypos_loss + 0.5*self.goalpos_loss #For Imitation Learning Part # self.bc_loss = 0.5 * tf.reduce_mean(tf.contrib.keras.backend.categorical_crossentropy(self.optimal_actions_onehot,self.policy)) # self.next_loc_loss_il = 0.2 * tf.reduce_sum(tf.sqrt(tf.square(self.next_loc_mean[:-1,:] - self.il_nextloc))) # self.imitation_loss = self.bc_loss #+ self.next_loc_loss_il
tensorflow.reshape
1,867
import tensorflow as tf distance_fn=embedding_sample_distance_fn) if anchor_mining_embeddings is None and match_mining_embeddings is None: anchor_match_mining_distance_matrix = anchor_match_distance_matrix else: anchor_match_mining_distance_matrix = distance_utils.compute_distance_matrix( anchor_embeddings if anchor_mining_embeddings is None else maybe_expand_sample_dim(anchor_mining_embeddings), match_embeddings if match_mining_embeddings is None else maybe_expand_sample_dim(match_mining_embeddings), distance_fn=embedding_sample_distance_fn) num_total_triplets = tf.cast(tf.shape(anchor_embeddings)[0], dtype=tf.float32) def compute_loss_and_create_summaries(use_semi_hard): """Computes loss and creates summaries.""" (loss, num_active_triplets, negative_distances, mining_loss, num_active_mining_triplets, negative_mining_distances) = ( compute_hard_negative_triplet_loss( anchor_positive_distances, anchor_match_distance_matrix, anchor_match_negative_indicator_matrix, margin=margin, use_semi_hard=use_semi_hard,
tensorflow.shape
1,868
import tensorflow as tf # load pretrained model vars_list = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES) assign_ops = [] for var in vars_list: vname = var.name from_name = vname var_value = tf.contrib.framework.load_variable(MODEL_DIR, from_name) assign_ops.append(tf.assign(var, var_value)) sess.run(assign_ops) print('Model loaded.') result = sess.run(output) cv2.imwrite("output.png", result[0]) tf.reset_default_graph() #return FileResponse("output.png", media_type="image/png")
tensorflow.assign
1,869
import tensorflow as tf def full_featurespec(): return { 'bounding_box_samples': tf.io.FixedLenFeature([100000, 4], tf.float32), 'depth_renders': tf.io.FixedLenFeature([20, 224, 224, 1], tf.float32), 'mesh_name': tf.io.FixedLenFeature([], tf.string), 'near_surface_samples': tf.io.FixedLenFeature([100000, 4], tf.float32), 'grid': tf.io.FixedLenFeature([32, 32, 32], tf.float32), 'world2grid': tf.io.FixedLenFeature([4, 4], tf.float32), 'surface_point_samples': tf.io.FixedLenFeature([10000, 6], tf.float32) } def parse_tf_example(example_proto): d = tf.io.parse_single_example(example_proto, full_featurespec()) return (d['bounding_box_samples'], d['depth_renders'], d['mesh_name'],
tensorflow.io.FixedLenFeature
1,870
from tensorflow.python.framework import tensor_shape as _tensor_shape defined shape for TPUs. send_device: A fully-specified tensorflow device. recv_device: A fully-specified tensorflow device. name: A name for the channel (optional). """ current_graph = _ops.get_default_graph() assert current_graph, "A channel is scoped within a tf.Graph" self._dtype = dtype self._send_device = send_device self._recv_device = recv_device self._name = current_graph.unique_name(name if name else "channel") assert shape is not None shape = _tensor_shape.TensorShape(shape) self._shape = shape self._send_tpu_core = _TpuCore(send_device) self._recv_tpu_core = _TpuCore(recv_device) self._send_called = False self._recv_op = None assert ((self._send_tpu_core == -1) == (self._recv_tpu_core == -1)), ( "Mixing TPU and non-TPU: %s and %s" % (send_device, recv_device)) if self._send_tpu_core >= 0: assert self._shape.is_fully_defined(), ( "TPU channel must have fully defined shape. Name: %s, shape: %s" % (self._name, self._shape))
tensorflow.python.framework.tensor_shape.TensorShape
1,871
import tensorflow as tf np.random.seed(self.seed) os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) graph = tf.Graph() with graph.as_default(): tf.set_random_seed(self.seed) self.user_id = tf.placeholder(shape=[None, ], dtype=tf.int32, name='user_id')
tensorflow.Graph
1,872
import tensorflow as tf grads, _ = tf.clip_by_global_norm(grads, 40.0) # copy weights from the parameter server to the local model self.sync = tf.group(*[v1.assign(v2) for v1, v2 in zip(pi.var_list, self.network.var_list)]) grads_and_vars = list(zip(grads, self.network.var_list)) self.inc_step = self.global_step.assign_add(tf.shape(pi.x)[0]) # each worker has a different set of adam optimizer parameters opt = tf.train.AdamOptimizer(1e-4) self.train_op = tf.group(opt.apply_gradients(grads_and_vars), self.inc_step) self.summary_writer = None
tensorflow.shape
1,873
import tensorflow as tf and then sharply drops to `learning_rate` at each cycle. Learning rate starting from `learning_rate` then increasing. It is computed as:: decayed_learning_rate = (max_lr - learning_rate) * (floor(global_step / step_size) - global_step / step_size) + learning_rate """ with tf.name_scope(name): learning_rate = tf.cast(learning_rate, dtype=tf.float32) global_step = tf.cast(global_step, dtype=tf.float32) step_size = tf.cast(step_size, dtype=tf.float32) max_lr = tf.cast(max_lr, dtype=tf.float32) if mode == 'tri': periodic_comp = tf.mod((global_step + step_size / 4) / step_size, 1) first_factor = tf.abs(periodic_comp - 0.5) second_factor = 2 * (max_lr - learning_rate) second_comp = learning_rate elif mode == 'sin': first_factor = (learning_rate - max_lr) / 2. second_factor = tf.sin((pi * global_step) / step_size) second_comp = (learning_rate + max_lr) / 2.
tensorflow.cast
1,874
import tensorflow as tf self.output_dir = paths.trial(paths.experiment(constants.EXPERIMENT_PATH, 'big_two_layer'), trial) def train_once(self, iteration, presets=None, masks=None): tf.reset_default_graph() sess = tf.Session() dataset = dataset_mnist.DatasetMnist(
tensorflow.reset_default_graph
1,875
import tensorflow as tf pred = valid_images_masked + predicted_patch # valid_annotations = np.squeeze(valid_annotations, axis=3) # pred = np.squeeze(pred, axis=3) print(valid_images.shape) print(valid_annotations.shape) print(pred.shape) for itr in range(FLAGS.batch_size): utils.save_image(valid_images_masked[itr].astype(np.uint8), FLAGS.logs_dir, name="inp_" + str(5+itr)) utils.save_image(valid_annotations[itr].astype(np.uint8), FLAGS.logs_dir, name="gt_" + str(5+itr)) utils.save_image(pred[itr].astype(np.uint8), FLAGS.logs_dir, name="predz_" + str(5+itr)) print("Saved image: %d" % itr) if __name__ == "__main__": tf.app.run()
tensorflow.app.run
1,876
import tensorflow as tf self.b1 = tf.get_variable('b1', [1024],initializer=tf.constant_initializer(0.0)) self.b2 = tf.get_variable('b2', [classnum],initializer=tf.constant_initializer(0.0)) def inference(self,images): images=tf.cast(images,tf.float32)/255.0 l1 = tf.matmul(images, self.w1)+self.b1 l1=tf.nn.relu(l1) out = tf.matmul(l1, self.w2)+self.b2 return out
tensorflow.matmul
1,877
import tensorflow as tf configs = _get_configs_for_model('ssd_inception_v2_pets') configs['model'].ssd.num_classes = 37 eval_input_fn = inputs.create_eval_input_fn( eval_config=configs['eval_config'], eval_input_config=configs['eval_input_configs'][0], model_config=configs['eval_config']) # Expecting `DetectionModel`. with self.assertRaises(TypeError): eval_input_fn() def test_output_equal_in_replace_empty_string_with_random_number(self): string_placeholder = tf.placeholder(tf.string, shape=[]) replaced_string = inputs._replace_empty_string_with_random_number( string_placeholder) test_string = 'hello world' feed_dict = {string_placeholder: test_string} with self.test_session() as sess: out_string = sess.run(replaced_string, feed_dict=feed_dict)
tensorflow.placeholder
1,878
import tensorflow as tf cell_drop=tf.contrib.rnn.DropoutWrapper(gru,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob) elif activation == 'relu': gru=tf.nn.rnn_cell.GRUCell(state_size, activation = tf.nn.relu) cell_drop=tf.contrib.rnn.DropoutWrapper(gru,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob) else: gru=tf.nn.rnn_cell.GRUCell(state_size) cell_drop=tf.contrib.rnn.DropoutWrapper(gru,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob) else: if activation == 'linear': cell_basic = tf.contrib.rnn.BasicRNNCell(state_size,activation=tf.identity) cell_drop=tf.contrib.rnn.DropoutWrapper(cell_basic,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob) elif activation == 'relu': cell_basic = tf.contrib.rnn.BasicRNNCell(state_size, activation=tf.nn.relu) cell_drop = tf.contrib.rnn.DropoutWrapper(cell_basic, variational_recurrent=True, dtype=tf.float32, input_size=num_input, input_keep_prob=input_prob, state_keep_prob=state_prob) else: #tanh by default cell_basic = tf.contrib.rnn.BasicRNNCell(state_size) cell_drop = tf.contrib.rnn.DropoutWrapper(cell_basic, variational_recurrent=True, dtype=tf.float32, input_size=num_input, input_keep_prob=input_prob,
tensorflow.contrib.rnn.DropoutWrapper
1,879
import tensorflow as tf use_tpu=FLAGS.use_tpu, model_fn=model_fn, config=run_config, train_batch_size=FLAGS.train_batch_size, eval_batch_size=FLAGS.eval_batch_size) if FLAGS.do_train: train_file = os.path.join(FLAGS.output_dir, "train.tf_record") filed_based_convert_examples_to_features( train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file) tf.logging.info("***** Running training *****") tf.logging.info(" Num examples = %d", len(train_examples)) tf.logging.info(" Batch size = %d", FLAGS.train_batch_size) tf.logging.info(" Num steps = %d", num_train_steps) train_input_fn = file_based_input_fn_builder( input_file=train_file, seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True) estimator.train(input_fn=train_input_fn, max_steps=num_train_steps) if FLAGS.do_eval: eval_examples = processor.get_dev_examples(FLAGS.data_dir) eval_file = os.path.join(FLAGS.output_dir, "eval.tf_record") filed_based_convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file)
tensorflow.logging.info
1,880
import tensorflow as tf def testEmbeddingAttentionDecoder(self): with self.test_session() as sess: with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): inp = [tf.constant(0.5, shape=[2, 2])] * 2 cell = tf.nn.rnn_cell.GRUCell(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(i, tf.int32, shape=[2]) for i in range(3)] dec, mem = tf.nn.seq2seq.embedding_attention_decoder( dec_inp, enc_state, attn_states, cell, num_symbols=4, embedding_size=2, output_size=3)
tensorflow.reshape
1,881
import tensorflow as tf tf.add_to_collection(self._final_state_name, state_tuple.c) tf.add_to_collection(self._final_state_name, state_tuple.h) def import_state_tuples(self, state_tuples, name, num_replicas): restored = [] for i in range(len(state_tuples) * num_replicas): c = tf.get_collection_ref(name)[2 * i + 0] h = tf.get_collection_ref(name)[2 * i + 1] restored.append(tf.contrib.rnn.LSTMStateTuple(c, h)) return tuple(restored) def import_ops(self): if self._is_training: self._train_op = tf.get_collection_ref('train_op')[0]
tensorflow.get_collection_ref
1,882
from tensorflow.python.ops import array_ops with self.cached_session(): embed_np = embeds[ids] embed_tf = ops.embedding_lookup(embeds, ids).eval() self.assertEqual(embed_np.shape, embed_tf.shape) self.assertAllClose(embed_np, embed_tf) def test_categorical_variable(self): random_seed.set_random_seed(42) with self.cached_session() as sess: cat_var_idx = array_ops.placeholder(dtypes.int64, [2, 2]) embeddings = ops.categorical_variable( cat_var_idx, n_classes=5, embedding_size=10, name="my_cat_var") sess.run(variables.global_variables_initializer()) emb1 = sess.run(embeddings, feed_dict={cat_var_idx.name: [[0, 1], [2, 3]]}) emb2 = sess.run(embeddings, feed_dict={cat_var_idx.name: [[0, 2], [1, 3]]}) self.assertEqual(emb1.shape, emb2.shape)
tensorflow.python.ops.array_ops.placeholder
1,883
import tensorflow as tf class DynamicBatchingBenchmarks(tf.test.Benchmark): def benchmark_batching_small(self): with tf.Session() as session: @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.ones
1,884
import tensorflow as tf return tf.matmul(tf.reshape(input_var,[-1,dims]),w) + b else : return tf.matmul(input_var,w)+b def get_variables(self): return {'w':self.w,'b':self.b} class WeightNormLinear(object): def __init__(self,name,input_dim,output_dim,stddev=0.02,epsilon=1e-10) : with tf.variable_scope(name) : self.v = tf.get_variable('v',[input_dim, output_dim], initializer=tf.random_normal_initializer(stddev=stddev)) self.g = tf.get_variable('g',[output_dim], initializer=tf.constant_initializer(float('nan'))) self.b = tf.get_variable('b',[output_dim], initializer=tf.constant_initializer(float('nan'))) self.epsilon = epsilon
tensorflow.variable_scope
1,885
import tensorflow as tf def cross_entropy_layer(tensor, target, **opts): if _rank(tensor) > 1: target = tf.reshape(target, shape=(-1, )) cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=tensor, labels=target) mask = tf.cast(tf.not_equal(target, tf.zeros_like(target)), dtype=tf.float32) out = cross_entropy * mask return out
tensorflow.zeros_like
1,886
import tensorflow as tf gold_spans = np.logical_and(gold_ends >= word_offset, gold_starts < word_offset + num_words) gold_starts = gold_starts[gold_spans] - word_offset gold_ends = gold_ends[gold_spans] - word_offset cluster_ids = cluster_ids[gold_spans] return tokens, context_word_emb, head_word_emb, lm_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids def get_candidate_labels(self, candidate_starts, candidate_ends, labeled_starts, labeled_ends, labels): same_start = tf.equal(tf.expand_dims(labeled_starts, 1), tf.expand_dims(candidate_starts, 0)) # [num_labeled, num_candidates] same_end = tf.equal(tf.expand_dims(labeled_ends, 1), tf.expand_dims(candidate_ends, 0)) # [num_labeled, num_candidates] same_span = tf.logical_and(same_start, same_end) # [num_labeled, num_candidates] candidate_labels = tf.matmul(tf.expand_dims(labels, 0), tf.to_int32(same_span)) # [1, num_candidates] candidate_labels = tf.squeeze(candidate_labels, 0) # [num_candidates] return candidate_labels def get_dropout(self, dropout_rate, is_training): return 1 - (tf.to_float(is_training) * dropout_rate) def coarse_to_fine_pruning(self, top_span_emb, top_span_mention_scores, c): k = util.shape(top_span_emb, 0) top_span_range = tf.range(k) # [k] antecedent_offsets = tf.expand_dims(top_span_range, 1) - tf.expand_dims(top_span_range, 0) # [k, k]
tensorflow.expand_dims
1,887
import tensorflow as tf inp = [tf.constant(0.5, shape=[2, 2])] * 2 _, enc_state = tf.nn.rnn( tf.nn.rnn_cell.GRUCell(2), inp, dtype=tf.float32) dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3
tensorflow.nn.rnn_cell.GRUCell
1,888
import tensorflow as tf flattened_image_features, self._num_classes * self._box_code_size, activation_fn=None, scope='BoxEncodingPredictor') class_predictions_with_background = slim.fully_connected( flattened_image_features, self._num_classes + 1, activation_fn=None, scope='ClassPredictor') box_encodings = tf.reshape( box_encodings, [-1, 1, self._num_classes, self._box_code_size]) class_predictions_with_background = tf.reshape( class_predictions_with_background, [-1, 1, self._num_classes + 1]) predictions_dict = { BOX_ENCODINGS: box_encodings, CLASS_PREDICTIONS_WITH_BACKGROUND: class_predictions_with_background } if self._predict_instance_masks: with slim.arg_scope(self._conv_hyperparams): upsampled_features = tf.image.resize_bilinear(
tensorflow.reshape
1,889
import tensorflow as tf random_actions = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=num_actions, dtype=tf.int64) chose_random = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=1, dtype=tf.float32) < eps stochastic_actions = tf.where(chose_random, random_actions, deterministic_actions) output_actions = tf.cond(stochastic_ph, lambda: stochastic_actions, lambda: deterministic_actions) update_eps_expr = eps.assign(tf.cond(update_eps_ph >= 0, lambda: update_eps_ph, lambda: eps)) act = U.function(inputs=[observations_ph, stochastic_ph, update_eps_ph], outputs=[output_actions, update_eps_expr, eps],
tensorflow.cond
1,890
import tensorflow as tf round(FLAGS.train_batch_size * FLAGS.target_train_batch_multiplier)) finetune_data = tfds.load(name=FLAGS.target_dataset, split='train') finetune_data = finetune_data.shuffle(512).repeat().batch( target_train_batch_size) target_val_batch_size = int( round(FLAGS.train_batch_size * FLAGS.target_val_batch_multiplier)) target_data = tfds.load(name=FLAGS.target_dataset, split='validation') target_data = target_data.shuffle(512).repeat().batch(target_val_batch_size) dataset = tf.data.Dataset.zip((train_data, finetune_data, target_data)) dataset = dataset.map(_merge_datasets) dataset = dataset.prefetch(buffer_size=tf.contrib.data.AUTOTUNE) return dataset max_train_steps = FLAGS.train_steps l2tl_classifier.train(make_input_dataset, max_steps=max_train_steps) if __name__ == '__main__': tf.logging.set_verbosity(tf.logging.INFO)
tensorflow.data.Dataset.zip
1,891
import tensorflow as tf unicode strings """ chars_total = 0 for fname in filepaths: chars_this_file = 0 tf.logging.info("reading file %s" % fname) for text in self.filepath_to_unicode_strings(fname): if (max_chars_per_file and chars_this_file + len(text) > max_chars_per_file): text = text[:max_chars_per_file - chars_this_file]
tensorflow.logging.info
1,892
import tensorflow as tf tf.app.flags.DEFINE_float('beta', 0.0005, 'Reconstruction from noisy data loss weight') tf.app.flags.DEFINE_float('epsilon', 0.000001, 'Diameter of epsilon sphere comparing to distance to a neighbour. <= 0.5') tf.app.flags.DEFINE_float('gamma', 50., 'Loss weight for large distances') tf.app.flags.DEFINE_float('distance', 0.01, 'Maximum allowed interpoint distance') tf.app.flags.DEFINE_float('delta', 1., 'Loss weight for stacked objective') tf.app.flags.DEFINE_string('comment', '', 'Comment to leave by the model') tf.app.flags.DEFINE_float('test_max', 10000, 'max number of examples in the test set')
tensorflow.app.flags.DEFINE_float
1,893
import tensorflow as tf from tensorflow_transform.tf_metadata import schema_utils from google.protobuf import text_format import unittest from tensorflow_metadata.proto.v0 import schema_pb2 def _make_tensors_with_override(): x = tf.compat.v1.placeholder(tf.int64, (None,)) schema_inference.set_tensor_schema_override(x, tf.constant(5), tf.constant(6)) return {'x': x} class SchemaInferenceTest(test_case.TransformTestCase): # pylint: disable=g-long-lambda
tensorflow.compat.v1.placeholder
1,894
import tensorflow as tf # compute optimization op (potentially with gradient clipping) gradients = optimizer.compute_gradients(weighted_error, var_list=q_func_vars) if grad_norm_clipping is not None: for i, (grad, var) in enumerate(gradients): if grad is not None: gradients[i] = (tf.clip_by_norm(grad, grad_norm_clipping), var) with tf.variable_scope("input_info", reuse=False): tf.summary.scalar('rewards', tf.reduce_mean(rew_t_ph)) tf.summary.scalar('importance_weights', tf.reduce_mean(importance_weights_ph)) if full_tensorboard_log: tf.summary.histogram('rewards', rew_t_ph) tf.summary.histogram('importance_weights', importance_weights_ph) if tf_util.is_image(obs_phs[0]): tf.summary.image('observation', obs_phs[0])
tensorflow.reduce_mean
1,895
import tensorflow as tf act_f = build_act(make_obs_ph, q_func, num_actions, scope=scope, reuse=reuse) with tf.variable_scope(scope, reuse=reuse): # set up placeholders obs_t_input = U.ensure_tf_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 = U.ensure_tf_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 = U.scope_vars(U.absolute_scope_name("q_func")) # target q network evalution q_tp1 = q_func(obs_tp1_input.get(), num_actions, scope="target_q_func") target_q_func_vars = U.scope_vars(U.absolute_scope_name("target_q_func"))
tensorflow.placeholder
1,896
from tensorflow.python.ops import gradients_impl initializer = init_ops.random_uniform_initializer(-0.01, 0.01, seed=127) cell = rnn_cell.LSTMCell( num_units=num_units, initializer=initializer, state_is_tuple=True) multi_cell = rnn_cell.MultiRNNCell( [cell() for _ in range(num_layers)]) outputs, final_state = core_rnn.static_rnn( multi_cell, inputs, dtype=dtypes.float32) trainable_variables = ops.get_collection( ops.GraphKeys.TRAINABLE_VARIABLES) gradients = gradients_impl.gradients([outputs, final_state], trainable_variables) training_op = control_flow_ops.group(*gradients) self._BenchmarkOp(training_op, "tf_rnn_lstm %s %s" % (config_name, self._GetConfigDesc(config))) def benchmarkTfRNNLSTMBlockCellTraining(self): test_configs = self._GetTestConfig() for config_name, config in test_configs.items(): num_layers = config["num_layers"]
tensorflow.python.ops.gradients_impl.gradients
1,897
import tensorflow as tf """Get loss and log probs for the next sentence prediction.""" # Simple binary classification. Note that 0 is "next sentence" and 1 is # "random sentence". This weight matrix is not used after pre-training. with tf.variable_scope("cls/seq_relationship"): output_weights = tf.get_variable( "output_weights", shape=[2, bert_config.hidden_size],
tensorflow.variable_scope
1,898
import tensorflow as tf def cond(batch, output, i): return tf.less(i, tf.shape(batch)[1]) def body(batch, output, i): self_attention_tmp = din_fcn_attention(batch[:, i, :], batch, ATTENTION_SIZE, mask, softmax_stag=1, stag=stag, mode='LIST') self_attention_tmp = tf.reduce_sum(self_attention_tmp, 1) output = output.write(i, self_attention_tmp) return batch, output, i + 1 output_ta = tf.TensorArray(dtype=tf.float32, size=0, dynamic_size=True,
tensorflow.reduce_sum
1,899