seed
stringlengths
25
2.89k
seed_api
stringlengths
14
102
index
int64
0
14.8k
import tensorflow as tf dtype=tf.float32) self.assertAllClose(ious.numpy(), expected_ious.numpy()) def test_instance_non_maximum_suppression_1d_scores(self): mask0 = tf.constant([[1, 0], [0, 1]], dtype=tf.float32) mask1 = tf.constant([[1, 1], [0, 1]], dtype=tf.float32) mask2 = tf.constant([[1, 0], [1, 1]], dtype=tf.float32) mask3 = tf.constant([[1, 1], [1, 1]], dtype=tf.float32) mask4 = tf.constant([[0, 0], [0, 0]], dtype=tf.float32) mask5 = tf.constant([[1, 0], [1, 0]], dtype=tf.float32) masks = tf.stack([mask0, mask1, mask2, mask3, mask4, mask5]) classes = tf.constant([1, 2, 3, 1, 2, 3], dtype=tf.int32) scores = tf.constant([1.0, 0.9, 0.8, 0.95, 0.85, 0.6], dtype=tf.float32) (nms_masks1,
tensorflow.constant
8,400
import tensorflow as tf 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 src_mask = tf.to_float(tf.sequence_mask(source_length, maxlen=src_len)) mask = tf.matmul(tf.expand_dims(trg_mask, axis=2), tf.expand_dims(src_mask, axis=1)) monotonous = tf.sqrt(((true_trg_len * src_indices - true_src_len * trg_indices) ** 2) / (true_trg_len**2 + true_src_len**2)) monotonous = tf.to_float(monotonous < monotonicity_dist) non_monotonous = (1 - monotonous) * mask attn_loss = tf.reduce_sum(attention_weights * tf.stop_gradient(non_monotonous)) / tf.to_float(batch_size) if monotonicity_decay:
tensorflow.sequence_mask
8,401
import tensorflow as tf values = tf.argmax(values,axis=2) x = tf.cast(values, dtype=tf.int32) y = tf.cast(answers, dtype=tf.int32) res = tf.equal(x, y) res = tf.cast(res, dtype=tf.float32) res = tf.multiply(res, loss_weights)
tensorflow.equal
8,402
from tensorflow.python.training import moving_averages def moving_average_update(variable, value, momentum): try: return moving_averages.assign_moving_average( variable, value, momentum, zero_debias=False)
tensorflow.python.training.moving_averages.assign_moving_average
8,403
import tensorflow as tf return example def main(_): tf.logging.set_verbosity(tf.logging.INFO) if not FLAGS.do_train and not FLAGS.do_eval: raise ValueError("At least one of `do_train` or `do_eval` must be True.")
tensorflow.logging.set_verbosity
8,404
import tensorflow as tf self.kernel = self.gaussian_kernel(size,mean,std) self.kernel = tf.tile(self.kernel[:, :, tf.newaxis, tf.newaxis], [1, 1, 3, 1]) self.paddings = tf.convert_to_tensor([[size,size],[size,size],[0,0]]) x_aug = tf.nn.separable_conv2d(tf.expand_dims(tf.pad(x,self.paddings,'SYMMETRIC'), 0), self.kernel, self.pointwise_filter,strides=[1, 1, 1, 1], padding='VALID') x_aug = tf.squeeze(x_aug) return tf.concat([x, x_aug],axis=2)
tensorflow.squeeze
8,405
from tensorflow.python.ops import math_ops predictions.get_shape().assert_is_compatible_with(labels.get_shape()) predictions, normalizer = tensor_util.remove_squeezable_dimensions( predictions, normalizer) predictions.get_shape().assert_is_compatible_with(normalizer.get_shape()) relative_errors = math_ops.select( math_ops.equal(normalizer, 0.0), array_ops.zeros_like(labels), math_ops.div(math_ops.abs(labels - predictions), normalizer)) return streaming_mean(relative_errors, weights, metrics_collections, updates_collections, name or 'mean_relative_error') def streaming_mean_squared_error(predictions, labels, weights=None, metrics_collections=None, updates_collections=None,
tensorflow.python.ops.math_ops.abs
8,406
import tensorflow as tf def test_get_inputs_cancelled(self): with tf.Graph().as_default(): @dynamic_batching.batch_fn def f(a): return a f(tf.constant([1])) # Intentionally using tf.Session() instead of self.test_session() to have # control over closing the session. test_session() is a cached session. with tf.Session(): coord = tf.train.Coordinator() tf.train.start_queue_runners(coord=coord)
tensorflow.constant
8,407
import tensorflow as tf [tf.placeholder(name=t.name, dtype=t.dtype, shape=[self.batch_size // self.total_core_num] + list(t.shape)) for t in nest.flatten(self.tensor_structure)]) for tensor in nest.flatten(tensors): tf.get_default_graph().clear_collection(tensor.name) tf.add_to_collection(tensor.name, self) self._original_tensors = tensors self._tensors = tensors if not self.has_batch: self._tensors = nest.pack_sequence_as(self.tensor_structure,
tensorflow.add_to_collection
8,408
import tensorflow as tf self.graph = graph with self.graph.as_default(): with tf.device('/cpu:0'): embedding = tf.get_variable( 'embedding', [vocab_size, hidden_size], dtype=tf.float32) inputs = tf.nn.embedding_lookup(embedding, input_.input_data) if is_training and config.keep_prob < 1: inputs = tf.nn.dropout(inputs, config.keep_prob) output, state = self._build_rnn_graph(inputs, config, is_training) softmax_w = tf.get_variable( 'softmax_w', [hidden_size, vocab_size], dtype=tf.float32) softmax_b = tf.get_variable('softmax_b', [vocab_size], dtype=tf.float32) logits = tf.nn.xw_plus_b(output, softmax_w, softmax_b) logits = tf.reshape(logits, [self.batch_size, self.num_steps, vocab_size])
tensorflow.nn.dropout
8,409
import tensorflow as tf return outputs # 这个就是在tensorboard上可视化的时候的区别: # 使用with tf.name_scope('inputs')可以将xs和ys包含进来 # 形成一个大的图层,图层的名字就是with tf.name_scope()方法里的参数。 with tf.name_scope('inputs'): xs = tf.placeholder(tf.float32, [None, 1], name='x_input') # 这个name的属性,也是为了使用tensorboard,添加上来的 ys = tf.placeholder(tf.float32, [None, 1], name='y_input') # 同上 # add hidden layer l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu,nameScope="layerTest1") # add output layer prediction = add_layer(l1, 10, 1, activation_function=None,nameScope="layerTest2")
tensorflow.placeholder
8,410
import tensorflow as tf checkpoints = list(set(checkpoints) - set(ys) - set(xs)) # check that we have some nodes to checkpoint if not checkpoints: raise Exception('no checkpoints nodes found or given as input! ') # disconnect dependencies between checkpointed tensors checkpoints_disconnected = {} for x in checkpoints: if x.op and x.op.name is not None: grad_node = tf.stop_gradient(x, name=x.op.name+"_sg") else: grad_node = tf.stop_gradient(x) checkpoints_disconnected[x] = grad_node # partial derivatives to the checkpointed tensors and xs ops_to_copy = fast_backward_ops(seed_ops=[y.op for y in ys], stop_at_ts=checkpoints, within_ops=fwd_ops) debug_print("Found %s ops to copy within fwd_ops %s, seed %s, stop_at %s", len(ops_to_copy), fwd_ops, [r.op for r in ys], checkpoints) debug_print("ops_to_copy = %s", ops_to_copy) debug_print("Processing list %s", ys) copied_sgv, info = ge.copy_with_input_replacements(ge.sgv(ops_to_copy), {}) for origin_op, op in info._transformed_ops.items():
tensorflow.stop_gradient
8,411
import tensorflow as tf 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"): cell1 = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=False) dec, mem = tf.nn.seq2seq.embedding_rnn_seq2seq( enc_inp, dec_inp, cell1, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2)
tensorflow.variable_scope
8,412
import tensorflow as tf """ Batch normalization on convolutional maps. Args: x: Tensor, 4D BHWD input maps n_out: integer, depth of input maps phase_train: boolean tf.Variable, true indicates training phase scope: string, variable scope affn: whether to affn-transform outputs Return: normed: batch-normalized maps Ref: http://stackoverflow.com/questions/33949786/how-could-i-use-batch-normalization-in-tensorflow/33950177 """ name = 'batch_norm' with tf.variable_scope(name): phase_train = tf.convert_to_tensor(phase_train, dtype=tf.bool) n_out = int(x.get_shape()[3]) beta = tf.Variable(tf.constant(0.0, shape=[n_out], dtype=x.dtype), name=name+'/beta', trainable=True, dtype=x.dtype) 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]):
tensorflow.variable_scope
8,413
import tensorflow as tf for i in six.moves.range(FLAGS.eval_batch_count): time_start = time.time() (nor_img,true_label) = sess.run([images,labels]) adv_img = sess.run(adv_image_craft,feed_dict={image:nor_img}) # Local logits (predict_NOR, predict_ADV, logits_part_nor, logits_part_adv) = sess.run( [predict_nor, predict_adv, tsne_logit_nor, tsne_logit_adv], feed_dict={image: nor_img, 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} ) entropy_test_adv_all = np.concatenate((entropy_test_adv_all, entropy_test_adv_help), axis=0) confidence_test_adv_all = np.concatenate((confidence_test_adv_all, confidence_test_adv_help), axis=0) entropy_test_nor_all = np.concatenate((entropy_test_nor_all, entropy_test_nor_help), axis=0) confidence_test_nor_all = np.concatenate((confidence_test_nor_all, confidence_test_nor_help), axis=0) logits_nor_all = np.concatenate((logits_nor_all, logits_part_nor), axis=0) labels_nor_all = np.concatenate((labels_nor_all, labels_nor_help), axis=0)
tensorflow.argmax
8,414
import tensorflow as tf x = tf.concat([tf.squeeze(v, 1) for v in x], 3) return tf.reshape(x, (batch_size, d*r, h*r, w*r, 1))
tensorflow.reshape
8,415
import tensorflow as tf if mode != 'gen': targets_nunroll = tf.placeholder(dtype, shape=[batch_size, rnn_nunroll]) # TODO: tf.ones acts as an overridable placeholder but this is still awkward target_weights_nunroll = tf.ones([batch_size, rnn_nunroll], dtype) # Reshape input tensors to remove nunroll dim; will briefly restore later during RNN if necessary if cnn_rnn_zack: feats_audio = tf.reshape(feats_audio_nunroll, shape=[batch_size, rnn_nunroll + zack_hack, audio_nbands, audio_nchannels]) else: feats_audio = tf.reshape(feats_audio_nunroll, shape=[batch_size * rnn_nunroll, audio_context_len, audio_nbands, audio_nchannels]) feats_other = tf.reshape(feats_other_nunroll, shape=[batch_size * rnn_nunroll, nfeats]) if mode != 'gen': targets = tf.reshape(targets_nunroll, shape=[batch_size * rnn_nunroll]) target_weights = tf.reshape(target_weights_nunroll, shape=[batch_size * rnn_nunroll]) # CNN cnn_output = feats_audio if do_cnn: layer_last = feats_audio nfilt_last = audio_nchannels for i, ((ntime, nband, nfilt), (ptime, pband)) in enumerate(zip(cnn_filter_shapes, cnn_pool)): layer_name = 'cnn_{}'.format(i) with tf.variable_scope(layer_name): filters = tf.get_variable('filters', [ntime, nband, nfilt_last, nfilt], initializer=cnn_init, dtype=dtype) biases = tf.get_variable('biases', [nfilt], initializer=tf.constant_initializer(0.1), dtype=dtype) if cnn_rnn_zack:
tensorflow.reshape
8,416
import tensorflow as tf reader = tf.TFRecordReader # Features in Pascal VOC TFRecords. keys_to_features = { 'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''), 'image/format': tf.FixedLenFeature((), tf.string, default_value='jpeg'), 'image/height': tf.FixedLenFeature([1], tf.int64), 'image/width': tf.FixedLenFeature([1], tf.int64), 'image/channels': tf.FixedLenFeature([1], tf.int64), 'image/shape': tf.FixedLenFeature([3], tf.int64), 'image/object/bbox/xmin': tf.VarLenFeature(dtype=tf.float32), 'image/object/bbox/ymin': tf.VarLenFeature(dtype=tf.float32), 'image/object/bbox/xmax': tf.VarLenFeature(dtype=tf.float32),
tensorflow.FixedLenFeature
8,417
import tensorflow as tf name="squared_difference" ) print_obj(func_name, "squared_difference", squared_difference) # Get gradient penalty scalar. gradient_penalty = tf.reduce_mean( input_tensor=squared_difference, name="gradient_penalty" ) print_obj(func_name, "gradient_penalty", gradient_penalty) # Multiply with lambda to get gradient penalty loss. gradient_penalty_loss = tf.multiply( x=params["discriminator_gradient_penalty_coefficient"], y=gradient_penalty, name="gradient_penalty_loss" ) return gradient_penalty_loss def get_discriminator_loss( self, cur_batch_size,
tensorflow.multiply
8,418
import tensorflow as tf # Mean-square-error i.e. quadratic-cost mse = tf.reduce_sum(tf.squared_difference(y, x_recon), 1) mse = tf.reduce_mean(mse) # in theano: mse = ((y - x) ** 2 ).sum(axis=1).mean()
tensorflow.squared_difference
8,419
import tensorflow as tf self.a = a self.q = self._build_net(S, self.a, 'eval_net', trainable=True) # Input (s_, a_), output q_ for q_target self.q_ = self._build_net(S_, a_, 'target_net', trainable=False) # target_q is based on a_ from Actor's target_net self.e_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Critic/eval_net') self.t_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Critic/target_net') with tf.variable_scope('target_q'): self.target_q = R + self.gamma * self.q_ with tf.variable_scope('abs_TD'): self.abs_td = tf.abs(self.target_q - self.q) self.ISWeights = tf.placeholder(tf.float32, [None, 1], name='IS_weights') with tf.variable_scope('TD_error'): self.loss = tf.reduce_mean(self.ISWeights * tf.squared_difference(self.target_q, self.q)) with tf.variable_scope('C_train'): self.train_op = tf.train.AdamOptimizer(self.lr).minimize(self.loss, global_step=GLOBAL_STEP) with tf.variable_scope('a_grad'): self.a_grads = tf.gradients(self.q, a)[0] # tensor of gradients of each sample (None, a_dim)
tensorflow.variable_scope
8,420
import tensorflow as tf qh_emb = tf.reduce_max(qh_emb, axis=1) ch_emb = tf.reshape(ch_emb, [N * self.max_p_num, PL, -1]) qh_emb = tf.reshape(qh_emb, [N * self.max_p_num, QL, -1]) c_emb = tf.nn.dropout(tf.nn.embedding_lookup(self.word_mat, self.c), 1.0 - self.dropout) q_emb = tf.nn.dropout(tf.nn.embedding_lookup(self.word_mat, self.q), 1.0 - self.dropout) c_emb = tf.concat([c_emb, ch_emb], axis=2) q_emb = tf.concat([q_emb, qh_emb], axis=2) self.c_emb = highway(c_emb, size=d, scope="highway", dropout=self.dropout, reuse=None)
tensorflow.nn.embedding_lookup
8,421
import tensorflow as tf print('\ntranspose(D)=') print(sess.run(tf.transpose(D))) print('\ninverse(D)=') print(sess.run(tf.matrix_inverse(D))) print('\ndeterminant(D)={:.1f}'.format(sess.run(tf.matrix_determinant(D)))) print('\ncholesky(D):') print(sess.run(tf.cholesky(identity_matrix))) print('\nselfAdjointEig(D):') print(sess.run(tf.self_adjoint_eig(D))) print(sess.run(tf.div(13, 4))) print(sess.run(tf.truediv(13, 4))) print(sess.run(tf.floordiv(13, 4))) print(sess.run(tf.mod(13.2, 4)))
tensorflow.cholesky
8,422
import tensorflow as tf (predicted_classes, predicted_sdfs, predicted_poses)]): for i in range(classes.shape[0]): if class_id == classes[i]: sdf = tf.expand_dims(sdfs[i], -1) sdf = sdf * -1.0 # inside positive, outside zero samples_object = centernet_utils.transform_pointcloud( tf.reshape(samples_world, [1, 1, -1, 3]), tf.reshape(poses[2][i], [1, 1, 3]), tf.reshape(poses[0][i], [1, 1, 3, 3]), tf.reshape(poses[1][i], [1, 1, 3]), inverse=True) * 2.0 samples_object = \ (samples_object * (29.0/32.0) / 2.0 + 0.5) * 32.0 - 0.5 samples = tf.squeeze(samples_object) interpolated = trilinear.interpolate(sdf, samples) sdf_values += tf.math.sign(tf.nn.relu(interpolated + self.tol)) status2 = False if status2: a = 2 values = interpolated inter = tf.reshape(values, [self.resolution, self.resolution, self.resolution]) inter = tf.transpose(tf.reduce_max(inter, axis=a)) im = axs[fig_obj_count, mtype * 2 + 0].matshow(inter.numpy()) plt.colorbar(im, ax=axs[fig_obj_count, mtype * 2 + 0]) print(mtype, fig_obj_count, 0) values = tf.math.sign(tf.nn.relu(interpolated + self.tol)) inter = tf.reshape(values, [self.resolution,
tensorflow.nn.relu
8,423
import tensorflow as tf std = tf.random.uniform(shape=[],minval=5,maxval=10,dtype=tf.float32) # std [5-10] size = tf.random.uniform(shape=[],minval=3,maxval=7,dtype=tf.int32) # size [7-15] self.kernel = self.gaussian_kernel(size,mean,std) self.kernel = tf.tile(self.kernel[:, :, tf.newaxis, tf.newaxis], [1, 1, 3, 1]) self.paddings = tf.convert_to_tensor([[size,size],[size,size],[0,0]]) x_aug = tf.nn.separable_conv2d(tf.expand_dims(tf.pad(x,self.paddings,'SYMMETRIC'), 0), self.kernel, self.pointwise_filter,strides=[1, 1, 1, 1], padding='VALID') x_aug = tf.squeeze(x_aug) return tf.concat([x, x_aug],axis=2)
tensorflow.convert_to_tensor
8,424
import tensorflow as tf s= len(tensor) #number of tensors in the list for i in range(s): dl = tensor[i] #take one element of the gradient list (hence the zero) d1, d2 = dl.get_shape() #Obtain tensor dimensions fl = tf.reshape(dl,[-1, d1*d2]) #reshape the tensor to a (1, d1*d2) tensor #concatenate over all the elemets in the list if i==0: flattened = fl # the first time else: flattened = tf.concat([flattened, fl], axis=1) return flattened #Hessian def hessian(grads, par): ''' Evaluates the exact Hessian matrix. This function uses the same convention of the Autograd package. Inputs:
tensorflow.concat
8,425
import tensorflow as tf "input_mask": tf.constant( all_input_mask, shape=[num_examples, seq_length], dtype=tf.int32), "segment_ids": tf.constant( all_segment_ids, shape=[num_examples, seq_length], dtype=tf.int32), "label_ids": tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32), }) if is_training: d = d.repeat() d = d.shuffle(buffer_size=100) d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder) return d return input_fn
tensorflow.constant
8,426
import tensorflow as tf if proposal_type == "smoothing": assert rev_rnn_cell, "Must provide rev_rnn_cell for smoothing proposal." def zero_state(self, batch_size, dtype): super_state = super(TrainableVRNN, self).zero_state(batch_size, dtype) return TrainableVRNNState( rnn_out=tf.zeros([batch_size, self.rnn_cell.output_size], dtype=dtype), **super_state._asdict()) def set_observations(self, observations, seq_lengths): """Stores the model's observations.
tensorflow.zeros
8,427
import tensorflow as tf 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)) updates = [ update_eps_expr, tf.cond(reset_ph, lambda: perturb_vars(original_scope="q_func", perturbed_scope="perturbed_q_func"), lambda: tf.group(*[])), tf.cond(update_param_noise_scale_ph, lambda: update_scale(), lambda: tf.Variable(0., trainable=False)), update_param_noise_threshold_expr,
tensorflow.cond
8,428
import tensorflow as tf channels = im.get_shape().as_list()[4] x = tf.to_float(x) y = tf.to_float(y) z = tf.to_float(z) depth_f = tf.to_float(depth) height_f = tf.to_float(height) width_f = tf.to_float(width) # Number of disparity interpolated. out_depth = out_size[0] out_height = out_size[1] out_width = out_size[2] zero = tf.zeros([], dtype='int32') # 0 <= z < depth, 0 <= y < height & 0 <= x < width.
tensorflow.to_float
8,429
import tensorflow as tf if len(variables) == 0: return [] if semver.match(tf.__version__, '<1.0.0'): init_flag = sess.run( tf.pack([tf.is_variable_initialized(v) for v in variables])) else: init_flag = sess.run( tf.stack([tf.is_variable_initialized(v) for v in variables])) return [v for v, f in zip(variables, init_flag) if not f]
tensorflow.is_variable_initialized
8,430
from tensorflow.contrib.framework import deprecated_args ValueError: If `ignore_mask` is not `None` and its shape doesn't match `values`, or if `weights` is not `None` and its shape doesn't match `values`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ is_below_threshold = math_ops.to_float(math_ops.less(values, threshold)) return streaming_mean(is_below_threshold, _mask_weights(ignore_mask, weights), metrics_collections, updates_collections, name or 'percentage_below_threshold') @deprecated_args(IGNORE_MASK_DATE, IGNORE_MASK_INSTRUCTIONS, 'ignore_mask') def streaming_mean_iou(predictions, labels, num_classes, ignore_mask=None, weights=None, metrics_collections=None, updates_collections=None, name=None): """Calculate per-step mean Intersection-Over-Union (mIOU). Mean Intersection-Over-Union is a common evaluation metric for
tensorflow.contrib.framework.deprecated_args
8,431
import tensorflow as tf is_real_example = None if "is_real_example" in features: is_real_example = tf.cast(features["is_real_example"], dtype=tf.float32) else: is_real_example = tf.ones(tf.shape(label_ids), dtype=tf.float32) is_training = (mode == tf.estimator.ModeKeys.TRAIN)
tensorflow.shape
8,432
import tensorflow as tf tf.app.flags.DEFINE_float('beta', 0.0005, 'Reconstruction from noisy data loss weight') tf.app.flags.DEFINE_float('epsilon', 0.000001, 'Diameter of epsilon sphere comparing to distance to a neighbour. <= 0.5') tf.app.flags.DEFINE_float('gamma', 50., 'Loss weight for large distances') tf.app.flags.DEFINE_float('distance', 0.01, 'Maximum allowed interpoint distance') tf.app.flags.DEFINE_float('delta', 1., 'Loss weight for stacked objective')
tensorflow.app.flags.DEFINE_float
8,433
import tensorflow as tf warmup_steps = tf.to_float(params.warmup_steps) multiplier = params.hidden_size ** -0.5 decay = params.r0 * multiplier * tf.minimum((step + 1) * (warmup_steps ** -1.0) * (warmup_steps ** -0.5), (step + 1) ** -0.5) return learning_rate * decay elif params.learning_rate_decay == "rnnplus_warmup_decay": step = tf.to_float(global_step) n = float(len(params.device_list)) warmup_steps = tf.to_float(params.warmup_steps) decay = tf.minimum(1 + step * (n - 1) / (n * warmup_steps), tf.minimum(n, n * ((2*n) ** ((params.s - n * step) / (params.e - params.s))))) return tf.maximum(learning_rate * decay, 5e-6) elif params.learning_rate_decay == "piecewise_constant": return tf.train.piecewise_constant(tf.to_int32(global_step), params.learning_rate_boundaries, params.learning_rate_values) elif params.learning_rate_decay == "none": return learning_rate else:
tensorflow.minimum
8,434
import tensorflow as tf def main(unused_argv): tf.set_random_seed(FLAGS.random_seed) run_config_args = { 'model_dir': FLAGS.model_dir, 'save_checkpoints_steps': FLAGS.save_checkpoints_steps, 'log_step_count_steps': FLAGS.log_step_count_steps, 'keep_checkpoint_max': 100, } config = tf.contrib.tpu.RunConfig(**run_config_args) if FLAGS.warm_start_ckpt_path: var_names = [] checkpoint_path = FLAGS.warm_start_ckpt_path reader = tf.train.NewCheckpointReader(checkpoint_path) for key in reader.get_variable_to_shape_map(): keep_str = 'Momentum|global_step|finetune_global_step' if not re.findall('({})'.format(keep_str,), key): var_names.append(key)
tensorflow.contrib.tpu.RunConfig
8,435
import tensorflow as tf tf.initialize_all_variables().run() self.assertEqual(111, v0.eval()) save.restore(sess, save_path + "-00000-of-00002") self.assertEqual(10, v0.eval()) # Restore a different "v1" from shard 1 of the saved files. with tf.Session( target="", config=tf.ConfigProto(device_count={"CPU": 2})) as sess: with sess.graph.device("/cpu:0"): v1 = tf.Variable(222) save = tf.train.Saver({"v1": v1}, sharded=True) tf.initialize_all_variables().run() self.assertEqual(222, v1.eval()) save.restore(sess, save_path + "-00001-of-00002") self.assertEqual(20, v1.eval())
tensorflow.ConfigProto
8,436
import tensorflow as tf """ summaries = [] for grad, var in grads_and_vars: if grad is not None: if isinstance(grad, tf.IndexedSlices): grad_values = grad.values else: grad_values = grad summaries.append(tf.histogram_summary(var.op.name + ':gradient', grad_values)) summaries.append(tf.histogram_summary(var.op.name + ':gradient_norm', tf.global_norm([grad_values]))) else: tf.logging.info('Var %s has no gradient', var.op.name) return summaries class DeploymentConfig(object): """Configuration for deploying a model with `deploy()`. You can pass an instance of this class to `deploy()` to specify exactly how to deploy the model to build. If you do not pass one, an instance built
tensorflow.global_norm
8,437
import tensorflow as tf net = {} current = image for i, name in enumerate(layers): kind = name[:4] if kind == 'conv': kernels, bias = weights[i][0][0][0][0] # matconvnet: weights are [width, height, in_channels, out_channels] # tensorflow: weights are [height, width, in_channels, out_channels] kernels = utils.get_variable(np.transpose(kernels, (1, 0, 2, 3)), name=name + "_w") bias = utils.get_variable(bias.reshape(-1), name=name + "_b") current = utils.conv2d_basic(current, kernels, bias) elif kind == 'relu': current = tf.nn.relu(current, name=name) if FLAGS.debug: utils.add_activation_summary(current) elif kind == 'pool': current = utils.avg_pool_2x2(current) net[name] = current return net ''' def decoder(image): model_data = utils.get_model_data(FLAGS.model_dir, MODEL_URL)
tensorflow.nn.relu
8,438
import tensorflow as tf p.input_modality["inputs_position"] = identity p.input_modality["targets_segmentation"] = identity p.input_modality["targets_position"] = identity def example_reading_spec(self): data_fields = {"targets": tf.VarLenFeature(tf.int64)} if self.has_inputs: data_fields["inputs"] = tf.VarLenFeature(tf.int64) if self.packed_length: if self.has_inputs: data_fields["inputs_segmentation"] = tf.VarLenFeature(tf.int64) data_fields["inputs_position"] = tf.VarLenFeature(tf.int64) data_fields["targets_segmentation"] = tf.VarLenFeature(tf.int64) data_fields["targets_position"] = tf.VarLenFeature(tf.int64) data_items_to_decoders = None return (data_fields, data_items_to_decoders) def eval_metrics(self): return [ metrics.Metrics.ACC, metrics.Metrics.ACC_TOP5,
tensorflow.VarLenFeature
8,439
import tensorflow as tf loss = tf.maximum(0.0, loss - float(config.free_nats)) objectives.append(Objective('divergence', loss, min, include, exclude)) elif name == 'overshooting': shape = tools.shape(graph.data['action']) length = tf.tile(tf.constant(shape[1])[None], [shape[0]]) _, priors, posteriors, mask = tools.overshooting( graph.cell, {}, graph.embedded, graph.data['action'], length, config.overshooting_distance, posterior) posteriors, priors, mask = tools.nested.map(
tensorflow.constant
8,440
import tensorflow as tf log_probs = tf.nn.log_softmax(logits, axis=-1) label_ids = tf.reshape(label_ids, [-1])
tensorflow.reshape
8,441
import tensorflow as tf "How many steps to make in each estimator call.") flags.DEFINE_integer("max_eval_steps", 100, "Maximum number of eval steps.") flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.") tf.flags.DEFINE_string( "tpu_name", None, "The Cloud TPU to use for training. This should be either the name " "used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 " "url.")
tensorflow.flags.DEFINE_string
8,442
import tensorflow as tf
tensorflow.GradientTape
8,443
import tensorflow as tf tf.logging.info("%s\tshape %s", v.name[:-2].ljust(80), str(v.shape).ljust(20)) v_size = np.prod(np.array(v.shape.as_list())).tolist() # mutiple all dimension size total_size += v_size tf.logging.info("Total trainable variables size: %d", total_size) learning_rate = get_learning_rate_decay(params.learning_rate, global_step, params) learning_rate = tf.convert_to_tensor(learning_rate, dtype=tf.float32) tf.summary.scalar("learning_rate", learning_rate) # Create optimizer opt = tf.train.AdamOptimizer(learning_rate, beta1=params.adam_beta1, beta2=params.adam_beta2, epsilon=params.adam_epsilon)
tensorflow.convert_to_tensor
8,444
import tensorflow as tf if self.temperature is not None: logits /= self.temperature if self.tanh_constant is not None: logits = self.tanh_constant * tf.tanh(logits) index = tf.multinomial(logits, 1) index = tf.to_int32(index) index = tf.reshape(index, [1]) arc_seq = arc_seq.write(start_id + 2 * i, index) curr_log_prob = tf.nn.sparse_softmax_cross_entropy_with_logits( logits=logits, labels=index) log_prob += curr_log_prob curr_ent = tf.stop_gradient(tf.nn.softmax_cross_entropy_with_logits( logits=logits, labels=tf.nn.softmax(logits))) entropy += curr_ent prev_layers.append(anchors.read(tf.reduce_sum(index))) inputs = prev_layers[-1] for i in range(2): # op_1, op_2 next_c, next_h = stack_lstm(inputs, prev_c, prev_h, self.w_lstm) prev_c, prev_h = next_c, next_h logits = tf.matmul(next_h[-1], self.w_soft) + self.b_soft if self.temperature is not None: logits /= self.temperature if self.tanh_constant is not None:
tensorflow.nn.softmax
8,445
import tensorflow as tf cropped_shape = control_flow_ops.with_dependencies( [rank_assertion], tf.pack([crop_height, crop_width, original_shape[2]])) size_assertion = tf.Assert( tf.logical_and( tf.greater_equal(original_shape[0], crop_height), tf.greater_equal(original_shape[1], crop_width)), ['Crop size greater than the image size.']) offsets = tf.to_int32(tf.pack([offset_height, offset_width, 0])) # Use tf.slice instead of crop_to_bounding box as it accepts tensors to # define the crop size. image = control_flow_ops.with_dependencies( [size_assertion], tf.slice(image, offsets, cropped_shape)) return tf.reshape(image, cropped_shape)
tensorflow.pack
8,446
from tensorflow.python.framework import dtypes one_hot=False, dtype=dtypes.float32, reshape=True): """Construct a DataSet. one_hot arg is used only if fake_data is true. `dtype` can be either `uint8` to leave the input as `[0, 255]`, or `float32` to rescale into `[0, 1]`. """ dtype = dtypes.as_dtype(dtype).base_dtype if dtype not in (dtypes.uint8, dtypes.float32): raise TypeError('Invalid image dtype %r, expected uint8 or float32' % dtype) if fake_data: self._num_examples = 10000 self.one_hot = one_hot else:
tensorflow.python.framework.dtypes.as_dtype
8,447
import tensorflow as tf self.assertEqual((2, 2), res[0].shape) def testTiedRNNSeq2Seq(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 dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3 cell = tf.nn.rnn_cell.OutputProjectionWrapper( tf.nn.rnn_cell.GRUCell(2), 4) dec, mem = tf.nn.seq2seq.tied_rnn_seq2seq(inp, dec_inp, cell) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape) res = sess.run([mem])
tensorflow.nn.rnn_cell.GRUCell
8,448
import tensorflow as tf features = tf.parse_single_example( serialized_example, features={ 'wav_raw': tf.FixedLenFeature([], tf.string), 'noisy_raw': tf.FixedLenFeature([], tf.string), }) wave = tf.decode_raw(features['wav_raw'], tf.int32) wave.set_shape(canvas_size) wave = (2./65535.) * tf.cast((wave - 32767), tf.float32) + 1. noisy = tf.decode_raw(features['noisy_raw'], tf.int32) noisy.set_shape(canvas_size) noisy = (2./65535.) * tf.cast((noisy - 32767), tf.float32) + 1. if preemph > 0: wave = tf.cast(pre_emph(wave, preemph), tf.float32) noisy = tf.cast(pre_emph(noisy, preemph), tf.float32) return wave, noisy
tensorflow.decode_raw
8,449
import tensorflow as tf def input_fn(params): """The actual input function.""" batch_size = params["batch_size"] # For training, we want a lot of parallel reading and shuffling. # For eval, we want no shuffling and parallel reading doesn't matter. d = tf.data.TFRecordDataset(input_file) if is_training: d = d.repeat() d = d.shuffle(buffer_size=100) d = d.apply(
tensorflow.data.TFRecordDataset
8,450
import tensorflow as tf tf.add_to_collection(tf.GraphKeys.GLOBAL_VARIABLES, mu) tf.add_to_collection('mu_sigma_bn', mu) sigma = tf.get_variable('sigma', batch_var.shape, dtype=tf.float32, initializer=tf.ones_initializer(), trainable=False) tf.add_to_collection(tf.GraphKeys.GLOBAL_VARIABLES, sigma) tf.add_to_collection('mu_sigma_bn', sigma) beta = tf.get_variable('beta', batch_mean.shape, dtype=tf.float32, initializer=tf.zeros_initializer())
tensorflow.add_to_collection
8,451
import tensorflow as tf scaffold_fn = None if init_checkpoint: (assignment_map, initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) if use_tpu: def tpu_scaffold(): tf.train.init_from_checkpoint(init_checkpoint, assignment_map) return tf.train.Scaffold() scaffold_fn = tpu_scaffold else: tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf.logging.info("**** Trainable Variables ****") for var in tvars: init_string = "" if var.name in initialized_variable_names: init_string = ", *INIT_FROM_CKPT*" tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape, init_string) output_spec = None if mode == tf.estimator.ModeKeys.TRAIN:
tensorflow.train.init_from_checkpoint
8,452
import tensorflow as tf encoder_state = tuple(encoder_state[-1] for _ in range(num_layers)) decoder_cell = attention(encoder_out, seq_lens) dense_layer = tf.layers.Dense(n_mels * resampled)
tensorflow.layers.Dense
8,453
import tensorflow as tf output_bias = tf.get_variable( "output_bias", [num_labels], initializer=tf.zeros_initializer()) with tf.variable_scope("loss"): if is_training: # I.e., 0.1 dropout output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) logits = tf.matmul(output_layer, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias) probabilities = tf.nn.softmax(logits, axis=-1) log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1) loss = tf.reduce_mean(per_example_loss) return (loss, per_example_loss, logits, probabilities) def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_tpu,
tensorflow.nn.log_softmax
8,454
import tensorflow as tf if not white: q_mu = tf.matrix_triangular_solve(Luu, q_mu, lower=True) Luu_tiled = tf.tile(Luu[None, :, :], [num_func, 1, 1]) # remove line once issue 216 is fixed q_sqrt_r = tf.matrix_triangular_solve(Luu_tiled, q_sqrt_r, lower=True) Li_eKuf = tf.matrix_triangular_solve(Luu, eKuf, lower=True) # M x N fmean = tf.matmul(Li_eKuf, q_mu, transpose_a=True)
tensorflow.matrix_triangular_solve
8,455
import tensorflow as tf self.seq_lens = tf.placeholder(tf.int64, [batch_size], name='seq_lens') self.example_weights = tf.placeholder(tf.float32, [batch_size], name='example_weights') embeddings = c2v.GetEmbeddings(self.x) self._inputs = [tf.squeeze(input_, [1]) for input_ in tf.split(1, max_sequence_len, embeddings)] # Need to prepare a mask to zero out the padding symbols. # Make a batch_size x max_sequence_len matrix where each # row contains the length repeated max_sequence_len times. lengths_transposed = tf.expand_dims(tf.to_int32(self.seq_lens), 1) lengths_tiled = tf.tile(lengths_transposed, [1, max_sequence_len]) # Make a matrix where each row contains [0, 1, ..., max_sequence_len] r = tf.range(0, max_sequence_len, 1) range_row = tf.expand_dims(r, 0) range_tiled = tf.tile(range_row, [batch_size, 1]) self.lengths_transposed = lengths_transposed self.lengths_tiled = lengths_tiled self.range_row = range_row self.range_tiled = range_tiled
tensorflow.to_int32
8,456
import tensorflow as tf out = tf.nn.embedding_lookup(embedding_matrix, tensor) return out @layer def recurrent_layer(tensor, cell=None, hidden_dims=128, sequence_length=None, decoder_fn=None, activation=tf.nn.tanh, initializer=tf.orthogonal_initializer(), initial_state=None, keep_prob=1.0, return_final_state=False, return_next_cell_input=True, **opts): if cell is None: cell = tf.contrib.rnn.BasicRNNCell(hidden_dims, activation=activation) # cell = tf.contrib.rnn.LSTMCell(hidden_dims, activation=activation) if keep_prob < 1.0: keep_prob = _global_keep_prob(keep_prob) cell = tf.contrib.rnn.DropoutWrapper(cell, keep_prob, keep_prob) if opts.get("name"): tf.add_to_collection(opts.get("name"), cell) if decoder_fn is None: outputs, final_state = tf.nn.dynamic_rnn(cell, tensor, sequence_length=sequence_length, initial_state=initial_state, dtype=tf.float32) final_context_state = None else: # TODO: turn off sequence_length? outputs, final_state, final_context_state = seq2seq.dynamic_rnn_decoder( cell, decoder_fn, inputs=None, sequence_length=sequence_length) if return_final_state:
tensorflow.contrib.rnn.DropoutWrapper
8,457
from tensorflow.python.ops import math_ops # whether we should use the first or last index in case of ties. min_val = math_ops.reduce_min(math_ops.abs(sensitivities - sensitivity)) indices_at_minval = math_ops.equal( math_ops.abs(sensitivities - sensitivity), min_val) indices_at_minval = math_ops.to_int64(indices_at_minval) indices_at_minval = math_ops.cumsum(indices_at_minval) tf_index = math_ops.argmax(indices_at_minval, 0) tf_index = math_ops.cast(tf_index, dtypes.int32) # Now, we have the implicit threshold, so compute the specificity: return math_ops.div(tn[tf_index], tn[tf_index] + fp[tf_index] + kepsilon,
tensorflow.python.ops.math_ops.argmax
8,458
import tensorflow as tf scores = d_layer_3_all if mask is not None: mask = tf.equal(mask, tf.ones_like(mask)) key_masks = tf.expand_dims(mask, 1) # [B, 1, T] paddings = tf.ones_like(scores) * (-2 ** 32 + 1) scores = tf.where(key_masks, scores, paddings) # [B, 1, T] # Activation if softmax_stag: scores = tf.nn.softmax(scores) # [B, 1, T] # Weighted sum if mode == 'SUM': output = tf.matmul(scores, facts) # [B, 1, H] # output = tf.reshape(output, [-1, tf.shape(facts)[-1]]) else: scores = tf.reshape(scores, [-1, tf.shape(facts)[1]]) output = facts * tf.expand_dims(scores, -1) output = tf.reshape(output, tf.shape(facts)) if return_alphas: return output, scores return output class VecAttGRUCell(RNNCell):
tensorflow.matmul
8,459
import tensorflow as tf 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) res = sess.run([mem]) self.assertEqual(1, len(res)) self.assertEqual((2, 2), res[0].c.shape) self.assertEqual((2, 2), res[0].h.shape) def testEmbeddingRNNSeq2Seq(self): with self.test_session() as sess: with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): enc_inp = [tf.constant(1, tf.int32, shape=[2]) for i in range(2)] dec_inp = [tf.constant(i, tf.int32, shape=[2]) for i in range(3)] cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True) dec, mem = tf.nn.seq2seq.embedding_rnn_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, 2), res[0].c.shape) self.assertEqual((2, 2), res[0].h.shape) # Test with state_is_tuple=False.
tensorflow.constant
8,460
import tensorflow as tf def deconv2d(x, dim=(32, [3, 3], [1, 1]), pad='SAME', scope="deconv2d", training=True, ema=None, init=False, bias_initializer=tf.constant_initializer(0.)): num_filters, filter_size, stride = dim xs = x.get_shape().as_list() if pad=='SAME': target_shape = [tf.shape(x)[0], xs[1]*stride[0], xs[2]*stride[1], num_filters] else: target_shape = [tf.shape(x)[0], xs[1]*stride[0] + filter_size[0]-1, xs[2]*stride[1] + filter_size[1]-1, num_filters] with tf.variable_scope(scope): V = tf.get_variable("V", shape=list(filter_size) + [num_filters, int(x.get_shape()[-1])], dtype=tf.float32, initializer=tf.random_normal_initializer(0, 0.05), trainable=True) g = tf.get_variable("g", shape=[num_filters], dtype=tf.float32, initializer=tf.constant_initializer(1.), trainable=True) b = tf.get_variable("b", shape=[num_filters], dtype=tf.float32, initializer=bias_initializer, trainable=True) def maybe_avg(v): if ema is not None and not init: v = tf.cond(training, lambda: v, lambda: ema.average(v)) return v if init:
tensorflow.random_normal_initializer
8,461
import tensorflow as tf def buildLstmLayer(self): return tf.keras.layers.StackedRNNCells([ tf.lite.experimental.nn.TFLiteLSTMCell( self.num_units, use_peepholes=True, forget_bias=1.0, name="rnn1"), tf.lite.experimental.nn.TFLiteLSTMCell( self.num_units, num_proj=8, forget_bias=1.0, name="rnn2"), tf.lite.experimental.nn.TFLiteLSTMCell( self.num_units // 2, use_peepholes=True, num_proj=8, forget_bias=0, name="rnn3"), tf.lite.experimental.nn.TFLiteLSTMCell( self.num_units, forget_bias=1.0, name="rnn4") ]) def buildModel(self, lstm_layer, is_dynamic_rnn): """Build Mnist recognition model. Args: lstm_layer: The lstm layer either a single lstm cell or a multi lstm cell. is_dynamic_rnn: Use dynamic_rnn or not. Returns:
tensorflow.lite.experimental.nn.TFLiteLSTMCell
8,462
import tensorflow as tf search_space = Box([0, 0], [1, 1]) num_initial_points = 3 initial_query_points = search_space.sample(num_initial_points) initial_observations = objective(initial_query_points.numpy(), sleep=False) initial_data = Dataset( query_points=initial_query_points, observations=tf.constant(initial_observations, dtype=tf.float64), ) import gpflow from trieste.models.gpflow import GaussianProcessRegression def build_model(data): variance = tf.math.reduce_variance(data.observations) kernel = gpflow.kernels.RBF(variance=variance) gpr = gpflow.models.GPR(data.astuple(), kernel, noise_variance=1e-5) gpflow.set_trainable(gpr.likelihood, False) return GaussianProcessRegression(gpr) # these imports will be used later for optimization from trieste.acquisition import LocalPenalizationAcquisitionFunction from trieste.acquisition.rule import AsynchronousGreedy, EfficientGlobalOptimization from trieste.ask_tell_optimization import AskTellOptimizer # %% [markdown] # ## Multiprocessing setup #
tensorflow.math.reduce_variance
8,463
import tensorflow as tf def testEmbeddingRNNSeq2Seq(self): with self.test_session() as sess: with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): enc_inp = [tf.constant(1, tf.int32, shape=[2]) for i in range(2)] dec_inp = [tf.constant(i, tf.int32, shape=[2]) for i in range(3)]
tensorflow.constant_initializer
8,464
import tensorflow as tf # The return value. sum_loss = None # Individual components of the loss that will need summaries. clone_loss = None regularization_loss = None # Compute and aggregate losses on the clone device. with tf.device(clone.device): all_losses = [] clone_losses = tf.get_collection(tf.GraphKeys.LOSSES, clone.scope) if clone_losses: clone_loss = tf.add_n(clone_losses, name='clone_loss') if num_clones > 1: clone_loss = tf.div(clone_loss, 1.0 * num_clones, name='scaled_clone_loss') all_losses.append(clone_loss) if regularization_losses: regularization_loss = tf.add_n(regularization_losses, name='regularization_loss') all_losses.append(regularization_loss) if all_losses:
tensorflow.add_n
8,465
import tensorflow as tf self.v = tf.get_variable('v', [k_h, k_w, input_dim, output_dim], 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),
tensorflow.nn.l2_normalize
8,466
import tensorflow as tf A namedtuple of input and target data. """ input_text = tf.map_fn(lambda x: x[:-1], chunk) target_text = tf.map_fn(lambda x: x[1:], chunk) return (input_text, target_text) def build_to_ids_fn(vocab, max_seq_len): """Constructs function mapping examples to sequences of token indices.""" _, _, bos, eos = get_special_tokens(len(vocab)) table_values = np.arange(len(vocab), dtype=np.int64) table = tf.lookup.StaticVocabularyTable( tf.lookup.KeyValueTensorInitializer(vocab, table_values), num_oov_buckets=1) def to_ids(example): sentence = tf.reshape(example['tokens'], shape=[1]) words = tf.strings.split(sentence, sep=' ').values truncated_words = words[:max_seq_len] tokens = table.lookup(truncated_words) + 1 tokens = tf.cond( tf.less(tf.size(tokens), max_seq_len), lambda: tf.concat([tokens, [eos]], 0), lambda: tokens) return tf.concat([[bos], tokens], 0)
tensorflow.lookup.KeyValueTensorInitializer
8,467
import tensorflow as tf # check_shape([rho, distribution_f, q_value], [[self.n_envs * self.n_steps, self.n_act]] * 2) # Truncated importance sampling adv = qret - value log_f = tf.log(f_i + eps) # [n_envs * n_steps] gain_f = log_f * tf.stop_gradient(adv * tf.minimum(self.correction_term, rho_i)) loss_f = -tf.reduce_mean(gain_f) # Bias correction for the truncation adv_bc = (q_value - tf.reshape(value, [self.n_envs * self.n_steps, 1])) # [n_envs * n_steps, n_act] # check_shape([adv_bc, log_f_bc], [[self.n_envs * self.n_steps, self.n_act]] * 2) if continuous:
tensorflow.reduce_mean
8,468
import tensorflow as tf with self.assertRaisesRegexp( tf.errors.InvalidArgumentError, 'Output shape must have the same batch dimension as the input batch ' 'size. Expected: 1 Observed: 4'): coord.join() def test_get_inputs_cancelled(self): with tf.Graph().as_default(): @dynamic_batching.batch_fn def f(a): return a f(tf.constant([1]))
tensorflow.Graph
8,469
from tensorflow.python.framework import ops """Computes hyperbolic tangent of `x` element-wise. Args: x: A Tensor with type `float`, `double`, `int32`, `complex64`, `int64`, or `qint32`. name: A name for the operation (optional). Returns: A Tensor with the same type as `x` if `x.dtype != qint32` otherwise the return type is `quint8`. """ with ops.op_scope([x], name, "Tanh") as name: x = ops.convert_to_tensor(x, name="x") return gen_math_ops._tanh(x, name=name) ops.RegisterShape("Abs")(common_shapes.unchanged_shape) ops.RegisterShape("Ceil")(common_shapes.unchanged_shape) ops.RegisterShape("Conj")(common_shapes.unchanged_shape) ops.RegisterShape("Cos")(common_shapes.unchanged_shape) ops.RegisterShape("Exp")(common_shapes.unchanged_shape) ops.RegisterShape("Floor")(common_shapes.unchanged_shape) ops.RegisterShape("Imag")(common_shapes.unchanged_shape) ops.RegisterShape("Inv")(common_shapes.unchanged_shape)
tensorflow.python.framework.ops.convert_to_tensor
8,470
import tensorflow as tf self.assertAllEqual(x + y, var_value) self.assertAllEqual(x + y, op_value) var_value, op_value = self._initAssignSubFetch(x, y, use_gpu=False) self.assertAllEqual(x - y, var_value) self.assertAllEqual(x - y, op_value) def testBasic(self): self._testTypes(np.arange(0, 20).reshape([4, 5])) def testAssignNonStrictShapeChecking(self): with self.test_session(): data = tf.fill([1024, 1024], 0) p = tf.Variable([1]) a = tf.assign(p, data, validate_shape=False) a.op.run() self.assertAllEqual(p.eval(), data.eval()) # Assign to yet another shape data2 = tf.fill([10, 10], 1) a2 = tf.assign(p, data2, validate_shape=False) a2.op.run() self.assertAllEqual(p.eval(), data2.eval()) def testInitRequiredAssignAdd(self): with self.test_session(): p = tf.Variable(tf.fill([1024, 1024], 1),
tensorflow.assign
8,471
import tensorflow as tf masks1 = tf.constant([[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0]], dtype=tf.int32) masks2 = tf.constant([[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 0], [1, 0, 1, 1, 1]], dtype=tf.int32)
tensorflow.constant
8,472
import tensorflow as tf # character sequences in this batch were padded to the same fixed length so # that they could be easily fed through the above RNN loop. The # `sequence_length` vector tells us the true lengths of the character # sequences, letting us obtain for each sequence the hidden state that was # generated by its non-padding characters. batch_range = [i for i in range(batch_size)] indices = tf.stack([sequence_length - 1, batch_range], axis=1) hidden_states = tf.gather_nd(chars, indices) return self.relu(hidden_states) def loss(labels, predictions): """Computes mean squared loss.""" return tf.reduce_mean(tf.squared_difference(predictions, labels)) def test(model, eval_data): """Computes the average loss on eval_data, which should be a Dataset.""" avg_loss = tfe.metrics.Mean("loss") for (labels, chars, sequence_length) in tfe.Iterator(eval_data): predictions = model((chars, sequence_length), training=False) avg_loss(loss(labels, predictions)) print("eval/loss: %.6f\n" % avg_loss.result()) with tf.contrib.summary.always_record_summaries(): tf.contrib.summary.scalar("loss", avg_loss.result())
tensorflow.squared_difference
8,473
import tensorflow as tf activation=common_layers.belu, padding="SAME") flat_x = tf.layers.flatten(x) flat_x = tf.nn.dropout(flat_x, rate=dropout)
tensorflow.layers.flatten
8,474
import tensorflow as tf tf.summary.scalar("learning_rate", model.learning_rate) # Control learning rate decay speed if hparams.tacotron_teacher_forcing_mode == "scheduled": tf.summary.scalar("teacher_forcing_ratio", model.ratio) # Control teacher forcing # ratio decay when mode = "scheduled" gradient_norms = [tf.norm(grad) for grad in model.gradients] tf.summary.histogram("gradient_norm", gradient_norms) tf.summary.scalar("max_gradient_norm", tf.reduce_max(gradient_norms)) # visualize # gradients (in case of explosion) return tf.summary.merge_all() def add_eval_stats(summary_writer, step, linear_loss, before_loss, after_loss, stop_token_loss,
tensorflow.reduce_max
8,475
from tensorflow.python.ops import nn `false_negatives` variables appropriately, and whose value matches `recall`. Raises: ValueError: If `ignore_mask` is not `None` and its shape doesn't match `predictions`, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ default_name = _at_k_name('recall', k, class_id=class_id) with ops.name_scope(name, default_name, (predictions, labels)) as scope: _, top_k_idx = nn.top_k(predictions, k) top_k_idx = math_ops.to_int64(top_k_idx) weights = _mask_weights(ignore_mask, weights) tp, tp_update = _streaming_sparse_true_positive_at_k( predictions_idx=top_k_idx, labels=labels, k=k, class_id=class_id, weights=weights) fn, fn_update = _streaming_sparse_false_negative_at_k( predictions_idx=top_k_idx, labels=labels, k=k, class_id=class_id, weights=weights) metric = math_ops.div(tp, math_ops.add(tp, fn), name=scope)
tensorflow.python.ops.nn.top_k
8,476
import tensorflow as tf def _add_score_summary(self, key, tensor): tf.summary.histogram('SCORE/' + tensor.op.name + '/' + key + '/scores', tensor) def _add_train_summary(self, var): tf.summary.histogram('TRAIN/' + var.op.name, var) # Custom Layers # def _reshape_layer(self, bottom, num_dim, name): input_shape = tf.shape(bottom) with tf.variable_scope(name): # change the channel to the caffe format # 18个通道[,18,none,none],分别显示得分,前9个为前景得分,后9个为背景得分 # 第二次[1,2,none,none] to_caffe = tf.transpose(bottom, [0, 3, 1, 2]) # then force it to have channel 2 #[1,2,none.none],将9个anchor的前景得分和背景得分分开 # 第二次[1,18,none,none] reshaped = tf.reshape(to_caffe, tf.concat(axis=0, values=[[self._batch_size], [num_dim, -1], [input_shape[2]]])) # then swap the channel back
tensorflow.variable_scope
8,477
import tensorflow as tf mode, data_parallelism=data_parallelism, decode_hparams=decode_hparams) global_step = tf.train.get_global_step() mesh_shape = mtf.convert_to_shape(hparams.mesh_shape) layout_rules = mtf.convert_to_layout_rules(hparams.layout)
tensorflow.train.get_global_step
8,478
import tensorflow as tf tf.float32, size=self.num_cells + 2, clear_after_read=False) arc_seq = tf.TensorArray(tf.int32, size=self.num_cells * 4)
tensorflow.TensorArray
8,479
import tensorflow as tf if reuse: tf.get_variable_scope().reuse_variables() else: assert tf.get_variable_scope().reuse is False """U-Net Generator""" def lrelu(x, alpha,name='lrelu'): with tf.variable_scope(name): return tf.nn.relu(x) - alpha * tf.nn.relu(-x) def instance_norm(x,name='instance_norm'): with tf.variable_scope(name): if reuse: tf.get_variable_scope().reuse_variables()
tensorflow.nn.relu
8,480
import tensorflow as tf for i in range(self.config["coref_depth"]): with tf.variable_scope("coref_layer", reuse=(i > 0)):
tensorflow.variable_scope
8,481
import tensorflow as tf """ with tf.name_scope(name):
tensorflow.name_scope
8,482
import tensorflow as tf # 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) 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,
tensorflow.cast
8,483
import tensorflow as tf 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]) b_init = np.array([10.0, 10.0] + [0] * (self.num_branches - 2), dtype=np.float32) self.b_soft = tf.get_variable( "b", [1, self.num_branches], initializer=tf.constant_initializer(b_init)) b_soft_no_learn = np.array( [0.25, 0.25] + [-0.25] * (self.num_branches - 2), dtype=np.float32)
tensorflow.get_variable
8,484
import tensorflow as tf pred_label = tf.argmax(distillation_loss["st_logits"], axis=-1, output_type=tf.int32) correct = tf.equal( tf.cast(tf.ones_like(label_ids, dtype=tf.int32), tf.int32), tf.cast(pred_label, tf.int32) ) st_accuracy = tf.reduce_mean(tf.cast(correct, tf.float32)) pred_label = tf.argmax(distillation_loss["te_logits"], axis=-1, output_type=tf.int32) correct = tf.equal( tf.cast(tf.zeros_like(label_ids, dtype=tf.int32), tf.int32), tf.cast(pred_label, tf.int32) ) te_accuracy = tf.reduce_mean(tf.cast(correct, tf.float32)) except: te_accuracy = tf.constant(0.0) st_accuracy = tf.constant(0.0) try:
tensorflow.zeros_like
8,485
import tensorflow as tf self_attn_result = tf.reduce_sum(attn_score * rep_map_tile, 3) # bs,bn,bl,vec with tf.variable_scope('source2token_self_attn'): inter_block_logits = bn_dense_layer(self_attn_result, ivec, True, 0., 'bn_dense_map', 'linear',
tensorflow.variable_scope
8,486
import tensorflow as tf Returns: A boolean tensor with the same shape as input (indicator) tensor """ indices = tf.where(indicator) indices = tf.random.shuffle(indices) indices = tf.reshape(indices, [-1]) num_samples = tf.minimum(tf.size(indices), num_samples) selected_indices = tf.slice(indices, [0], tf.reshape(num_samples, [1])) selected_indicator = ops.indices_to_dense_vector(selected_indices, tf.shape(indicator)[0]) return tf.equal(selected_indicator, 1) def sample_balanced_positive_negative(indicator, sample_size, labels, positive_fraction=0.5): """Subsamples minibatches to a desired balance of positives and negatives. Arguments: - *indicator*: boolean tensor of shape [N] whose True entries can be sampled. - *sample_size*: desired batch size. If None, keeps all positive samples and
tensorflow.shape
8,487
import tensorflow as tf v_norm = tf.nn.l2_normalize(self.v,axis=[0,1,3]) t = tf.nn.conv2d_transpose(input_var,v_norm,
tensorflow.nn.conv2d_transpose
8,488
import tensorflow as tf # Reshape immages to display them input_images = tf.reshape(x_input, [-1, 28, 28, 1]) generated_images = tf.reshape(decoder_output, [-1, 28, 28, 1]) # 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)
tensorflow.summary.scalar
8,489
import tensorflow as tf import tensorflow as tf import memory_util memory_util.vlog(1) sess = tf.Session() with sess.as_default(): tensor = tf.range(10) print_op = tf.print("tensors:", tensor, {'2': tensor * 2}, output_stream=sys.stderr) with tf.control_dependencies([print_op]): tripled_tensor = tensor * 3 with memory_util.capture_stderr() as stderr: print(sess.run(tripled_tensor)) print(stderr.getvalue())
tensorflow.control_dependencies
8,490
from tensorflow.contrib.metrics.python.ops import set_ops return sparse_ops.sparse_retain( ids, math_ops.equal(ids.values, selected_id)) # TODO(ptucker): Make this more efficient, maybe add a sparse version of # tf.equal and tf.reduce_any? # Shape of filled IDs is the same as `ids` with the last dim collapsed to 1. ids_shape = array_ops.shape(ids, out_type=dtypes.int64) ids_last_dim = array_ops.size(ids_shape) - 1 filled_selected_id_shape = math_ops.reduced_shape( ids_shape, array_ops.reshape(ids_last_dim, [1])) # Intersect `ids` with the selected ID. filled_selected_id = array_ops.fill( filled_selected_id_shape, math_ops.to_int64(selected_id)) result = set_ops.set_intersection(filled_selected_id, ids) return ops.SparseTensor( indices=result.indices, values=result.values, shape=ids_shape) def _maybe_select_class_id(labels, predictions_idx, selected_id=None): """If class ID is specified, filter all other classes. Args: labels: `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch_size, num_labels]. [D1, ... DN] must match `predictions_idx`. predictions_idx: `int64` `Tensor` of class IDs, with shape [D1, ... DN, k]
tensorflow.contrib.metrics.python.ops.set_ops.set_intersection
8,491
import tensorflow as tf # 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() sess.run(init) writer = tf.summary.FileWriter(logdir=tensorboard_path, graph=sess.graph) x_l, y_l = mnist.test.next_batch(n_labeled) for i in range(n_epochs): n_batches = int(n_labeled / batch_size) print("------------------Epoch {}/{}------------------".format(i, n_epochs)) for b in range(1, n_batches + 1): z_real_dist = np.random.randn(batch_size, z_dim) * 5. real_cat_dist = np.random.randint(low=0, high=10, size=batch_size)
tensorflow.summary.FileWriter
8,492
import tensorflow as tf scope=self.name) def linear(input_, output_size, scope=None, stddev=0.02, bias_start=0.0, with_w=False): shape = input_.get_shape().as_list() with tf.variable_scope(scope or "Linear"): matrix = tf.get_variable("Matrix", [shape[1], output_size], tf.float32, tf.random_normal_initializer(stddev=stddev)) bias = tf.get_variable("bias", [output_size], initializer=tf.constant_initializer(bias_start)) if with_w: return tf.matmul(input_, matrix) + bias, matrix, bias else: return tf.matmul(input_, matrix) + bias def deconv2d(input_, output_shape, k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02, name="deconv2d", with_w=False): with tf.variable_scope(name): # filter : [height, width, output_channels, in_channels] w = tf.get_variable('w', [k_h, k_w, output_shape[-1], input_.get_shape()[-1]],
tensorflow.matmul
8,493
import tensorflow as tf import numpy as np import argparse import facenet import lfw import os import sys from tensorflow.python.ops import data_flow_ops from sklearn import metrics from scipy.optimize import brentq from scipy import interpolate import time def main(args): with tf.Graph().as_default(): config = tf.ConfigProto(inter_op_parallelism_threads=args.num_inter_threads, intra_op_parallelism_threads=args.num_intra_threads) with tf.Session(config = config) as sess: # Read the file containing the pairs used for testing pairs = lfw.read_pairs(os.path.expanduser(args.lfw_pairs)) # Get the paths for the corresponding images paths, actual_issame = lfw.get_paths(os.path.expanduser(args.lfw_dir), pairs) image_paths_placeholder = tf.placeholder(tf.string, shape=(None,1), name='image_paths') labels_placeholder = tf.placeholder(tf.int32, shape=(None,1), name='labels') batch_size_placeholder = tf.placeholder(tf.int32, name='batch_size')
tensorflow.Graph
8,494
import tensorflow as tf rel_embedding_shape = [rel_cnt, self.embedding_size * self.embedding_size] entity_init = tf.truncated_normal(entity_embedding_shape, stddev=init_sd) rel_init = tf.truncated_normal(rel_embedding_shape, stddev=init_sd) if self.maxnorm is not None: # Ensure maxnorm constraints are initially satisfied entity_init = dense_maxnorm(entity_init, self.maxnorm) rel_init = dense_maxnorm(rel_init, self.maxnorm) self.entity_embedding_vars = tf.Variable(entity_init) 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) # Reshape rel_embed into square D x D matrices rel_embed_square = tf.reshape(rel_embed, (-1, self.embedding_size, self.embedding_size)) # Reshape head_embed and tail_embed to be suitable for the matrix multiplication head_embed_row = tf.expand_dims(head_embed, 1) # embeddings as row vectors tail_embed_col = tf.expand_dims(tail_embed, 2) # embeddings as column vectors head_rel_mult = tf.batch_matmul(head_embed_row, rel_embed_square) # Output needs a squeeze into a 1d vector raw_output = tf.squeeze(tf.batch_matmul(head_rel_mult, tail_embed_col)) self.output, self.loss = self._create_output_and_loss(raw_output) # Optimization self.train_step = self.opt.minimize(self.loss)
tensorflow.nn.embedding_lookup
8,495
import tensorflow as tf def true_positive_rate_at_false_positive_rate_loss(labels, logits, target_rate, weights=1.0, dual_rate_factor=0.1, label_priors=None, surrogate_type='xent', lambdas_initializer=tf.constant_initializer(1.0), reuse=None, variables_collections=None, trainable=True, scope=None): """Computes true positive rate at false positive rate loss. The loss is based on a surrogate of the form wt * loss(+) + lambdas * (wt * loss(-) - r * (1 - pi))
tensorflow.constant_initializer
8,496
import tensorflow as tf inf=work.inference(batch_image) loss=work.softmax_loss(inf,batch_label) opti=work.optimer(loss,learnrate) test_image_batch,test_label_batch=get_test_batch(test_image,test_label,testnum) test_inf=work.test_inference(test_image_batch) test_labels=tf.one_hot(test_label_batch,classnum) test_pre = tf.reshape(test_inf, [testnum, classnum]) correct_prediction=tf.equal(tf.argmax(test_inf,1),tf.argmax(test_labels,1)) accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) test_pre = tf.argmax(test_pre, 1) test_true = tf.argmax(test_labels, 1) valid_image_batch,valid_label_batch=get_valid_batch(valid_image,valid_label,validnum)
tensorflow.reshape
8,497
import tensorflow as tf # now to upscale to actual image size deconv_shape1 = image_net["pool4"].get_shape() W_t1 = utils.weight_variable([4, 4, deconv_shape1[3].value, NUM_OF_CLASSESS], name="W_t1") b_t1 = utils.bias_variable([deconv_shape1[3].value], name="b_t1") conv_t1 = utils.conv2d_transpose_strided(conv8, W_t1, b_t1, output_shape=tf.shape(image_net["pool4"])) fuse_1 = tf.add(conv_t1, image_net["pool4"], name="fuse_1") deconv_shape2 = image_net["pool3"].get_shape() W_t2 = utils.weight_variable([4, 4, deconv_shape2[3].value, deconv_shape1[3].value], name="W_t2") b_t2 = utils.bias_variable([deconv_shape2[3].value], name="b_t2") conv_t2 = utils.conv2d_transpose_strided(fuse_1, W_t2, b_t2, output_shape=tf.shape(image_net["pool3"]))
tensorflow.add
8,498
import tensorflow as tf self.manager_lstm.state_out[1] ] # for v in self.var_list: # print v def build_placeholders(self): # standard for all policies self.obs = tf.placeholder(tf.float32, [None, self.obs_space]) # ! self.obs = tf.placeholder(tf.float32, [None] + list(self.obs_space)) # ! self.obs_space = env.observation_space.shape self.r = tf.placeholder(tf.float32, (None,1)) self.ac = tf.placeholder(tf.float32, (None, self.act_space)) self.adv = tf.placeholder(tf.float32, [None]) # unused # specific to FeUdal self.prev_g = tf.placeholder(tf.float32, (None, None, self.g_dim)) self.ri = tf.placeholder(tf.float32, (None,)) self.s_diff = tf.placeholder(tf.float32, (None, self.g_dim)) def build_perception(self): self._obs = tf.expand_dims(self.obs, -1) # ! self._obs = tf.expand_dims(self._obs, -1) # ! conv1 = tf.layers.conv2d(inputs=self._obs, filters=16, kernel_size=[2, 1], # ! kernel_size = [8,8] activation=tf.nn.elu, strides=1) # ! strides = 4 conv2 = tf.layers.conv2d(inputs=conv1, filters=32, kernel_size=[2, 1], # ! kernel_size = [4,4]
tensorflow.placeholder
8,499