seed
stringlengths
25
2.89k
seed_api
stringlengths
14
102
index
int64
0
14.8k
import tensorflow as tf return filename class TranslateDistillProblem(TranslateProblem): """Base class for translation problems.""" def is_generate_per_split(self): return True def example_reading_spec(self): data_fields = {"dist_targets": tf.VarLenFeature(tf.int64)} if self.has_inputs: data_fields["inputs"] = tf.VarLenFeature(tf.int64) # hack: ignoring true targets and putting dist_targets in targets data_items_to_decoders = { "inputs": tf.contrib.slim.tfexample_decoder.Tensor("inputs"), "targets": tf.contrib.slim.tfexample_decoder.Tensor("dist_targets"), } return (data_fields, data_items_to_decoders) def get_or_create_vocab(self, data_dir, tmp_dir, force_get=False): """Get vocab for distill problems.""" # We assume that vocab file is present in data_dir directory where the # data generated will be stored.
tensorflow.VarLenFeature
12,900
import tensorflow as tf [rank_assertions[0]], tf.shape(image_list[0])) image_height = image_shape[0] image_width = image_shape[1] crop_size_assert = tf.Assert( tf.logical_and( tf.greater_equal(image_height, crop_height), tf.greater_equal(image_width, crop_width)), ['Crop size greater than the image size.']) asserts = [rank_assertions[0], crop_size_assert] for i in range(1, len(image_list)): image = image_list[i]
tensorflow.greater_equal
12,901
import tensorflow as tf self.saver_train = tf.train.Saver(self.vars) def __build_eval(self): """Build the evaluation graph.""" with tf.Graph().as_default(): # create a TF session for the current graph config = tf.ConfigProto() if FLAGS.enbl_multi_gpu: config.gpu_options.visible_device_list = str(mgw.local_rank()) # pylint: disable=no-member else: config.gpu_options.visible_device_list = '0' # pylint: disable=no-member self.sess_eval = tf.Session(config=config) # data input pipeline with tf.variable_scope(self.data_scope): iterator = self.build_dataset_eval() images, labels = iterator.get_next() # model definition - distilled model if FLAGS.enbl_dst: logits_dst = self.helper_dst.calc_logits(self.sess_eval, images) # model definition - weight-sparsified model
tensorflow.Session
12,902
import tensorflow as tf heatmap_size, tf.reshape(pred_heatmap * 255., [-1, heatmap_size, heatmap_size]),
tensorflow.reshape
12,903
import tensorflow as tf padded_tensor_dict[fields.InputDataFields.image].shape.as_list(), [5, 6, 1]) def test_gray_images_and_additional_channels(self): input_tensor_dict = { fields.InputDataFields.image: tf.placeholder(tf.float32, [None, None, 3]), fields.InputDataFields.image_additional_channels: tf.placeholder(tf.float32, [None, None, 2]), } # pad_input_data_to_static_shape assumes that image is already concatenated # with additional channels. padded_tensor_dict = inputs.pad_input_data_to_static_shapes( tensor_dict=input_tensor_dict, max_num_boxes=3, num_classes=3,
tensorflow.placeholder
12,904
import tensorflow as tf wd: add L2Loss weight decay multiplied by this float. If None, weight decay is not added for this Variable. use_xavier: bool, whether to use xavier initializer Returns: Variable Tensor """ if use_xavier: initializer = tf.contrib.layers.xavier_initializer() var = _variable_on_cpu(name, shape, initializer) else: # initializer = tf.truncated_normal_initializer(stddev=stddev) with tf.device('/cpu:0'): var = tf.truncated_normal(shape, stddev=np.sqrt(2 / shape[-1])) var = tf.round(var * tf.constant(1000, dtype=tf.float32)) / tf.constant(1000, dtype=tf.float32) var = tf.Variable(var, name='weights') if wd is not None: weight_decay = tf.multiply(tf.nn.l2_loss(var), wd, name='weight_loss') tf.add_to_collection('losses', weight_decay) return var def conv1d(inputs, num_output_channels, kernel_size, scope, stride=1, padding='SAME',
tensorflow.constant
12,905
import tensorflow as tf 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,
tensorflow.one_hot
12,906
import tensorflow as tf self.dropout_mask = [] self.scope = scope for layer in range(num_layers): input_size_ = input_size if layer == 0 else 2 * num_units gru_fw = tf.contrib.rnn.GRUCell(num_units) gru_bw = tf.contrib.rnn.GRUCell(num_units) init_fw = tf.tile(tf.Variable( tf.zeros([1, num_units])), [batch_size, 1]) init_bw = tf.tile(tf.Variable( tf.zeros([1, num_units])), [batch_size, 1]) mask_fw = dropout(tf.ones([batch_size, 1, input_size_], dtype=tf.float32), keep_prob=keep_prob, is_train=is_train, mode=None) mask_bw = dropout(tf.ones([batch_size, 1, input_size_], dtype=tf.float32), keep_prob=keep_prob, is_train=is_train, mode=None) self.grus.append((gru_fw, gru_bw, )) self.inits.append((init_fw, init_bw, )) self.dropout_mask.append((mask_fw, mask_bw, )) def __call__(self, inputs, seq_len, keep_prob=1.0, is_train=None, concat_layers=True): outputs = [inputs]
tensorflow.ones
12,907
import tensorflow as tf graph_results = _train_step(inputs, labels, training=True) init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) if "plugin" in args.optimizer: init_op = tf.group(init_op, emb_opt.initializer) save_op = list() for i, embedding_layer in enumerate(sok_sparse_demo.embedding_layers): control_inputs = [save_op[-1]] if save_op else None with tf.control_dependencies(control_inputs): if args.save_params: filepath = r"./embedding_variables/" utils.try_make_dirs(filepath) op = sok_saver.dump_to_file(embedding_layer.embedding_variable, filepath) else: op = tf.constant(1.0) save_op.append(op) sok_results = list() with tf.Session() as sess: sess.run(sok_init_op) sess.run([init_op, iterator_init]) sess.run(restore_op) sess.graph.finalize() for step in range(args.iter_num): loss_v, emb_vector_v = sess.run([*graph_results]) print("*" * 80) print(f"Step: {step}, loss: {loss_v}, embedding_vector:\n{emb_vector_v}")
tensorflow.constant
12,908
import tensorflow as tf """ mu, var = self.build_posterior_mean_var(X, Y, test_points, True) jitter = tfhacks.eye(tf.shape(mu)[0], var.dtype) * 1e-06 L = tf.batch_cholesky(tf.transpose(var, (2, 0, 1)) + jitter) V_shape = [tf.shape(L)[0], tf.shape(L)[1], num_samples] V = tf.random_normal(V_shape, dtype=L.dtype) samples = tf.expand_dims(tf.transpose(mu), -1) + tf.batch_matmul(L, V) return tf.transpose(samples)
tensorflow.shape
12,909
from tensorflow.python.ops import variables as vars_ if not isinstance(opt, optimizer_.Optimizer): raise ValueError("Unrecognized optimizer: function should return " "subclass of Optimizer. Got %s." % str(opt)) else: raise ValueError("Unrecognized optimizer: should be string, " "subclass of Optimizer, instance of " "subclass of Optimizer or function with one argument. " "Got %s." % str(optimizer)) # All trainable variables, if specific variables are not specified. if variables is None: variables = vars_.trainable_variables() # Compute gradients. gradients = opt.compute_gradients( loss, variables, colocate_gradients_with_ops=colocate_gradients_with_ops) # Optionally add gradient noise. if gradient_noise_scale is not None: gradients = _add_scaled_noise_to_gradients(gradients,
tensorflow.python.ops.variables.trainable_variables
12,910
import tensorflow as tf output = state[:, -cell_output_size:] if decoder.conditional_rnn: with tf.variable_scope('conditional_1'): output, state = update(state, input_) elif decoder.update_first:
tensorflow.variable_scope
12,911
import tensorflow as tf cell_drop=tf.contrib.rnn.DropoutWrapper(lstm,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob) elif activation == 'relu': lstm=tf.nn.rnn_cell.LSTMCell(num_units=state_size, activation = tf.nn.relu, state_is_tuple=True) cell_drop=tf.contrib.rnn.DropoutWrapper(lstm,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob) else: #tanh by default lstm=tf.nn.rnn_cell.LSTMCell(num_units=state_size, state_is_tuple=True) cell_drop=tf.contrib.rnn.DropoutWrapper(lstm,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob) elif cell_type == 'GRU': if activation == 'linear': gru=tf.nn.rnn_cell.GRUCell(state_size, activation = tf.identity) cell_drop=tf.contrib.rnn.DropoutWrapper(gru,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob) elif activation == 'relu': gru=tf.nn.rnn_cell.GRUCell(state_size, activation = tf.nn.relu) cell_drop=tf.contrib.rnn.DropoutWrapper(gru,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob) else: gru=tf.nn.rnn_cell.GRUCell(state_size) cell_drop=tf.contrib.rnn.DropoutWrapper(gru,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob) else: if activation == 'linear': cell_basic = tf.contrib.rnn.BasicRNNCell(state_size,activation=tf.identity)
tensorflow.nn.rnn_cell.GRUCell
12,912
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] query = tf.layers.dense(query, facts_size, activation=None, name='f1' + stag) query = prelu(query) queries = tf.tile(query, [1, tf.shape(facts)[1]]) queries = tf.reshape(queries, tf.shape(facts)) din_all = tf.concat([queries, facts, queries-facts, queries*facts], axis=-1) d_layer_1_all = tf.layers.dense(din_all, 80, activation=tf.nn.sigmoid, name='f1_att' + stag) d_layer_2_all = tf.layers.dense(d_layer_1_all, 40, activation=tf.nn.sigmoid, name='f2_att' + stag) d_layer_3_all = tf.layers.dense(d_layer_2_all, 1, activation=None, name='f3_att' + stag) d_layer_3_all = tf.reshape(d_layer_3_all, [-1, 1, tf.shape(facts)[1]]) scores = d_layer_3_all
tensorflow.concat
12,913
import tensorflow as tf [6, 6, 5, 4, 0, 1, 2, 3, 3], # [6, 6, 5, 4, 0, 1, 2, 3, 3], # ], [ [6, 6, 5, 4, 0, 1, 2, 3, 3], # [6, 6, 5, 4, 0, 1, 2, 3, 3], # [6, 6, 5, 4, 0, 1, 2, 3, 3], # ], ] self.assertAllEqual( expected, relative_pos_gen.make_local_relative_att_ids( seq_len=3, local_radius=4, batch_size=tf.shape(dummy_batch)[0])) def test_make_local_relative_att_ids_invalid_arguments(self): relative_pos_gen = feature_utils.RelativePositionGenerator(max_distance=3) with self.assertRaises(ValueError): relative_pos_gen.make_local_relative_att_ids(seq_len=0, local_radius=3) with self.assertRaises(ValueError): relative_pos_gen.make_local_relative_att_ids(seq_len=5, local_radius=0) with self.assertRaises(ValueError):
tensorflow.shape
12,914
import tensorflow as tf with tf.variable_scope("conv_block_" + str(num_filters) + "_" + name): for i in range(2): with tf.variable_scope("conv1d_%s" % str(i)): filter_shape = [3, inputs.get_shape()[2], num_filters] W = tf.get_variable(name='W', shape=filter_shape, initializer=he_normal, regularizer=regularizer) inputs = tf.nn.conv1d(inputs, W, stride=1, padding="SAME")
tensorflow.get_variable
12,915
import tensorflow as tf with self.test_session(): x = tf.constant([1.0, 2.0], tf.float64) y = tf.constant([2.0, 3.0], tf.float64) z = tf.py_func(my_func, [x, y], [tf.float64]) self.assertAllEqual( z[0].eval(), my_func([1.0, 2.0], [2.0, 3.0]).astype(np.float64)) # a bit exotic type (complex64) with self.test_session(): x = tf.constant(1+2j, tf.complex64) y = tf.constant(3+4j, tf.complex64) z, = tf.py_func(my_func, [x, y], [tf.complex64]) self.assertAllClose(z.eval(), my_func(1+2j, 3+4j)) # a bit excotic function (rfft) with self.test_session(): x = tf.constant([1., 2., 3., 4.], tf.float32) def rfft(x): return np.fft.rfft(x).astype(np.complex64)
tensorflow.constant
12,916
import tensorflow as tf config.add_hparam("n_classes", 10) config.add_hparam("dataset", "cifar-10") x = tf.random_normal( shape=(self.config.batch_size,) + self.config.input_shape) t = tf.random_uniform( shape=(self.config.batch_size,), minval=0, maxval=self.config.n_classes, dtype=tf.int32) global_step = tf.Variable(0., trainable=False) model = revnet.RevNet(config=config) _, saved_hidden = model(x) grads, _ = model.compute_gradients(saved_hidden=saved_hidden, labels=t) optimizer = tf.train.AdamOptimizer(learning_rate=1e-3) train_op = optimizer.apply_gradients( zip(grads, model.trainable_variables), global_step=global_step) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for _ in range(1): sess.run(train_op) # Benchmark related def device_and_data_format(): return ("/gpu:0", "channels_first") if tf.test.is_gpu_available() else ("/cpu:0",
tensorflow.train.AdamOptimizer
12,917
import tensorflow as tf use_pretrained, pretrained_model_file_path): kwargs = {'pretrained': use_pretrained} net = get_model(model_name, **kwargs) input_image_size = net.in_size[0] if hasattr(net, 'in_size') else 224 x = tf.placeholder( dtype=tf.float32, shape=(None, 3, input_image_size, input_image_size), name='xx') y_net = net(x) if use_pretrained or pretrained_model_file_path:
tensorflow.placeholder
12,918
import tensorflow as tf Returns: Nx#class logits """ def optimizer(self): lr = tf.get_variable('learning_rate', initializer=0.1, trainable=False) tf.summary.scalar('learning_rate-summary', lr) return tf.train.MomentumOptimizer(lr, 0.9, use_nesterov=True) def image_preprocess(self, image): with tf.name_scope('image_preprocess'):
tensorflow.get_variable
12,919
import tensorflow as tf pred1, pred2 = tf.split(pred, 2, axis=0) tgt1, tgt2 = tf.split(tgt, 2, axis=0) geq = tf.cast((tgt1 - tgt2) > 0, tf.bool) tgt_larg = tf.where(geq, tgt1, tgt2) tgt_small = tf.where(geq, tgt2, tgt1) pred_larg = tf.where(geq, pred1, pred2) pred_small = tf.where(geq, pred2, pred1) loss = tf.maximum(0.0, (tgt_larg - tgt_small) - (pred_larg - pred_small)) loss = tf.reduce_mean(loss)
tensorflow.where
12,920
import tensorflow as tf tvars = tf.trainable_variables() initialized_variable_names = {} scaffold_fn = None if init_checkpoint: (assignment_map, initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) if use_tpu: def tpu_scaffold(): tf.train.init_from_checkpoint(init_checkpoint, assignment_map) return tf.train.Scaffold() scaffold_fn = tpu_scaffold else: init_op=tf.train.init_from_checkpoint(init_checkpoint, assignment_map) scaffold_fn=tf.train.Scaffold(init_op=init_op) # def train_scafflod(): # tf.train.init_from_checkpoint(init_checkpoint, assignment_map) # # scaffold_fn=tf.train.Scaffold(init_fn=train_scafflod) tf.logging.info("**** Trainable Variables ****") for var in tvars: init_string = "" if var.name in initialized_variable_names: init_string = ", *INIT_FROM_CKPT*"
tensorflow.train.init_from_checkpoint
12,921
import tensorflow as tf processed_l1_h2, getattr(self, 'ff_bias_%s' % idx)) processed_l1_h2 = self.ff_nl(processed_l1_h2) if self.batch_norm: with tf.variable_scope( 'l1_h2_bn_ff_%s' % idx, reuse=self.scope_reuse) as scope: processed_l1_h2 = tf.contrib.layers.batch_norm(
tensorflow.variable_scope
12,922
import tensorflow as tf num_items = params["num_items"] users = tf.random_uniform([batch_size], dtype=tf.int32, minval=0, maxval=num_users) items = tf.random_uniform([batch_size], dtype=tf.int32, minval=0, maxval=num_items) if is_training:
tensorflow.random_uniform
12,923
import tensorflow as tf X = tf.nn.avg_pool(X, ksize=(1, filter_size, filter_size, 1), strides=[1, stride, stride, 1], padding='SAME') X = tf.reshape(X, (-1, w // stride, h // stride, ch)) # Sanity shape check return X def _add_identity_op(self, X, input_idx, ni, w, h, ch, is_reduction, is_dynamic, is_train): stride = 2 if is_reduction else 1 with tf.variable_scope('identity_op'): # If stride > 1, calibrate, else, just return itself if stride > 1: X = self._calibrate(X, w, h, ch, w // stride, h // stride, ch, is_train=is_train) X = tf.reshape(X, (-1, w // stride, h // stride, ch)) # Sanity shape check return X
tensorflow.variable_scope
12,924
import tensorflow as tf logits = tf.reshape(logits, [self.batch_size, self.num_steps, vocab_size]) loss = tf.contrib.seq2seq.sequence_loss( logits, input_.targets, tf.ones([self.batch_size, self.num_steps], dtype=tf.float32), average_across_timesteps=False, average_across_batch=True) self._cost = tf.reduce_sum(loss)
tensorflow.ones
12,925
import tensorflow as tf # AC net def build_anet(self, state_in, name, reuse=False, batch_size=64): reg = None with tf.variable_scope(name, reuse=reuse): layer_a1 = tf.layers.dense(state_in, 512, tf.nn.relu, kernel_regularizer=reg) layer_a2 = tf.layers.dense(layer_a1, 256, tf.nn.relu, kernel_regularizer=reg) lstm_a = tf.nn.rnn_cell.LSTMCell(num_units=256) lstm_a = tf.nn.rnn_cell.DropoutWrapper(lstm_a, output_keep_prob=self.keep_prob) state_init_a = lstm_a.zero_state(batch_size=batch_size, dtype=tf.float32) lstm_ain = tf.expand_dims(layer_a2, axis=1) out_a, state_final_a = tf.nn.dynamic_rnn(cell=lstm_a, inputs=lstm_ain, initial_state=state_init_a) cell_out_a = tf.reshape(out_a, [-1, 256]) mu = tf.layers.dense(cell_out_a, self.a_dim, tf.nn.tanh, kernel_regularizer=reg) sigma = tf.layers.dense(cell_out_a, self.a_dim, tf.nn.softplus, kernel_regularizer=reg)
tensorflow.nn.rnn_cell.DropoutWrapper
12,926
import tensorflow as tf best_target_per_prior_index = tf.math.argmax(ious, axis=1) # size: num_targets best_prior_per_target = tf.math.reduce_max(ious, axis=0) best_prior_per_target_index = tf.math.argmax(ious, axis=0)
tensorflow.math.reduce_max
12,927
import tensorflow as tf rnn_outputs = \ tf.scan( self.output_step_scan, rnn_states, initializer=tf.zeros([self.N_batch, self.N_out]), parallel_iterations= 1) return tf.transpose(rnn_outputs, [1, 0, 2]), tf.unstack(rnn_states) # fix spectral radius of recurrent matrix def initial_W(self):
tensorflow.unstack
12,928
import tensorflow as tf b8 = utils.bias_variable([150], name="b8") # W_h = utils.weight_variable([1, 7, 7, 4], name="Wh") conv8 = tf.reshape(utils.conv2d_basic(relu_dropout7, W8, b8),[-1,4*4*150]) fc1 = tf.reshape(tf.layers.dense(conv8,4*4*150,activation = tf.nn.relu),[-1,4,4,150])
tensorflow.layers.dense
12,929
from tensorflow.contrib.metrics.python.ops import metric_ops def _streaming_auc(predictions, labels, weights=None): return metric_ops.streaming_auc( predictions, labels, weights=_float_weights_or_none(weights)) def _accuracy_at_threshold(threshold): def _accuracy_metric(predictions, labels, weights=None): threshold_predictions = math_ops.to_float( math_ops.greater_equal(predictions, threshold)) return metric_ops.streaming_accuracy( predictions=threshold_predictions, labels=labels, weights=weights) return _accuracy_metric def _streaming_at_threshold(streaming_metrics_fn, threshold): def _streaming_metrics(predictions, labels, weights=None): precision_tensor, update_op = streaming_metrics_fn( predictions, labels=labels,
tensorflow.contrib.metrics.python.ops.metric_ops.streaming_accuracy
12,930
import tensorflow as tf tf.reshape(byte, shape=[]), 3, **JPEG_OPT) image = resize_shortest_edge(image, jpeg_shape, 224) image = center_crop(image, 224) return image image = tf.cond(is_bad, bad, good) # TODO other imgproc image = lighting(image, 0.1, eigval=np.array([0.2175, 0.0188, 0.0045], dtype='float32') * 255.0, eigvec=np.array([[-0.5675, 0.7192, 0.4009], [-0.5808, -0.0045, -0.8140], [-0.5836, -0.6948, 0.4203]], dtype='float32')) image = tf.image.random_flip_left_right(image) image = tf.reverse(image, axis=[2]) # to BGR return image return training_mapper if isTrain else validation_mapper """ ====== Model & Evaluation ======= """
tensorflow.image.random_flip_left_right
12,931
import tensorflow as tf dis_train_op = while_loop(cond, body, inputs) # tf.contrib.gan's train op does not manage global steps in it train_op = tf.group( dis_train_op, gan_train_ops.generator_train_op, global_step.assign_add(1)) if params['use_tpu']: # TPU version of EstimatorSpec return tf.contrib.tpu.TPUEstimatorSpec( mode=mode, predictions=predictions, loss=loss, train_op=train_op,) else: return tf.estimator.EstimatorSpec( mode=mode, predictions=predictions, loss=loss,
tensorflow.contrib.tpu.TPUEstimatorSpec
12,932
import tensorflow as tf """ if max_cpus > 1: from garage.sampler import singleton_pool singleton_pool.initialize(max_cpus) self.sess = sess or tf.Session() self.sess_entered = False self.has_setup = False self.plot = False
tensorflow.Session
12,933
from tensorflow.contrib.learn.python.learn.estimators import dnn_linear_combined # distributed jobs, such as "/job:ps" which are not present. config._cluster_spec = server_lib.ClusterSpec({}) classifier = dnn_linear_combined.DNNLinearCombinedClassifier( linear_feature_columns=(sparse_feature,), dnn_feature_columns=(embedding_feature,),
tensorflow.contrib.learn.python.learn.estimators.dnn_linear_combined.DNNLinearCombinedClassifier
12,934
import tensorflow as tf all_perturbed_vars = scope_vars(absolute_scope_name(perturbed_scope)) assert len(all_vars) == len(all_perturbed_vars) perturb_ops = [] for var, perturbed_var in zip(all_vars, all_perturbed_vars): if param_noise_filter_func(perturbed_var): # Perturb this variable. op = tf.assign(perturbed_var, var + tf.random_normal(shape=tf.shape(var), mean=0., stddev=param_noise_scale)) else: # Do not perturb, just assign. op = tf.assign(perturbed_var, var) perturb_ops.append(op) assert len(perturb_ops) == len(all_vars) return tf.group(*perturb_ops) # Set up functionality to re-compute `param_noise_scale`. This perturbs yet another copy # of the network and measures the effect of that perturbation in action space. If the perturbation # is too big, reduce scale of perturbation, otherwise increase. q_values_adaptive = q_func(observations_ph.get(), num_actions, scope="adaptive_q_func") perturb_for_adaption = perturb_vars(original_scope="q_func", perturbed_scope="adaptive_q_func") kl = tf.reduce_sum(tf.nn.softmax(q_values) * (tf.log(tf.nn.softmax(q_values)) - tf.log(tf.nn.softmax(q_values_adaptive))), axis=-1) mean_kl = tf.reduce_mean(kl) def update_scale(): with tf.control_dependencies([perturb_for_adaption]): update_scale_expr = tf.cond(mean_kl < param_noise_threshold,
tensorflow.group
12,935
import tensorflow as tf output = self.activation(net_input) # output: p_s * b_s * o_s return output @property def regularization(self): return self.model_lam * ( self.model_prob * tf.reduce_sum(tf.square(self.model_W)) + tf.reduce_sum(tf.square(self.model_b)) ) # def generate_dropout_mask_placeholders(x_dim, hidden_sizes=(32,)): # dropout_mask_placeholders = [] # for l, size in enumerate((x_dim, *hidden_sizes)): # dropout_mask_placeholders.append(tf.placeholder(dtype=tf.float32, shape=(size,),
tensorflow.square
12,936
from tensorflow.contrib.opt.python.training import variable_clipping_optimizer def _setupDense(self, is_distributed, dtype): with self._maybeWithDevice("/job:ps" if is_distributed else None): var0 = variables.Variable([[0.0, 1.0], [2.0, 3.0]], dtype=dtype) var1 = variables.Variable([4.0, 5.0], dtype=dtype) with self._maybeWithDevice("/job:worker" if is_distributed else None): grads0 = constant_op.constant([[0.1, 0.1], [0.1, 0.1]], dtype=dtype) grads1 = constant_op.constant([0.01, 0.01], dtype=dtype) sgd = gradient_descent.GradientDescentOptimizer(3.0) clip_opt = variable_clipping_optimizer.VariableClippingOptimizer( sgd, {var0: [1]}, 2.0) update_op = clip_opt.apply_gradients( list(zip([grads0, grads1], [var0, var1]))) variables.global_variables_initializer().run() return var0, var1, update_op def _assertDenseCorrect(self, var0, var1, update_op):
tensorflow.contrib.opt.python.training.variable_clipping_optimizer.VariableClippingOptimizer
12,937
import tensorflow as tf shapes = tf.shape(input_var) shapes = tf.stack([shapes[0],shapes[1]*self.strides[1],shapes[2]*self.strides[2],tf.shape(self.b)[0]]) def _init(): v_norm = tf.nn.l2_normalize(self.v,axis=[0,1,3]) t = tf.nn.conv2d_transpose(input_var,v_norm, output_shape=shapes, strides=self.strides,
tensorflow.nn.l2_normalize
12,938
import tensorflow as tf combined_idx = use_identity * distances + (1 - use_identity) * logspace_idx return tf.clip_by_value(combined_idx, 0, 9) def get_slow_antecedent_scores(self, top_span_emb, top_antecedents, top_antecedent_emb, top_antecedent_offsets, top_span_speaker_ids, genre_emb): k = util.shape(top_span_emb, 0) c = util.shape(top_antecedents, 1) feature_emb_list = [] if self.config["use_metadata"]: top_antecedent_speaker_ids = tf.gather(top_span_speaker_ids, top_antecedents) # [k, c] same_speaker = tf.equal(tf.expand_dims(top_span_speaker_ids, 1), top_antecedent_speaker_ids) # [k, c] speaker_pair_emb = tf.gather(tf.get_variable("same_speaker_emb", [2, self.config["feature_size"]]), tf.to_int32(same_speaker)) # [k, c, emb] feature_emb_list.append(speaker_pair_emb) tiled_genre_emb = tf.tile(tf.expand_dims(tf.expand_dims(genre_emb, 0), 0), [k, c, 1]) # [k, c, emb] feature_emb_list.append(tiled_genre_emb) if self.config["use_features"]: antecedent_distance_buckets = self.bucket_distance(top_antecedent_offsets) # [k, c] antecedent_distance_emb = tf.gather(tf.get_variable("antecedent_distance_emb", [10, self.config["feature_size"]]), antecedent_distance_buckets) # [k, c] feature_emb_list.append(antecedent_distance_emb) feature_emb = tf.concat(feature_emb_list, 2) # [k, c, emb]
tensorflow.to_int32
12,939
import tensorflow as tf def apply_attack_carlini(hps): # Construct graph images, labels = input_name.build_input( FLAGS.dataset, FLAGS.eval_data_path, hps.batch_size, FLAGS.mode) # FLAGS.mode='attack', batch_size=200 Res = model_name.ResNet(hps, images, FLAGS.mode, Reuse=False) Res.build_graph() saver = tf.train.Saver() # Open session and restore checkpoint sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) tf.train.start_queue_runners(sess) sess.run(tf.global_variables_initializer()) ckpt_state = tf.train.get_checkpoint_state(FLAGS.log_root) # Choose dir according to rt tf.logging.info('Loading checkpoint %s', ckpt_state.model_checkpoint_path) saver.restore(sess, ckpt_state.model_checkpoint_path) num_sample = hps.batch_size * FLAGS.eval_batch_count # Initialize results to save entropy_test_adv_all = np.array([]) confidence_test_adv_all = np.array([]) entropy_test_nor_all = np.array([]) confidence_test_nor_all = np.array([]) logits_adv_all = np.reshape(np.array([]), (0, 64)) logits_nor_all = np.reshape(np.array([]), (0, 64)) labels_adv_all = np.array([]) labels_true_all = np.array([]) labels_nor_all = np.array([])
tensorflow.logging.info
12,940
import tensorflow as tf # # %% def plot_samples(samples, parameters, y_axis_label): plt.figure(figsize=(8, 4)) for val, param in zip(samples, parameters): plt.plot(tf.squeeze(val), label=param_to_name[param]) plt.legend(bbox_to_anchor=(1.0, 1.0)) plt.xlabel("HMC iteration") plt.ylabel(y_axis_label)
tensorflow.squeeze
12,941
import tensorflow as tf Returns: samples: an integer `Tensor`. logits: a list of `Tensor`s, one per datashard. losses: a dictionary: {loss-name (string): floating point `Scalar`}. """ logits, losses = self(features) # pylint: disable=not-callable if self.hparams.sampling_method == "argmax": samples = tf.argmax(logits, axis=-1) else: assert self.hparams.sampling_method == "random" def multinomial_squeeze(logits, temperature=1.0): logits_shape = common_layers.shape_list(logits) reshaped_logits = ( tf.reshape(logits, [-1, logits_shape[-1]]) / temperature) choices = tf.multinomial(reshaped_logits, 1) choices = tf.reshape(choices, logits_shape[:-1]) return choices samples = multinomial_squeeze(logits, self.hparams.sampling_temp) return samples, logits, losses def _shard_features(self, features): # pylint: disable=missing-docstring sharded_features = dict() for k, v in six.iteritems(features): v = tf.convert_to_tensor(v) v_shape = common_layers.shape_list(v)
tensorflow.reshape
12,942
import tensorflow as tf import tensorflow as tf import model3 as M import datareader import numpy as np import tqdm import network def grad_loss(x, model): x2d, x3d = x with tf.GradientTape() as tape: pred, K, reprojected, crit_fake = model(x2d) crit_real = model.crit(x3d) crit_dis = tf.reduce_mean(tf.square(crit_real - tf.ones_like(crit_real))) + tf.reduce_mean(tf.square(crit_fake - tf.zeros_like(crit_fake))) crit_gen = tf.reduce_mean(tf.square(crit_fake - tf.ones_like(crit_fake))) rep_loss = tf.reduce_mean(tf.square(pred - x2d)) KK = tf.matmul(K, K, transpose_b=True) K_trace = tf.expand_dims(tf.expand_dims(tf.trace(KK), -1), -1) K_loss = tf.reduce_mean(tf.abs(KK / K_trace - tf.eye(2))) loss_total_gen = crit_gen + rep_loss + K_loss gen_var = model.get_gen_vars() dis_var = model.dis.trainable_variables
tensorflow.ones_like
12,943
import tensorflow as tf def _get_optimizer(self): lr = tf.get_variable('learning_rate', initializer=5e-4, trainable=False) opt = tf.train.AdamOptimizer(lr, epsilon=1e-3) return optimizer.apply_grad_processors(
tensorflow.train.AdamOptimizer
12,944
import tensorflow as tf # target for LM loss tgt = tf.transpose(features["target"], [1, 0]) # target mask for LM loss tgt_mask = tf.transpose(features["target_mask"], [1, 0]) # construct xlnet config and save to model_dir xlnet_config = xlnet.XLNetConfig(FLAGS=FLAGS)
tensorflow.transpose
12,945
import tensorflow as tf 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)
tensorflow.gather
12,946
import tensorflow as tf self.optimizer_func = tf.train.AdagradOptimizer if self.hparams.grad_strategy == 'sgd': self.optimizer_func = tf.train.GradientDescentOptimizer self.separate_gradient_update() tf.summary.scalar('Gradient Norm', self.norm, collections=['train']) tf.summary.scalar('Learning Rate', self.ranker_learning_rate, collections=['train']) tf.summary.scalar('Final Loss', tf.reduce_mean(self.loss), collections=['train']) clipped_labels = tf.clip_by_value(reshaped_train_labels, clip_value_min=0, clip_value_max=1) pad_removed_train_output = self.remove_padding_for_metric_eval(self.docid_inputs, train_output) for metric in self.exp_settings['metrics']: for topn in self.exp_settings['metrics_topn']: list_weights = tf.reduce_mean(self.propensity_weights * clipped_labels, axis=1, keep_dims=True) metric_value = utils.make_ranking_metric_fn(metric, topn)(reshaped_train_labels, pad_removed_train_output, None) tf.summary.scalar('%s_%d' % (metric, topn), metric_value, collections=['train']) weighted_metric_value = utils.make_ranking_metric_fn(metric, topn)(reshaped_train_labels, pad_removed_train_output, list_weights) tf.summary.scalar('Weighted_%s_%d' % (metric, topn), weighted_metric_value, collections=['train']) self.train_summary = tf.summary.merge_all(key='train') self.eval_summary = tf.summary.merge_all(key='eval') self.saver = tf.train.Saver(tf.global_variables()) def separate_gradient_update(self): denoise_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, "denoising_model") ranking_model_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, "ranking_model") self.weighs_propen=denoise_params
tensorflow.reduce_mean
12,947
import tensorflow as tf for i in range(classes.shape[0]): 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) occupancy_value = tf.math.sign(tf.nn.relu(interpolated + self.tol)) sdf_values += occupancy_value intersection = tf.reduce_sum(tf.math.sign(tf.nn.relu(sdf_values - 1))) if intersection > prev_intersection: prev_intersection = intersection num_collisions += 1 status2 = False if status2: a = 1 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, 0].matshow(inter.numpy())
tensorflow.nn.relu
12,948
import tensorflow as tf with tf.variable_scope('lstm', reuse=(t!=0)): _, (c, h) = lstm_cell(inputs=tf.concat(axis=1, values=[x[:,t,:], context]), state=[c, h])
tensorflow.concat
12,949
import tensorflow as tf Args: predictions: 4D tensor or array, [batch_size, width, height, out_channels] predictions of the network . inputs: 4D tensor or array, [batch_size, width, height, num_classes] ground truth labels or target labels. name: Optional scope/name for op_scope. Returns: A tensor with the discretized mix logistic loss. """ with tf.name_scope(name): inputs_shape = list(map(int, inputs.get_shape())) predictions_shape = list(map(int, predictions.get_shape())) nr_mix = int(predictions_shape[-1] / 10) logit_probs = predictions[:, :, :, :nr_mix] predictions = tf.reshape(predictions[:, :, :, nr_mix:], inputs_shape + [nr_mix * 3]) means = predictions[:, :, :, :, :nr_mix] log_scales = tf.maximum(predictions[:, :, :, :, nr_mix:2 * nr_mix], -7.) coeffs = tf.nn.tanh(predictions[:, :, :, :, 2 * nr_mix:3 * nr_mix]) inputs = tf.reshape(inputs, inputs_shape + [1]) + tf.zeros(inputs_shape + [nr_mix]) m2 = tf.reshape(means[:, :, :, 1, :] + coeffs[:, :, :, 0, :] * inputs[:, :, :, 0, :], [inputs_shape[0], inputs_shape[1], inputs_shape[2], 1, nr_mix]) m3 = tf.reshape( means[:, :, :, 2, :] + coeffs[:, :, :, 1, :] * inputs[:, :, :, 0, :] + coeffs[:, :, :, 2, :] * inputs[:, :, :, 1, :], [inputs_shape[0], inputs_shape[1], inputs_shape[2], 1, nr_mix]) means = tf.concat([ tf.reshape(means[:, :, :, 0, :], [inputs_shape[0], inputs_shape[1], inputs_shape[2], 1, nr_mix]), m2, m3 ],
tensorflow.reshape
12,950
import tensorflow as tf For Pendulum-v0 """ class PolicyEstimator_Pendulum(): def __init__(self, entropy_beta=0.01, learning_rate=0.01, par_idx=0,scope="policy_estimator"): w_init = tf.random_normal_initializer(0.,.1); with tf.variable_scope(scope+"_"+str(par_idx)): # state, target and action self.state = tf.placeholder(tf.float32, [None,num_state], name="state") self.target = tf.placeholder(tf.float32,[None,1], name="target") self.a_his = tf.placeholder(tf.float32, [None, num_action], name="action_hist") # 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
tensorflow.layers.dense
12,951
import tensorflow as tf d = tf.contrib.layers.conv2d(layer_input,filters,kernel_size=f_size,stride=stride,padding=padding) if norm: d = tf.contrib.layers.batch_norm(d) d = lrelu(d,alpha=0.2) return d #def common_deconv2d(layer_input,skip_input, filters,f_size=4,stride=2,dropout_rate=0,name='common_deconv2d'): def common_deconv2d(layer_input,filters,f_size=4,stride=2,padding='SAME',dropout_rate=0,name='common_deconv2d'): """Layers used during upsampling""" with tf.variable_scope(name): if reuse: tf.get_variable_scope().reuse_variables() else: assert tf.get_variable_scope().reuse is False u = tf.contrib.layers.conv2d_transpose(layer_input,filters,f_size,stride=stride,padding=padding) if dropout_rate: u = tf.contrib.layers.dropout(u,keep_prob=dropout_rate) u = tf.contrib.layers.batch_norm(u) u = tf.nn.relu(u) # u = tf.contrib.keras.layers.concatenate([skip_input,u])
tensorflow.get_variable_scope
12,952
import tensorflow as tf optimizer = tf.train.GradientDescentOptimizer(self._lr) self._train_op = optimizer.apply_gradients( zip(grads, tvars), global_step=tf.train.get_or_create_global_step()) self._new_lr = tf.placeholder(
tensorflow.train.get_or_create_global_step
12,953
import tensorflow as tf if self.demo: self.c = tf.placeholder(tf.int32, [None, self.config.max_p_len], "context") self.q = tf.placeholder(tf.int32, [None, self.config.max_q_len], "question") self.ch = tf.placeholder(tf.int32, [None, self.config.max_p_len, self.config.max_ch_len], "context_char")
tensorflow.placeholder
12,954
import tensorflow as tf 'especially for TPU inference.') flags.DEFINE_string('model_name', 'amoeba_net', 'Serving model name used for the model server.') flags.DEFINE_multi_integer( 'inference_batch_sizes', [8], 'Known inference batch sizes used to warm up for each core.') FLAGS = flags.FLAGS def build_run_config(): """Return RunConfig for TPU estimator.""" tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver( FLAGS.tpu, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project) eval_steps = FLAGS.num_eval_images // FLAGS.eval_batch_size iterations_per_loop = (eval_steps if FLAGS.mode == 'eval' else FLAGS.iterations_per_loop) save_checkpoints_steps = FLAGS.save_checkpoints_steps or iterations_per_loop run_config = tf.contrib.tpu.RunConfig( cluster=tpu_cluster_resolver, model_dir=FLAGS.model_dir,
tensorflow.contrib.cluster_resolver.TPUClusterResolver
12,955
import tensorflow as tf def _to_tensor(x, dtype): x = tf.convert_to_tensor(x) if x.dtype != dtype: x = tf.cast(x, dtype) return x
tensorflow.cast
12,956
import tensorflow as tf activeBlockIndices = op.inputs[2] bsize = op.inputs[3] bstride = op.inputs[4] boffset = op.inputs[5] transpose = op.get_attr("transpose") # if scatter is overlapping then gradient should still work # because we are overwriting the same values # compute dOutput/dx result = sbnet_module.sparse_scatter( grad, binCounts, activeBlockIndices, tf.zeros_like(x), # output base tensor to add on top of dynamic_bsize=bsize, dynamic_bstride=bstride, dynamic_boffset=boffset, add=True, transpose=transpose, atomic=True) return [result, None, None, None, None, None] # no gradients wrt indices or block params @ops.RegisterGradient("SparseScatter") def _sparse_scatter_grad(op, grad):
tensorflow.zeros_like
12,957
import tensorflow as tf row_splits=[0, 4, 4, 7, 8, 8]), } with tf.compat.v1.Session(graph=graph) as session: schema = schema_inference.infer_feature_schema(outputs, graph, session)
tensorflow.compat.v1.Session
12,958
import tensorflow as tf indices = np.column_stack((L.row, L.col)) L = tf.SparseTensor(indices, L.data, L.shape) return tf.sparse_reorder(L) @property def output_size(self): output_size = self._num_nodes * self._num_units if self._num_proj is not None: output_size = self._num_nodes * self._num_proj return output_size @staticmethod def _concat(x, x_): x_ = tf.expand_dims(x_, 0) return tf.concat([x, x_], axis=0) def __call__(self, inputs, bias_start=0.0): """Graph convolution between input and the graph matrix. :param args: a 2D Tensor or a list of 2D, batch x n, Tensors. :param output_size: :param bias: :param bias_start: :param scope: :return: """ # Reshape input to (batch_size, num_nodes, input_dim) output_size = self._num_units batch_size = inputs.get_shape()[0].value
tensorflow.concat
12,959
import tensorflow as tf # TODO: test with huber loss (it would avoid too high values) qf1_loss = 0.5 * tf.reduce_mean(((q_backup - qf1) ** 2)*self.weight_ph) qf1_loss_col = tf.reduce_mean(((q_backup - qf1) ** 2),1) qf2_loss = 0.5 * tf.reduce_mean(((q_backup - qf2) ** 2)*self.weight_ph) if self.n_step: q_backup_n = tf.stop_gradient( self.rewards_ph_n + (1 - self.terminals_ph_n) *( self.gamma**self.n_step_length ) * self.value_target_n) qf1_loss_n = 0.5 * tf.reduce_mean(((q_backup_n - qf1) ** 2)*self.weight_ph) qf1_loss_n_col = tf.reduce_mean(((q_backup_n - qf1) ** 2),1)
tensorflow.stop_gradient
12,960
import tensorflow as tf self.param_eta_non_lin = init_eta self.param_omega_non_lin = init_omega param_eta = tf.placeholder(dtype=tf.float32, shape=[], name="param_eta") param_omega = tf.placeholder(dtype=tf.float32, shape=[], name="param_omega") old_entropy = tf.placeholder(dtype=tf.float32, shape=[], name="old_entropy") varphis = tf.placeholder(dtype=tf.float32, shape=[None, None], name="varphis") Kt = tf.placeholder(dtype=tf.float32, shape=[None, None], name="Kt") prec = tf.placeholder(dtype=tf.float32, shape=[None, None], name="prec") Waa = tf.placeholder(dtype=tf.float32, shape=[None, None], name="Waa") Wsa = tf.placeholder(dtype=tf.float32, shape=[None, None], name="Wsa") wa = tf.placeholder(dtype=tf.float32, shape=[None, None], name="wa") # varphis = ext.new_tensor( # 'varphis', # ndim=2, # dtype=theano.config.floatX # )
tensorflow.placeholder
12,961
import tensorflow as tf tf.logging.info('Warm-starting tensors: %s', sorted(var_names)) vars_to_warm_start = var_names warm_start_settings = tf.estimator.WarmStartSettings( ckpt_to_initialize_from=checkpoint_path, vars_to_warm_start=vars_to_warm_start)
tensorflow.estimator.WarmStartSettings
12,962
from tensorflow.python.ops import math_ops or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ with variable_scope.variable_scope(name, 'mean', [values, weights]): total = _create_local('total_tensor', shape=values.get_shape()) count = _create_local('count_tensor', shape=values.get_shape()) num_values = array_ops.ones_like(values) if weights is not None: weights = math_ops.to_float(weights) values = math_ops.mul(values, weights) num_values = math_ops.mul(num_values, weights) total_compute_op = state_ops.assign_add(total, values) count_compute_op = state_ops.assign_add(count, num_values) def compute_mean(total, count, name): non_zero_count = math_ops.maximum(count, array_ops.ones_like(count), name=name) return math_ops.truediv(total, non_zero_count, name=name)
tensorflow.python.ops.math_ops.mul
12,963
import tensorflow as tf with tf.variable_scope('softmax'): W = tf.get_variable('W', [self.num_hidden, self.num_classes], # initializer=tf.random_uniform_initializer(-0.003, 0.003)) initializer=tf.contrib.layers.xavier_initializer()) # initializer=tf.truncated_normal_initializer(stddev=0.1)) b = tf.get_variable('b', [self.num_classes], initializer=tf.constant_initializer(0.1)) logits = tf.matmul(last_outputs, W) + b self.embed_inputs = embed_inputs return logits
tensorflow.constant_initializer
12,964
from tensorflow.python.ops import variable_scope as vs * `optimizer` has the wrong type. * `clip_gradients` is neither float nor callable. * `learning_rate` and `learning_rate_decay_fn` are supplied, but no `global_step` is available. * `gradients` is empty. """ loss = ops.convert_to_tensor(loss) contrib_framework.assert_scalar(loss) if global_step is None: global_step = train.get_global_step() else: train.assert_global_step(global_step) with vs.variable_scope(name, "OptimizeLoss", [loss, global_step]): # Update ops take UPDATE_OPS collection if not provided. if update_ops is None: update_ops = set(ops.get_collection(ops.GraphKeys.UPDATE_OPS)) # Make sure update ops are ran before computing loss. if update_ops: loss = control_flow_ops.with_dependencies(list(update_ops), loss) # Learning rate variable, with possible decay. lr = None if learning_rate is not None: if (isinstance(learning_rate, ops.Tensor) and
tensorflow.python.ops.variable_scope.variable_scope
12,965
import tensorflow as tf out = tf.reduce_mean(loss) tf.summary.scalar('cost', out)
tensorflow.summary.scalar
12,966
import tensorflow as tf x = tf.layers.dense(flat_x, 256, activation=tf.nn.relu) x = tf.layers.dense(flat_x, 128, activation=tf.nn.relu) logits = tf.layers.dense(x, self.hparams.problem.num_actions) value = tf.layers.dense(x, 1)[..., 0] return {"target_policy": logits, "target_value": value} @registry.register_model
tensorflow.layers.dense
12,967
import tensorflow as tf xent = xent * loss_weights xent = tf.reduce_sum(xent, axis=-1)
tensorflow.reduce_sum
12,968
import tensorflow as tf 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: biases = tf.get_variable( 'biases', [num_out_channels], self.data_type, tf.constant_initializer(0.0)) biased = tf.reshape( tf.nn.bias_add( conv, biases, data_format=self.data_format), conv.get_shape()) else: self.top_layer = conv self.top_size = num_out_channels biased = self.batch_norm(**self.batch_norm_config) if activation == 'relu':
tensorflow.constant_initializer
12,969
from tensorflow.python.framework import ops def binary_op_wrapper(x, y): with ops.op_scope([x, y], None, op_name) as name: assert isinstance(x, ops.Tensor) y = ops.convert_to_tensor(y, dtype=x.dtype.base_dtype, name="y") return func(x, y, name=name) ops.Tensor._override_operator("__%s__" % op_name, binary_op_wrapper)
tensorflow.python.framework.ops.convert_to_tensor
12,970
import tensorflow as tf self.dropout_mask = [] for layer in range(num_layers): input_size_ = input_size if layer == 0 else 2 * num_units gru_fw = tf.contrib.cudnn_rnn.CudnnGRU(1, num_units) gru_bw = tf.contrib.cudnn_rnn.CudnnGRU(1, num_units) init_fw = tf.tile(tf.Variable( tf.zeros([1, 1, num_units])), [1, batch_size, 1]) init_bw = tf.tile(tf.Variable( tf.zeros([1, 1, num_units])), [1, batch_size, 1]) mask_fw = dropout(tf.ones([1, batch_size, input_size_], dtype=tf.float32), keep_prob=keep_prob, is_train=is_train, mode=None) mask_bw = dropout(tf.ones([1, batch_size, input_size_], dtype=tf.float32),
tensorflow.zeros
12,971
import tensorflow as tf dec, mem = tf.nn.seq2seq.embedding_rnn_seq2seq( enc_inp, dec_inp, cell1, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 5), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 4), res[0].shape) # Test externally provided output projection. w = tf.get_variable("proj_w", [2, 5]) b = tf.get_variable("proj_b", [5]) with tf.variable_scope("proj_seq2seq"): dec, _ = tf.nn.seq2seq.embedding_rnn_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, output_projection=(w, b)) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 2), res[0].shape) # Test that previous-feeding model ignores inputs after the first. dec_inp2 = [tf.constant(0, tf.int32, shape=[2]) for _ in range(3)] with tf.variable_scope("other"): d3, _ = tf.nn.seq2seq.embedding_rnn_seq2seq( enc_inp, dec_inp2, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, feed_previous=tf.constant(True))
tensorflow.nn.seq2seq.embedding_rnn_seq2seq
12,972
import tensorflow as tf with self.test_session() as sess: with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True) cell = tf.nn.rnn_cell.MultiRNNCell(cells=[cell] * 2, state_is_tuple=True) inp = [tf.constant(0.5, shape=[2, 2])] * 2 enc_outputs, enc_state = tf.nn.rnn(cell, inp, dtype=tf.float32) attn_states = tf.concat(1, [tf.reshape(e, [-1, 1, cell.output_size]) for e in enc_outputs]) dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3 dec, mem = tf.nn.seq2seq.attention_decoder( dec_inp, enc_state, attn_states, cell, output_size=4) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape) res = sess.run([mem]) self.assertEqual(2, len(res[0])) self.assertEqual((2, 2), res[0][0].c.shape) self.assertEqual((2, 2), res[0][0].h.shape) self.assertEqual((2, 2), res[0][1].c.shape) self.assertEqual((2, 2), res[0][1].h.shape) # pylint: disable=unused-variable,invalid-name
tensorflow.global_variables_initializer
12,973
import tensorflow as tf t = tf.to_int32(t) example[name] = t return example def input_fn(params): batch_size = params["batch_size"] d = tf.data.TFRecordDataset(input_file) if is_training: d = d.repeat() d = d.shuffle(buffer_size=100) d = d.apply(tf.contrib.data.map_and_batch( lambda record: _decode_record(record, name_to_features),
tensorflow.data.TFRecordDataset
12,974
import tensorflow as tf def add_eval_stats(summary_writer, step, linear_loss, before_loss, after_loss, stop_token_loss, loss): values = [ tf.Summary.Value(tag="Tacotron_eval_model/eval_stats/eval_before_loss", simple_value=before_loss), tf.Summary.Value(tag="Tacotron_eval_model/eval_stats/eval_after_loss", simple_value=after_loss),
tensorflow.Summary.Value
12,975
import tensorflow as tf span_emb_list.append(span_width_emb) if self.config["model_heads"]: span_indices = tf.expand_dims(tf.range(self.config["max_span_width"]), 0) + tf.expand_dims(span_starts, 1) # [k, max_span_width] span_indices = tf.minimum(util.shape(context_outputs, 0) - 1, span_indices) # [k, max_span_width] span_text_emb = tf.gather(head_emb, span_indices) # [k, max_span_width, emb]
tensorflow.range
12,976
import tensorflow as tf 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: L = tf.matrix_band_part(q_sqrt, -1, 0) # R x M x M A_tiled = tf.tile(tf.expand_dims(A, 0), tf.stack([num_func, 1, 1])) LTA = tf.matmul(L, A_tiled, transpose_a=True) # R x M x N else: # pragma: no cover raise ValueError("Bad dimension for q_sqrt: %s" % str(q_sqrt.get_shape().ndims)) if full_cov: fvar = fvar + tf.matmul(LTA, LTA, transpose_a=True) # R x N x N else:
tensorflow.matmul
12,977
import tensorflow as tf hparams.add_hparam("kv_filter_width", 1) return hparams class LatentLayersTest(tf.test.TestCase): @tf.contrib.eager.run_test_in_graph_and_eager_modes() def testTransformerAutoencoder(self): hparams = imagetransformer_latent_tiny() hparams.mode = tf.estimator.ModeKeys.TRAIN block_dim = int(hparams.hidden_size // hparams.num_blocks) block_v_size = 2**(hparams.bottleneck_bits /
tensorflow.contrib.eager.run_test_in_graph_and_eager_modes
12,978
import tensorflow as tf raise ValueError("Expected hparams.coupling to be in %s, got %s" % (exp_coupling, self.hparams.coupling)) if self.is_training: init_features = self.create_init_batch(features) init_op = self.objective_tower(init_features, init=True) init_op = tf.Print( init_op, [init_op], message="Triggering data-dependent init.", first_n=20) tf.add_to_collection("glow_init_op", init_op) train_op = self.objective_tower(features, init=False)
tensorflow.Print
12,979
import tensorflow as tf cstr_pct = tf.math.count_nonzero(loss, dtype=tf.float32) / tf.cast(tf.reduce_prod(tf.shape(loss)), tf.float32) final_loss = tf.reduce_mean(loss) return final_loss, cstr_pct def contra_traj_lossV7(pred, tgt, horizon=12, temp=100): horizon_pred, horizon_tgt = horizon_sumV1(pred, horizon), horizon_sumV1(tgt, horizon) # horizon_pred, horizon_tgt = horizon_sumV2(pred, tgt, horizon) pred_flat1, pred_flat2 = tf.reshape(horizon_pred, [-1, 1]), tf.reshape(horizon_pred, [1, -1]) tgt_flat1, tgt_flat2 = tf.reshape(horizon_tgt, [-1, 1]), tf.reshape(horizon_tgt, [1, -1]) tgt_dif = tgt_flat1 - tgt_flat2 pred_dif = pred_flat1 - pred_flat2 geq = tf.cast(tgt_dif > 0, tf.bool) tgt_posi_dif = tf.where(geq, tgt_dif, -tgt_dif) pred_posi_dif = tf.where(geq, pred_dif, -pred_dif) loss = tf.maximum(0., tgt_posi_dif - pred_posi_dif) cstr_pct = tf.math.count_nonzero(loss, dtype=tf.float32) / tf.cast(tf.reduce_prod(tf.shape(loss)), tf.float32) unorm_w = tf.exp((tgt_flat1 + tgt_flat2)/temp) loss = unorm_w * loss / (tf.reduce_sum(unorm_w)) a = tf.print(tf.reduce_sum(unorm_w)) with tf.control_dependencies([a]): final_loss = tf.reduce_sum(loss) return final_loss, cstr_pct def contra_traj_lossV8(pred, tgt, horizon=12):
tensorflow.where
12,980
import tensorflow as tf if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict: raise ValueError( "At least one of `do_train`, `do_eval` or `do_predict' must be True.") bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length > bert_config.max_position_embeddings: raise ValueError( "Cannot use sequence length %d because the BERT model " "was only trained up to sequence length %d" % (FLAGS.max_seq_length, bert_config.max_position_embeddings)) tf.gfile.MakeDirs(FLAGS.output_dir) task_name = FLAGS.task_name.lower() if task_name not in processors: raise ValueError("Task not found: %s" % (task_name)) processor = processors[task_name]() label_list = processor.get_labels() tokenizer = tokenization.FullTokenizer(
tensorflow.gfile.MakeDirs
12,981
import tensorflow as tf img_h2 = lrelu(conv2d(img_h1, nf2, d_h=ns2, d_w=ns2, name='h2_conv')) img_h3 = lrelu(conv2d(img_h2, nf3, d_h=ns3, d_w=ns3, name='h3_conv')) print(img_h3.get_shape()) img_h4 = lrelu(linear(tf.nn.dropout(tf.reshape(img_h3, [self.batch_size, -1]), keep_prob), featsize, 'h4_lin')) img_z = lrelu(linear(tf.nn.dropout(img_h4, keep_prob), featsize, 'hz_lin')) return img_h0, img_h1, img_h2, img_h3, img_h4, img_z with tf.variable_scope("conv") as scope: srcimg_h0, srcimg_h1, srcimg_h2, srcimg_h3, srcimg_h4, srcimg_z = encode(srcimg) scope.reuse_variables() tgtimg_h0, tgtimg_h1, tgtimg_h2, tgtimg_h3, tgtimg_h4, tgtimg_z = encode(tgtimg) tgtctx_h0, tgtctx_h1, tgtctx_h2, tgtctx_h3, tgtctx_h4, tgtctx_z = encode(tgtctx) with tf.variable_scope("translate") as scope: trans_h0 = lrelu(linear(tf.nn.dropout(tf.concat([srcimg_z, tgtctx_z], 1), keep_prob), featsize, 'trans_h0')) trans_z = linear(tf.nn.dropout(trans_h0, keep_prob), featsize, 'trans_z') self.translated_z = trans_z s_h, s_w = self.output_height, self.output_width s_h0, s_h1, s_h2, s_h3 = \ int(s_h/ns0), int(s_h/ns0/ns1), int(s_h/ns0/ns1/ns2), int(s_h/ns0/ns1/ns2/ns3) s_w0, s_w1, s_w2, s_w3 = \ int(s_w/ns0), int(s_w/ns0/ns1), int(s_w/ns0/ns1/ns2), int(s_w/ns0/ns1/ns2/ns3) def decode(z, skip_h3, skip_h2, skip_h1, skip_h0): z_ = lrelu(linear(tf.nn.dropout(z, keep_prob), nf3*s_h3*s_w3, 'd_h0_lin')) h0 = tf.nn.dropout(tf.reshape(z_, [-1, s_h3, s_w3, nf3]), keep_prob) import IPython IPython.embed() h1 = lrelu(deconv2d(tf.concat([h0, skip_h3], 3),
tensorflow.nn.dropout
12,982
import tensorflow as tf num_blocks=3) z = tf.random_normal([2, 10], dtype=tf.float32) x, _ = networks.generator( z, progress, _num_filters_stub, networks.ResolutionSchedule( start_resolutions=(4, 4), scale_base=2, num_resolutions=3)) fake_loss = tf.reduce_sum(tf.square(x)) grad_norms = [ _get_grad_norm( fake_loss, tf.trainable_variables('.*/progressive_gan_block_1/.*')), _get_grad_norm( fake_loss, tf.trainable_variables('.*/progressive_gan_block_2/.*')), _get_grad_norm( fake_loss, tf.trainable_variables('.*/progressive_gan_block_3/.*')) ] grad_norms_output = None with self.test_session(use_gpu=True) as sess: sess.run(tf.global_variables_initializer()) x1_np = sess.run(x, feed_dict={current_image_id_ph: 0.12}) x2_np = sess.run(x, feed_dict={current_image_id_ph: 1.8}) grad_norms_output = np.array([ sess.run(grad_norms, feed_dict={current_image_id_ph: i}) for i in range(15) # total num of images ])
tensorflow.trainable_variables
12,983
import tensorflow as tf with tf.variable_scope("other"): d3, _ = tf.nn.seq2seq.embedding_rnn_seq2seq( enc_inp, dec_inp2, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, feed_previous=tf.constant(True)) sess.run([tf.global_variables_initializer()]) tf.get_variable_scope().reuse_variables() d1, _ = tf.nn.seq2seq.embedding_rnn_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, feed_previous=True)
tensorflow.global_variables_initializer
12,984
import tensorflow as tf tf.summary.scalar('Gradient Norm', self.norm, collections=['train']) tf.summary.scalar('Learning Rate', self.ranker_learning_rate, collections=['train']) tf.summary.scalar('Final Loss', tf.reduce_mean(self.loss), collections=['train']) clipped_labels = tf.clip_by_value(reshaped_train_labels, clip_value_min=0, clip_value_max=1) pad_removed_train_output = self.remove_padding_for_metric_eval(self.docid_inputs, train_output) for metric in self.exp_settings['metrics']: for topn in self.exp_settings['metrics_topn']: list_weights = tf.reduce_mean(self.propensity_weights * clipped_labels, axis=1, keep_dims=True) metric_value = utils.make_ranking_metric_fn(metric, topn)(reshaped_train_labels, pad_removed_train_output, None) tf.summary.scalar('%s_%d' % (metric, topn), metric_value, collections=['train']) weighted_metric_value = utils.make_ranking_metric_fn(metric, topn)(reshaped_train_labels, pad_removed_train_output, list_weights) tf.summary.scalar('Weighted_%s_%d' % (metric, topn), weighted_metric_value, collections=['train']) self.train_summary = tf.summary.merge_all(key='train') self.eval_summary = tf.summary.merge_all(key='eval') self.saver = tf.train.Saver(tf.global_variables()) def separate_gradient_update(self): denoise_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, "denoising_model") ranking_model_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, "ranking_model") self.weighs_propen=denoise_params if self.hparams.l2_loss > 0: for p in denoise_params: # self.weighs_propen=p # p=tf.Print(p,[p],message="show the weights") self.exam_loss += self.hparams.l1_loss * tf.reduce_sum(tf.abs(p)) for p in ranking_model_params: self.rank_loss += self.hparams.l2_loss * tf.nn.l2_loss(p)
tensorflow.summary.merge_all
12,985
import tensorflow as tf num_acts = self.act_space # Calculate U self.worker_lstm = SingleStepLSTM(tf.expand_dims(self.z, [0]), size=num_acts * self.k, step_size=tf.shape(self.obs)[:1]) flat_logits = self.worker_lstm.output self.worker_vf = self.build_value(flat_logits) U = tf.reshape(flat_logits, [-1, num_acts, self.k]) # Calculate w cut_g = tf.stop_gradient(self.g) cut_g = tf.expand_dims(cut_g, [1]) gstack = tf.concat([self.prev_g, cut_g], axis=1) self.last_c_g = gstack[:, 1:] # print self.last_c_g gsum = tf.reduce_sum(gstack, axis=1) phi = tf.get_variable("phi", (self.g_dim, self.k)) w = tf.matmul(gsum, phi) w = tf.expand_dims(w, [2]) # Calculate policy and sample logits = tf.reshape(tf.matmul(U, w), [-1, num_acts]) self.pi = tf.nn.softmax(logits) self.log_pi = tf.nn.log_softmax(logits) self.sample = policy_utils.categorical_sample(
tensorflow.expand_dims
12,986
import tensorflow as tf 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.floordiv
12,987
import tensorflow as tf if mode != 'gen': neg_log_lhoods = tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=targets) if target_weight_strategy == 'rect': avg_neg_log_lhood = tf.reduce_mean(neg_log_lhoods) else: neg_log_lhoods = tf.multiply(neg_log_lhoods, target_weights) # be careful to have at least one weight be nonzero # should we be taking the mean elem-wise by batch? i think this is a big bug avg_neg_log_lhood = tf.reduce_sum(neg_log_lhoods) / tf.reduce_sum(target_weights) neg_log_lhoods_inspect = tf.reshape(neg_log_lhoods, [batch_size, rnn_nunroll]) # Train op if mode == 'train': lr = tf.Variable(0.0, trainable=False) self._lr = lr self._lr_summary = tf.summary.scalar('learning_rate', self._lr) tvars = tf.trainable_variables()
tensorflow.reshape
12,988
import tensorflow as tf # ===============================================================================DECODER with tf.variable_scope(decoderscope) as scope: if reuse_decoder: scope.reuse_variables() # print('vnet scope', is_train, reuse_unet) # print('VNET Latent:', X.get_shape().as_list()) with tf.variable_scope('decoder'): X = decoder_conf('d3', X, 512, F, 1, norm, reuse_decoder, is_train, self.args.dropout) # 12 > 14 if self.args.skip_connections: X = tf.concat((X, X2), axis=-1) X = decoder_conf('u4', X, 256, F, 2, norm, reuse_decoder, is_train, self.args.dropout) # 14 > 28 X = decoder_conf('d4', X, 256, F, 1, norm, reuse_decoder, is_train, self.args.dropout) # 28 > 30 if self.args.skip_connections: X = tf.concat((X, X1), axis=-1) X = decoder_conf('u5', X, 128, F, 2, norm, reuse_decoder, is_train, self.args.dropout) # 30 > 60 X_LATE = X X = decoder_conf('d5', X, 128, F, 1, norm, reuse_decoder, is_train, self.args.dropout) # 60 > 62 if self.args.skip_connections: X = tf.concat((X, X0), axis=-1)
tensorflow.concat
12,989
import tensorflow as tf output = tf.concat([output_fw, output_bw], axis=-1) else: outputs = outputs_fw hidden = hidden_fw output = output_fw outputs = tf.transpose(outputs, perm=[1, 0, 2]) return (outputs, hidden, output)
tensorflow.transpose
12,990
import tensorflow as tf import numpy as np import tensorflow as tf from evaluation import factory def write_summary(logs, summary_writer, current_step): """Write out summaries of current training step for the checkpoint.""" with tf.Graph().as_default(): summaries = [tf.Summary.Value(tag=tag, simple_value=value) for tag, value in logs.items()] tf_summary = tf.Summary(value=summaries) summary_writer.add_summary(tf_summary, current_step) class TpuExecutor(object):
tensorflow.Graph
12,991
import tensorflow as tf if all([isinstance(output, list) for output in outputs]): if all([all( [isinstance(entry, tf.Tensor) for entry in output_list]) for output_list in outputs]): return [tf.stack(output_tuple) for output_tuple in zip(*outputs)] raise ValueError('`fn` should return a Tensor or a list of Tensors.')
tensorflow.stack
12,992
import tensorflow as tf for i in range(self.n_gpus): worker = '/gpu:{}'.format(i) device_setter = tf.train.replica_device_setter( worker_device=worker, ps_device='/cpu:0', ps_tasks=1) with tf.name_scope('{}_{}'.format(mode, i)) as scope: with tf.device(device_setter): net_outputs = self._model(shards[i], mode, **self.config) if mode == Mode.TRAIN: loss = self._loss(net_outputs, shards[i], **self.config) loss += tf.reduce_sum( tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES, scope)) model_params = tf.trainable_variables() grad = tf.gradients(loss, model_params) tower_losses.append(loss) tower_gradvars.append(zip(grad, model_params)) if i == 0: update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope) elif mode == Mode.EVAL: tower_metrics.append(self._metrics( net_outputs, shards[i], **self.config)) else: tower_preds.append(net_outputs) if mode == Mode.TRAIN:
tensorflow.gradients
12,993
import tensorflow as tf 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]) self.assertEqual((2, 2), res[0].shape) def testBasicRNNSeq2Seq(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.basic_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]) self.assertEqual((2, 2), res[0].shape)
tensorflow.constant
12,994
import tensorflow as tf linear_var = tf.Variable(tf.linspace(start=0.0, stop=1.0, num=3)) # Generates [0.0, 0.5, 1.0] includes the end sequence_var = tf.Variable(tf.range(start=6, limit=15, delta=3)) # Generates [6, 9, 12] doesn't include the end sess.run(linear_var.initializer) sess.run(sequence_var.initializer) print(sess.run(linear_var)) print(sess.run(sequence_var)) rnorm_var = tf.random_normal([row_dim, col_dim], mean=0.0, stddev=1.0) runif_var = tf.random_uniform([row_dim, col_dim], minval=0, maxval=4) print(sess.run(rnorm_var)) print(sess.run(runif_var)) ops.reset_default_graph() sess = tf.Session() my_var = tf.Variable(tf.zeros([1,20]))
tensorflow.random_normal
12,995
import tensorflow as tf if monotonicity_weight: monotonicity_dist = monotonicity_dist or 1.0 batch_size = tf.shape(attention_weights)[0] src_len = tf.shape(attention_weights)[2] trg_len = tf.shape(attention_weights)[1] src_indices = tf.tile(tf.reshape(tf.range(src_len), shape=[1, 1, src_len]), [batch_size, trg_len, 1]) trg_indices = tf.tile(tf.reshape(tf.range(trg_len), shape=[1, trg_len, 1]), [batch_size, 1, src_len]) source_length = encoder_input_length[0] target_length = tf.to_int32(tf.reduce_sum(trg_mask, axis=1)) true_src_len = tf.reshape(source_length, shape=[batch_size, 1, 1]) - 1 true_trg_len = tf.reshape(target_length, shape=[batch_size, 1, 1]) - 1 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)
tensorflow.reshape
12,996
import tensorflow as tf return image image = tf.cond(is_bad, bad, good) # TODO other imgproc
tensorflow.cond
12,997
import tensorflow as tf images, labels = input_name.build_input( FLAGS.dataset, FLAGS.eval_data_path, hps.batch_size, FLAGS.mode) # FLAGS.mode='attack', batch_size=200 Res = model_name.ResNet(hps, images, FLAGS.mode, Reuse=False) Res.build_graph() saver = tf.train.Saver() # Open session and restore checkpoint sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) tf.train.start_queue_runners(sess) sess.run(tf.global_variables_initializer()) ckpt_state = tf.train.get_checkpoint_state(FLAGS.log_root) # Choose dir according to rt tf.logging.info('Loading checkpoint %s', ckpt_state.model_checkpoint_path) saver.restore(sess, ckpt_state.model_checkpoint_path) model_carlini = models_carlini(hps) if FLAGS.attack_method == 'carliniLi':
tensorflow.global_variables_initializer
12,998
import tensorflow as tf def test_inference(self,images): images=tf.cast(images,tf.float32)/255.0 l1 = tf.matmul(images, self.w1)+self.b1 l1=tf.nn.relu(l1) l2 = tf.matmul(l1, self.w2)+self.b2 l2=tf.nn.relu(l2) l3=tf.matmul(l2, self.w3)+self.b3 l3=tf.nn.relu(l3) out=tf.matmul(l3, self.w4)+self.b4 return out def valid_inference(self,images): images=tf.cast(images,tf.float32)/255.0 l1 = tf.matmul(images, self.w1)+self.b1 l1=tf.nn.relu(l1) l2 = tf.matmul(l1, self.w2)+self.b2 l2=tf.nn.relu(l2) l3=tf.matmul(l2, self.w3)+self.b3 l3=tf.nn.relu(l3) out=tf.matmul(l3, self.w4)+self.b4 return out def softmax_loss(self,predicts,labels): predicts=tf.nn.softmax(predicts) labels=tf.one_hot(labels,classnum) loss=-tf.reduce_sum(labels*tf.log(predicts)) return loss def optimer(self,loss,lr=0.001):
tensorflow.nn.relu
12,999