seed
stringlengths
25
2.89k
seed_api
stringlengths
14
102
index
int64
0
14.8k
import tensorflow as tf return weighted_average, weights def no_attention(state, hidden_states, *args, **kwargs): batch_size = tf.shape(state)[0] weighted_average = tf.zeros(shape=tf.stack([batch_size, 0])) weights = tf.zeros(shape=[batch_size, tf.shape(hidden_states)[1]]) return weighted_average, weights def average_attention(hidden_states, encoder_input_length, *args, **kwargs): # attention with fixed weights (average of all hidden states)
tensorflow.shape
2,100
import tensorflow as tf self.rel_embedding_vars = tf.Variable(rel_init) # Embedding layer for each (head, rel, tail) triple being fed in as input head_embed = tf.nn.embedding_lookup(self.entity_embedding_vars, self.head_input) tail_embed = tf.nn.embedding_lookup(self.entity_embedding_vars, self.tail_input) rel_embed = tf.nn.embedding_lookup(self.rel_embedding_vars, self.rel_input) # Relationship vector acts as a translation in entity embedding space diff_vec = tail_embed - (head_embed + rel_embed) # negative dist so higher scores are better (important for pairwise loss)
tensorflow.nn.embedding_lookup
2,101
import tensorflow as tf optimizer = 'adam', metrics = ['mae', 'mape']) # mean absolute [percentage] error return keras.estimator.model_to_estimator(model, model_dir=output_dir) # Create the inference model def simple_rnn(features, labels, mode): # 0. Reformat input shape to become a sequence x = tf.split(features[TIMESERIES_COL], N_INPUTS, 1) # 1. Configure the RNN lstm_cell = rnn.BasicLSTMCell(LSTM_SIZE, forget_bias = 1.0) outputs, _ = rnn.static_rnn(lstm_cell, x, dtype = tf.float32) # Slice to keep only the last cell of the RNN
tensorflow.split
2,102
import tensorflow as tf hard_num = tf.cast(tools.shape(pred1)[0] * hard_ratio, tf.int32) loss = tf.reshape(loss, [-1]) hard_loss, _ = tf.math.top_k(loss, k=hard_num) return hard_loss return loss def sample_pair(batch): num_sam = tools.shape(batch)[0] index = tf.range(num_sam) tgt1 = tf.slice(batch, [0, 1], [num_sam, 1]) pred1 = tf.slice(batch, [0, 0], [num_sam, 1]) def uniform(): batch2 = tf.gather(batch, tf.random.shuffle(index)) pred2 = tf.slice(batch2, [0, 0], [num_sam, 1]) tgt2 = tf.slice(batch2, [0, 1], [num_sam, 1]) return pred1, pred2, tgt1, tgt2 return uniform def contra_traj_lossV5(pred, tgt, horizon=12, resample=1, hard_ratio=1.0): horizon_pred = horizon_sumV1(pred, horizon) horizon_tgt = horizon_sumV1(tgt, horizon) pred_flat = tf.reshape(horizon_pred, [-1]) tgt_flat = tf.reshape(horizon_tgt, [-1]) batch = tf.stack([pred_flat, tgt_flat], 1) sample_func = sample_pair(batch)
tensorflow.slice
2,103
import tensorflow as tf perturb_for_adaption = perturb_vars(original_scope="q_func", perturbed_scope="adaptive_q_func") kl = tf.reduce_sum(tf.nn.softmax(q_values) * (tf.log(tf.nn.softmax(q_values)) - tf.log(tf.nn.softmax(q_values_adaptive))), axis=-1) mean_kl = tf.reduce_mean(kl) def update_scale(): with tf.control_dependencies([perturb_for_adaption]): update_scale_expr = tf.cond(mean_kl < param_noise_threshold, lambda: param_noise_scale.assign(param_noise_scale * 1.01), lambda: param_noise_scale.assign(param_noise_scale / 1.01),
tensorflow.control_dependencies
2,104
import tensorflow as tf """Decodes a record to a TensorFlow example.""" example = tf.parse_single_example(record, name_to_features) # tf.Example only supports tf.int64, but the TPU only supports tf.int32. # So cast all int64 to int32. for name in list(example.keys()): t = example[name] if t.dtype == tf.int64: t = tf.to_int32(t) example[name] = t return example def input_fn(params): """The actual input function.""" batch_size = params["batch_size"]
tensorflow.to_int32
2,105
import tensorflow as tf :param strides: [list] List of 4 int, convolution strides. :param padding: [string] `VALID` or `SAME`, padding method for sparse convolution. :return [Tensor] [N, H', W', C]. Convolution results. """ blk_shape = tf.shape(blk_indices) blk_indices_ = tf.reshape(blk_indices, [-1, 3]) ksize = tf.shape(w) # Calculate the block strides. bstrides = _calc_block_strides(blk_shape, ksize, strides) # Calculate the output size. x_shape = tf.shape(x)
tensorflow.shape
2,106
import tensorflow as tf # If the input is a 2D tensor of shape [batch_size, seq_length], we # reshape to [batch_size, seq_length, 1]. if input_ids.shape.ndims == 2: input_ids = tf.expand_dims(input_ids, axis=[-1]) embedding_table = tf.get_variable( name=word_embedding_name, shape=[vocab_size, embedding_size], initializer=create_initializer(initializer_range)) if use_one_hot_embeddings: flat_input_ids = tf.reshape(input_ids, [-1]) one_hot_input_ids = tf.one_hot(flat_input_ids, depth=vocab_size) output = tf.matmul(one_hot_input_ids, embedding_table) else: output = tf.nn.embedding_lookup(embedding_table, input_ids) input_shape = get_shape_list(input_ids) output = tf.reshape(output, input_shape[0:-1] + [input_shape[-1] * embedding_size]) return (output, embedding_table) def embedding_postprocessor(input_tensor, use_token_type=False, token_type_ids=None, token_type_vocab_size=16, token_type_embedding_name="token_type_embeddings", use_position_embeddings=True,
tensorflow.nn.embedding_lookup
2,107
import tensorflow as tf self.assertEqual(set(six.iterkeys(losses)), {"extra", "extra_loss", "latent_pred"}) self.evaluate(tf.global_variables_initializer()) decoder_output_, extra_loss_, latent_pred_ = self.evaluate( [decoder_output, losses["extra_loss"], losses["latent_pred"]]) self.assertEqual(decoder_output_.shape, (batch_size,
tensorflow.global_variables_initializer
2,108
import tensorflow as tf 'rpn_score_loss', tf.reduce_mean(rpn_score_loss), step=global_step) tf.contrib.summary.scalar( 'rpn_box_loss', tf.reduce_mean(rpn_box_loss), step=global_step) tf.contrib.summary.scalar( 'total_fast_rcnn_loss', tf.reduce_mean(total_fast_rcnn_loss), step=global_step) tf.contrib.summary.scalar( 'fast_rcnn_class_loss', tf.reduce_mean(fast_rcnn_class_loss), step=global_step) tf.contrib.summary.scalar( 'fast_rcnn_box_loss', tf.reduce_mean(fast_rcnn_box_loss), step=global_step) if params['include_mask']: tf.contrib.summary.scalar( 'mask_loss', tf.reduce_mean(mask_loss), step=global_step) tf.contrib.summary.scalar( 'learning_rate', tf.reduce_mean(learning_rate), step=global_step) return tf.contrib.summary.all_summary_ops() # To log the loss, current learning rate, and epoch for Tensorboard, the # summary op needs to be run on the host CPU via host_call. host_call # expects [batch_size, ...] Tensors, thus reshape to introduce a batch # dimension. These Tensors are implicitly concatenated to # [params['batch_size']]. global_step_t = tf.reshape(global_step, [1]) total_loss_t = tf.reshape(total_loss, [1]) total_rpn_loss_t = tf.reshape(total_rpn_loss, [1])
tensorflow.reduce_mean
2,109
import tensorflow as tf X = tf.contrib.layers.instance_norm(X, scope=scope, reuse=reuse) elif norm == 'B': X = tf.layers.batch_normalization(X, reuse=reuse, training=is_train, name=name) elif norm == 'G': X = tf.contrib.layers.group_norm(X, groups=16, scope=scope, reuse=reuse) if dropout > 0.0: X = tf.layers.dropout(X, dropout, training=is_train) if slope < 1.0:
tensorflow.contrib.layers.group_norm
2,110
import tensorflow as tf raw_data = reader.ptb_raw_data(FLAGS.data_path) train_data, valid_data, test_data, _ = raw_data config = get_config() eval_config = get_config() eval_config.batch_size = 1 eval_config.num_steps = 1 with tf.Graph().as_default(): initializer = tf.random_uniform_initializer(-config.init_scale, config.init_scale) with tf.name_scope("Train"): train_input = PTBInput(config=config, data=train_data, name="TrainInput") with tf.variable_scope("Model", reuse=None, initializer=initializer): m = PTBModel(is_training=True, config=config, input_=train_input) tf.summary.scalar("Training Loss", m.cost) tf.summary.scalar("Learning Rate", m.lr) with tf.name_scope("Valid"): valid_input = PTBInput(config=config, data=valid_data, name="ValidInput") with tf.variable_scope("Model", reuse=True, initializer=initializer): mvalid = PTBModel(is_training=False, config=config, input_=valid_input) tf.summary.scalar("Validation Loss", mvalid.cost)
tensorflow.name_scope
2,111
import tensorflow as tf dims = tf.reduce_prod(tf.shape(input_var)[1:]) input_var = tf.reshape(input_var,[-1,dims]) def _init(): v_norm = tf.nn.l2_normalize(self.v,axis=0) t = tf.matmul(input_var,v_norm) mu,var = tf.nn.moments(t,axes=[0]) 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]) with tf.control_dependencies(init_ops):
tensorflow.sqrt
2,112
import tensorflow as tf #w=[-1,head,n_ctx,n_ctx] w = tf.matmul(q, k) if scale: n_state = shape_list(v)[-1] w = w*tf.rsqrt(tf.cast(n_state, tf.float32)) w = mask_attn_weights(w) w = tf.nn.softmax(w) w = dropout(w, attn_pdrop, train) #w=[-1,head,n_ctx,n_ctx],v=[-1,head,n_ctx,emb] a = tf.matmul(w, v) return a
tensorflow.nn.softmax
2,113
import tensorflow as tf "metadata.") tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
tensorflow.flags.DEFINE_string
2,114
import tensorflow as tf attn_dists.append(attn_dist_t) p_gens.append(p_gen_t) vocab_scores.append(output_t) # The vocabulary distributions. state_t_1 = state_t context_t_1 = context_t coverage_t_1 = coverage_t if mode_gen == 'greedy': wordidx_t = tf.argmax(output_t, 1) # [batch_size] wordidx_t = tf.reshape(wordidx_t, [-1]) # [batch_size] elif mode_gen == 'sample': log_score_t = tf.log(output_t) # [batch_size, vsize] wordidx_t = tf.multinomial(log_score_t, 1) # [batch_size, 1] wordidx_t = tf.reshape(wordidx_t, [-1]) # [batch_size] elif mode_gen in ('ce_train', 'loss',): wordidx_t = answer_batch_unstack[i] else:
tensorflow.argmax
2,115
import tensorflow as tf else: X = self.t_conv(name + '_deconf', X, filter, f_size, 1, (not norm) and use_bias, "VALID", stddev) if norm == 'I': X = tf.contrib.layers.instance_norm(X, scope=scope, reuse=reuse) elif norm == 'B': X = tf.layers.batch_normalization(X, reuse=reuse, training=is_train, name=name) elif norm == 'G': X = tf.contrib.layers.group_norm(X, groups=16, scope=scope, reuse=reuse) if dropout > 0.0: X = tf.layers.dropout(X, dropout, training=is_train) if slope < 1.0: X = tf.nn.leaky_relu(X, slope) if slope > 0.0 else tf.nn.relu(X) return X F = 3 norm = self.args.norm # print('norm', norm) # print('skip cons', self.args.skip_connections) # print('VNET In:', I.get_shape().as_list()) if adaption_net: # print('ada scope T/R', is_train, reuse_ada)
tensorflow.nn.leaky_relu
2,116
import tensorflow as tf step_size=step_size, scale_fn=lambda x: 1.0, scale_mode=scale_mode, name=name, ) @tf.keras.utils.register_keras_serializable(package="Addons") class Triangular2CyclicalLearningRate(CyclicalLearningRate): def __init__( self, initial_learning_rate, maximal_learning_rate, step_size,
tensorflow.keras.utils.register_keras_serializable
2,117
import tensorflow as tf x = inputs x0 = tf.transpose(x, perm=[1, 2,0]) # (num_nodes, total_arg_size, batch_size) x0 = tf.reshape(x0, shape=[self._num_nodes, input_size * batch_size]) x = tf.expand_dims(x0, axis=0) scope = tf.get_variable_scope() with tf.variable_scope(scope): if self._max_diffusion_step == 0: pass else: for support in self._supports: x1 = tf.sparse_tensor_dense_matmul(support, x0)
tensorflow.variable_scope
2,118
from tensorflow.contrib import metrics as metrics_lib def _predictions_streaming_mean(predictions, unused_targets): return metrics_lib.streaming_mean(predictions)
tensorflow.contrib.metrics.streaming_mean
2,119
import tensorflow as tf to create a local gradient computation on their machine. """ _, _, grads = self._build_model(x, y) return grads def _build_validation_model(self, x, y): predictions, loss, _ = self._build_model(x, y) most_likely = tf.argmax(predictions, axis=1) return most_likely, loss def _build_data_pipeline(self): def normalize(image, label): image = tf.cast(image, tf.float32) / 255.0 return image, label dataset = tf.data.TFRecordDataset(["./data/train.tfrecord"]) dataset = dataset.map(decode) dataset = dataset.map(normalize) dataset = dataset.batch(50) dataset = dataset.take(1) # keep validating on the same items dataset = dataset.repeat() iterator = dataset.make_one_shot_iterator() return iterator.get_next()
tensorflow.cast
2,120
import tensorflow as tf def get_session(): tf.reset_default_graph() tf_config = tf.ConfigProto( inter_op_parallelism_threads=1, intra_op_parallelism_threads=1)
tensorflow.ConfigProto
2,121
import tensorflow as tf v = tf.Variable(tf.random_normal([attention_size], stddev=0.1)) with tf.name_scope('v'): # Applying fully connected layer with non-linear activation to each of the B*T timestamps; # 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 def din_fcn_attention(query, facts, attention_size, mask, stag='null', mode='SUM', softmax_stag=1, time_major=False, return_alphas=False, forCnn=False):
tensorflow.where
2,122
import tensorflow as tf ckpt: Path to existing checkpoint. If present, returns only the subset of variables that exist in given checkpoint. Returns: List of all variables that need to be saved/restored. """ model_vars = tf.trainable_variables() # Add batchnorm variables. bn_vars = [v for v in tf.global_variables() if 'moving_mean' in v.op.name or 'moving_variance' in v.op.name or 'mu' in v.op.name or 'sigma' in v.op.name or 'global_scale_var' in v.op.name]
tensorflow.trainable_variables
2,123
import tensorflow as tf tf.app.flags.DEFINE_string('postfix', '', 'Postfix for the training folder') tf.app.flags.DEFINE_float('alpha', 10, 'Predictive reconstruction loss weight') 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')
tensorflow.app.flags.DEFINE_float
2,124
import tensorflow as tf # Add a summary to track the learning rate. summaries.append(tf.summary.scalar('learning_rate', lr))
tensorflow.summary.scalar
2,125
import tensorflow as tf # for summary with tf.name_scope('accuracy') as scope: correct = tf.equal(tf.arg_max(logits,1), tf.arg_max(labels,1)) correct = tf.cast(correct, tf.float32) accuracy = tf.reduce_mean(correct)*100.0 tf.summary.scalar(scope+'accuracy',accuracy) return accuracy
tensorflow.reduce_mean
2,126
import tensorflow as tf [per_example_loss, label_ids, logits, is_real_example]) output_spec = tf.contrib.tpu.TPUEstimatorSpec( mode=mode, loss=total_loss, eval_metrics=eval_metrics, scaffold_fn=scaffold_fn) else: # The code to modify out_put nodes output_spec = tf.contrib.tpu.TPUEstimatorSpec( mode=mode, predictions={"probabilities": probabilities}, scaffold_fn=scaffold_fn) return output_spec return model_fn
tensorflow.contrib.tpu.TPUEstimatorSpec
2,127
import tensorflow as tf logits = tf.matmul(input_tensor, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias)
tensorflow.nn.bias_add
2,128
import tensorflow as tf """Convert indices to one-hot.""" shape = input_.get_shape().as_list() n_elem = numpy.prod(shape) indices = tf.range(n_elem) indices = tf.cast(indices, tf.int64) indices_input = tf.concat(axis=0, values=[indices, tf.reshape(input_, [-1])]) indices_input = tf.reshape(indices_input, [2, -1]) indices_input = tf.transpose(indices_input)
tensorflow.cast
2,129
from tensorflow.python.layers import convolutional as conv_layers padding = [[0, 0], [pad_beg, pad_end], [pad_beg, pad_end], [0, 0]] if self.data_format == 'NCHW': padding = [padding[0], padding[3], padding[1], padding[2]] input_layer = tf.pad(input_layer, padding) conv = conv_layers.conv2d( input_layer, num_out_channels, [k_height, k_width], strides=[d_height, d_width],
tensorflow.python.layers.convolutional.conv2d
2,130
from tensorflow.python.framework import ops as _ops tensor=tensor, tensor_name=tensor_name, send_device=send_device, send_device_incarnation=0, recv_device=recv_device, client_terminated=False, name=name if name else "Send") return result _ops.RegisterShape("_Send")(None) def _XlaSend(tensor, tensor_name, name=None): r"""Sends the named tensor from send_device to recv_device. Args: tensor: A `Tensor`. The tensor to send. tensor_name: A `string`. The name of the tensor to send. name: A name for the operation (optional).
tensorflow.python.framework.ops.RegisterShape
2,131
from tensorflow.python.ops import gen_state_ops shape = shape.merge_with(input_tensor.get_shape()) if not shape.is_fully_defined(): # TODO(pbar): Make a version of assign_add that accepts an uninitialized # lvalue, and takes its shape from that? This would allow accumulate_n to # work in all situations that add_n currently works. raise ValueError("Cannot infer the shape of the accumulator for " "accumulate_n. Pass the shape argument, or set the shape " "of at least one of the inputs.") with ops.op_scope(inputs, name, "AccumulateN") as name: var = gen_state_ops._temporary_variable(shape=shape, dtype=tensor_dtype) var_name = var.op.name var = state_ops.assign(var, array_ops.zeros_like(inputs[0])) update_ops = [] for input_tensor in inputs: op = state_ops.assign_add(var, input_tensor, use_locking=True) update_ops.append(op) with ops.control_dependencies(update_ops): return gen_state_ops._destroy_temporary_variable(var,
tensorflow.python.ops.gen_state_ops._temporary_variable
2,132
import tensorflow as tf e_related_to_mean = tf.zeros((num_data, num_func, num_func), dtype=settings.float_type) else: # Update mean: \mu(x) + m(x) fmean = fmean + expectation(pXnew, mean_function) # Calculate: m(x) m(x)^T + m(x) \mu(x)^T + \mu(x) m(x)^T, # where m(x) is the mean_function and \mu(x) is fmean e_mean_mean = expectation(pXnew, mean_function, mean_function) # N x D x D Lit_q_mu = tf.matrix_triangular_solve(Luu, q_mu, adjoint=True) e_mean_Kuf = expectation(pXnew, mean_function, (kern, feat)) # N x D x M # einsum isn't able to infer the rank of e_mean_Kuf, hence we explicitly set the rank of the tensor: e_mean_Kuf = tf.reshape(e_mean_Kuf, [num_data, num_func, num_ind]) e_fmean_mean = tf.einsum("nqm,mz->nqz", e_mean_Kuf, Lit_q_mu) # N x D x D e_related_to_mean = e_fmean_mean + tf.matrix_transpose(e_fmean_mean) + e_mean_mean if full_output_cov:
tensorflow.matrix_triangular_solve
2,133
import tensorflow as tf else: mean_loss = tf.reduce_mean(all_shards) losses[loss_name] = mean_loss return losses def summarize_features(features, num_shards=1): with tf.name_scope("input_stats"): for (k, v) in six.iteritems(features): if isinstance(v, tf.Tensor) and v.get_shape().ndims > 1: tf.summary.scalar("%s_batch" % k, tf.shape(v)[0] // num_shards) tf.summary.scalar("%s_length" % k, tf.shape(v)[1]) nonpadding = tf.to_float(tf.not_equal(v, 0)) nonpadding_tokens = tf.reduce_sum(nonpadding) tf.summary.scalar("%s_nonpadding_tokens" % k, nonpadding_tokens) tf.summary.scalar("%s_nonpadding_fraction" % k, tf.reduce_mean(nonpadding)) _already_logged = set() def _eager_log(level, *args):
tensorflow.shape
2,134
from tensorflow.contrib.distributions.python.ops import distribution_util (1. + self.alpha) * math_ops.digamma(self.alpha)) @distribution_util.AppendDocstring( """The mean of an inverse gamma distribution is `beta / (alpha - 1)`,
tensorflow.contrib.distributions.python.ops.distribution_util.AppendDocstring
2,135
import tensorflow as tf self.y2 = tf.argmax(tf.slice(self.y2, [0, 0], [N, self.c_maxlen]),axis=-1) else: self.c_maxlen, self.q_maxlen = config.para_limit, config.ques_limit self.ch_len = tf.reshape(tf.reduce_sum( tf.cast(tf.cast(self.ch, tf.bool), tf.int32), axis=2), [-1]) self.qh_len = tf.reshape(tf.reduce_sum( tf.cast(tf.cast(self.qh, tf.bool), tf.int32), axis=2), [-1]) self.forward() total_params() if trainable: self.lr = tf.minimum(config.learning_rate, 0.001 / tf.log(999.) * tf.log(tf.cast(self.global_step, tf.float32) + 1)) self.opt = tf.train.AdamOptimizer(learning_rate = self.lr, beta1 = 0.8, beta2 = 0.999, epsilon = 1e-7) grads = self.opt.compute_gradients(self.loss) gradients, variables = zip(*grads) capped_grads, _ = tf.clip_by_global_norm( gradients, config.grad_clip) self.train_op = self.opt.apply_gradients( zip(capped_grads, variables), global_step=self.global_step) def forward(self): config = self.config N, PL, QL, CL, d, dc, nh = config.batch_size if not self.demo else config.batch_size, self.c_maxlen, self.q_maxlen, config.char_limit, config.hidden, config.char_dim, config.num_heads
tensorflow.log
2,136
import tensorflow as tf scope.reuse_variables() print('D in:', X.get_shape().as_list()) X = self.conv('DZ1', X, 512, 1, 1) X = tf.nn.leaky_relu(X, 0.2) X = self.conv('DZ2', X, 512, 1, 1) X = tf.nn.leaky_relu(X, 0.2) X = self.conv('DZ3', X, 512, 1, 1) X = tf.nn.leaky_relu(X, 0.2) X = self.conv('DZ4', X, 512, 1, 1) X = tf.nn.leaky_relu(X, 0.2) X = discrim_conv('d_out', X, 1, 1, norm=False, nonlin=False, init_stddev=0.02)
tensorflow.nn.leaky_relu
2,137
import tensorflow as tf attended_span_emb = tf.reduce_sum(tf.expand_dims(top_antecedent_weights, 2) * top_antecedent_emb, 1) # [k, emb] with tf.variable_scope("f"): f = tf.sigmoid(util.projection(tf.concat([top_span_emb, attended_span_emb], 1), util.shape(top_span_emb, -1))) # [k, emb] top_span_emb = f * attended_span_emb + (1 - f) * top_span_emb # [k, emb]
tensorflow.concat
2,138
import tensorflow as tf if decoder.pred_deep_layer: deep_layer_size = decoder.pred_deep_layer_size or decoder.embedding_size if decoder.layer_norm: output_ = dense(output_, deep_layer_size, use_bias=False, name='deep_output') output_ = tf.contrib.layers.layer_norm(output_, activation_fn=tf.nn.tanh, scope='output_layer_norm') else: output_ = dense(output_, deep_layer_size, activation=tf.tanh, use_bias=True, name='deep_output') if decoder.use_dropout: size = tf.shape(output_)[1] noise_shape = [1, size] if decoder.pervasive_dropout else None output_ = tf.nn.dropout(output_, keep_prob=decoder.deep_layer_keep_prob, noise_shape=noise_shape) else: if decoder.pred_maxout_layer: maxout_size = decoder.maxout_size or cell_output_size output_ = dense(output_, maxout_size, use_bias=True, name='maxout') if decoder.old_maxout: # for back-compatibility with old models output_ = tf.nn.pool(tf.expand_dims(output_, axis=2), window_shape=[2], pooling_type='MAX', padding='SAME', strides=[2])
tensorflow.shape
2,139
import tensorflow as tf with tf.variable_scope("loss", reuse=reuse): # set up placeholders act_t_ph = tf.placeholder(tf.int32, [None], name="action") rew_t_ph = tf.placeholder(tf.float32, [None], name="reward") done_mask_ph = tf.placeholder(tf.float32, [None], name="done") importance_weights_ph = tf.placeholder(tf.float32, [None], name="weight")
tensorflow.placeholder
2,140
import tensorflow as tf # data processing inputs_list = [] for i in range(num_gpu): img = tf.expand_dims(img_batch[i], axis=0) pretrain_zoo = PretrainModelZoo() if self.cfgs.NET_NAME in pretrain_zoo.pth_zoo or self.cfgs.NET_NAME in pretrain_zoo.mxnet_zoo: img = img / tf.constant([cfgs.PIXEL_STD]) gtboxes_and_label_r = tf.py_func(backward_convert, inp=[gtboxes_and_label_batch[i]], Tout=tf.float32) gtboxes_and_label_r = tf.reshape(gtboxes_and_label_r, [-1, 6]) gtboxes_and_label_h = get_horizen_minAreaRectangle(gtboxes_and_label_batch[i]) gtboxes_and_label_h = tf.reshape(gtboxes_and_label_h, [-1, 5]) num_objects = num_objects_batch[i] num_objects = tf.cast(tf.reshape(num_objects, [-1, ]), tf.float32) img_h = img_h_batch[i] img_w = img_w_batch[i]
tensorflow.reshape
2,141
import tensorflow as tf "used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 " "url.") tf.flags.DEFINE_string( "tpu_zone", None, "[Optional] GCE zone where the Cloud TPU is located in. If not " "specified, we will attempt to automatically detect the GCE project from " "metadata.") tf.flags.DEFINE_string( "gcp_project", None, "[Optional] Project name for the Cloud TPU-enabled project. If not " "specified, we will attempt to automatically detect the GCE project from " "metadata.") tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.") flags.DEFINE_integer(
tensorflow.flags.DEFINE_string
2,142
import tensorflow as tf original_shape = labels.get_shape().as_list() if labels.get_shape().ndims > 0: original_shape[0] = -1 if labels.get_shape().ndims <= 1: labels = tf.reshape(labels, [-1, 1]) logits = tf.reshape(logits, [-1, 1]) if weights.get_shape().ndims == 1: # Weights has shape [batch_size]. Reshape to [batch_size, 1].
tensorflow.reshape
2,143
import tensorflow as tf except ImportError: pass else: tf.set_random_seed(i) np.random.seed(i) random.seed(i)
tensorflow.set_random_seed
2,144
import tensorflow as tf # (T,B,D) => (B,T,D) facts = tf.array_ops.transpose(facts, [1, 0, 2])
tensorflow.array_ops.transpose
2,145
import tensorflow as tf self.assertEqual((2, 5), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].c.shape) self.assertEqual((2, 2), res[0].h.shape) # Test with state_is_tuple=False. with tf.variable_scope("no_tuple"): cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=False) dec, mem = tf.nn.seq2seq.embedding_attention_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 5), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 4), res[0].shape) # Test externally provided output projection. w = tf.get_variable("proj_w", [2, 5]) b = tf.get_variable("proj_b", [5]) with tf.variable_scope("proj_seq2seq"):
tensorflow.global_variables_initializer
2,146
import tensorflow as tf if time_major: # (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' + 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, 80, activation=tf.nn.sigmoid, name='f1_att' + stag) d_layer_2_all = tf.layers.dense(d_layer_1_all, 40, activation=tf.nn.sigmoid, name='f2_att' + stag)
tensorflow.layers.dense
2,147
import tensorflow as tf except: t_vars = tf.all_variables()
tensorflow.all_variables
2,148
import tensorflow as tf def _anchor_component(self): with tf.variable_scope('ANCHOR_' + 'default'): # just to get the shape right # 根据原始输入图片通过VGG16的conv5_3后,缩小16倍,得到RPN的输入feature map大小 height = tf.to_int32(tf.ceil(self._im_info[0, 0] / np.float32(self._feat_stride[0]))) width = tf.to_int32(tf.ceil(self._im_info[0, 1] / np.float32(self._feat_stride[0]))) #得到一张输入图片的所有anchor在原输入image上的坐标,以及anchor的数量 anchors, anchor_length = tf.py_func(generate_anchors_pre, [height, width, self._feat_stride, self._anchor_scales, self._anchor_ratios], [tf.float32, tf.int32], name="generate_anchors") anchors.set_shape([None, 4]) anchor_length.set_shape([]) self._anchors = anchors self._anchor_length = anchor_length
tensorflow.py_func
2,149
import tensorflow as tf self.replace_target_iter = replace_target_iter self.memory_size = memory_size self.batch_size = batch_size self.epsilon = epsilon self.epsilon_decay = epsilon_decay self.epsilon_min = 0.1 self.learn_step_cnt = 0 # total learning step self.episode_cnt = 0 self.memory = [] self.memory_counter = 0 self._build_net() t_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name + '/target_net') e_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name + '/eval_net') e_params += tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name + '/mixing_net' + '/eval_hyper') t_params += tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name + '/mixing_net' + '/target_hyper') with tf.variable_scope('soft_replacement'): self.target_replace_op = [tf.assign(t, e) for t, e in zip(t_params, e_params)] self.sess = tf.Session() self.sess.run(tf.global_variables_initializer()) current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") train_log_dir = 'logs/' + current_time self.summary_writer = tf.summary.FileWriter(train_log_dir, self.sess.graph) def _build_net(self): # we use parameter sharing among agents with tf.variable_scope(self.name):
tensorflow.get_collection
2,150
import tensorflow as tf 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]]) scores = d_layer_3_all # Mask if mask is not None: # key_masks = tf.sequence_mask(facts_length, tf.shape(facts)[1]) # [B, T] key_masks = tf.expand_dims(mask, 1) # [B, 1, T] paddings = tf.ones_like(scores) * (-2 ** 32 + 1) if not forCnn: scores = tf.where(key_masks, scores, paddings) # [B, 1, T] # Scale # scores = scores / (facts.get_shape().as_list()[-1] ** 0.5) # Activation
tensorflow.expand_dims
2,151
import tensorflow as tf if dropout: h_logits = tf.nn.dropout(h_logits, 0.5) out_logits = tf.matmul(h_logits, w_out) + b_out return out_logits
tensorflow.matmul
2,152
import tensorflow as tf self.assertEqual((2, 2), res[0].shape) def testDynamicAttentionDecoder2(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.dynamic_rnn(cell, inp, dtype=tf.float32) attn_states = enc_outputs dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3
tensorflow.nn.rnn_cell.GRUCell
2,153
import tensorflow as tf # time-step. dec_inp_dict2 = {} dec_inp_dict2["0"] = [ tf.constant(0, tf.int32, shape=[2]) for _ in range(3)] dec_inp_dict2["1"] = [ tf.constant(0, tf.int32, shape=[2]) for _ in range(4)]
tensorflow.constant
2,154
import tensorflow as tf 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]]) scores = d_layer_3_all # Mask # key_masks = tf.sequence_mask(facts_length, tf.shape(facts)[1]) # [B, T] key_masks = tf.expand_dims(mask, 1) # [B, 1, T] paddings = tf.ones_like(scores) * (-2 ** 32 + 1) if not forCnn: scores = tf.where(key_masks, scores, paddings) # [B, 1, T] # Scale # scores = scores / (facts.get_shape().as_list()[-1] ** 0.5) # Activation
tensorflow.expand_dims
2,155
import tensorflow as tf learning_rate=config.learning_rate).minimize(cost) 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.argmax
2,156
from tensorflow.python.ops import sparse_ops hashed_output=True, num_buckets=1024, hash_key=layers.SPARSE_FEATURE_CROSS_DEFAULT_HASH_KEY) cross_dense = sparse_ops.sparse_tensor_to_dense(cross) with session.Session(): values = cross_dense.eval()
tensorflow.python.ops.sparse_ops.sparse_tensor_to_dense
2,157
import tensorflow as tf images = tf.cast(images, data_type) network = ConvNetBuilder( images, input_nchan, phase_train, self.data_format, data_type) self.model_conf.add_inference(network) # Add the final fully-connected class layer logits = network.affine(nclass, activation='linear') if not phase_train: top_1_op = tf.reduce_sum( tf.cast(tf.nn.in_top_k(logits, labels, 1), data_type)) top_5_op = tf.reduce_sum( tf.cast(tf.nn.in_top_k(logits, labels, 5), data_type)) return (logits, top_1_op, top_5_op) loss = loss_function(logits, labels) params = self.variable_mgr.trainable_variables_on_device(device_num) l2_loss = tf.add_n([tf.nn.l2_loss(v) for v in params]) weight_decay = FLAGS.weight_decay
tensorflow.nn.in_top_k
2,158
import tensorflow as tf decay=self._decay_rate, name="update_moving_mean").op update_variance_op = moving_averages.assign_moving_average( variable=self._moving_variance, value=variance, decay=self._decay_rate, name="update_moving_variance").op return update_mean_op, update_variance_op def build_no_ops(): return (tf.no_op(), tf.no_op()) # Only make the ops if we know that `is_training=True`, or the value of # `is_training` is unknown. is_training_const = utils.constant_value(is_training) if is_training_const is None or is_training_const: update_mean_op, update_variance_op = utils.smart_cond( is_training, build_update_ops, build_no_ops, )
tensorflow.no_op
2,159
from tensorflow.python.framework import ops """ with ops.op_scope([x], name, "Sigmoid") as name:
tensorflow.python.framework.ops.op_scope
2,160
import tensorflow as tf ) return params def import_params(model_dir, model_name, params): model_dir = os.path.abspath(model_dir) p_name = os.path.join(model_dir, "params.json") m_name = os.path.join(model_dir, model_name + ".json") if not tf.gfile.Exists(p_name) or not tf.gfile.Exists(m_name): return params with tf.gfile.Open(p_name) as fd: tf.logging.info("Restoring hyper parameters from %s" % p_name) json_str = fd.readline() params.parse_json(json_str) with tf.gfile.Open(m_name) as fd: tf.logging.info("Restoring model parameters from %s" % m_name)
tensorflow.gfile.Exists
2,161
import tensorflow as tf tgt_flat = tf.reshape(tgt, [-1]) batch = tf.stack([pred_flat, tgt_flat], 1) num_sam = tools.shape(batch)[0] index = tf.range(num_sam) divider = tf.constant(resample, dtype=tf.float32)
tensorflow.range
2,162
import tensorflow as tf batch_size = tf.shape(attention_weights)[0] src_len = tf.shape(attention_weights)[2] trg_len = tf.shape(attention_weights)[1] src_indices = tf.tile(tf.reshape(tf.range(src_len), shape=[1, 1, src_len]), [batch_size, trg_len, 1]) trg_indices = tf.tile(tf.reshape(tf.range(trg_len), shape=[1, trg_len, 1]), [batch_size, 1, src_len]) source_length = encoder_input_length[0] target_length = tf.to_int32(tf.reduce_sum(trg_mask, axis=1)) true_src_len = tf.reshape(source_length, shape=[batch_size, 1, 1]) - 1 true_trg_len = tf.reshape(target_length, shape=[batch_size, 1, 1]) - 1
tensorflow.range
2,163
import tensorflow as tf channels = shape[3] res = tf.reshape(input_, [batch_size, height, 1, width, 1, channels]) res = tf.concat( axis=2, values=[res, tf.zeros([batch_size, height, stride - 1, width, 1, channels])]) res = tf.concat(axis=4, values=[ res, tf.zeros([batch_size, height, stride, width, stride - 1, channels]) ]) res = tf.reshape(res, [batch_size, stride * height, stride * width, channels]) return res
tensorflow.zeros
2,164
import tensorflow as tf out = layers.fully_connected(out, num_outputs=512, activation_fn=tf.nn.relu) out = layers.fully_connected(out, num_outputs=num_actions, activation_fn=None) return out def simple_model(img_in, num_actions, scope, reuse=False, num_filters=64): with tf.variable_scope(scope, reuse=reuse): out = img_in gauss_initializer = initializers.xavier_initializer(uniform=False) # stddev = 1/n with tf.variable_scope("convnet"): out = layers.convolution2d( out, num_outputs=num_filters, kernel_size=8, stride=4, activation_fn=tf.nn.relu, weights_initializer=gauss_initializer, trainable=False) out = layers.flatten(out) with tf.variable_scope("action_value"): out = layers.fully_connected(out, num_outputs=num_actions, activation_fn=None) return out
tensorflow.variable_scope
2,165
import tensorflow as tf # Optimizer for Non-Variational Autoencoders if model_name in ('gcn_ae', 'linear_ae', 'deep_gcn_ae'): opt = OptimizerAE(preds = model.reconstructions, labels = tf.reshape(tf.sparse_tensor_to_dense(placeholders['adj_orig'], validate_indices = False), [-1]), pos_weight = pos_weight,
tensorflow.sparse_tensor_to_dense
2,166
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'], d['near_surface_samples'], d['grid'], d['world2grid'], d['surface_point_samples'])
tensorflow.io.FixedLenFeature
2,167
from tensorflow.python.framework import constant_op from tensorflow.python.ops import variables from tensorflow.python.ops import array_ops from tensorflow.python.platform import test class OpsTest(test.TestCase): """Ops tests.""" def test_softmax_classifier(self): with self.cached_session() as session: features = array_ops.placeholder(dtypes.float32, [None, 3]) labels = array_ops.placeholder(dtypes.float32, [None, 2]) weights = constant_op.constant([[0.1, 0.1], [0.1, 0.1], [0.1, 0.1]]) biases = constant_op.constant([0.2, 0.3]) class_weight = constant_op.constant([0.1, 0.9]) prediction, loss = ops.softmax_classifier(features, labels, weights, biases, class_weight) self.assertEqual(prediction.get_shape()[1], 2) self.assertEqual(loss.get_shape(), []) value = session.run(loss, {features: [[0.2, 0.3, 0.2]], labels: [[0, 1]]}) self.assertAllClose(value, 0.55180627) def test_embedding_lookup(self): d_embed = 5
tensorflow.python.framework.constant_op.constant
2,168
import tensorflow as tf 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
2,169
import tensorflow as tf return tf.SparseTensor(*sp_returns[:3]), tf.SparseTensor(*sp_returns[3:6]), \ tf.SparseTensor(*sp_returns[6:])
tensorflow.SparseTensor
2,170
import tensorflow as tf indices.active_block_indices, x, dynamic_bsize=tf.constant(block_params.bsize_out, dtype=tf.int32), dynamic_bstride=tf.constant(block_params.bstrides, dtype=tf.int32), dynamic_boffset=tf.constant([0, 0], dtype=tf.int32), add=False, transpose=transpose, atomic=atomic) else: y = sbnet_module.sparse_scatter( q, indices.bin_counts, indices.active_block_indices, x, dynamic_bsize=tf.constant(block_params.bsize_out, dtype=tf.int32), dynamic_bstride=tf.constant(block_params.bsize_out, dtype=tf.int32), dynamic_boffset=tf.constant([0, 0], dtype=tf.int32), add=False, transpose=transpose, atomic=atomic) return y def _batch_norm(name, x, is_training, data_format='NHWC'): """ Applies batch normalization. :param name: [string] Name of the variable scope.
tensorflow.constant
2,171
import tensorflow as tf # Calculate the gradients for each model tower. tower_grads = [] with tf.variable_scope(tf.get_variable_scope()): for i in xrange(FLAGS.num_gpus): with tf.device('/gpu:%d' % i): with tf.name_scope('%s_%d' % (cifar10.TOWER_NAME, i)) as scope: # Calculate the loss for one tower of the CIFAR model. This function # constructs the entire CIFAR model but shares the variables across # all towers. loss = tower_loss(scope)
tensorflow.name_scope
2,172
import tensorflow as tf features = self.features # batch normalize feature vectors features = self._batch_norm(features, mode='test', name='conv_features') c, h = self._get_initial_lstm(features=features) features_proj = self._project_features(features=features) sampled_word_list = [] alpha_list = [] beta_list = [] lstm_cell = tf.contrib.rnn.BasicLSTMCell(num_units=self.H, reuse=tf.get_variable_scope().reuse) for t in range(max_len): if t == 0: x = self._word_embedding(inputs=tf.fill([tf.shape(features)[0]], self._start)) else: x = self._word_embedding(inputs=sampled_word, reuse=True) context, alpha = self._attention_layer(features, features_proj, h, reuse=(t!=0)) alpha_list.append(alpha) if self.selector: context, beta = self._selector(context, h, reuse=(t!=0)) beta_list.append(beta) with tf.variable_scope('lstm', reuse=(t!=0)): _, (c, h) = lstm_cell(inputs=tf.concat(axis=1, values=[x, context]), state=[c, h]) logits = self._decode_lstm(x, h, context, reuse=(t!=0))
tensorflow.shape
2,173
import tensorflow as tf tf.summary.scalar('rewards', tf.reduce_mean(self.reward_ph)) tf.summary.scalar('learning_rate', tf.reduce_mean(self.learning_rate)) tf.summary.scalar('advantage', tf.reduce_mean(adv)) tf.summary.scalar('action_probability', tf.reduce_mean(self.mu_ph)) if self.full_tensorboard_log: tf.summary.histogram('rewards', self.reward_ph) tf.summary.histogram('learning_rate', self.learning_rate) tf.summary.histogram('advantage', adv) tf.summary.histogram('action_probability', self.mu_ph) if tf_util.is_image(self.observation_space): tf.summary.image('observation', train_model.obs_ph) else: tf.summary.histogram('observation', train_model.obs_ph) trainer = tf.train.RMSPropOptimizer(learning_rate=self.learning_rate_ph, decay=self.rprop_alpha,
tensorflow.summary.histogram
2,174
import tensorflow as tf Returns: A 1-D tensor of length batch_size of same type as logits with softmax focal loss """ with tf.name_scope(scope, 'focal_loss', [cls_preds, onehot_labels]) as sc: logits = tf.convert_to_tensor(cls_preds) onehot_labels = tf.convert_to_tensor(onehot_labels) precise_logits = tf.cast(logits, tf.float32) if ( logits.dtype == tf.float16) else logits onehot_labels = tf.cast(onehot_labels, precise_logits.dtype) predictions = tf.nn.sigmoid(logits) predictions_pt = tf.where(tf.equal(onehot_labels, 1), predictions, 1.-predictions) # add small value to avoid 0 epsilon = 1e-8 alpha_t = tf.scalar_mul(alpha, tf.ones_like(onehot_labels, dtype=tf.float32)) alpha_t = tf.where(tf.equal(onehot_labels, 1.0), alpha_t, 1-alpha_t) losses = tf.reduce_sum(-alpha_t * tf.pow(1. - predictions_pt, gamma) * tf.log(predictions_pt+epsilon), name=name, axis=1)
tensorflow.cast
2,175
import tensorflow as tf if isinstance(k_size, list): filter_shape = [k_size[0], k_size[1]] + [in_channel, out_dims] else: filter_shape = [k_size, k_size] + [in_channel, out_dims] if w_init is None: w_init = tf.contrib.layers.variance_scaling_initializer() if b_init is None: b_init = tf.constant_initializer() w = tf.get_variable('W', filter_shape, initializer=w_init) b = None if use_bias: b = tf.get_variable('b', [out_dims], initializer=b_init) conv = tf.nn.atrous_conv2d(value=input_tensor, filters=w, rate=rate, padding=padding, name='dilation_conv') if use_bias: ret = tf.add(conv, b) else: ret = conv return ret @staticmethod def spatial_dropout(input_tensor, keep_prob, is_training, name, seed=1234): """
tensorflow.get_variable
2,176
import tensorflow as tf else: scalar = reduce_fn(args[i]) with tf.contrib.summary.record_summaries_every_n_global_steps( 100, global_step=step): tf.contrib.summary.scalar(prefix + name, scalar, step=step) return tf.contrib.summary.all_summary_ops() global_step_tensor = tf.reshape(tf.train.get_or_create_global_step(), [1]) other_tensors = [tf.reshape(monitor_dict[key], [1]) for key in metric_names] return host_call_fn, [global_step_tensor] + other_tensors
tensorflow.contrib.summary.all_summary_ops
2,177
import tensorflow as tf is_succ = 'Fail' print('Finish attack 2. The %d batch in total %d(%f sec) %s' % ( i, FLAGS.eval_batch_count, time.time() - time_start, is_succ)) else: print('The %d batch in total %d, the eps = %f (%f sec)' % ( i, FLAGS.eval_batch_count, 0.05 * k, time.time() - time_start)) #Local logits (predict_ADV,logits_part_adv) = sess.run( [predict_adv, tsne_logit_adv],feed_dict={adv_image:adv_img} ) #Local entropy and confidence for nor_img (entropy_test_nor_help,labels_nor_help,confidence_test_nor_help) = sess.run( [entropy,tf.argmax(predict,axis=1),tf.reduce_max(predict, axis=1)],feed_dict={predict:predict_NOR} ) # Local entropy and confidence for adv_img (entropy_test_adv_help, labels_adv_help, confidence_test_adv_help) = sess.run( [entropy, tf.argmax(predict, axis=1), tf.reduce_max(predict, axis=1)], feed_dict={predict: predict_ADV} ) if FLAGS.attack_method == 'carliniL2_specific' or FLAGS.attack_method == 'carliniL2_highden': print('Log-density-ratio in attacking function of nor/adv is %f'%np.sum(log_density_ratio)) m_tsne_logits_adv = (copy.copy(logits_part_adv)).reshape((1, 64)) m_tsne_logits_adv = np.repeat(m_tsne_logits_adv,100,axis=0) kernel_train = (copy.copy(e_kernel_train[:,:,np.argmax(target_lab)])).reshape((100,64)) log_density_ratio2 = -np.log(1e-30+np.mean(np.exp(-np.sum(np.square(m_tsne_logits_adv
tensorflow.argmax
2,178
import tensorflow as tf features["label_ids"] = create_int_feature([feature.label_id]) features["is_real_example"] = create_int_feature( [int(feature.is_real_example)]) tf_example = tf.train.Example(features=tf.train.Features(feature=features)) writer.write(tf_example.SerializeToString()) writer.close()
tensorflow.train.Features
2,179
import tensorflow as tf data_format='channels_last', padding= "same", strides=(2, 1), activation=tf.nn.relu) pool5 = conv5 pool5 = tf.transpose(pool5, [0, 3, 1, 2]) size = pool5.shape[-1] * pool5.shape[-2] * pool5.shape[-3] logits = tf.layers.dense(tf.reshape(pool5,(-1, size)), units=256*amp_factor) return logits
tensorflow.reshape
2,180
import tensorflow as tf # Tensorboard visualization tf.summary.scalar(name='Autoencoder Loss', tensor=autoencoder_loss) tf.summary.scalar(name='Discriminator gauss Loss', tensor=dc_g_loss) tf.summary.scalar(name='Discriminator categorical Loss', tensor=dc_c_loss) tf.summary.scalar(name='Generator Loss', tensor=generator_loss) tf.summary.scalar(name='Supervised Encoder Loss', tensor=supervised_encoder_loss) tf.summary.histogram(name='Encoder Gauss Distribution', values=encoder_output_latent) tf.summary.histogram(name='Real Gauss Distribution', values=real_distribution) tf.summary.histogram(name='Encoder Categorical Distribution', values=encoder_output_label) tf.summary.histogram(name='Real Categorical Distribution', values=categorial_distribution) tf.summary.image(name='Input Images', tensor=input_images, max_outputs=10) tf.summary.image(name='Generated Images', tensor=generated_images, max_outputs=10) summary_op = tf.summary.merge_all() # Saving the model
tensorflow.summary.histogram
2,181
import tensorflow as tf tf.summary.image(name='Input Images', tensor=input_images, max_outputs=10) tf.summary.image(name='Generated Images', tensor=generated_images, max_outputs=10) summary_op = tf.summary.merge_all() # Saving the model saver = tf.train.Saver() step = 0 with tf.Session() as sess: if train_model: tensorboard_path, saved_model_path, log_path = form_results()
tensorflow.train.Saver
2,182
import tensorflow as tf for i in range(2, 2 + len(expected_extra_dims)): mask = tf.expand_dims(mask, axis=i) mask = tf.tile(mask, [1, 1] + expected_extra_dims) return tf.where(mask, expanded_tensor, if_masked_tensor) def initial_layer( window_feature: WindowFeatures, *, clip_magnitude=10.0, include_flux_and_time=False ) -> tf.Tensor: features = tf.expand_dims(window_feature.dflux_dt(clip_magnitude=clip_magnitude), 2) if include_flux_and_time: dflux = tf.expand_dims(window_feature.dflux, 2) dtime = tf.expand_dims(window_feature.dtime, 2) features = tf.concat([features, dflux, dtime], axis=2, name="initial_layer_concat") return features class CutoffData: def __init__(self, config_json: dict): self.window_size: int = config_json["window_size"]
tensorflow.expand_dims
2,183
import tensorflow as tf def _crop_pool_layer(self, bottom, rois, name): with tf.variable_scope(name): # tf.squeeze()返回一个张量,这个张量是将原始input中所有维度中为1的那些维都删掉的结果 batch_ids = tf.squeeze(tf.slice(rois, [0, 0], [-1, 1], name="batch_id"), [1]) # Get the normalized coordinates of bboxes bottom_shape = tf.shape(bottom)
tensorflow.slice
2,184
import tensorflow as tf active_loss = ( loss / tf.math.maximum(1e-12, tf.stop_gradient(active_triplet_ratio))) active_mining_loss = (
tensorflow.stop_gradient
2,185
import tensorflow as tf metrics.append(tf.summary.histogram('point_distance', dists)) metrics.append(tf.summary.scalar('training/trajectory_length', tf.reduce_sum(dists))) self.blur_ph = tf.placeholder(dtype=tf.float32) metrics.append(tf.summary.scalar('training/blur_sigma', self.blur_ph)) pred = self.embedding_test[1:-1]*2 - self.embedding_test[0:-2] pred_error = l2(pred - self.embedding_test[2:]) mean_dist, mean_pred_error = tf.reduce_mean(dists), tf.reduce_mean(pred_error) improvement = (mean_dist-mean_pred_error)/mean_dist pairwise_improvement = tf.nn.relu(dists[1:] - pred_error) pairwise_improvement_bool = tf.cast(pairwise_improvement > 0, pairwise_improvement.dtype) self.pairwise_improvement_bool = pairwise_improvement_bool metrics.append(tf.summary.scalar('training/avg_dist', mean_dist)) metrics.append(tf.summary.scalar('training/pred_dist', mean_pred_error)) metrics.append(tf.summary.scalar('training/improvement', improvement)) metrics.append(tf.summary.scalar('training/improvement_abs', tf.nn.relu(improvement))) metrics.append(tf.summary.histogram('training/improvement_abs_hist', nut.nan_to_zero(improvement))) metrics.append(tf.summary.scalar('training/improvement_pairwise', tf.reduce_mean(pairwise_improvement_bool))) metrics.append(tf.summary.histogram('training/improvement_pairwise_hist', pairwise_improvement_bool)) self.eval_summs = tf.summary.merge(metrics)
tensorflow.cast
2,186
import tensorflow as tf self.assertAllClose(9.656628, res) def testSequenceLossByExample(self): with self.test_session() as sess: output_classes = 5 logits = [tf.constant(i + 0.5, shape=[2, output_classes]) for i in range(3)] targets = [tf.constant(i, tf.int32, shape=[2]) for i in range(3)] weights = [tf.constant(1.0, shape=[2]) for i in range(3)] average_loss_per_example = tf.nn.seq2seq.sequence_loss_by_example( logits, targets, weights, average_across_timesteps=True) res = sess.run(average_loss_per_example)
tensorflow.constant
2,187
import tensorflow as tf A tuple of `SparseTensor` (neibors, weights). neighbors: A `SparseTensor` of `int64`. weights: A `SparseTensor` of `float`. types: A `SparseTensor` of `int32` """ sp_returns = base._LIB_OP.get_sorted_full_neighbor(nodes, edge_types) return tf.SparseTensor(*sp_returns[:3]), tf.SparseTensor(*sp_returns[3:6]), \ tf.SparseTensor(*sp_returns[6:]) def sample_fanout(nodes, edge_types, counts, default_node=-1): """ Sample multi-hop neighbors of nodes according to weight in graph.
tensorflow.SparseTensor
2,188
import tensorflow as tf name='linear_projection_2_predictions_arguments_bn') activation = tf.nn.relu(projection)
tensorflow.nn.relu
2,189
import tensorflow as tf # Now we construct the copy model. inp = [tf.placeholder(tf.int32, shape=[None]) for _ in range(8)] out = [tf.placeholder(tf.int32, shape=[None]) for _ in range(8)]
tensorflow.placeholder
2,190
import tensorflow as tf with tf.variable_scope(scope): d_memory = dropout(memory, keep_prob=keep_prob, is_train=is_train) s0 = tf.nn.tanh(dense(d_memory, hidden, scope="s0")) s = dense(s0, 1, use_bias=False, scope="s") s1 = softmax_mask(tf.squeeze(s, [2]), mask) a = tf.expand_dims(tf.nn.softmax(s1), axis=2) res = tf.reduce_sum(a * memory, axis=1) return res def dot_attention(inputs, memory, mask, hidden, keep_prob=1.0, is_train=None, scope="dot_attention"): with tf.variable_scope(scope): d_inputs = dropout(inputs, keep_prob=keep_prob, is_train=is_train) d_memory = dropout(memory, keep_prob=keep_prob, is_train=is_train) JX = tf.shape(inputs)[1] with tf.variable_scope("attention"): inputs_ = tf.nn.relu( dense(d_inputs, hidden, use_bias=False, scope="inputs")) memory_ = tf.nn.relu( dense(d_memory, hidden, use_bias=False, scope="memory")) outputs = tf.matmul(inputs_, tf.transpose( memory_, [0, 2, 1])) / (hidden ** 0.5) mask = tf.tile(tf.expand_dims(mask, axis=1), [1, JX, 1]) logits = tf.nn.softmax(softmax_mask(outputs, mask)) outputs = tf.matmul(logits, memory) res = tf.concat([inputs, outputs], axis=2) with tf.variable_scope("gate"):
tensorflow.shape
2,191
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]
tensorflow.reshape
2,192
import tensorflow as tf 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())
tensorflow.train.Supervisor
2,193
import tensorflow as tf if current_step < total_step: tf.logging.info('Starting training ...')
tensorflow.logging.info
2,194
import tensorflow as tf 'WS: pruning ratio protocol (\'uniform\' | \'heurist\' | \'optimal\')') tf.app.flags.DEFINE_integer('ws_nb_rlouts', 200, 'WS: # of roll-outs for the RL agent') tf.app.flags.DEFINE_integer('ws_nb_rlouts_min', 50, 'WS: minimal # of roll-outs for the RL agent to start training') tf.app.flags.DEFINE_string('ws_reward_type', 'single-obj', 'WS: reward type (\'single-obj\' OR \'multi-obj\')') tf.app.flags.DEFINE_float('ws_lrn_rate_rg', 3e-2, 'WS: learning rate for layerwise regression') tf.app.flags.DEFINE_integer('ws_nb_iters_rg', 20, 'WS: # of iterations for layerwise regression') tf.app.flags.DEFINE_float('ws_lrn_rate_ft', 3e-4, 'WS: learning rate for global fine-tuning') tf.app.flags.DEFINE_integer('ws_nb_iters_ft', 400, 'WS: # of iterations for global fine-tuning') tf.app.flags.DEFINE_integer('ws_nb_iters_feval', 25, 'WS: # of iterations for fast evaluation') tf.app.flags.DEFINE_float('ws_prune_ratio_exp', 3.0, 'WS: pruning ratio\'s exponent term')
tensorflow.app.flags.DEFINE_float
2,195
import tensorflow as tf x_min1, y_min1, x_max1, y_max1 = tf.split(boxlist1, 4, axis=1) x_min2, y_min2, x_max2, y_max2 = tf.split(boxlist2, 4, axis=1) all_pairs_min_ymax = tf.minimum(y_max1, tf.transpose(y_max2)) all_pairs_max_ymin = tf.maximum(y_min1, tf.transpose(y_min2)) intersect_heights = tf.maximum(0.0, all_pairs_min_ymax - all_pairs_max_ymin) all_pairs_min_xmax = tf.minimum(x_max1, tf.transpose(x_max2))
tensorflow.transpose
2,196
import tensorflow as tf # print(scope, 'out', activation.get_shape().as_list()) return activation def self_attention(x, channels, act_func=tf.nn.relu, scope='attention'): with tf.variable_scope(scope): batch_size, height, width, num_channels = x.get_shape().as_list() f = conv(x, scope='f_conv', filter_dims=[1, 1, channels//8], stride_dims=[1, 1], non_linear_fn=act_func) f = tf.layers.max_pooling2d(f, pool_size=2, strides=2, padding='SAME')
tensorflow.variable_scope
2,197
from tensorflow.python.ops import math_ops def _loss(self, logits, target, weight_tensor): if self._n_classes < 2: loss_vec = math_ops.square(logits - math_ops.to_float(target)) elif self._n_classes == 2: loss_vec = nn.sigmoid_cross_entropy_with_logits(logits, math_ops.to_float(target)) else: loss_vec = nn.sparse_softmax_cross_entropy_with_logits( logits, array_ops.reshape(target, [-1])) if weight_tensor is None: return math_ops.reduce_mean(loss_vec, name="loss") else: loss_vec = array_ops.reshape(loss_vec, shape=(-1,)) loss_vec = math_ops.mul( loss_vec, array_ops.reshape(weight_tensor, shape=(-1,))) return math_ops.div( math_ops.reduce_sum(loss_vec), math_ops.to_float(math_ops.reduce_sum(weight_tensor)), name="loss") def _get_linear_vars(self):
tensorflow.python.ops.math_ops.reduce_mean
2,198
import tensorflow as tf tf.app.flags.DEFINE_float( 'momentum', 0.9, 'The momentum for the MomentumOptimizer and RMSPropOptimizer.') tf.app.flags.DEFINE_float('learning_rate', 1e-4, 'Initial learning rate.')#1e-3 tf.app.flags.DEFINE_float( 'end_learning_rate', 0.000001, 'The minimal end learning rate used by a polynomial decay learning rate.') tf.app.flags.DEFINE_float( 'warmup_learning_rate', 0.00001, 'The start warm-up learning rate to avoid NAN.') tf.app.flags.DEFINE_integer( 'warmup_steps', 100, 'The total steps to warm-up.') # for learning rate piecewise_constant decay tf.app.flags.DEFINE_string( 'decay_boundaries', '2, 3', 'Learning rate decay boundaries by global_step (comma-separated list).') tf.app.flags.DEFINE_string( 'lr_decay_factors', '1, 0.5, 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', 'The path to a checkpoint from which to fine-tune.') tf.app.flags.DEFINE_string( 'checkpoint_model_scope', '', 'Model scope in the checkpoint. None if the same as the trained model.') tf.app.flags.DEFINE_string(
tensorflow.app.flags.DEFINE_string
2,199