seed
stringlengths
25
2.89k
seed_api
stringlengths
14
102
index
int64
0
14.8k
import tensorflow as tf self._lr = tf.Variable(0.0, trainable=False) tvars = tf.trainable_variables() grads, _ = tf.clip_by_global_norm(tf.gradients(self._cost, tvars), config.max_grad_norm) optimizer = tf.train.GradientDescentOptimizer(self._lr) self._train_op = optimizer.apply_gradients( zip(grads, tvars), global_step=tf.contrib.framework.get_or_create_global_step()) self._new_lr = tf.placeholder( tf.float32, shape=[], name="new_learning_rate") self._lr_update = tf.assign(self._lr, self._new_lr) def _build_rnn_graph(self, inputs, config, is_training): if config.rnn_mode == CUDNN: return self._build_rnn_graph_cudnn(inputs, config, is_training) else: return self._build_rnn_graph_lstm(inputs, config, is_training) def _build_rnn_graph_cudnn(self, inputs, config, is_training): """Build the inference graph using CUDNN cell.""" inputs = tf.transpose(inputs, [1, 0, 2])
tensorflow.assign
8,200
import tensorflow as tf if not silent: log_info("Doing %s took %.3f sec." % (msg, time.time() - start_time)) return res return fn_with_timing def _create_dummy_vars(): """Dummy vars for restore to work when not using TPU codepath.""" var_names = set([v.name for v in tf.global_variables()]) if "losses_avg/problem_0/total_loss:0" in var_names: return with tf.variable_scope("losses_avg"): with tf.variable_scope("problem_0"): for var_name in ["total", "extra", "training"]: tf.get_variable( "%s_loss" % var_name, initializer=100.0, trainable=False) with tf.variable_scope("train_stats"): tf.get_variable("problem_0_steps", initializer=0, trainable=False) # These metrics are implemented with py_funcs and therefore do no work with TPU TPU_METRIC_BLACKLIST = set([ metrics.Metrics.APPROX_BLEU, metrics.Metrics.ROUGE_2_F, metrics.Metrics.ROUGE_L_F,
tensorflow.variable_scope
8,201
import tensorflow as tf 'The directory where the dataset input data is stored.') tf.app.flags.DEFINE_string( 'dataset_name', '{}_????', 'The pattern of the dataset name to load.') tf.app.flags.DEFINE_string( 'model_dir', './logs_sext_cpn/', 'The parent directory where the model will be stored.') tf.app.flags.DEFINE_integer( 'log_every_n_steps', 10, 'The frequency with which logs are print.') tf.app.flags.DEFINE_integer( 'save_summary_steps', 100, 'The frequency with which summaries are saved, in seconds.') tf.app.flags.DEFINE_integer( 'save_checkpoints_secs', 3600, 'The frequency with which the model is saved, in seconds.') # model related configuration tf.app.flags.DEFINE_integer( 'train_image_size', 384,
tensorflow.app.flags.DEFINE_integer
8,202
from tensorflow.contrib.learn.python.learn.datasets import base SOURCE_URL + TEST_IMAGES) test_images = extract_images(local_file) local_file = base.maybe_download(TEST_LABELS, train_dir, SOURCE_URL + TEST_LABELS) test_labels = extract_labels(local_file, one_hot=one_hot)
tensorflow.contrib.learn.python.learn.datasets.base.maybe_download
8,203
import tensorflow as tf loss_class = tf.reshape(loss_class, [num_batch, num_prior]) loss_class_idx = tf.argsort(loss_class, axis=1, direction='DESCENDING') loss_class_idx_rank = tf.argsort(loss_class_idx, axis=1) mask_pos_per_batch = tf.reshape(mask_pos, [num_batch, num_prior]) num_pos_per_batch = tf.reduce_sum( tf.cast(mask_pos_per_batch, tf.float32), 1, keepdims=True) num_pos_per_batch = tf.maximum(num_pos_per_batch, 1) num_neg_per_batch = tf.minimum(neg_pos_ratio * num_pos_per_batch, tf.cast(num_prior, tf.float32) - 1) mask_hard_neg = tf.reshape( tf.cast(loss_class_idx_rank, tf.float32) < num_neg_per_batch, [num_batch * num_prior, 1])
tensorflow.maximum
8,204
import tensorflow as tf output_weight = tf.get_variable( "output_weights", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02) ) output_bias = tf.get_variable(
tensorflow.truncated_normal_initializer
8,205
import tensorflow as tf 'ftol' : 1.0 * np.finfo(float).eps}) self.optimizer_Adam = tf.compat.v1.train.AdamOptimizer() self.train_op_Adam = self.optimizer_Adam.minimize(self.loss) init = tf.global_variables_initializer() self.sess.run(init) self.loss_log = []
tensorflow.global_variables_initializer
8,206
import tensorflow as tf #need to fix if self.ms_task: with tf.variable_scope('mixed'): #add fake pc as a rotation class num_to_add = int(max(self.batch_size/self.num_angles, 1)) idx = tf.range(0, self.batch_size, 1) idx = tf.random_shuffle(idx)[0:num_to_add] self.fake_to_add = tf.gather(self.generator_out, idx) self.mixed_pc = tf.concat([self.real_pc_rotated, self.fake_to_add], 0) self.mixed_label = tf.concat([self.rot_label_pl, tf.constant(self.num_angles, shape = (num_to_add,))], axis = 0)
tensorflow.range
8,207
import tensorflow as tf if len(facts.get_shape().as_list()) == 2: facts = tf.expand_dims(facts, 1)
tensorflow.expand_dims
8,208
from tensorflow.python.framework import ops vector_dim = vector_dim.merge_with(beta_shape[0]) return [input_shape] + ([tensor_shape.vector(vector_dim)] * 4) ops.RegisterShape("Conv2D")(common_shapes.conv2d_shape) ops.RegisterShape("DepthwiseConv2dNative")( common_shapes.depthwise_conv2d_native_shape) ops.RegisterShape("AvgPool")(common_shapes.avg_pool_shape) ops.RegisterShape("MaxPool")(common_shapes.max_pool_shape)
tensorflow.python.framework.ops.RegisterShape
8,209
import tensorflow as tf x: The input tensor. prediction: The prediction class tensor. output_class: The output tensor. sess: The graph session. """ # input label placeholder y = tf.placeholder("float", [None, self.n_classes]) # Loss function loss = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y)) # Optimization opt = tf.train.AdamOptimizer( learning_rate=self.learning_rate).minimize(loss) # Initialize variables init = tf.global_variables_initializer() sess.run(init) for _ in range(TRAIN_STEPS): batch_x, batch_y = self.mnist.train.next_batch( batch_size=self.batch_size, shuffle=False) batch_x = batch_x.reshape((self.batch_size, self.time_steps, self.n_input)) sess.run(opt, feed_dict={x: batch_x, y: batch_y}) def saveAndRestoreModel(self, lstm_layer, sess, saver, is_dynamic_rnn): """Saves and restores the model to mimic the most common use case. Args: lstm_layer: The lstm layer either a single lstm cell or a multi lstm cell.
tensorflow.global_variables_initializer
8,210
import tensorflow as tf confidence_scores = tf.concat(1, [tf.matmul(o_, confidence_mat) for o_ in self._inputs]) # dropout on confidence_scores random_tensor = (1.0 - self._dropout_keep_prob + tf.random_uniform(tf.shape(confidence_scores))) binary_tensor = -50.0 * tf.floor(random_tensor) csshape = confidence_scores.get_shape() self.cs = tf.nn.softmax(tf.constant(1.0, shape=csshape)) # The final prediction is the average of the predictions for each word
tensorflow.floor
8,211
import tensorflow as tf attn_score = mask_for_high_rank(attn_score, attn_mask) attn_result = tf.reduce_sum(attn_score * rep_map_tile, 2) # bs,slh,vec -> head_org_idx
tensorflow.reduce_sum
8,212
import tensorflow as tf add_weight_decay(params['weight_decay']) regularization_loss = tf.losses.get_regularization_loss() # create localization and classification losses losses = ssd.loss(labels, params) tf.losses.add_loss(params['localization_loss_weight'] * losses['localization_loss']) tf.losses.add_loss(params['classification_loss_weight'] * losses['classification_loss']) tf.summary.scalar('regularization_loss', regularization_loss) tf.summary.scalar('localization_loss', losses['localization_loss']) tf.summary.scalar('classification_loss', losses['classification_loss']) total_loss = tf.losses.get_total_loss(add_regularization_losses=True) if mode == tf.estimator.ModeKeys.EVAL: batch_size = features['images'].shape[0].value assert batch_size == 1
tensorflow.summary.scalar
8,213
import tensorflow as tf 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)
tensorflow.reduce_mean
8,214
import tensorflow as tf with tf.control_dependencies(update_ops), tf.variable_scope('optimizer'): optimizer = tf.train.AdamOptimizer(learning_rate) grads_and_vars = optimizer.compute_gradients(total_loss) train_op = optimizer.apply_gradients(grads_and_vars, global_step) for g, v in grads_and_vars: tf.summary.histogram(v.name[:-2] + '_hist', v) tf.summary.histogram(v.name[:-2] + '_grad_hist', g) with tf.control_dependencies([train_op]), tf.name_scope('ema'): ema = tf.train.ExponentialMovingAverage(decay=MOVING_AVERAGE_DECAY, num_updates=global_step) train_op = ema.apply(tf.trainable_variables()) return tf.estimator.EstimatorSpec(mode, loss=total_loss, train_op=train_op)
tensorflow.summary.histogram
8,215
import tensorflow as tf gpu_compute_stage_ops.extend( [put_op for _, (put_op, _) in six.iteritems(staging_ops)]) enqueue_ops.append(tf.group(*gpu_compute_stage_ops)) if gpu_grad_stage_ops:
tensorflow.group
8,216
import tensorflow as tf class ACnet(object): # 这个class即可用于生产global net,也可生成 worker net,因为结构相同 def __init__(self, scope, globalAC=None, global_step=None): # scope 用于确定生成什么网络 # global GLOBALE_STEP # self.global_step = GLOBALE_STEP if scope == GLOBAL_NET_SCOPE: # 创建中央大脑 with tf.variable_scope(scope): self.global_step = tf.get_variable("global_step", [], tf.int32, initializer=tf.constant_initializer(0, dtype=tf.int32), trainable=False) self.obs_space = N_S self.act_space = N_A self.k = 16 self.g_dim = 256 self.c = 10 self.vf_hidden_size = 128 # for value function network self.alpha = 0.5 # for build loss
tensorflow.constant_initializer
8,217
from tensorflow.contrib.metrics.python.ops import set_ops weights: `Tensor` whose shape is broadcastable to the the first [D1, ... DN] dimensions of `predictions_idx` and `labels`. Returns: A [D1, ... DN] `Tensor` of false positive counts. """ with ops.name_scope(None, 'false_positives', (predictions_idx, labels)): labels, predictions_idx = _maybe_select_class_id(labels, predictions_idx, class_id) fp = set_ops.set_size(set_ops.set_difference( predictions_idx, labels, aminusb=True)) fp = math_ops.to_double(fp) if weights is not None: weights = math_ops.to_double(weights) fp = math_ops.mul(fp, weights) return fp def _streaming_sparse_false_positive_at_k(predictions_idx,
tensorflow.contrib.metrics.python.ops.set_ops.set_difference
8,218
import tensorflow as tf def look(time, state, input_, prev_weights=None, pos=None, context=None): prev_weights_ = [prev_weights if i == align_encoder_id else None for i in range(len(encoders))] pos_ = None if decoder.pred_edits: pos_ = [pos if i == align_encoder_id else None for i in range(len(encoders))] if decoder.attn_prev_word: state = tf.concat([state, input_], axis=1) if decoder.attn_prev_attn and context is not None: state = tf.concat([state, context], axis=1) if decoder.hidden_state_scaling: attention_states_ = [states * decoder.hidden_state_scaling for states in attention_states] else: attention_states_ = attention_states parameters = dict(hidden_states=attention_states_, encoder_input_length=encoder_input_length, encoders=encoders, aggregation_method=decoder.aggregation_method)
tensorflow.concat
8,219
import tensorflow as tf y0_f = tf.to_float(y0) y1_f = tf.to_float(y1) z0_f = tf.to_float(z0) z1_f = tf.to_float(z1) # Check the out-of-boundary case. x0_valid = tf.to_float(
tensorflow.to_float
8,220
import tensorflow as tf facts_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer querry_size = query.get_shape().as_list()[-1] queries = tf.tile(query, [1, tf.shape(facts)[1]]) queries = tf.reshape(queries, tf.shape(facts))
tensorflow.shape
8,221
import tensorflow as tf if len(episode_rewards) > 0: mean_episode_reward = np.mean(episode_rewards[-100:]) if len(episode_rewards) > 100: best_mean_episode_reward = max(best_mean_episode_reward, mean_episode_reward) if t % DEBUG_LOG_EVERY_N_STEPS == 0: print('Timestep = {} | Elapsed time = {:.3f}sec'.format(t,time.time() - start)) if t % LOG_EVERY_N_STEPS == 0 and model_initialized: print("Timestep %d" % (t,)) print("mean reward (100 episodes) %f" % mean_episode_reward) print("best mean reward %f" % best_mean_episode_reward) print("episodes %d" % len(episode_rewards)) print("exploration %f" % exploration.value(t)) print("learning_rate %f" % optimizer_spec.lr_schedule.value(t)) mean_rew_summ = tf.Summary(value=[tf.Summary.Value(tag='mean_rew',simple_value=mean_episode_reward)]) best_mean_rew_summ = tf.Summary(value=[tf.Summary.Value(tag='best_mean_rew',simple_value=best_mean_episode_reward)]) writer.add_summary(mean_rew_summ, global_step=t) writer.add_summary(best_mean_rew_summ, global_step=t) sys.stdout.flush() def gather_2d(vectors,indices): return tf.gather_nd(vectors, tf.stack([tf.range(tf.shape(vectors)[0]), indices], axis=1))
tensorflow.Summary.Value
8,222
import tensorflow as tf if full_cov: fvar = Knn - tf.matmul(A, A, transpose_a=True) fvar = tf.tile(fvar[None, :, :], [num_func, 1, 1]) # R x N x N else: fvar = Knn - tf.reduce_sum(tf.square(A), 0) fvar = tf.tile(fvar[None, :], [num_func, 1]) # R x N # another backsubstitution in the unwhitened case if not white: A = tf.matrix_triangular_solve(tf.transpose(Lm), A, lower=False) # construct the conditional mean fmean = tf.matmul(A, f, transpose_a=True) if q_sqrt is not None: if q_sqrt.get_shape().ndims == 2: LTA = A * tf.expand_dims(tf.transpose(q_sqrt), 2) # R x M x N elif q_sqrt.get_shape().ndims == 3:
tensorflow.transpose
8,223
import tensorflow as tf else: raise NotImplementedError(nl_type) def update_params(self, kwargs): """Update the class attributes with kwargs.""" if kwargs is not None: for k, v in kwargs.iteritems(): setattr(self, k, v) def symmetric_weights(self, w, name): """Apply symmetric weight sharing.""" conv_w_t = tf.transpose(w, (2, 3, 0, 1)) conv_w_symm = 0.5 * (conv_w_t + tf.transpose(conv_w_t, (1, 0, 2, 3))) conv_w = tf.transpose(conv_w_symm, (2, 3, 0, 1), name=name) return conv_w def prepare_tensors(self): """ Prepare recurrent/forward weight matrices. (np.prod([h, w, k]) / 2) - k params in the surround filter """ # FEEDFORWARD AND FEEDBACK KERNELS lower_feats = self.in_k for idx, (higher_feats, ff_dhw, fb_dhw) in enumerate( zip(self.ff_conv_k,
tensorflow.transpose
8,224
import tensorflow as tf gamma = tf.Variable(tf.constant(1.0, shape=[n_out], dtype=x.dtype), name=name+'/gamma', trainable=True, dtype=x.dtype) batch_mean, batch_var = tf.nn.moments(x, [0,1,2], name='moments') ema = tf.train.ExponentialMovingAverage(decay=0.9) def mean_var_with_update(): ema_apply_op = ema.apply([batch_mean, batch_var]) with tf.control_dependencies([ema_apply_op]): return tf.identity(batch_mean), tf.identity(batch_var) mean, var = control_flow_ops.cond(phase_train, mean_var_with_update, lambda: (ema.average(batch_mean), ema.average(batch_var))) normed = tf.nn.batch_normalization(x, mean, var, beta, gamma, 1e-3) return normed
tensorflow.control_dependencies
8,225
import tensorflow as tf with tf.variable_scope("model"): # ------------------------------------------------ # Random initialization Load weights from weights path # for Initial state, Weight matrices, and bias weights # ------------------------------------------------ if self.load_weights_path is None: # random initializations init_state_initializer = tf.random_normal_initializer(mean=0.1, stddev=0.01) W_in_initializer = tf.constant_initializer( 0.1 * np.random.uniform(-1, 1, size=(self.N_rec, self.N_in))) W_rec_initializer = tf.constant_initializer(self.initial_W()) W_out_initializer = tf.constant_initializer( 0.1 * np.random.uniform(-1, 1, size=(self.N_out, self.N_rec))) b_rec_initializer = tf.constant_initializer(0.0) b_out_initializer = tf.constant_initializer(0.0) else: print("Loading Weights") weights = np.load(self.load_weights_path) init_state_initializer = tf.constant_initializer(weights['init_state']) W_in_initializer = tf.constant_initializer(weights['W_in']) W_rec_initializer = tf.constant_initializer(weights['W_rec']) W_out_initializer = tf.constant_initializer(weights['W_out']) b_rec_initializer = tf.constant_initializer(weights['b_rec']) b_out_initializer = tf.constant_initializer(weights['b_out']) self.input_connectivity_mask = weights['input_Connectivity'] self.recurrent_connectivity_mask = weights['rec_Connectivity']
tensorflow.constant_initializer
8,226
import tensorflow as tf x1_f = tf.to_float(x1) y0_f = tf.to_float(y0) y1_f = tf.to_float(y1) z0_f = tf.to_float(z0) z1_f = tf.to_float(z1) # Check the out-of-boundary case. x0_valid = tf.to_float( tf.less_equal(x0, max_x) & tf.greater_equal(x0, 0)) x1_valid = tf.to_float( tf.less_equal(x1, max_x) & tf.greater_equal(x1, 0)) y0_valid = tf.to_float( tf.less_equal(y0, max_y) & tf.greater_equal(y0, 0)) y1_valid = tf.to_float( tf.less_equal(y1, max_y) & tf.greater_equal(y1, 0)) z0_valid = tf.to_float( tf.less_equal(z0, max_z) & tf.greater_equal(z0, 0)) z1_valid = tf.to_float( tf.less_equal(z1, max_z) & tf.greater_equal(z1, 0)) w_z0_y0_x0 = tf.expand_dims(((x1_f - x) * (y1_f - y) * (z1_f - z) * x1_valid * y1_valid * z1_valid), 1) w_z0_y0_x1 = tf.expand_dims(((x - x0_f) * (y1_f - y) * (z1_f - z) * x0_valid * y1_valid * z1_valid), 1) w_z0_y1_x0 = tf.expand_dims(((x1_f - x) * (y - y0_f) * (z1_f - z) * x1_valid * y0_valid * z1_valid), 1) w_z0_y1_x1 = tf.expand_dims(((x - x0_f) * (y - y0_f) * (z1_f - z) * x0_valid * y0_valid * z1_valid),
tensorflow.less_equal
8,227
import tensorflow as tf tf.summary.scalar('location_loss', loc_loss) tf.losses.add_loss(loc_loss) # Add weight decay to the loss. We exclude the batch norm variables because # doing so leads to a small improvement in accuracy. loss = cross_entropy + loc_loss + params['weight_decay'] * tf.add_n( [tf.nn.l2_loss(v) for v in tf.trainable_variables() if 'batch_normalization' not in v.name]) total_loss = tf.identity(loss, name='total_loss') if mode == tf.estimator.ModeKeys.TRAIN: global_step = tf.train.get_or_create_global_step() lr_values = [params['learning_rate'] * decay for decay in params['lr_decay_factors']] learning_rate = tf.train.piecewise_constant(tf.cast(global_step, tf.int32), [int(_) for _ in params['decay_boundaries']],
tensorflow.identity
8,228
import tensorflow as tf with arg_scope([slim.conv2d, slim.conv2d_in_plane, slim.conv2d_transpose, slim.separable_conv2d, slim.fully_connected], weights_regularizer=weights_regularizer, biases_regularizer=biases_regularizer, biases_initializer=tf.constant_initializer(0.0)): rois, cls_prob, bbox_pred = self.build_network(sess, training) layers_to_output = {'rois': rois}
tensorflow.constant_initializer
8,229
from tensorflow.python.framework import ops "of at least one of the inputs.") with ops.op_scope(inputs, name, "AccumulateN") as name:
tensorflow.python.framework.ops.op_scope
8,230
import tensorflow as tf candidate_start_sentence_indices = tf.gather(flattened_sentence_indices, candidate_starts) # [num_words, max_span_width] candidate_end_sentence_indices = tf.gather(flattened_sentence_indices, tf.minimum(candidate_ends, num_words - 1)) # [num_words, max_span_width] candidate_mask = tf.logical_and(candidate_ends < num_words, tf.equal(candidate_start_sentence_indices, candidate_end_sentence_indices)) # [num_words, max_span_width] flattened_candidate_mask = tf.reshape(candidate_mask, [-1]) # [num_words * max_span_width] candidate_starts = tf.boolean_mask(tf.reshape(candidate_starts, [-1]), flattened_candidate_mask) # [num_candidates] candidate_ends = tf.boolean_mask(tf.reshape(candidate_ends, [-1]), flattened_candidate_mask) # [num_candidates] candidate_sentence_indices = tf.boolean_mask(tf.reshape(candidate_start_sentence_indices, [-1]), flattened_candidate_mask) # [num_candidates] candidate_cluster_ids = self.get_candidate_labels(candidate_starts, candidate_ends, gold_starts, gold_ends, cluster_ids) # [num_candidates] candidate_span_emb = self.get_span_emb(flattened_head_emb, context_outputs, candidate_starts, candidate_ends) # [num_candidates, emb] candidate_mention_scores = self.get_mention_scores(candidate_span_emb) # [k, 1] candidate_mention_scores = tf.squeeze(candidate_mention_scores, 1) # [k] k = tf.to_int32(tf.floor(tf.to_float(tf.shape(context_outputs)[0]) * self.config["top_span_ratio"])) top_span_indices = coref_ops.extract_spans(tf.expand_dims(candidate_mention_scores, 0), tf.expand_dims(candidate_starts, 0), tf.expand_dims(candidate_ends, 0), tf.expand_dims(k, 0), util.shape(context_outputs, 0), True) # [1, k] top_span_indices.set_shape([1, None]) top_span_indices = tf.squeeze(top_span_indices, 0) # [k] top_span_starts = tf.gather(candidate_starts, top_span_indices) # [k] top_span_ends = tf.gather(candidate_ends, top_span_indices) # [k] top_span_emb = tf.gather(candidate_span_emb, top_span_indices) # [k, emb] top_span_cluster_ids = tf.gather(candidate_cluster_ids, top_span_indices) # [k] top_span_mention_scores = tf.gather(candidate_mention_scores, top_span_indices) # [k] top_span_sentence_indices = tf.gather(candidate_sentence_indices, top_span_indices) # [k]
tensorflow.expand_dims
8,231
import tensorflow as tf pareto = tfd.Pareto(concentration, scale) self.assertEqual(self.evaluate(pareto.batch_shape_tensor()), (5,)) self.assertEqual(pareto.batch_shape, tf.TensorShape([5])) self.assertAllEqual(self.evaluate(pareto.event_shape_tensor()), []) self.assertEqual(pareto.event_shape, tf.TensorShape([])) def testParetoShapeBroadcast(self): scale = tf.constant([[3., 2.]]) concentration = tf.constant([[4.], [5.], [6.]]) pareto = tfd.Pareto(concentration, scale) self.assertAllEqual(self.evaluate(pareto.batch_shape_tensor()), (3, 2)) self.assertAllEqual(pareto.batch_shape, tf.TensorShape([3, 2])) self.assertAllEqual(self.evaluate(pareto.event_shape_tensor()), []) self.assertEqual(pareto.event_shape, tf.TensorShape([])) def testInvalidScale(self): invalid_scales = [-.01, 0., -2.] concentration = 3. for scale in invalid_scales: with self.assertRaisesOpError("Condition x > 0"): pareto = tfd.Pareto(concentration, scale, validate_args=True) self.evaluate(pareto.scale) def testInvalidConcentration(self): scale = 1. invalid_concentrations = [-.01, 0., -2.] for concentration in invalid_concentrations: with self.assertRaisesOpError("Condition x > 0"):
tensorflow.TensorShape
8,232
import tensorflow as tf return losses, [outputs], encoder_state, attention_states, attention_weights, samples, beam_fun, initial_data def softmax(logits, dim=-1, mask=None): e = tf.exp(logits) if mask is not None: e *= mask return e / tf.clip_by_value(tf.reduce_sum(e, axis=dim, keep_dims=True), 10e-37, 10e+37) def sequence_loss(logits, targets, weights, average_across_timesteps=False, average_across_batch=True, rewards=None): batch_size = tf.shape(targets)[0] time_steps = tf.shape(targets)[1] logits_ = tf.reshape(logits, tf.stack([time_steps * batch_size, logits.get_shape()[2].value]))
tensorflow.reduce_sum
8,233
import tensorflow as tf if tt_rank.size == 1: tt_rank = tt_rank * np.ones(num_dims - 1) tt_rank = np.concatenate([[1], tt_rank, [1]]) shape = shape.astype(int) tt_rank = tt_rank.astype(int) cr_exponent = -1.0 / (2 * num_dims) var = np.prod(tt_rank ** cr_exponent) core_stddev = stddev ** (1.0 / num_dims) * var with tf.name_scope(name): tt = matrix_batch_with_random_cores(shape, tt_rank=tt_rank, stddev=core_stddev, batch_size=batch_size, dtype=dtype) if np.abs(mean) < 1e-8: return tt else: raise NotImplementedError('non-zero mean is not supported yet')
tensorflow.name_scope
8,234
import tensorflow as tf data_format=self.channel_pos, use_bias=False) else: rate = 1 # Unused (for 'a trous' convolutions) kernel_size_effective = k_height + (k_width - 1) * (rate - 1) pad_total = kernel_size_effective - 1 pad_beg = pad_total // 2 pad_end = pad_total - pad_beg 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], padding='VALID', data_format=self.channel_pos, use_bias=False) if batch_norm is None: batch_norm = self.use_batch_norm if not batch_norm:
tensorflow.pad
8,235
import tensorflow as tf initializer=tf.truncated_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.strides = [1, d_h, d_w, 1] self.padding = padding self.epsilon = epsilon def __call__(self,input_var,name=None,**kwargs) : def _init(): v_norm = tf.nn.l2_normalize(self.v,axis=[0,1,2]) t = tf.nn.conv2d(input_var,v_norm,self.strides,self.padding,data_format='NHWC') mu,var = tf.nn.moments(t,axes=[0,1,2]) std = tf.sqrt(var+self.epsilon) return [tf.assign(self.g,1/std),tf.assign(self.b,-1.*mu/std)] require_init = tf.reduce_any(tf.is_nan(self.g)) init_ops = tf.cond(require_init,_init,lambda : [self.g,self.b]) with tf.control_dependencies(init_ops): w = tf.reshape(self.g,[1,1,1,tf.shape(self.v)[-1]]) * tf.nn.l2_normalize(self.v,axis=[0,1,2]) return tf.nn.bias_add( tf.nn.conv2d(input_var, w,data_format='NHWC', strides=self.strides, padding=self.padding), self.b,data_format='NHWC',name=name) def get_variables(self):
tensorflow.nn.moments
8,236
import tensorflow.contrib.graph_editor as ge fwd_ops = [op for op in fwd_ops if not '/read' in op.name] ts_all = ge.filter_ts(fwd_ops, True) # get the tensors
tensorflow.contrib.graph_editor.filter_ts
8,237
import tensorflow as tf :param white: boolean of whether to use the whitened representation as described above. :return: - mean: N x R - variance: N x R (full_cov = False), R x N x N (full_cov = True) """ logger.debug("Conditional: Kernel") num_data = tf.shape(X)[0] # M Kmm = kern.K(X) + tf.eye(num_data, dtype=settings.float_type) * settings.numerics.jitter_level Kmn = kern.K(X, Xnew) if full_cov: Knn = kern.K(Xnew) else: Knn = kern.Kdiag(Xnew) mean, var = base_conditional(Kmn, Kmm, Knn, f, full_cov=full_cov, q_sqrt=q_sqrt, white=white)
tensorflow.eye
8,238
import tensorflow as tf if(h < len(layers_width)-2): # Perform affine mapping at each layer of the neural network Z = tf.layers.dense(Z, n_basis//2) # Define variational parameters
tensorflow.layers.dense
8,239
import tensorflow as tf 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.get_variable
8,240
import tensorflow as tf loss_class = tf.where(mask_neg, 1 - class_pred[:, 0][..., tf.newaxis], 0) # 2. hard negative mining loss_class = tf.reshape(loss_class, [num_batch, num_prior]) loss_class_idx = tf.argsort(loss_class, axis=1, direction='DESCENDING') loss_class_idx_rank = tf.argsort(loss_class_idx, axis=1) mask_pos_per_batch = tf.reshape(mask_pos, [num_batch, num_prior]) num_pos_per_batch = tf.reduce_sum( tf.cast(mask_pos_per_batch, tf.float32), 1, keepdims=True)
tensorflow.argsort
8,241
from tensorflow.python.platform import tf_logging as logging """ logging.info("Create CheckpointSaver.")
tensorflow.python.platform.tf_logging.info
8,242
import tensorflow as tf def _add_dynamic_cell(self, cell_arch, layers, w, h, block_ch, drop_path_keep_prob, is_train=False): b = CELL_NUM_BLOCKS # Downsample inputs to have same dimensions as blocks with tf.variable_scope('layer_-1_calibrate'): layers[-1] = (self._calibrate(*layers[-1], w, h, block_ch, is_train=is_train), w, h, block_ch) with tf.variable_scope('layer_-2_calibrate'): layers[-2] = (self._calibrate(*layers[-2], w, h, block_ch, is_train=is_train), w, h, block_ch)
tensorflow.variable_scope
8,243
from tensorflow.python.framework import ops """Pass resource_variable_ops.is_resource_variable check.""" pass def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False): """Converts a variable to a tensor.""" # pylint: disable=protected-access if _enclosing_tpu_context() is None: if hasattr(self._primary_var, '_dense_var_to_tensor'): return self._primary_var._dense_var_to_tensor(dtype, name, as_ref) else: return ops.convert_to_tensor(self._primary_var) # pylint: enable=protected-access if dtype is not None and dtype != self.dtype: return NotImplemented if as_ref: return self.handle else: return self.read_value()
tensorflow.python.framework.ops.convert_to_tensor
8,244
import tensorflow as tf log("Tacotron training set to a maximum of {} steps".format(args.tacotron_train_steps)) # Memory allocation on the GPU as needed config = tf.ConfigProto() config.gpu_options.allow_growth = True config.allow_soft_placement = True
tensorflow.ConfigProto
8,245
import tensorflow as tf 'number of batches to run, excluding warmup') tf.flags.DEFINE_integer('num_warmup_batches', None, 'number of batches to run before timing') tf.flags.DEFINE_integer('autotune_threshold', None, 'The autotune threshold for the models') tf.flags.DEFINE_integer('num_gpus', 1, 'the number of GPUs to run on') tf.flags.DEFINE_integer('display_every', 10, """Number of local steps after which progress is printed out""") tf.flags.DEFINE_string('data_dir', None, """Path to dataset in TFRecord format (aka Example protobufs). If not specified, synthetic data will be used.""") tf.flags.DEFINE_string('data_name', None, """Name of dataset: imagenet or flowers. If not specified, it is automatically guessed based on --data_dir.""") tf.flags.DEFINE_string('resize_method', 'bilinear', """Method for resizing input images:
tensorflow.flags.DEFINE_string
8,246
import tensorflow as tf total_loss = tf.nn.seq2seq.sequence_loss( logits, targets, weights, average_across_timesteps=False, average_across_batch=False) res = sess.run(total_loss) 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) self.assertAllClose(np.asarray([1.609438, 1.609438]), res)
tensorflow.constant
8,247
import tensorflow as tf tf.app.flags.DEFINE_string('eval_data_path', '', 'Filepattern for eval data') tf.app.flags.DEFINE_string('train_dir', '', 'Directory to keep training outputs.') tf.app.flags.DEFINE_string('eval_dir', '', 'Directory to keep eval outputs.') tf.app.flags.DEFINE_integer('eval_batch_count', 10, 'Number of batches to eval.') tf.app.flags.DEFINE_bool('eval_once', False, 'Whether evaluate the model only once.') tf.app.flags.DEFINE_string('log_root', '', 'Directory to keep the checkpoints. Should be a ' 'parent directory of FLAGS.train_dir/eval_dir.') tf.app.flags.DEFINE_integer('num_gpus', 0, 'Number of gpus used for training. (0 or 1)') tf.app.flags.DEFINE_integer('num_residual_units', 5, 'num of residual units') tf.app.flags.DEFINE_string('Optimizer', 'mom', 'The optimizer used to train the model.') tf.app.flags.DEFINE_bool('RCE_train', False, 'Whether use RCE to train the model.') tf.app.flags.DEFINE_string('attack_method', 'fgsm', 'The attacking method used') tf.app.flags.DEFINE_float('eps', 0.01, 'The eps in attacking methods.') tf.app.flags.DEFINE_string('save_pwd', None,
tensorflow.app.flags.DEFINE_integer
8,248
import tensorflow.contrib.layers as layers out = img_in with tf.variable_scope("convnet"): # original architecture out = layers.convolution2d(out, num_outputs=32, kernel_size=8, stride=4, activation_fn=tf.nn.relu) out = layers.convolution2d(out, num_outputs=64, kernel_size=4, stride=2, activation_fn=tf.nn.relu) out = layers.convolution2d(out, num_outputs=64, kernel_size=3, stride=1, activation_fn=tf.nn.relu)
tensorflow.contrib.layers.convolution2d
8,249
import tensorflow as tf def commutes_with_sum(self): """See base class.""" return True @property def decode_needs_input_shape(self): """See base class.""" return False def get_params(self): """See base class.""" params = {self.FACTOR_PARAM_KEY: tf.constant(2.0)} return params, params def encode(self, x, encode_params): """See base class.""" return {self.ENCODED_VALUES_KEY: x * encode_params[self.FACTOR_PARAM_KEY]} def decode(self, encoded_tensors, decode_params, num_summands=None,
tensorflow.constant
8,250
import tensorflow as tf labels=masked_lm_ids, predictions=masked_lm_predictions, weights=masked_lm_weights) masked_lm_mean_loss = tf.metrics.mean( values=masked_lm_example_loss, weights=masked_lm_weights) next_sentence_log_probs = tf.reshape( next_sentence_log_probs, [-1, next_sentence_log_probs.shape[-1]]) next_sentence_predictions = tf.argmax( next_sentence_log_probs, axis=-1, output_type=tf.int32) next_sentence_labels = tf.reshape(next_sentence_labels, [-1]) next_sentence_accuracy = tf.metrics.accuracy(
tensorflow.reshape
8,251
import tensorflow as tf inputs.append(inputs_) encoder_inputs_ = tf.concat(inputs, axis=2) # if encoder.convolution_activation.lower() == 'relu': encoder_inputs_ = tf.nn.relu(encoder_inputs_) if encoder.maxout_stride: if encoder.binary: raise NotImplementedError stride = encoder.maxout_stride k = tf.to_int32(tf.ceil(time_steps / stride) * stride) - time_steps # TODO: simpler pad = tf.zeros([batch_size, k, tf.shape(encoder_inputs_)[2]]) encoder_inputs_ = tf.concat([encoder_inputs_, pad], axis=1) encoder_inputs_ = tf.nn.pool(encoder_inputs_, window_shape=[stride], pooling_type='MAX', padding='VALID', strides=[stride]) encoder_input_length_ = tf.to_int32(tf.ceil(encoder_input_length_ / stride)) if encoder.highway_layers: x = encoder_inputs_ for j in range(encoder.highway_layers): size = x.shape[2].value with tf.variable_scope('highway_{}'.format(j + 1)): g = tf.layers.dense(x, size, activation=tf.nn.sigmoid, use_bias=True, name='g') y = tf.layers.dense(x, size, activation=tf.nn.relu, use_bias=True, name='y') x = g * y + (1 - g) * x
tensorflow.nn.pool
8,252
import tensorflow as tf # sess.close() identity_matrix = tf.diag([1.0, 3.0, 1.0]) A = tf.truncated_normal([2, 3]) B = tf.fill([2, 3], 5.0) C = tf.random_uniform([3, 2], maxval=100) D = tf.convert_to_tensor(np.array([[1., 2., 3.], [-3., -7., -1.], [0., 5., -2.]])) sess = tf.Session() # sess.run(tf.global_variables_initializer())
tensorflow.fill
8,253
import tensorflow as tf name="biases") hidden1 = tf.nn.relu(tf.matmul(images, weights) + biases) # Hidden 2 with tf.name_scope("hidden2"): weights = tf.Variable( tf.truncated_normal([128, 32], stddev=1.0 / math.sqrt(float(128))), name="weights") biases = tf.Variable(tf.zeros([32]), name="biases") hidden2 = tf.nn.relu(tf.matmul(hidden1, weights) + biases) # Linear with tf.name_scope("softmax_linear"): weights = tf.Variable( tf.truncated_normal([32, 10], stddev=1.0 / math.sqrt(float(32))),
tensorflow.zeros
8,254
from tensorflow.python.framework import constant_op constant_op.constant(indices, dtypes.int64, [len(indices), 2]), constant_op.constant(values, value_type, [len(indices)]), constant_op.constant(shape, dtypes.int64))
tensorflow.python.framework.constant_op.constant
8,255
import tensorflow as tf self.assertEqual((2, 2), res[0].shape) def testEmbeddingRNNDecoder(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.BasicLSTMCell(2, state_is_tuple=True) _, enc_state = tf.nn.rnn(cell, inp, dtype=tf.float32) dec_inp = [tf.constant(i, tf.int32, shape=[2]) for i in range(3)] dec, mem = tf.nn.seq2seq.embedding_rnn_decoder( dec_inp, enc_state, cell, num_symbols=4, embedding_size=2) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 2), res[0].shape)
tensorflow.constant
8,256
import tensorflow as tf import numpy as np import tensorflow as tf import layers as L import vat FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_string('device', '/gpu:0', "device") tf.app.flags.DEFINE_string('dataset', 'cifar10', "{cifar10, svhn}") tf.app.flags.DEFINE_string('log_dir', "", "log_dir") tf.app.flags.DEFINE_integer('seed', 1, "initial random seed") tf.app.flags.DEFINE_bool('validation', False, "") tf.app.flags.DEFINE_integer('batch_size', 32, "the number of examples in a batch") tf.app.flags.DEFINE_integer('ul_batch_size', 128, "the number of unlabeled examples in a batch") tf.app.flags.DEFINE_integer('eval_batch_size', 100, "the number of eval examples in a batch") tf.app.flags.DEFINE_integer('eval_freq', 5, "") tf.app.flags.DEFINE_integer('num_epochs', 120, "the number of epochs for training") tf.app.flags.DEFINE_integer('epoch_decay_start', 80, "epoch of starting learning rate decay") tf.app.flags.DEFINE_integer('num_iter_per_epoch', 400, "the number of updates per epoch") tf.app.flags.DEFINE_float('learning_rate', 0.001, "initial leanring rate") tf.app.flags.DEFINE_float('mom1', 0.9, "initial momentum rate") tf.app.flags.DEFINE_float('mom2', 0.5, "momentum rate after epoch_decay_start") tf.app.flags.DEFINE_string('method', 'vat', "{vat, vatent, baseline}")
tensorflow.app.flags.DEFINE_bool
8,257
import tensorflow as tf return two_stream_loss(FLAGS, features, labels, mems, is_training) else: return two_stream_loss(FLAGS, features, labels, mems, is_training) def get_classification_loss( FLAGS, features, n_class, is_training): """Loss for downstream classification tasks.""" bsz_per_core = tf.shape(features["input_ids"])[0] inp = tf.transpose(features["input_ids"], [1, 0]) seg_id = tf.transpose(features["segment_ids"], [1, 0]) inp_mask = tf.transpose(features["input_mask"], [1, 0]) label = tf.reshape(features["label_ids"], [bsz_per_core]) xlnet_config = xlnet.XLNetConfig(json_path=FLAGS.model_config_path) run_config = xlnet.create_run_config(is_training, True, FLAGS) xlnet_model = xlnet.XLNetModel( xlnet_config=xlnet_config, run_config=run_config, input_ids=inp, seg_ids=seg_id, input_mask=inp_mask)
tensorflow.transpose
8,258
import tensorflow as tf def dice(_x, axis=-1, epsilon=0.000000001, name=''): with tf.variable_scope(name, reuse=tf.AUTO_REUSE): alphas = tf.get_variable('alpha'+name, _x.get_shape()[-1], initializer=tf.constant_initializer(0.0), dtype=_x.dtype) input_shape = list(_x.get_shape()) reduction_axes = list(range(len(input_shape))) del reduction_axes[axis] broadcast_shape = [1] * len(input_shape) broadcast_shape[axis] = input_shape[axis] # case: train mode (uses stats of the current batch) mean = tf.reduce_mean(_x, axis=reduction_axes) brodcast_mean = tf.reshape(mean, broadcast_shape) std = tf.reduce_mean(tf.square(_x - brodcast_mean) + epsilon, axis=reduction_axes) std = tf.sqrt(std) brodcast_std = tf.reshape(std, broadcast_shape) x_normed = (_x - brodcast_mean) / (brodcast_std + epsilon) # x_normed = tf.layers.batch_normalization(_x, center=False, scale=False) x_p = tf.sigmoid(x_normed) return alphas * (1.0 - x_p) * _x + x_p * _x class QAAttGRUCell(RNNCell): """Gated Recurrent Unit cell (cf. http://arxiv.org/abs/1406.1078). Args: num_units: int, The number of units in the GRU cell. activation: Nonlinearity to use. Default: `tanh`.
tensorflow.square
8,259
import tensorflow as tf self.char_mat = tf.get_variable( "char_mat", initializer=tf.constant(char_mat, dtype=tf.float32)) self.c_mask = tf.cast(self.c, tf.bool) 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) if opt: # we have to hardcode the max batch size here! use the batch size from the generator as this will be used for PG N, CL = config.batch_size if not self.demo else config.batch_size, config.char_limit self.c_maxlen = tf.reduce_max(self.c_len) self.q_maxlen = tf.reduce_max(self.q_len) self.c = tf.slice(self.c, [0, 0], [N, self.c_maxlen]) self.q = tf.slice(self.q, [0, 0], [N, self.q_maxlen]) self.c_mask = tf.slice(self.c_mask, [0, 0], [N, self.c_maxlen]) self.q_mask = tf.slice(self.q_mask, [0, 0], [N, self.q_maxlen]) self.ch = tf.slice(self.ch, [0, 0, 0], [N, self.c_maxlen, CL]) self.qh = tf.slice(self.qh, [0, 0, 0], [N, self.q_maxlen, CL]) self.y1 = tf.argmax(tf.slice(self.y1, [0, 0], [N, self.c_maxlen]),axis=-1) self.y2 = tf.argmax(tf.slice(self.y2, [0, 0], [N, self.c_maxlen]),axis=-1) else:
tensorflow.reduce_max
8,260
import tensorflow as tf def to_one_hot(i, n_classes=None): a = np.zeros(n_classes, 'uint8') a[i] = 1 return a render = False # display the game environment running_reward = None tf.reset_default_graph() ## Define Q-network q(a,s) that ouput the rewards of 4 actions by given state, i.e. Action-Value Function. # 4x4 grid can be represented by one-hot vector with 16 integers. inputs = tf.placeholder(shape=[1, 16], dtype=tf.float32) net = InputLayer(inputs, name='observation') net = DenseLayer(net, n_units=4, act=tf.identity, W_init=tf.random_uniform_initializer(0, 0.01), b_init=None, name='q_a_s') y = net.outputs # action-value / rewards of 4 actions predict = tf.argmax(y, 1) # chose action greedily with reward. in Q-Learning, policy is greedy, so we use "max" to select the next action. ## Below we obtain the loss by taking the sum of squares difference between the target and prediction Q values. nextQ = tf.placeholder(shape=[1, 4], dtype=tf.float32) loss = tl.cost.mean_squared_error(nextQ, y, is_mean=False) # tf.reduce_sum(tf.square(nextQ - y)) train_op = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(loss)
tensorflow.placeholder
8,261
import tensorflow as tf generator_loss = generator_c_loss + generator_g_loss # Supervised Encoder Loss supervised_encoder_loss = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=y_input, logits=encoder_output_label_)) all_variables = tf.trainable_variables() dc_g_var = [var for var in all_variables if 'dc_g_' in var.name] dc_c_var = [var for var in all_variables if 'dc_c_' in var.name] en_var = [var for var in all_variables if 'e_' in var.name] # Optimizers autoencoder_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1).minimize(autoencoder_loss) discriminator_g_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1).minimize(dc_g_loss, var_list=dc_g_var) discriminator_c_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1).minimize(dc_c_loss, var_list=dc_c_var) generator_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1).minimize(generator_loss, var_list=en_var) supervised_encoder_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1).minimize(supervised_encoder_loss, var_list=en_var)
tensorflow.train.AdamOptimizer
8,262
import tensorflow as tf """Creates an `input_fn` closure to be passed to TPUEstimator.""" def input_fn(params): """The actual input function.""" # batch_size = params["batch_size"] name_to_features = { "input_ids": tf.FixedLenFeature([max_seq_length], tf.int64), "input_mask": tf.FixedLenFeature([max_seq_length], tf.int64), "segment_ids": tf.FixedLenFeature([max_seq_length], tf.int64), "masked_lm_positions": tf.FixedLenFeature([max_predictions_per_seq], tf.int64), "masked_lm_ids": tf.FixedLenFeature([max_predictions_per_seq], tf.int64), "masked_lm_weights": tf.FixedLenFeature([max_predictions_per_seq], tf.float32), "next_sentence_labels":
tensorflow.FixedLenFeature
8,263
import tensorflow as tf # layers l_a = tf.layers.dense(self.state, 200, tf.nn.relu6, kernel_initializer=w_init, name='la') self.mu = tf.layers.dense(l_a, num_action, tf.nn.tanh, kernel_initializer=w_init, name='mu') # estimated action value self.sigma = tf.layers.dense(l_a, num_action, tf.nn.softplus, kernel_initializer=w_init, name='sigma') # estimated variance # wrap output self.mu = self.mu * action_bound[1]; self.sigma = self.sigma + 1e-4 # get action from distribution self.normal_dist = tf.contrib.distributions.Normal(self.mu, self.sigma) self.action = tf.squeeze(self.normal_dist.sample(1),axis=0); self.action = tf.clip_by_value(self.action, action_bound[0], action_bound[1]) # Loss and train op self.loss = -self.normal_dist.log_prob(self.a_his) * self.target # Add cross entropy cost to encourage exploration self.loss -= entropy_beta * self.normal_dist.entropy() self.optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) self.grads_and_vars = self.optimizer.compute_gradients(self.loss) self.grads=[];
tensorflow.contrib.distributions.Normal
8,264
import tensorflow.contrib.eager as tfe examples_per_sec = num_epochs * num_batches * batch_size / wall_time self.report_benchmark( name="eager_train_%s" % ("gpu" if tfe.num_gpus() > 0 else "cpu"), iters=num_epochs * num_batches, extras={"examples_per_sec": examples_per_sec}, wall_time=wall_time)
tensorflow.contrib.eager.num_gpus
8,265
import tensorflow as tf 'adj_orig': tf.sparse_placeholder(tf.float32), 'dropout': tf.placeholder_with_default(0., shape=())
tensorflow.placeholder_with_default
8,266
import tensorflow as tf tf.compat.v2.summary.scalar( name="max_q", data=tf.reduce_mean(max_q), step=global_step) ### End metrics # For both state-centric and goal-centric relabelling, the implementation of # mixing is the same: we randomly replace some of the indices with the # diagonal. relabelled_tasks = tf.gather(candidate_tasks, tf.squeeze(relabel_indices)) if self._relabel_prob == 0: relabelled_tasks = orig_tasks elif 0 < self._relabel_prob < 1: logits = tf.log([1.0 - self._relabel_prob, self._relabel_prob]) mask = tf.squeeze( tf.random.categorical( logits[None], num_samples=self._sample_batch_size)) mask = tf.cast(mask, tf.float32)[:, None] relabelled_tasks = mask * orig_tasks + (1 - mask) * relabelled_tasks states_and_tasks = self._task_distribution.combine(states, relabelled_tasks) next_states_and_tasks = self._task_distribution.combine( next_states, relabelled_tasks) new_observation = tf.concat( [states_and_tasks[:, None], next_states_and_tasks[:, None]], axis=1) assert new_observation.shape == experience.observation.shape
tensorflow.log
8,267
import tensorflow as tf y_true = tf.reshape(y_true, shape=(batch_size, -1, num_of_joints)) heatmap_true_list = tf.split(value=y_true, # y_true执行与y_pred相同的操作 num_or_size_splits=num_of_joints, axis=-1) losses = [] # 计算每一个关键点的损失值,并累加求平均 for i in range(num_of_joints): heatmap_pred = tf.squeeze(heatmap_pred_list[i]) heatmap_true = tf.squeeze(heatmap_true_list[i]) loss = 0.5 * tf.losses.mean_squared_error(y_pred=heatmap_pred * true_weight[:, i], y_true=heatmap_true * true_weight[:, i]) losses.append(loss) return tf.reduce_mean(loss)
tensorflow.squeeze
8,268
import tensorflow as tf encoder_output_label, encoder_output_latent = encoder(x_input) # Concat class label and the encoder output decoder_input = tf.concat([encoder_output_label, encoder_output_latent], 1) decoder_output = decoder(decoder_input)
tensorflow.concat
8,269
import tensorflow as tf return tf.contrib.layers.xavier_initializer() elif params.initializer == "uniform": max_val = params.initializer_gain return tf.random_uniform_initializer(-max_val, max_val) elif params.initializer == "normal": return tf.random_normal_initializer(0.0, params.initializer_gain)
tensorflow.random_uniform_initializer
8,270
import tensorflow as tf - one_hot_labels_arguments * tf.log(tf.clip_by_value(self.predictions_arguments, 1e-10, 1.0)), name='loss' ) self.loss = loss_action + loss_arguments tf.scalar_summary('loss', self.loss) with tf.name_scope('accuracy'): correct_prediction_action = tf.equal( tf.argmax(one_hot_labels_action, 1), tf.argmax(self.predictions_action, 1) ) self.accuracy_action = tf.reduce_mean(tf.cast(correct_prediction_action, 'float')) tf.scalar_summary('accuracy_action', self.accuracy_action) correct_prediction_arguments = tf.equal(tf.argmax(one_hot_labels_arguments, 2), tf.argmax(self.predictions_arguments, 2)) self.accuracy_arguments = tf.reduce_mean(tf.cast(correct_prediction_arguments, 'float')) tf.scalar_summary('accuracy_arguments', self.accuracy_arguments)
tensorflow.cast
8,271
import tensorflow as tf 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)
tensorflow.cast
8,272
import tensorflow as tf q_func_results = q_func(observations_ph.get(), num_actions, scope="q_func") q_values = q_func_results['q'] s_value = q_func_results['s'] a_values = q_func_results['a'] deterministic_actions = tf.argmax(q_values, axis=1) batch_size = tf.shape(observations_ph.get())[0] random_actions = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=num_actions, dtype=tf.int64) chose_random = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=1, dtype=tf.float32) < eps stochastic_actions = tf.where(chose_random, random_actions, deterministic_actions) 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, q_values, s_value, a_values, update_eps_expr], givens={update_eps_ph: test_epsilon, stochastic_ph: False},
tensorflow.stack
8,273
import tensorflow as tf return True def _infer_raw_shape(tt_cores): """Tries to infer the (static) raw shape from the TT-cores.""" num_dims = len(tt_cores) num_tensor_shapes = len(tt_cores[0].get_shape().as_list()) - 2 raw_shape = [[] for _ in range(num_tensor_shapes)] for dim in range(num_dims): curr_core_shape = tt_cores[dim].get_shape() for i in range(num_tensor_shapes): raw_shape[i].append(curr_core_shape[i + 1]) for i in range(num_tensor_shapes): raw_shape[i] = tf.TensorShape(raw_shape[i]) return tuple(raw_shape) def _infer_tt_ranks(tt_cores): """Tries to infer the (static) raw shape from the TT-cores.""" tt_ranks = [] for i in range(len(tt_cores)): tt_ranks.append(tt_cores[i].get_shape()[0]) tt_ranks.append(tt_cores[-1].get_shape()[-1]) return tf.TensorShape(tt_ranks)
tensorflow.TensorShape
8,274
import tensorflow as tf apply_gradient_op = opt.apply_gradients(grads, global_step=global_step) summary_op = tf.summary.merge_all() # save moving average variable_averages = tf.train.ExponentialMovingAverage( FLAGS.moving_average_decay, global_step) variables_averages_op = variable_averages.apply(tf.trainable_variables()) # batch norm updates with tf.control_dependencies([variables_averages_op, apply_gradient_op, batch_norm_updates_op]): train_op = tf.no_op(name='train_op') saver = tf.train.Saver(tf.global_variables()) summary_writer = tf.summary.FileWriter(FLAGS.checkpoint_path, tf.get_default_graph()) init = tf.global_variables_initializer() if FLAGS.pretrained_model_path is not None: variable_restore_op = slim.assign_from_checkpoint_fn(FLAGS.pretrained_model_path, slim.get_trainable_variables(), ignore_missing_vars=True) config = tf.ConfigProto() custom_op = config.graph_options.rewrite_options.custom_optimizers.add() custom_op.name = "NpuOptimizer" custom_op.parameter_map["use_off_line"].b = True # 在昇腾AI处理器执行训练
tensorflow.get_default_graph
8,275
import tensorflow as tf # Train with tf.Session(config=config) as sess: try: summary_writer = tf.summary.FileWriter(tensorboard_dir, sess.graph) sess.run(tf.global_variables_initializer()) # saved model restoring if args.restore: # Restore saved model if the user requested it, default = True try:
tensorflow.global_variables_initializer
8,276
import tensorflow as tf res = tf.cast(res, dtype=tf.float32) res = tf.multiply(res, loss_weights) return tf.reduce_sum(res)
tensorflow.reduce_sum
8,277
import tensorflow as tf 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)
tensorflow.contrib.rnn.DropoutWrapper
8,278
from tensorflow.python.ops import math_ops def _prepare(self): self._lr_t = ops.convert_to_tensor(self._lr, name="learning_rate") self._beta1_t = ops.convert_to_tensor(self._beta1, name="beta1") self._beta2_t = ops.convert_to_tensor(self._beta2, name="beta2") def _create_slots(self, var_list): # Create slots for the first and second moments. for v in var_list: self._zeros_slot(v, "m", self._name) self._zeros_slot(v, "v", self._name) self._zeros_slot(v, "g", self._name) def _apply_dense(self, grad, var): lr_t = math_ops.cast(self._lr_t, var.dtype.base_dtype) beta1_t = math_ops.cast(self._beta1_t, var.dtype.base_dtype) beta2_t = math_ops.cast(self._beta2_t, var.dtype.base_dtype) if var.dtype.base_dtype == tf.float16: eps = 1e-7 # Can't use 1e-8 due to underflow -- not sure if it makes a big difference. else: eps = 1e-8 v = self.get_slot(var, "v") v_t = v.assign(beta2_t * v + (1. - beta2_t) * tf.square(grad)) m = self.get_slot(var, "m") m_t = m.assign(beta1_t * m + (1. - beta1_t) * grad) v_t_hat = tf.div(v_t, 1. - beta2_t) m_t_hat = tf.div(m_t, 1. - beta1_t) g_t = tf.div(m_t_hat, tf.sqrt(v_t_hat) + eps) g_t_1 = self.get_slot(var, "g")
tensorflow.python.ops.math_ops.cast
8,279
import tensorflow as tf 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]
tensorflow.log
8,280
import tensorflow as tf def _create_params(self): initializer = tf.random_uniform_initializer(minval=-0.1, maxval=0.1) with tf.variable_scope(self.name, initializer=initializer): with tf.variable_scope("lstm"): self.w_lstm = [] for layer_id in range(self.lstm_num_layers): with tf.variable_scope("layer_{}".format(layer_id)): w = tf.get_variable("w", [2 * self.lstm_size, 4 * self.lstm_size]) self.w_lstm.append(w) self.g_emb = tf.get_variable("g_emb", [1, self.lstm_size]) with tf.variable_scope("emb"): self.w_emb = tf.get_variable("w", [self.num_branches, self.lstm_size]) with tf.variable_scope("softmax"): self.w_soft = tf.get_variable("w", [self.lstm_size, self.num_branches])
tensorflow.get_variable
8,281
import tensorflow as tf self.user_id = tf.placeholder(shape=[None, ], dtype=tf.int32, name='user_id') self.item_id = tf.placeholder(shape=[None, ], dtype=tf.int32, name='item_id') self.labels = tf.placeholder(shape=[None, 1], dtype=tf.float32, name='labels') self.interaction = gmf(uid=self.user_id, iid=self.item_id, num_users=self.train_set.num_users,
tensorflow.placeholder
8,282
import tensorflow as tf """ context, sequence = tf.parse_single_sequence_example(
tensorflow.parse_single_sequence_example
8,283
from tensorflow.python.ops import variable_scope as vs 2 * self._num_units, True, bias_initializer=bias_ones, kernel_initializer=self._kernel_initializer) value = math_ops.sigmoid(self._gate_linear([inputs, state])) r, u = array_ops.split(value=value, num_or_size_splits=2, axis=1) r_state = r * state if self._candidate_linear is None: with vs.variable_scope("candidate"): self._candidate_linear = _Linear( [inputs, r_state], self._num_units, True, bias_initializer=self._bias_initializer, kernel_initializer=self._kernel_initializer) c = self._activation(self._candidate_linear([inputs, r_state])) new_h = (1. - att_score) * state + att_score * c return new_h, new_h
tensorflow.python.ops.variable_scope.variable_scope
8,284
import tensorflow as tf # loss = tf.maximum(0.0, tf.math.abs(tgt_larg - pred_larg) - tf.math.abs(tgt_small - pred_small)) loss = tf.reduce_mean(loss) return loss def contra_step_lossV5(pred, tgt, resample=1): # p = tf.print('begin loss v5', [resample, pred.shape,tgt.shape]) # with tf.control_dependencies([p]): pred_flat = tf.reshape(pred, [-1]) 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) def sample_compute(cur_loss, i):
tensorflow.reshape
8,285
import tensorflow as tf base_z0_y1 = base + z0_clip * dim2 + y1_clip * dim3 base_z1_y0 = base + z1_clip * dim2 + y0_clip * dim3 base_z1_y1 = base + z1_clip * dim2 + y1_clip * dim3 idx_z0_y0_x0 = base_z0_y0 + x0_clip idx_z0_y0_x1 = base_z0_y0 + x1_clip idx_z0_y1_x0 = base_z0_y1 + x0_clip idx_z0_y1_x1 = base_z0_y1 + x1_clip idx_z1_y0_x0 = base_z1_y0 + x0_clip idx_z1_y0_x1 = base_z1_y0 + x1_clip idx_z1_y1_x0 = base_z1_y1 + x0_clip idx_z1_y1_x1 = base_z1_y1 + x1_clip # Use indices to lookup pixels in the flat image and restore # channels dim im_flat = tf.reshape(im, tf.stack([-1, channels])) im_flat = tf.to_float(im_flat) i_z0_y0_x0 = tf.gather(im_flat, idx_z0_y0_x0) i_z0_y0_x1 = tf.gather(im_flat, idx_z0_y0_x1) i_z0_y1_x0 = tf.gather(im_flat, idx_z0_y1_x0) i_z0_y1_x1 = tf.gather(im_flat, idx_z0_y1_x1) i_z1_y0_x0 = tf.gather(im_flat, idx_z1_y0_x0) i_z1_y0_x1 = tf.gather(im_flat, idx_z1_y0_x1) i_z1_y1_x0 = tf.gather(im_flat, idx_z1_y1_x0) i_z1_y1_x1 = tf.gather(im_flat, idx_z1_y1_x1) # Finally calculate interpolated values. x0_f = tf.to_float(x0) x1_f = tf.to_float(x1) y0_f = tf.to_float(y0)
tensorflow.stack
8,286
import tensorflow as tf scale_init = init_scale / tf.sqrt(v_init + 1e-10) with tf.control_dependencies([g.assign(g * scale_init), b.assign_add(-m_init * scale_init)]): x = tf.reshape(scale_init, [1, 1, 1, num_filters]) * (x - tf.reshape(m_init, [1, 1, 1, num_filters]))
tensorflow.reshape
8,287
import tensorflow as tf sqrt_diag_data = rng.randn(M, N) # M x N K_batch_data = make_K_batch_data(rng, N, M) @pytest.fixture def mu(session_tf): return tf.convert_to_tensor(Datum.mu_data) @pytest.fixture def sqrt_diag(session_tf): return tf.convert_to_tensor(Datum.sqrt_diag_data) @pytest.fixture def K(session_tf): return tf.convert_to_tensor(Datum.K_data) @pytest.fixture def K_batch(session_tf): return tf.convert_to_tensor(Datum.K_batch_data)
tensorflow.convert_to_tensor
8,288
import tensorflow as tf range_tiled = tf.tile(range_row, [batch_size, 1]) self.lengths_transposed = lengths_transposed self.lengths_tiled = lengths_tiled self.range_row = range_row self.range_tiled = range_tiled # Use the logical operations to create a mask indicator = tf.less(range_tiled, lengths_tiled+1) #i.e. where seq len is less than index trim = np.ones(indicator.get_shape()) trim[:,0] = 0 #ignore start symbol indicator = tf.logical_and(indicator, trim.astype(bool)) self.indicator = indicator sz = [batch_size, max_sequence_len] self._mask = tf.select(indicator, tf.ones(sz), tf.zeros(sz)) #-------------------------------# self.weights = tf.constant(weights, dtype=tf.float32, name='class_weights') hidden_size = model_params['model_hidden_size'] proj_size = model_params['model_proj_size'] # optional, can be None def GetCell(): """Creates an LSTM cell with dropout.""" c = tf.nn.rnn_cell.LSTMCell(hidden_size, use_peepholes=model_params['peepholes'], num_proj=proj_size) if dropout_keep_prob is not None:
tensorflow.ones
8,289
import tensorflow as tf attn_states, cell, output_size=4) sess.run([tf.global_variables_initializer()])
tensorflow.global_variables_initializer
8,290
import tensorflow as tf self.t_replace_iter = t_replace_iter self.t_replace_counter = 0 with tf.variable_scope('Actor'): # input s, output a self.a = self._build_net(S, scope='eval_net', trainable=True) # input s_, output a, get a_ for critic self.a_ = self._build_net(S_, scope='target_net', trainable=False) self.e_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Actor/eval_net') self.t_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Actor/target_net') def _build_net(self, s, scope, trainable): with tf.variable_scope(scope): init_w = tf.random_normal_initializer(0., 0.01) init_b = tf.constant_initializer(0.01) net = tf.layers.dense(s, 500, activation=tf.nn.relu, kernel_initializer=init_w, bias_initializer=init_b, name='l1', trainable=trainable) net = tf.layers.dense(net, 200, activation=tf.nn.relu, kernel_initializer=init_w, bias_initializer=init_b, name='l2', trainable=trainable) with tf.variable_scope('a'): actions = tf.layers.dense(net, self.a_dim, activation=tf.nn.tanh, kernel_initializer=init_w, bias_initializer=init_b, name='a', trainable=trainable) scaled_a = tf.multiply(actions, self.action_bound, name='scaled_a') # Scale output to -action_bound to action_bound return scaled_a def learn(self, s): # batch update self.sess.run(self.train_op, feed_dict={S: s})
tensorflow.random_normal_initializer
8,291
import tensorflow as tf def metric_fn( masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids, masked_lm_weights, next_sentence_example_loss, next_sentence_log_probs, next_sentence_labels, ): """Computes the loss and accuracy of the model.""" masked_lm_log_probs = tf.reshape( masked_lm_log_probs, [-1, masked_lm_log_probs.shape[-1]] ) masked_lm_predictions = tf.argmax( masked_lm_log_probs, axis=-1, output_type=tf.int32 ) masked_lm_example_loss = tf.reshape(masked_lm_example_loss, [-1]) masked_lm_ids = tf.reshape(masked_lm_ids, [-1]) masked_lm_weights = tf.reshape(masked_lm_weights, [-1]) masked_lm_accuracy = tf.metrics.accuracy( labels=masked_lm_ids, predictions=masked_lm_predictions, weights=masked_lm_weights, ) masked_lm_mean_loss = tf.metrics.mean( values=masked_lm_example_loss, weights=masked_lm_weights )
tensorflow.argmax
8,292
import tensorflow as tf w = tf.get_variable("w", [nx, ny], initializer=w_init) b = tf.get_variable("b", [ny], initializer=b_init) return tf.matmul(x, w)+b def model(X, M, Y, train=False, reuse=False): with tf.variable_scope('model', reuse=reuse): we = tf.get_variable("we", [n_vocab+n_special+n_ctx, n_embd], initializer=tf.random_normal_initializer(stddev=0.02)) we = dropout(we, embd_pdrop, train) #X:[n_batch_train, 2, n_ctx, 2] -> [n_batch_train*2,n_ctx,2]
tensorflow.variable_scope
8,293
import tensorflow as tf # train the model using Adam def train(self, sess, generator, learning_rate=.001, training_iters=50000, batch_size=64, display_step=10,weight_save_step=100, save_weights_path= None, generator_function= None, training_weights_path = None): # train with gradient clipping optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) grads = optimizer.compute_gradients(self.loss) clipped_grads = [(tf.clip_by_norm(grad, 1.0), var) if grad is not None else (grad, var) for grad, var in grads] # add vanishing gradient regularizer #out, test = self.dOmega_dWrec() #clipped_grads[0] = (tf.add(out[0], clipped_grads[0][0]), clipped_grads[0][1]) #clipped_grads[0] = (tf.Print(clipped_grads[0][0], [clipped_grads[0][0]], "gw_rec"), clipped_grads[0][1]) optimize = optimizer.apply_gradients(clipped_grads)
tensorflow.clip_by_norm
8,294
import tensorflow as tf def concat_and_add_mask(features, targets): """Concatenate input and output frames to form a language modeling setup.""" inp = features['inputs'] concat = tf.concat([inp, targets], axis=0) mask = tf.concat([tf.zeros_like(inp), tf.ones_like(targets)], axis=0) concat = tf.reshape(concat, (-1,)) mask = tf.reshape(mask, (-1,)) concat = tf.cast(concat, tf.int32) mask = tf.cast(mask, tf.float32) features['inputs'] = features['targets'] = concat features['mask'] = mask return features, concat dataset = dataset.map(concat_and_add_mask) return dataset
tensorflow.cast
8,295
import tensorflow as tf weight: a scalar weight for the loss. scope: optional name scope for summary tags. Returns: a scalar tensor representing the correlation loss value. """ with tf.name_scope(name): source_samples -= tf.reduce_mean(source_samples, 0) target_samples -= tf.reduce_mean(target_samples, 0) source_samples = tf.nn.l2_normalize(source_samples, 1) target_samples = tf.nn.l2_normalize(target_samples, 1) source_cov = tf.matmul(tf.transpose(source_samples), source_samples) target_cov = tf.matmul(tf.transpose(target_samples), target_samples) corr_loss = tf.reduce_mean(tf.square(source_cov - target_cov)) * weight assert_op = tf.Assert(tf.is_finite(corr_loss), [corr_loss])
tensorflow.reduce_mean
8,296
import tensorflow as tf best_trial_info_file = os.path.join(FLAGS.output_dir, "best_trial.txt") def _best_trial_info(): """Returns information about which checkpoints have been evaled so far.""" if tf.gfile.Exists(best_trial_info_file): with tf.gfile.GFile(best_trial_info_file, "r") as best_info: global_step, best_metric_global_step, metric_value = ( best_info.read().split(":")) global_step = int(global_step) best_metric_global_step = int(best_metric_global_step)
tensorflow.gfile.GFile
8,297
import tensorflow as tf dist_loss1 = self._distance_loss(models[1].encode - models[0].encode) dist_loss2 = self._distance_loss(models[1].encode - models[2].encode) # Stitch it all together and train self.loss_reco = tf.add_n(reco_losses) self.loss_pred = pred_loss_0 + pred_loss_2 self.loss_dist = dist_loss1 + dist_loss2 self.losses = [self.loss_reco, self.loss_pred] def _distance_loss(self, distances): error = tf.nn.relu(l2(distances) - FLAGS.distance ** 2) return tf.reduce_sum(error) def _prediction_decode(self, prediction, target, model): """Predict encoding t3 by encoding (t2 and t1) and expect a good reconstruction""" predict_decode = interpreter.build_decoder(prediction, self.model.config, reuse=True, masks=model.mask_list) predict_loss = 1./2 * interpreter.l2_loss(predict_decode, target, alpha=FLAGS.alpha) self.models += [predict_decode] return predict_loss * FLAGS.gamma def build_denoising_model(self):
tensorflow.reduce_sum
8,298
import tensorflow as tf scope.reuse_variables() var = variable_on_cpu( "var", [dim], tf.constant_initializer(1.), trainable=False) mean = variable_on_cpu( "mean", [dim], tf.constant_initializer(0.), trainable=False) step = variable_on_cpu("step", [], tf.constant_initializer(0.), trainable=False) # choose the appropriate moments if train: used_mean, used_var = tf.nn.moments(input_, axes, name="batch_norm") cur_mean, cur_var = used_mean, used_var if bn_lag > 0.: used_var = stable_var(input_=input_, mean=used_mean, axes=axes) cur_var = used_var used_mean -= (1 - bn_lag) * (used_mean - tf.stop_gradient(mean)) used_mean /= (1. - bn_lag**(step + 1)) used_var -= (1 - bn_lag) * (used_var - tf.stop_gradient(var)) used_var /= (1. - bn_lag**(step + 1)) else: used_mean, used_var = mean, var cur_mean, cur_var = used_mean, used_var # update variables if train: with tf.name_scope(name, "AssignMovingAvg", [mean, cur_mean, decay]): with ops.colocate_with(mean): new_mean = tf.assign_sub( mean, tf.check_numerics( decay * (mean - cur_mean), "NaN in moving mean.")) with tf.name_scope(name, "AssignMovingAvg", [var, cur_var, decay]):
tensorflow.stop_gradient
8,299