seed
stringlengths
25
2.89k
seed_api
stringlengths
14
102
index
int64
0
14.8k
import tensorflow as tf b = tf.get_variable("proj_b", [5]) with tf.variable_scope("proj_seq2seq"):
tensorflow.variable_scope
8,000
import tensorflow as tf lm_emb = lm_emb[sentence_offset:sentence_offset + max_training_sentences, :, :, :] char_index = char_index[sentence_offset:sentence_offset + max_training_sentences, :, :] text_len = text_len[sentence_offset:sentence_offset + max_training_sentences] speaker_ids = speaker_ids[word_offset: word_offset + num_words] gold_spans = np.logical_and(gold_ends >= word_offset, gold_starts < word_offset + num_words) gold_starts = gold_starts[gold_spans] - word_offset gold_ends = gold_ends[gold_spans] - word_offset cluster_ids = cluster_ids[gold_spans] return tokens, context_word_emb, head_word_emb, lm_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids def get_candidate_labels(self, candidate_starts, candidate_ends, labeled_starts, labeled_ends, labels): same_start = tf.equal(tf.expand_dims(labeled_starts, 1), tf.expand_dims(candidate_starts, 0)) # [num_labeled, num_candidates] same_end = tf.equal(tf.expand_dims(labeled_ends, 1), tf.expand_dims(candidate_ends, 0)) # [num_labeled, num_candidates] same_span = tf.logical_and(same_start, same_end) # [num_labeled, num_candidates] candidate_labels = tf.matmul(tf.expand_dims(labels, 0), tf.to_int32(same_span)) # [1, num_candidates] candidate_labels = tf.squeeze(candidate_labels, 0) # [num_candidates] return candidate_labels def get_dropout(self, dropout_rate, is_training): return 1 - (tf.to_float(is_training) * dropout_rate) def coarse_to_fine_pruning(self, top_span_emb, top_span_mention_scores, c): k = util.shape(top_span_emb, 0) top_span_range = tf.range(k) # [k]
tensorflow.expand_dims
8,001
import tensorflow as tf Train RNN graph for multiple series """ def train_rnn_multi(raw_data_x, raw_data_y, val_data_x, val_data_y, timeindex_train, timeindex_val, g, num_epochs, num_steps, batch_size, input_prob, output_prob, state_prob, epoch_before_val = 50, max_checks_without_progress=50,epoch_overlap=None, verbose=True, save=False): with tf.Session() as sess: "initialize the variables" sess.run(tf.global_variables_initializer()) "see the trainable variables" # print("The trainable variables are:") variable_names = [v.name for v in tf.trainable_variables()] variable_shapes = [v.get_shape() for v in tf.trainable_variables()] parameter_num = 0 for name, shape in zip(variable_names, variable_shapes): # print('{}\nShape: {}'.format(name, shape)) parameter_num += shape[0]*shape[1] if np.size(shape)>1 else shape[0] "train the graph" training_losses = [] val_losses = [] #set early_stopping cretirion checks_without_progress = 0 best_loss = np.infty
tensorflow.trainable_variables
8,002
import tensorflow as tf prediction_final = tf.squeeze(tf.slice(prediction_inspect, [0, rnn_nunroll - 1], [-1, 1]), squeeze_dims=[1]) print('logit: {}'.format(logits.get_shape())) # Compute loss 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)
tensorflow.multiply
8,003
import tensorflow as tf # invalid position mask such as query and special symbols (PAD, SEP, CLS) p_mask = features["p_mask"] # logit of the start position with tf.variable_scope("start_logits"): start_logits = tf.layers.dense( output, 1, kernel_initializer=initializer) start_logits = tf.transpose(tf.squeeze(start_logits, -1), [1, 0]) start_logits_masked = start_logits * (1 - p_mask) - 1e30 * p_mask start_log_probs = tf.nn.log_softmax(start_logits_masked, -1) # logit of the end position with tf.variable_scope("end_logits"): if is_training: # during training, compute the end logits based on the # ground truth of the start position start_positions = tf.reshape(features["start_positions"], [-1]) start_index = tf.one_hot(start_positions, depth=seq_len, axis=-1, dtype=tf.float32)
tensorflow.nn.log_softmax
8,004
from tensorflow.contrib.eager.python.examples.l2hmc import l2hmc hparams = get_default_hparams() energy_fn, _, _ = l2hmc.get_scg_energy_fn() dynamics = l2hmc.Dynamics( x_dim=hparams.x_dim,
tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.Dynamics
8,005
import tensorflow as tf import tensorflow as tf _SLEEP_TIME = 1.0 class DynamicBatchingTest(tf.test.TestCase): def test_one(self): with self.test_session() as session: @dynamic_batching.batch_fn def f(a, b): batch_size = tf.shape(a)[0] return a + b, tf.tile([batch_size], [batch_size]) output = f(tf.constant([[1, 3]]), tf.constant([2])) tf.train.start_queue_runners() result, batch_size = session.run(output) self.assertAllEqual([[3, 5]], result) self.assertAllEqual([1], batch_size) def test_two(self): with self.test_session() as session:
tensorflow.tile
8,006
import tensorflow as tf tf.gfile.DeleteRecursively(tmp_dir) def run(dataset_dir): """Runs the download and conversion operation. Args: dataset_dir: The dataset directory where the dataset is stored. """ if not tf.gfile.Exists(dataset_dir): tf.gfile.MakeDirs(dataset_dir) dataset_utils.download_and_uncompress_tarball(_DATA_URL, dataset_dir) # First, process the training data: #with tf.python_io.TFRecordWriter(training_filename) as tfrecord_writer: filenames = [] for i in range(_NUM_TRAIN_FILES): filenames.append(os.path.join(dataset_dir, 'cifar-10-batches-py',
tensorflow.gfile.MakeDirs
8,007
import tensorflow as tf resize_side_min: The lower bound for the smallest side of the image for aspect-preserving resizing. resize_side_max: The upper bound for the smallest side of the image for aspect-preserving resizing. Returns: A preprocessed image. """ resize_side = tf.random_uniform( [], minval=resize_side_min, maxval=resize_side_max+1, dtype=tf.int32) image = _aspect_preserving_resize(image, resize_side) image = _random_crop([image], output_height, output_width)[0] image.set_shape([output_height, output_width, 3]) image = tf.to_float(image) image = tf.image.random_flip_left_right(image) return _mean_image_subtraction(image, [_R_MEAN, _G_MEAN, _B_MEAN]) def preprocess_for_eval(image, output_height, output_width, resize_side): """Preprocesses the given image for evaluation. Args: image: A `Tensor` representing an image of arbitrary size. output_height: The height of the image after preprocessing. output_width: The width of the image after preprocessing. resize_side: The smallest side of the image for aspect-preserving resizing.
tensorflow.to_float
8,008
import tensorflow as tf precision = precision_score(labels_all,predicted_score) recall = recall_score(labels_all,predicted_score) apk_sc = rank_metrics.apk(actual, predicted, k=50) return roc_sc, auprc_score,accuracy,precision,recall,f ,apk_sc def construct_placeholders(edge_types): placeholders = { 'batch': tf.placeholder(tf.int32, name='batch'), 'batch_neg': tf.placeholder(tf.int32, name='batch_neg'), 'batch_node':tf.placeholder(tf.int32,name = 'batch_node'), 'adj_min_batch': tf.placeholder(tf.float32,name='adj_min_batch'), 'sim_min_batch': tf.placeholder(tf.float32,name='sim_min_batch'), 'batch_edge_type_idx': tf.placeholder(tf.int32, shape=(), name='batch_edge_type_idx'), 'batch_row_edge_type': tf.placeholder(tf.int32, shape=(), name='batch_row_edge_type'), 'batch_col_edge_type': tf.placeholder(tf.int32, shape=(), name='batch_col_edge_type'), 'degrees': tf.placeholder(tf.int32), 'dropout': tf.placeholder_with_default(0., shape=()), } placeholders.update({ 'adj_mats_%d,%d,%d' % (i, j, k): tf.sparse_placeholder(tf.float32) for i, j in edge_types for k in range(edge_types[i,j])}) placeholders.update({ 'feat_%d' % i: tf.sparse_placeholder(tf.float32) for i, _ in edge_types}) return placeholders
tensorflow.placeholder
8,009
import tensorflow as tf def _evaluate_spherical_harmonics_branch(degree, order, theta, phi, sign_order, var_type=tf.float64): sqrt_2 = tf.constant(1.41421356237, dtype=var_type) order_float = tf.cast(order, dtype=var_type) tmp = sqrt_2 * _spherical_harmonics_normalization( degree, order, var_type) * evaluate_legendre_polynomial( degree, order, tf.cos(theta)) positive = tmp * tf.cos(order_float * phi) negative = tmp * tf.sin(order_float * phi) return tf.where(tf.greater(sign_order, 0), positive, negative) def evaluate_spherical_harmonics( degree_l: TensorLike, order_m: TensorLike, theta: TensorLike, phi: TensorLike, name: str = "spherical_harmonics_evaluate_spherical_harmonics") -> TensorLike: # pylint: disable=line-too-long
tensorflow.cos
8,010
import tensorflow as tf if padding == "PARTIAL": with tf.variable_scope('mask'): _, h, w, _ = input.get_shape().as_list() slide_window = size[0] * size[1] mask = tf.ones(shape=[1, h, w, 1]) update_mask = tf.layers.conv2d(mask, filters=1, dilation_rate=(dilation, dilation), name='mask' + id, kernel_size=size, kernel_initializer=tf.constant_initializer(1.0), strides=stride, padding="SAME", use_bias=False, trainable=False) mask_ratio = slide_window / (update_mask + 1e-8) update_mask = tf.clip_by_value(update_mask, 0.0, 1.0) mask_ratio = mask_ratio * update_mask with tf.variable_scope('parconv'): x = tf.layers.conv2d(input, filters=channels, name='conv' + id, kernel_size=size, kernel_initializer=init, strides=stride, padding="SAME", use_bias=False) x = x * mask_ratio if use_bias: bias = tf.get_variable("bias" + id, [channels], initializer=tf.constant_initializer(0.0)) x = tf.nn.bias_add(x, bias) return x * update_mask if padding == "REFLECT": assert size[0] % 2 == 1 and size[1] % 2 == 1, "REFLECTION PAD ONLY WORKING FOR ODD FILTER SIZE.. " + str(size) pad_x = size[0] // 2 pad_y = size[1] // 2 input = tf.pad(input, [[0, 0], [pad_x, pad_x], [pad_y, pad_y], [0, 0]], "REFLECT") padding = "VALID"
tensorflow.layers.conv2d
8,011
import tensorflow as tf def add_grad_to_graph(self, a_grads): with tf.variable_scope('policy_grads'):
tensorflow.variable_scope
8,012
from tensorflow.keras.layers import Dense, Conv2D, MaxPool2D, Flatten # Block 1 conv1a = Conv2D(padding="same", filters=RNN_SIZE//8, kernel_size=[8, 8], strides=4, data_format='channels_last', kernel_initializer=w_init,activation=tf.nn.relu)(self.inputs) conv1b = Conv2D(padding="same", filters=RNN_SIZE//8, kernel_size=[3, 3], strides=1, data_format='channels_last', kernel_initializer=w_init,activation=tf.nn.relu)(conv1a) conv1c = Conv2D(padding="same", filters=RNN_SIZE//8, kernel_size=[3, 3], strides=1, data_format='channels_last', kernel_initializer=w_init,activation=tf.nn.relu)(conv1b) pool1 = MaxPool2D(pool_size=[2,2])(conv1c) # Block 2 conv2a = Conv2D(padding="same", filters=RNN_SIZE//4, kernel_size=[3, 3], strides=1, data_format='channels_last', kernel_initializer=w_init,activation=tf.nn.relu)(pool1) conv2b = Conv2D(padding="same", filters=RNN_SIZE//4, kernel_size=[3, 3], strides=1, data_format='channels_last', kernel_initializer=w_init,activation=tf.nn.relu)(conv2a) conv2c = Conv2D(padding="same", filters=RNN_SIZE//4, kernel_size=[3, 3], strides=1, data_format='channels_last', kernel_initializer=w_init,activation=tf.nn.relu)(conv2b) pool2 = MaxPool2D(pool_size=[2,2])(conv2c) # Block 3 conv3a = Conv2D(padding="same", filters=RNN_SIZE//2, kernel_size=[3, 3], strides=1, data_format='channels_last', kernel_initializer=w_init,activation=tf.nn.relu)(pool2)
tensorflow.keras.layers.Conv2D
8,013
from tensorflow import keras dataset = dataset.shuffle(buffer_size = 10 * batch_size) else: num_epochs = 1 # end-of-input after this dataset = dataset.repeat(num_epochs).batch(batch_size) iterator = dataset.make_one_shot_iterator() batch_features, batch_labels = iterator.get_next() return batch_features, batch_labels return _input_fn # Create inference model using Keras # The model here is a dnn regressor def make_keras_estimator(output_dir): from tensorflow import keras model = keras.models.Sequential() model.add(keras.layers.Dense(32, input_shape=(N_INPUTS,), name=TIMESERIES_INPUT_LAYER)) model.add(keras.layers.Activation('relu')) model.add(keras.layers.Dense(1)) model.compile(loss = 'mean_squared_error', optimizer = 'adam', metrics = ['mae', 'mape']) # mean absolute [percentage] error return keras.estimator.model_to_estimator(model, model_dir=output_dir) # Create the inference model def simple_rnn(features, labels, mode): # 0. Reformat input shape to become a sequence x = tf.split(features[TIMESERIES_COL], N_INPUTS, 1) # 1. Configure the RNN
tensorflow.keras.models.Sequential
8,014
import tensorflow as tf 'triplet_loss/Anchor/%s/Distance/Mean' % tag: tf.math.reduce_mean(negative_distances), 'triplet_loss/%s/Loss/All' % tag: loss, 'triplet_loss/%s/Loss/Active' % tag: active_loss, 'triplet_loss/%s/ActiveTripletNum' % tag: num_active_triplets, 'triplet_loss/%s/ActiveTripletRatio' % tag: active_triplet_ratio, # Summaries related to triplet mining. 'triplet_mining/Anchor/%s/Distance/Mean' % tag: tf.math.reduce_mean(negative_mining_distances), 'triplet_mining/%s/Loss/All' % tag: mining_loss, 'triplet_mining/%s/Loss/Active' % tag: active_mining_loss, 'triplet_mining/%s/ActiveTripletNum' % tag: num_active_mining_triplets, 'triplet_mining/%s/ActiveTripletRatio' % tag: active_mining_triplet_ratio, } if summarize_percentiles: summaries.update({ 'triplet_loss/Anchor/%s/Distance/Median' % tag:
tensorflow.math.reduce_mean
8,015
import tensorflow as tf sess.run(tf.global_variables_initializer()) tf.train.start_queue_runners(sess) sess.run(train_op) def testMulticlass(self): FLAGS.num_classes = 10 graphs.VatxtModel().classifier_graph() def testATMethods(self): at_methods = [None, 'rp', 'at', 'vat', 'atvat'] for method in at_methods: FLAGS.adv_training_method = method with tf.Graph().as_default(): graphs.VatxtModel().classifier_graph() # Ensure variables have been reused # Embedding + LSTM layers + hidden layers + logits layer expected_num_vars = 1 + 2 * FLAGS.rnn_num_layers + 2 * ( FLAGS.cl_num_layers) + 2 self.assertEqual(len(tf.trainable_variables()), expected_num_vars) def testSyncReplicas(self): FLAGS.sync_replicas = True graphs.VatxtModel().language_model_training()
tensorflow.Graph
8,016
import tensorflow as tf else: self.inputs = prev_layer.outputs # The name of placeholder for keep_prob is the same with the name # of the Layer. if is_fix: self.outputs = tf.nn.dropout(self.inputs, keep, seed=seed, name=name) else: LayersConfig.set_keep[name] = tf.placeholder(tf.float32) self.outputs = tf.nn.dropout(self.inputs, LayersConfig.set_keep[name], seed=seed, name=name) # 1.2 # self.all_layers = list(layer.all_layers)
tensorflow.nn.dropout
8,017
import tensorflow as tf # Add entropy coefficient optimization operation if needed if ent_coef_loss is not None: with tf.control_dependencies([train_values_op]): ent_coef_op = entropy_optimizer.minimize(ent_coef_loss, var_list=self.log_ent_coef) self.infos_names += ['ent_coef_loss', 'ent_coef'] self.step_ops += [ent_coef_op, ent_coef_loss, self.ent_coef] # Monitor losses and entropy in tensorboard tf.summary.scalar('policy_loss', policy_loss) tf.summary.scalar('qf1_loss', qf1_loss) tf.summary.scalar('qf2_loss', qf2_loss) tf.summary.scalar('value_loss', value_loss) tf.summary.scalar("Imitation_loss",self.actor_loss_di) tf.summary.scalar('entropy', self.entropy) tf.summary.scalar('importance weight',tf.reduce_mean(self.weight_ph)) if ent_coef_loss is not None: tf.summary.scalar('ent_coef_loss', ent_coef_loss)
tensorflow.summary.scalar
8,018
import tensorflow as tf with self.graph.as_default(): with tf.device('/cpu:0'): embedding = tf.get_variable( 'embedding', [vocab_size, hidden_size], dtype=tf.float32)
tensorflow.get_variable
8,019
import tensorflow as tf self.D_B_loss = (self.D_B_loss_real + self.D_B_loss_fake) / 2.0 self.D_A_loss_real = binary_cross_entropy_loss(tf.ones_like(self.D_A_real),self.D_A_real) self.D_A_loss_fake = binary_cross_entropy_loss(tf.zeros_like(self.D_A_fake),self.D_A_fake) self.D_A_loss = (self.D_A_loss_real + self.D_A_loss_fake) / 2.0 self.discriminator_loss = self.D_B_loss + self.D_A_loss self.loss_GABA_sum = tf.summary.scalar("g_loss_a2b", self.loss_GABA) self.loss_GBAB_sum = tf.summary.scalar("g_loss_b2a", self.loss_GBAB) self.g_total_loss_sum = tf.summary.scalar("g_loss", self.generator_loss) self.g_sum = tf.summary.merge([self.loss_GABA_sum,self.loss_GBAB_sum,self.g_total_loss_sum]) self.loss_db_sum = tf.summary.scalar("db_loss", self.D_B_loss) self.loss_da_sum = tf.summary.scalar("da_loss", self.D_A_loss) self.loss_d_sum = tf.summary.scalar("d_loss",self.discriminator_loss) self.db_loss_real_sum = tf.summary.scalar("db_loss_real", self.D_B_loss_real) self.db_loss_fake_sum = tf.summary.scalar("db_loss_fake", self.D_B_loss_fake) self.da_loss_real_sum = tf.summary.scalar("da_loss_real", self.D_A_loss_real) self.da_loss_fake_sum = tf.summary.scalar("da_loss_fake", self.D_A_loss_fake) self.d_sum = tf.summary.merge( [self.loss_da_sum, self.da_loss_real_sum, self.da_loss_fake_sum, self.loss_db_sum, self.db_loss_real_sum, self.db_loss_fake_sum, self.loss_d_sum] )
tensorflow.summary.scalar
8,020
from tensorflow.keras.layers import Dense, Conv2D, MaxPool2D, Flatten # FC layers to find next location loc_layer1 = Dense(units=loc_layer_size)(prev_loc) loc_layer2 = Dense(units=loc_layer_size)(loc_layer1)
tensorflow.keras.layers.Dense
8,021
import tensorflow as tf return (tf.data.TextLineDataset([filename]) .flat_map(_to_chars) .repeat() .batch(tf.to_int64(sequence_size)) .shuffle(1000) .batch(tf.to_int64(batch_size)))
tensorflow.to_int64
8,022
import tensorflow as tf heatmap_pred = tf.squeeze(heatmap_pred_list[i]) heatmap_true = tf.squeeze(heatmap_true_list[i]) loss = 0.5 * tf.losses.mean_squared_error(y_pred=heatmap_pred * true_weight[:, i], y_true=heatmap_true * true_weight[:, i])
tensorflow.losses.mean_squared_error
8,023
import tensorflow as tf 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.maximum
8,024
import tensorflow as tf if min_negative_keypoint_distance >= 0.0: anchor_match_negative_indicator_matrix = ( compute_negative_indicator_matrix( anchor_points=anchor_keypoints, match_points=match_keypoints, distance_fn=keypoint_distance_fn, min_negative_distance=min_negative_keypoint_distance, anchor_point_masks=anchor_keypoint_masks, match_point_masks=match_keypoint_masks)) else: num_anchors = tf.shape(anchor_keypoints)[0] anchor_match_negative_indicator_matrix = tf.math.logical_not( tf.eye(num_anchors, dtype=tf.bool)) anchor_positive_distances = embedding_sample_distance_fn( anchor_embeddings, positive_embeddings) if anchor_mining_embeddings is None and positive_mining_embeddings is None: anchor_positive_mining_distances = anchor_positive_distances else: anchor_positive_mining_distances = embedding_sample_distance_fn(
tensorflow.shape
8,025
import tensorflow as tf tf.app.flags.DEFINE_float( 'gpu_memory_fraction', 1., 'GPU memory fraction to use.') # scaffold related configuration tf.app.flags.DEFINE_string( 'data_dir', '../PASCAL/VOC_TF/VOC0712TF/', 'The directory where the dataset input data is stored.') tf.app.flags.DEFINE_string( 'dataset_name', 'pascalvoc_0712', 'The name of the dataset to load.') tf.app.flags.DEFINE_integer( 'num_classes', 21, 'Number of classes to use in the dataset.') tf.app.flags.DEFINE_string( 'dataset_split_name', 'train', 'The name of the train/test split.') tf.app.flags.DEFINE_string( 'model_dir', './logs_v3/', 'The directory where the model will be stored.') tf.app.flags.DEFINE_integer( 'log_every_n_steps', 10, 'The frequency with which logs are print.') tf.app.flags.DEFINE_integer( 'save_summary_steps', 500, 'The frequency with which summaries are saved, in seconds.') tf.app.flags.DEFINE_integer( 'save_checkpoints_secs', 7200, 'The frequency with which the model is saved, in seconds.')
tensorflow.app.flags.DEFINE_string
8,026
import tensorflow as tf TensorFlow's every time we want to use a std function that handles bounding boxes. Args: bboxes: A Tensor of shape (total_bboxes, 4) Returns: bboxes: A Tensor of shape (total_bboxes, 4) with the order swaped. """ with tf.name_scope('BoundingBoxTransform/change_order'): first_min, second_min, first_max, second_max = tf.unstack( bboxes, axis=1 ) bboxes = tf.stack( [second_min, first_min, second_max, first_max], axis=1 ) return bboxes if __name__ == '__main__': import numpy as np bboxes = tf.placeholder(tf.float32) bboxes_val = [[10, 10, 20, 22]] gt_boxes = tf.placeholder(tf.float32)
tensorflow.stack
8,027
import tensorflow as tf NUM_EVAL_EXAMPLES = 5000 def build_training_graph(x, y, ul_x, ul_u, lr, mom): global_step = tf.get_variable( name="global_step", shape=[], dtype=tf.float32, initializer=tf.constant_initializer(0.0), trainable=False, ) logit = vat.forward(x) nll_loss = L.ce_loss(logit, y) with tf.variable_scope(tf.get_variable_scope(), reuse=True): if FLAGS.method == 'vat': ul_logit = vat.forward(ul_x, is_training=True, update_batch_stats=False) vat_loss, ul_u_updated = vat.virtual_adversarial_loss(ul_x, ul_u, ul_logit) additional_loss = vat_loss
tensorflow.constant_initializer
8,028
from tensorflow.python.ops import array_ops target = array_ops.expand_dims(target, dim=[1]) loss_vec = nn.sigmoid_cross_entropy_with_logits(logits, math_ops.to_float(target)) return loss_vec def _softmax_cross_entropy_loss(logits, target): # sigmoid_cross_entropy_with_logits requires [batch_size, 1] target. # Check that we got int32/int64 for classification. if (not target.dtype.is_compatible_with(dtypes.int64) and not target.dtype.is_compatible_with(dtypes.int32)): raise ValueError("Target's dtype should be int32, int64 or compatible. " "Instead got %s." % target.dtype) # sparse_softmax_cross_entropy_with_logits requires [batch_size] target. if len(target.get_shape()) == 2: target = array_ops.squeeze(target, squeeze_dims=[1]) loss_vec = nn.sparse_softmax_cross_entropy_with_logits(logits, target) return loss_vec def _run_metrics(predictions, targets, metrics, weights): result = {} targets = math_ops.cast(targets, predictions.dtype) for name, metric in six.iteritems(metrics or {}): if "weights" in inspect.getargspec(metric)[0]: result[name] = metric(predictions, targets, weights=weights) else: result[name] = metric(predictions, targets) return result
tensorflow.python.ops.array_ops.squeeze
8,029
import tensorflow as tf return video_num_input_frames, video_num_target_frames @gin.configurable(module='trax.data', denylist=['dataset', 'training']) def bair_robot_pushing_preprocess(dataset, training): """Pre-processing function that concatenates input and target frames.""" del training def concat_and_add_mask(features, targets): """Concatenate input and output frames to form a language modeling setup.""" inp = features['inputs'] concat = tf.concat([inp, targets], axis=0) mask = tf.concat([tf.zeros_like(inp), tf.ones_like(targets)], axis=0) concat = tf.reshape(concat, (-1,)) mask = tf.reshape(mask, (-1,)) concat = tf.cast(concat, tf.int32) mask = tf.cast(mask, tf.float32) features['inputs'] = features['targets'] = concat features['mask'] = mask return features, concat dataset = dataset.map(concat_and_add_mask) return dataset def sentencepiece_tokenize(stream, spm_path=None, extra_ids=0): """Sentencepiece tokenization.""" spm_path = spm_path or t5_data().DEFAULT_SPM_PATH
tensorflow.reshape
8,030
import tensorflow as tf def _bottleneck_residual(x, ksize_list, strides, padding, is_training, data_format='NHWC', no_activation=False): with tf.variable_scope('sub1'): if not no_activation: x = _batch_norm('bn1', x, is_training, data_format) x = _relu('relu1', x) STRIDES_ERR_MSG = 'Strides height and width are not the same.' if data_format == 'NHWC':
tensorflow.variable_scope
8,031
from tensorflow.contrib.layers.python.layers.layers import _build_variable_getter, _add_variable_to_collections conv_dims: Optional convolution dimensionality, when set it would use the corresponding convolution (e.g. 2 for Conv 2D, 3 for Conv 3D, ..). When leaved to None it would select the convolution dimensionality based on the input rank (i.e. Conv ND, with N = input_rank - 2). Returns: A tensor representing the output of the operation. Raises: ValueError: If `data_format` is invalid. ValueError: Both 'rate' and `stride` are not uniformly 1. """ if data_format not in [None, 'NWC', 'NCW', 'NHWC', 'NCHW', 'NDHWC', 'NCDHW']: raise ValueError('Invalid data_format: %r' % (data_format,)) layer_variable_getter = _build_variable_getter({'bias': 'biases', 'kernel': 'weights'}) with variable_scope.variable_scope(scope, 'Conv', [inputs], reuse=reuse, custom_getter=layer_variable_getter) as sc: inputs = ops.convert_to_tensor(inputs) input_rank = inputs.get_shape().ndims if conv_dims is not None and conv_dims + 2 != input_rank: raise ValueError('Convolution expects input with rank %d, got %d' % (conv_dims + 2, input_rank)) if input_rank == 3: layer_class = convolutional_layers.Convolution1D elif input_rank == 4: layer_class = MyConv2D elif input_rank == 5:
tensorflow.contrib.layers.python.layers.layers._build_variable_getter
8,032
import tensorflow as tf w_h = tf.get_variable('w_h', [self.D, self.H], initializer=self.weight_initializer) b_h = tf.get_variable('b_h', [self.H], initializer=self.const_initializer) h = tf.nn.tanh(tf.matmul(features_mean, w_h) + b_h) w_c = tf.get_variable('w_c', [self.D, self.H], initializer=self.weight_initializer)
tensorflow.matmul
8,033
import tensorflow as tf """ with tf.name_scope(name): learning_rate = tf.cast(learning_rate, dtype=tf.float32) global_step = tf.cast(global_step, dtype=tf.float32) step_size = tf.cast(step_size, dtype=tf.float32) max_lr = tf.cast(max_lr, dtype=tf.float32) if mode == 'tri': periodic_comp = tf.mod((global_step + step_size / 4) / step_size, 1) first_factor = tf.abs(periodic_comp - 0.5)
tensorflow.cast
8,034
import tensorflow as tf cell = cell_fn(rnn_size) if mode == 'train' and rnn_keep_prob < 1.0: cell = tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob=rnn_keep_prob) if rnn_nlayers > 1:
tensorflow.nn.rnn_cell.DropoutWrapper
8,035
from tensorflow.python.ops import gen_nn_ops type `tf.float32`. ksize: A list of ints that has length >= 4. The size of the window for each dimension of the input tensor. strides: A list of ints that has length >= 4. The stride of the sliding window for each dimension of the input tensor. padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. data_format: A string. 'NHWC' and 'NCHW" are supported. name: Optional name for the operation. Returns: A `Tensor` with type `tf.float32`. The max pooled output tensor. """ with ops.op_scope([value], name, "MaxPool") as name: value = ops.convert_to_tensor(value, name="input") return gen_nn_ops._max_pool(value, ksize=ksize, strides=strides, padding=padding, data_format=data_format, name=name) ops.RegisterShape("Relu")(common_shapes.unchanged_shape) ops.RegisterShape("Relu6")(common_shapes.unchanged_shape) ops.RegisterShape("Elu")(common_shapes.unchanged_shape) ops.RegisterShape("Softplus")(common_shapes.unchanged_shape) ops.RegisterShape("Softsign")(common_shapes.unchanged_shape) @ops.RegisterShape("ReluGrad")
tensorflow.python.ops.gen_nn_ops._max_pool
8,036
import tensorflow as tf with tf.variable_scope("network_parameters"): with tf.variable_scope("policy"): x = flat_observations for size in config.policy_layers: x = tf.layers.dense(x, size, activation=tf.nn.relu) mean = tf.layers.dense( x, action_space.shape[0], activation=tf.tanh, kernel_initializer=mean_weights_initializer) logstd = tf.get_variable( "logstd", mean.shape[2:], tf.float32, logstd_initializer) logstd = tf.tile( logstd[None, None], [tf.shape(mean)[0], tf.shape(mean)[1]] + [1] * (mean.shape.ndims - 2)) with tf.variable_scope("value"): x = flat_observations for size in config.value_layers: x = tf.layers.dense(x, size, activation=tf.nn.relu) value = tf.layers.dense(x, 1)[..., 0] mean = tf.check_numerics(mean, "mean") logstd = tf.check_numerics(logstd, "logstd") value = tf.check_numerics(value, "value") policy = tfp.distributions.MultivariateNormalDiag(mean, tf.exp(logstd))
tensorflow.shape
8,037
import tensorflow as tf tf.summary.scalar('Loss/Entropy', loss_entropy) tf.summary.scalar('Loss/Total', loss) tf.summary.scalar('Var/Epsilon', epsilon_decay) tf.summary.scalar('Var/Policy Mode', tf.reduce_mean(pi.mode())) tf.summary.scalar('Var/Policy Sigma', tf.reduce_mean(pi.stddev())) tf.summary.scalar('Var/Value', tf.reduce_mean(self.vf)) self.summarise = tf.summary.merge(tf.get_collection(tf.GraphKeys.SUMMARIES)) # 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) # sigma = tf.get_variable(name='pi_sigma', shape=self.a_dim, initializer=tf.constant_initializer(0.5)) sigma = tf.clip_by_value(sigma, 0.0, 1.0) norm_dist = tf.distributions.Normal(loc=mu * self.a_bound, scale=sigma) params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=name) return norm_dist, params, state_init_a, state_final_a
tensorflow.nn.rnn_cell.LSTMCell
8,038
import tensorflow as tf # Load IRK weights tmp = np.float32(np.loadtxt('../../Utilities/IRK_weights/Butcher_IRK%d.txt' % (q), ndmin = 2)) weights = np.reshape(tmp[0:q**2+q], (q+1,q)) self.IRK_alpha = weights[0:-1,:] self.IRK_beta = weights[-1:,:] self.IRK_times = tmp[q**2+q:] # tf placeholders and graph self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True)) self.x0_tf = tf.placeholder(tf.float32, shape=(None, self.x0.shape[1])) self.x1_tf = tf.placeholder(tf.float32, shape=(None, self.x1.shape[1])) self.u0_tf = tf.placeholder(tf.float32, shape=(None, self.u0.shape[1])) self.u1_tf = tf.placeholder(tf.float32, shape=(None, self.u1.shape[1])) self.dummy_x0_tf = tf.placeholder(tf.float32, shape=(None, self.q)) # dummy variable for fwd_gradients self.dummy_x1_tf = tf.placeholder(tf.float32, shape=(None, self.q)) # dummy variable for fwd_gradients self.U0_pred = self.net_U0(self.x0_tf) # N0 x q self.U1_pred = self.net_U1(self.x1_tf) # N1 x q self.loss = tf.reduce_sum(tf.square(self.u0_tf - self.U0_pred)) + \ tf.reduce_sum(tf.square(self.u1_tf - self.U1_pred)) self.optimizer = tf.contrib.opt.ScipyOptimizerInterface(self.loss,
tensorflow.placeholder
8,039
import tensorflow as tf outputs = [inputs] with tf.variable_scope(self.scope): for layer in range(self.num_layers): gru_fw, gru_bw = self.grus[layer] init_fw, init_bw = self.inits[layer] mask_fw, mask_bw = self.dropout_mask[layer] with tf.variable_scope("fw_{}".format(layer)): out_fw, _ = tf.nn.dynamic_rnn( gru_fw, outputs[-1] * mask_fw, seq_len, initial_state=init_fw, dtype=tf.float32) with tf.variable_scope("bw_{}".format(layer)): inputs_bw = tf.reverse_sequence( outputs[-1] * mask_bw, seq_lengths=seq_len, seq_dim=1, batch_dim=0) out_bw, _ = tf.nn.dynamic_rnn( gru_bw, inputs_bw, seq_len, initial_state=init_bw, dtype=tf.float32)
tensorflow.nn.dynamic_rnn
8,040
import tensorflow as tf else: direct_mask = tf.less(head_idxs, dep_idxs) # [bs, slh, sld] # [bs, slh, slh] rep_mask_tile = tf.logical_and(tf.expand_dims(rep_dep_mask, 1), tf.expand_dims(rep_head_mask, 2)) attn_mask = tf.logical_and(direct_mask, rep_mask_tile) # [bs, slh, sld] # tensor tile rep_map_tile = tf.tile(tf.expand_dims(rep_dep_tensor, 1), [1, sl_head, 1, 1]) # bs,slh,sld,vec with tf.variable_scope('attention'): # bs,sl,sl,vec f_bias = tf.get_variable('f_bias', [ivec], tf.float32, tf.constant_initializer(0.)) dependent = linear(rep_dep_tensor_dp, ivec, False, scope='linear_dependent') # bs,sld,vec dependent_etd = tf.expand_dims(dependent, 1) # bs,1,sld,vec head = linear(rep_head_tensor_dp, ivec, False, scope='linear_head') # bs,slh,vec head_etd = tf.expand_dims(head, 2) # bs,slh,1,vec logits = scaled_tanh(dependent_etd + head_etd + f_bias, 5.0) # bs,slh,sld,vec logits_masked = exp_mask_for_high_rank(logits, attn_mask) # bs,slh,sld,vec attn_score = tf.nn.softmax(logits_masked, 2) # bs,slh,sld,vec attn_score = mask_for_high_rank(attn_score, attn_mask) attn_result = tf.reduce_sum(attn_score * rep_map_tile, 2) # bs,slh,vec -> head_org_idx return attn_result
tensorflow.expand_dims
8,041
import tensorflow as tf return tf.reshape(images,[batch_size,4096]),tf.reshape(labels,[batch_size]) def get_test_batch(image,label,batch_size): images,labels=tf.train.batch([image,label],batch_size=batch_size) return tf.reshape(images,[batch_size,4096]),tf.reshape(labels,[batch_size]) def get_valid_batch(image,label,batch_size): images,labels=tf.train.batch([image,label],batch_size=batch_size) return tf.reshape(images,[batch_size,4096]),tf.reshape(labels,[batch_size]) class trainwork(object): def __init__(self): with tf.variable_scope('scop'): self.w1=tf.get_variable('w1', [4096,1024],initializer=tf.contrib.layers.xavier_initializer_conv2d()) self.w2=tf.get_variable('w2', [1024,classnum],initializer=tf.contrib.layers.xavier_initializer_conv2d()) self.b1 = tf.get_variable('b1', [1024],initializer=tf.constant_initializer(0.0)) self.b2 = tf.get_variable('b2', [classnum],initializer=tf.constant_initializer(0.0)) def inference(self,images): images=tf.cast(images,tf.float32)/255.0 l1 = tf.matmul(images, self.w1)+self.b1 l1=tf.nn.relu(l1) out = tf.matmul(l1, self.w2)+self.b2 return out 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) out = tf.matmul(l1, self.w2)+self.b2
tensorflow.constant_initializer
8,042
import tensorflow as tf grad_and_var = (grad, v) average_grads.append(grad_and_var) return average_grads def train(): """Train CIFAR-10 for a number of steps.""" with tf.Graph().as_default(), tf.device('/cpu:0'): # Create a variable to count the number of train() calls. This equals the # number of batches processed * FLAGS.num_gpus. global_step = tf.get_variable( 'global_step', [], initializer=tf.constant_initializer(0), trainable=False)
tensorflow.device
8,043
import tensorflow as tf with tf.variable_scope(name) as scope: kernel = self.variable('weights', [kernel_size, kernel_size, output_channels, input_channels], initializer, regularizer=tf.contrib.layers.l2_regularizer(0.0005)) deconv = tf.nn.conv2d_transpose(bottom, kernel, output_shape, [1, stride, stride, 1], padding='SAME') biases = self.variable('biases', [output_channels], tf.constant_initializer(0.0)) deconv_layer = tf.nn.bias_add(deconv, biases) if bn:
tensorflow.constant_initializer
8,044
import tensorflow as tf self.epsilon = epsilon self.data_format = data_format self.name = name def __call__(self,input_var,**kwargs) : mean, var = tf.nn.moments(input_var, self.axis, keep_dims=True) ret = (input_var - mean) / tf.sqrt(var+self.epsilon) if self.gamma is None : return ret
tensorflow.nn.moments
8,045
from tensorflow.python.framework import ops as _ops else: with _ops.device(self._send_device): return _XlaSend( tensor, tensor_name=self._name, name="Send_" + self._name) def Recv(self): """Receives a tensor from the channel.""" if self._send_tpu_core == -1: return _Recv(self._dtype, self._name, self._send_device, self._recv_device) else: with _ops.device(self._recv_device): return _XlaRecv( self._dtype, tensor_name=self._name, shape=self._shape, name="Recv_" + self._name)
tensorflow.python.framework.ops.device
8,046
import tensorflow as tf tf.summary.scalar('Loss/Policy', loss_pg) tf.summary.scalar('Loss/Value', loss_vf) tf.summary.scalar('Loss/Entropy', - 0.01 * tf.reduce_mean(pi.entropy())) tf.summary.scalar('Var/Policy Mode', tf.reduce_mean(pi.mode())) tf.summary.scalar('Var/Policy Sigma', tf.reduce_mean(pi.stddev())) tf.summary.scalar('Var/Value', tf.reduce_mean(self.vf)) self.summarise = tf.summary.merge(tf.get_collection(tf.GraphKeys.SUMMARIES)) # AC net def build_anet(self, state_in, name, reuse=False): reg = tf.contrib.layers.l2_regularizer(1e-3) 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) mu = tf.layers.dense(layer_a2, self.a_dim, tf.nn.tanh, kernel_regularizer=reg) # sigma = tf.layers.dense(layer_a2, self.a_dim, tf.nn.softplus, kernel_regularizer=reg) sigma = tf.get_variable(name='pi_sigma', shape=self.a_dim, initializer=tf.constant_initializer(0.5)) sigma = tf.clip_by_value(sigma, 0.0, 1.0) norm_dist = tf.distributions.Normal(loc=mu * self.a_bound, scale=sigma) params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=name) return norm_dist, params def build_cnet(self, state_in, name, reuse=False): reg = tf.contrib.layers.l2_regularizer(1e-3) with tf.variable_scope(name, reuse=reuse): layer_c1 = tf.layers.dense(state_in, 512, tf.nn.relu, kernel_regularizer=reg) layer_c2 = tf.layers.dense(layer_c1, 256, tf.nn.relu, kernel_regularizer=reg) vf = tf.layers.dense(layer_c2, 1, kernel_regularizer=reg)
tensorflow.layers.dense
8,047
import tensorflow as tf Returns: Computed features after split separable conv2d. """ outputs = slim.separable_conv2d( inputs, None, 3, depth_multiplier=1, rate=rate, weights_initializer=tf.truncated_normal_initializer( stddev=depthwise_weights_initializer_stddev), weights_regularizer=None, scope=scope + '_depthwise') return slim.conv2d( outputs, filters, 1, weights_initializer=tf.truncated_normal_initializer(
tensorflow.truncated_normal_initializer
8,048
import tensorflow as tf class BenchmarkSparseTensorsMapVsSerialization(tf.test.Benchmark): def benchmarkVeryLarge2DFloatSparseTensor(self): np.random.seed(127) num_elements = 10000 batch_size = 64 indices_batch = np.random.randint( batch_size, size=num_elements, dtype=np.int64) indices_value = np.arange(num_elements, dtype=np.int64) indices = np.asarray( sorted(zip(indices_batch, indices_value)), dtype=np.int64) values = ["feature_value_for_embedding_lookup"] * num_elements shape = np.asarray([batch_size, num_elements], dtype=np.int64) with tf.Session() as sess: with tf.device("/cpu:0"): indices = tf.Variable(indices) values = tf.Variable(values) shape = tf.Variable(shape) st = tf.SparseTensor(indices, values, shape) st_handles = add_many_sparse_to_tensors_map(st) st_roundtrip = take_many_sparse_from_tensors_map( sparse_map_op=st_handles.op, sparse_handles=st_handles) st_roundtrip_op = st_roundtrip.values.op st_serialized = tf.serialize_many_sparse(st) st_deserialized = tf.deserialize_many_sparse(
tensorflow.Session
8,049
import tensorflow as tf pos = tf.reshape(pos, [-1, 1]) pos = tf.minimum(pos, encoder_input_length - 1) idx = tf.tile(tf.to_float(tf.range(attn_length)), tf.stack([batch_size])) idx = tf.reshape(idx, [-1, attn_length]) low = pos - encoder.attn_window_size high = pos + encoder.attn_window_size mlow = tf.to_float(idx < low) mhigh = tf.to_float(idx > high) m = mlow + mhigh m += tf.to_float(idx >= encoder_input_length) mask = tf.to_float(tf.equal(m, 0.0)) e = compute_energy(hidden_states, state, encoder, input_length=encoder_input_length, **kwargs) weights = softmax(e, mask=mask) if encoder.attn_window_size > 0:
tensorflow.to_float
8,050
import tensorflow as tf 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 # Mask # key_masks = tf.sequence_mask(facts_length, tf.shape(facts)[1]) # [B, T] key_masks = tf.expand_dims(mask, 1) # [B, 1, T] paddings = tf.ones_like(scores) * (-2 ** 32 + 1)
tensorflow.layers.dense
8,051
import tensorflow as tf projection = linear( input=activation, input_size=dialogue_state_size, output_size=action_templates_vocabulary_length, name='linear_projection_3_predictions_action' ) self.predictions_action = tf.nn.softmax(projection, name="softmax_output_prediction_action") # argument prediction # first encode decoded action template and teh true action template choice = tf.floor(tf.random_uniform([1], self.use_inputs_prob, 1 + self.use_inputs_prob, tf.float32)) prediction_action_argmax = tf.stop_gradient(tf.argmax(self.predictions_action, 1)) predicted_action_templates_embedding = embedding( input=prediction_action_argmax, length=action_templates_vocabulary_length, size=action_templates_embedding_size, name='action_templates_embedding' ) true_action_template_embedding = tf.gather(predicted_action_templates_embedding.embedding_table, actions_template) predicted_action_templates_embedding = tf.stop_gradient(predicted_action_templates_embedding) action_templates_embedding = choice * true_action_template_embedding + (1.0 - choice) * predicted_action_templates_embedding dialogue_state_action_template = tf.concat(
tensorflow.argmax
8,052
import tensorflow as tf if encoder.binary: raise NotImplementedError stride = encoder.maxout_stride k = tf.to_int32(tf.ceil(time_steps / stride) * stride) - time_steps # TODO: simpler pad = tf.zeros([batch_size, k, tf.shape(encoder_inputs_)[2]]) encoder_inputs_ = tf.concat([encoder_inputs_, pad], axis=1) encoder_inputs_ = tf.nn.pool(encoder_inputs_, window_shape=[stride], pooling_type='MAX', padding='VALID', strides=[stride]) encoder_input_length_ = tf.to_int32(tf.ceil(encoder_input_length_ / stride)) if encoder.highway_layers:
tensorflow.concat
8,053
import tensorflow as tf W_head = tf.get_variable("embed_W_head", [num_quantized_chars, embedding_size], initializer=initializer) embedded_head = tf.nn.embedding_lookup(W_head, self.input_head) embedded_head_expanded = tf.expand_dims(embedded_head, -1) cnn_inputs = tf.concat( [embedded_text_expand, embedded_tags_expanded, embedded_deps_expanded, embedded_head_expanded], -1) print("-" * 20)
tensorflow.concat
8,054
from tensorflow.python.ops import math_ops predictions, labels = tensor_util.remove_squeezable_dimensions( predictions, labels) predictions.get_shape().assert_is_compatible_with(labels.get_shape()) if labels.dtype != predictions.dtype: predictions = math_ops.cast(predictions, labels.dtype) is_correct = math_ops.to_float(math_ops.equal(predictions, labels)) return streaming_mean(is_correct, weights, metrics_collections, updates_collections, name or 'accuracy')
tensorflow.python.ops.math_ops.equal
8,055
from tensorflow.python.ops import math_ops raise ValueError( "logits to probabilities is not supported for _BinarySvmTargetColumn") logits = array_ops.concat([array_ops.zeros_like(logits), logits], 1) return math_ops.argmax(logits, 1) # TODO(zakaria): use contrib losses. def _mean_squared_loss(logits, target): # To prevent broadcasting inside "-". if len(target.get_shape()) == 1: target = array_ops.expand_dims(target, dim=[1]) logits.get_shape().assert_is_compatible_with(target.get_shape()) return math_ops.square(logits - math_ops.to_float(target)) def _log_loss_with_two_classes(logits, target): # sigmoid_cross_entropy_with_logits requires [batch_size, 1] target. if len(target.get_shape()) == 1: target = array_ops.expand_dims(target, dim=[1]) loss_vec = nn.sigmoid_cross_entropy_with_logits( labels=math_ops.to_float(target), logits=logits) return loss_vec def _softmax_cross_entropy_loss(logits, target): # Check that we got integer for classification.
tensorflow.python.ops.math_ops.to_float
8,056
import tensorflow as tf hidden2 = tf.nn.relu(tf.matmul(hidden1, weights) + biases) # Linear with tf.name_scope("softmax_linear"): weights = tf.Variable( tf.truncated_normal([32, 10], stddev=1.0 / math.sqrt(float(32))), name="weights") biases = tf.Variable(tf.zeros([10]), name="biases") logits = tf.matmul(hidden2, weights) + biases tf.add_to_collection("logits", logits) # Runs to logit. tf.initialize_all_variables().run() sess.run(logits) # Creates a saver. saver0 = tf.train.Saver() saver0.save(sess, saver0_ckpt) # Generates MetaGraphDef. saver0.export_meta_graph(filename)
tensorflow.add_to_collection
8,057
import tensorflow as tf self.initialize_tf_vars() logger.log(self.sess.graph) self.has_setup = True self.setup_args = SimpleNamespace( sampler_cls=sampler_cls, sampler_args=sampler_args) def initialize_tf_vars(self): """Initialize all uninitialized variables in session.""" with tf.name_scope('initialize_tf_vars'): uninited_set = [ e.decode() for e in self.sess.run(tf.report_uninitialized_variables()) ] self.sess.run( tf.variables_initializer([ v for v in tf.global_variables() if v.name.split(':')[0] in uninited_set ])) def _start_worker(self): """Start Plotter and Sampler workers.""" self.sampler.start_worker() if self.plot: from garage.tf.plotter import Plotter
tensorflow.report_uninitialized_variables
8,058
import tensorflow as tf def __init__(self,name,dims,axis=1,epsilon=1e-3,momentum=0.999,center=True,scale=True) : self.momentum = momentum self.epsilon = epsilon self.axis = axis self.center=center self.scale=scale with tf.variable_scope(name) as scope: with tf.variable_scope('bn') : self.gamma= tf.get_variable('gamma',[dims], initializer=tf.constant_initializer(1.0)) self.beta = tf.get_variable('beta',[dims], initializer=tf.constant_initializer(0.0)) self.moving_mean = tf.get_variable('moving_mean',[dims], initializer=tf.constant_initializer(0.0), trainable=False) self.moving_variance = tf.get_variable('moving_variance',[dims], initializer=tf.constant_initializer(1.0), trainable=False) self.scope = scope
tensorflow.variable_scope
8,059
import tensorflow as tf initializer=tf.contrib.layers.xavier_initializer(), l2_strength=0.0, dilation=1.0, bias=-1): with tf.variable_scope(name): stride = [1, stride[0], stride[1], 1] kernel_shape = [kernel_size[0], kernel_size[1], x.shape[-1], num_filters] w = variable_with_weight_decay(kernel_shape, initializer, l2_strength) variable_summaries(w) if dilation > 1: conv = tf.nn.atrous_conv2d(x, w, dilation, padding) else: if type(padding)==type(''): conv = tf.nn.conv2d(x, w, stride, padding) else: conv = tf.pad(x, padding, "CONSTANT") conv = tf.nn.conv2d(conv, w, stride, padding='VALID') if bias != -1: bias = tf.get_variable('biases', [num_filters], initializer=tf.constant_initializer(bias))
tensorflow.nn.atrous_conv2d
8,060
import tensorflow as tf if average_across_timesteps: total_size = tf.reduce_sum(weights, axis=1) total_size += 1e-12 # just to avoid division by 0 for all-0 weights log_perp /= total_size cost = tf.reduce_sum(log_perp) if average_across_batch: return cost / tf.to_float(batch_size) else: return cost def reinforce_baseline(decoder_states, reward): """ Center the reward by computing a baseline reward over decoder states.
tensorflow.to_float
8,061
import tensorflow as tf # 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",
tensorflow.stop_gradient
8,062
import tensorflow as tf def _init(): v_norm = tf.nn.l2_normalize(self.v,axis=0) t = tf.matmul(input_var,v_norm) mu,var = tf.nn.moments(t,axes=[0]) std = tf.sqrt(var+self.epsilon) return [tf.assign(self.g,1/std),tf.assign(self.b,-1.*mu/std)] require_init = tf.reduce_any(tf.is_nan(self.g)) init_ops = tf.cond(require_init,_init,lambda : [self.g,self.b])
tensorflow.assign
8,063
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)) act = U.function(inputs=[observations_ph, stochastic_ph, update_eps_ph], outputs=[output_actions, q_values, s_value, a_values, update_eps_expr], givens={update_eps_ph: test_epsilon, stochastic_ph: False}, updates=[update_eps_expr])
tensorflow.cond
8,064
import tensorflow as tf self.config.data["num_channels"]), name="X") # ex. (50000, 32, 32, 3) self.y = tf.compat.v1.placeholder(tf.int32, shape = (None, self.config.data["num_categories"]), name="y") # ex. (50000, 10) self.train = tf.compat.v1.placeholder(tf.bool) # The CNN architecture = conv/poo layers + flatten layer + connected layers with tf.name_scope("cnn"): # a. Create convolution/pooling layers = conv + drop + pool + conv + drop + pool + conv + pool + conv + drop self.conv1 = tf.layers.conv2d(self.X, self.config.cifar10_cnn["num_filters"],
tensorflow.name_scope
8,065
import tensorflow as tf Actor-Critics """ def mlp_actor_critic(x, a, hidden_sizes=(400,300), activation=tf.nn.relu, output_activation=tf.tanh, action_space=None, dropout_rate=0, nn_type='mlp_variational'): act_dim = a.shape.as_list()[-1] act_limit = action_space.high[0] if nn_type == 'mlp': with tf.variable_scope('pi'): pi = act_limit * mlp(x, list(hidden_sizes) + [act_dim], activation, output_activation) with tf.variable_scope('q1'): q1 = tf.squeeze(mlp(tf.concat([x, a], axis=-1), list(hidden_sizes) + [1], activation, None), axis=1) with tf.variable_scope('q2'): q2 = tf.squeeze(mlp(tf.concat([x, a], axis=-1), list(hidden_sizes) + [1], activation, None), axis=1) with tf.variable_scope('q1', reuse=True): q1_pi = tf.squeeze(mlp(tf.concat([x, pi], axis=-1), list(hidden_sizes) + [1], activation, None), axis=1) elif nn_type == 'mlp_dropout': with tf.variable_scope('pi'): pi = act_limit * mlp_dropout(x, list(hidden_sizes)+[act_dim], activation, output_activation) with tf.variable_scope('q'):
tensorflow.variable_scope
8,066
import tensorflow as tf if FLAGS.mode == 'attack': if is_carliniL2 == True: apply_attack_carlini(hps) else: apply_attack_loop(hps) elif FLAGS.mode == 'tSNE_logits': if is_carliniL2 == True: tSNE_visual_carliniLi(hps,num_batch) else: tSNE_visual(hps,num_batch) if __name__ == '__main__': tf.logging.set_verbosity(tf.logging.INFO) tf.app.run()
tensorflow.logging.set_verbosity
8,067
import tensorflow as tf drop_remainder=eval_drop_remainder) result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps) output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt") with tf.gfile.GFile(output_eval_file, "w") as writer: tf.logging.info("***** Eval results *****") for key in sorted(result.keys()): tf.logging.info(" %s = %s", key, str(result[key])) writer.write("%s = %s\n" % (key, str(result[key]))) if FLAGS.do_predict:
tensorflow.logging.info
8,068
import tensorflow as tf y, = tf.py_func(bad1, [], [tf.string]) z, = tf.py_func(bad2, [], [tf.float64]) with self.assertRaisesRegexp(errors.UnimplementedError, "Unsupported numpy type"): y.eval() with self.assertRaisesRegexp(errors.UnimplementedError, "Unsupported object type"): z.eval() if __name__ == "__main__": tf.test.main()
tensorflow.test.main
8,069
import tensorflow as tf seq_shape = get_shape_list(mask_sequence, expected_rank=2) seq_len = seq_shape[1] ones = tf.ones((1, seq_len, seq_len)) a_mask = tf.matrix_band_part(ones, -1, 0) s_ex12 = tf.expand_dims(tf.expand_dims(mask_sequence, 1), 2) s_ex13 = tf.expand_dims(tf.expand_dims(mask_sequence, 1), 3) a_mask = (1 - s_ex13) * (1 - s_ex12) + s_ex13 * a_mask # generate mask of batch x seq_len x seq_len a_mask = tf.reshape(a_mask, (-1, seq_len, seq_len)) out_mask = attention_mask * a_mask else: ones = tf.ones_like(attention_mask[:1]) mask = (tf.matrix_band_part(ones, -1, 0)) out_mask = attention_mask * mask else: out_mask = attention_mask
tensorflow.reshape
8,070
import tensorflow as tf types: A list of `Tensor` of `int32`, with shapes `[num_nodes * count1]`, `[num_nodes * count1 * count2]` ... """ neighbors_list = [tf.reshape(nodes, [-1])] weights_list = [] type_list = [] for hop_edge_types, count in zip(edge_types, counts): neighbors, weights, types = sample_neighbor( neighbors_list[-1], hop_edge_types, count, default_node=default_node) neighbors_list.append(tf.reshape(neighbors, [-1])) weights_list.append(tf.reshape(weights, [-1])) type_list.append(tf.reshape(types, [-1])) return neighbors_list, weights_list, type_list def get_multi_hop_neighbor(nodes, edge_types): """ Get multi-hop neighbors with adjacent matrix.
tensorflow.reshape
8,071
import tensorflow as tf i_z1_y1_x0 = tf.gather(im_flat, idx_z1_y1_x0) i_z1_y1_x1 = tf.gather(im_flat, idx_z1_y1_x1) # Finally calculate interpolated values. x0_f = tf.to_float(x0) x1_f = tf.to_float(x1) y0_f = tf.to_float(y0) y1_f = tf.to_float(y1) z0_f = tf.to_float(z0) z1_f = tf.to_float(z1) # Check the out-of-boundary case. x0_valid = tf.to_float( tf.less_equal(x0, max_x) & tf.greater_equal(x0, 0)) x1_valid = tf.to_float( tf.less_equal(x1, max_x) & tf.greater_equal(x1, 0)) y0_valid = tf.to_float( tf.less_equal(y0, max_y) & tf.greater_equal(y0, 0)) y1_valid = tf.to_float( tf.less_equal(y1, max_y) & tf.greater_equal(y1, 0)) z0_valid = tf.to_float( tf.less_equal(z0, max_z) & tf.greater_equal(z0, 0)) z1_valid = tf.to_float( tf.less_equal(z1, max_z) & tf.greater_equal(z1, 0))
tensorflow.greater_equal
8,072
import tensorflow as tf # Target for value fn regression # We update the vf towards the min of two Q-functions in order to # reduce overestimation bias from function approximation error. v_backup = tf.stop_gradient(min_qf_pi - self.ent_coef * logp_pi) value_loss = 0.5 * tf.reduce_mean(((value_fn - v_backup) ** 2)*self.weight_ph) #value_for_priority = tf.reduce_mean((value_fn - v_backup) ** 2,1) regularizervf = tf.contrib.layers.l1_l2_regularizer(scale_l1=0.0, scale_l2=1e-5, scope='model/values_fn') all_trainable_weights_vf = tf_util.get_trainable_vars('model/values_fn') regularization_penalty_vf = tf.contrib.layers.apply_regularization(regularizervf, all_trainable_weights_vf)
tensorflow.reduce_mean
8,073
import tensorflow as tf def testSharded(self): save_dir = os.path.join(self.get_temp_dir(), "max_to_keep_sharded") try: gfile.DeleteRecursively(save_dir) except OSError: pass # Ignore gfile.MakeDirs(save_dir) with tf.Session( target="", config=tf.ConfigProto(device_count={"CPU": 2})) as sess: with sess.graph.device("/cpu:0"): v0 = tf.Variable(111, name="v0") with sess.graph.device("/cpu:1"): v1 = tf.Variable(222, name="v1") save = tf.train.Saver({"v0": v0, "v1": v1}, sharded=True, max_to_keep=2) tf.initialize_all_variables().run() self.assertEqual([], save.last_checkpoints) s1 = save.save(sess, os.path.join(save_dir, "s1"))
tensorflow.ConfigProto
8,074
import tensorflow as tf tf.summary.histogram("mel_targets %d" % i, model.tower_mel_targets[i]) tf.summary.scalar("before_loss", model.before_loss) tf.summary.scalar("after_loss", model.after_loss) if hparams.predict_linear: tf.summary.scalar("linear_loss", model.linear_loss) for i in range(hparams.tacotron_num_gpus): tf.summary.histogram("mel_outputs %d" % i, model.tower_linear_outputs[i]) tf.summary.histogram("mel_targets %d" % i, model.tower_linear_targets[i]) tf.summary.scalar("regularization_loss", model.regularization_loss) tf.summary.scalar("stop_token_loss", model.stop_token_loss) tf.summary.scalar("loss", model.loss) 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()
tensorflow.summary.scalar
8,075
import tensorflow as tf maxpool = tf.nn.max_pool(inpOp, ksize=[1, kH, kW, 1], strides=[1, dH, dW, 1], padding=padding) return maxpool def apool(inpOp, kH, kW, dH, dW, padding, name): with tf.variable_scope(name): avgpool = tf.nn.avg_pool(inpOp, ksize=[1, kH, kW, 1], strides=[1, dH, dW, 1], padding=padding) return avgpool # def mfmpool(input1, input2, name): # with tf.variable_scope(name):
tensorflow.nn.avg_pool
8,076
import tensorflow as tf gtboxes_in_img_q = self.drawer.draw_boxes_with_categories( img_batch=tf.expand_dims(img[0, :, :, :], axis=0), boxes=gtboxes_and_label_q[0, :, :-1], labels=gtboxes_and_label_q[0, :, -1], method=2) tf.summary.image('Compare/gtboxes_q_gpu:%d' % i, gtboxes_in_img_q) gtboxes_in_img_h = self.drawer.draw_boxes_with_categories( img_batch=tf.expand_dims(img[0, :, :, :], axis=0), boxes=gtboxes_and_label_h[0, :, :-1],
tensorflow.summary.image
8,077
import tensorflow as tf heights = scales_grid / ratio_sqrts * base_size[1] widths = scales_grid * ratio_sqrts * base_size[0] x_centers = tf.cast(tf.range(features_width), tf.float32) x_centers = x_centers * stride[1] y_centers = tf.cast(tf.range(features_height), tf.float32) y_centers = y_centers * stride[0] # x_centers = x_centers + offset[1] # y_centers = y_centers + offset[0] x_centers, y_centers = tf.meshgrid(x_centers, y_centers)
tensorflow.range
8,078
import tensorflow as tf ################################ jupyter-vim ####################################### # https://github.com/qrsforever/vim/blob/master/bundle/.configs/jupyter-vim_conf.vim # %pylab --no-import-all # noqa ##################################################################################### # https://github.com/yaroslavvb/memory_util import sys 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.Session
8,079
import tensorflow as tf # Flatten CNN and concat with other features zack_hack_div_2 = 0 if cnn_rnn_zack: zack_hack_div_2 = zack_hack // 2 cnn_output = tf.slice(cnn_output, [0, zack_hack_div_2, 0, 0], [-1, rnn_nunroll, -1, -1]) nfeats_conv = reduce(lambda x, y: x * y, [int(x) for x in cnn_output.get_shape()[-2:]]) else: nfeats_conv = reduce(lambda x, y: x * y, [int(x) for x in cnn_output.get_shape()[-3:]]) feats_conv = tf.reshape(cnn_output, [batch_size * rnn_nunroll, nfeats_conv])
tensorflow.slice
8,080
import tensorflow as tf output_weights = tf.get_variable( "output_weights", shape=[2, bert_config.hidden_size], initializer=modeling.create_initializer(bert_config.initializer_range)) output_bias = tf.get_variable( "output_bias", shape=[2], initializer=tf.zeros_initializer()) logits = tf.matmul(input_tensor, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias) log_probs = tf.nn.log_softmax(logits, axis=-1) labels = tf.reshape(labels, [-1]) one_hot_labels = tf.one_hot(labels, depth=2, 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, log_probs) def gather_indexes(sequence_tensor, positions): """Gathers the vectors at the specific positions over a minibatch.""" sequence_shape = modeling.get_shape_list(sequence_tensor, expected_rank=3)
tensorflow.reshape
8,081
import tensorflow as tf name='conv', input=X, filter=W, strides=[1, 1, 1, 1], padding='VALID') #add bias of size = out cannels b = tf.get_variable( name='b', shape=[num_filter], initializer=tf.constant_initializer(0.0)) H = tf.nn.bias_add( name='H', value=conv, bias=b) # Apply nonlinearity H = tf.nn.relu(H, name="relu") # max pool pooled = tf.nn.max_pool(H, ksize=[1, sequence_length - filter_size + 1, 1, 1], strides=[1, 1, 1, 1],
tensorflow.nn.bias_add
8,082
import tensorflow as tf # Check that the parameter nodes have been initialized. self.assertEqual(1000.0, v0_2.eval()) self.assertEqual(2000.0, v1_2.eval()) # Restore the values saved earlier in the parameter nodes. save2.restore(sess, save_path) # Check that the parameter nodes have been restored. self.assertEqual(10.0, v0_2.eval()) self.assertEqual(20.0, v1_2.eval()) def _SaveAndLoad(self, var_name, var_value, other_value, save_path): with self.test_session() as sess: var = tf.Variable(var_value, name=var_name) save = tf.train.Saver({var_name: var}) var.initializer.run() val = save.save(sess, save_path) self.assertEqual(save_path, val) with self.test_session() as sess: var = tf.Variable(other_value, name=var_name) save = tf.train.Saver({var_name: var}) save.restore(sess, save_path) self.assertAllClose(var_value, var.eval()) def testCacheRereadsFile(self):
tensorflow.Variable
8,083
import tensorflow as tf **self.policy_kwargs) with tf.variable_scope("loss", reuse=False): self.done_ph = tf.placeholder(tf.float32, [self.n_batch]) # dones self.reward_ph = tf.placeholder(tf.float32, [self.n_batch]) # rewards, not returns self.mu_ph = tf.placeholder(tf.float32, [self.n_batch, self.n_act]) # mu's self.action_ph = train_model.pdtype.sample_placeholder([self.n_batch]) self.learning_rate_ph = tf.placeholder(tf.float32, []) eps = 1e-6
tensorflow.placeholder
8,084
import tensorflow as tf dec, mem = tf.nn.seq2seq.rnn_decoder(dec_inp, enc_state, 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) 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) 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
tensorflow.nn.rnn_cell.GRUCell
8,085
import tensorflow as tf # Structured numpy arrays aren't supported. return np.array([], dtype=[("foo", np.float32)]) def bad2(): # Non-string python objects aren't supported. return tf.float32 y, = tf.py_func(bad1, [], [tf.string]) z, = tf.py_func(bad2, [], [tf.float64]) with self.assertRaisesRegexp(errors.UnimplementedError, "Unsupported numpy type"): y.eval() with self.assertRaisesRegexp(errors.UnimplementedError, "Unsupported object type"):
tensorflow.py_func
8,086
import tensorflow as tf with tf.variable_scope(scope): n_state = shape_list(x)[-1] g = tf.get_variable("g", [n_state], initializer=tf.constant_initializer(1)) b = tf.get_variable("b", [n_state], initializer=tf.constant_initializer(0)) return _norm(x, g, b, axis=axis) def dropout(x, pdrop, train): if train and pdrop > 0: x = tf.nn.dropout(x, 1-pdrop) return x def mask_attn_weights(w): n = shape_list(w)[-1] b = tf.matrix_band_part(tf.ones([n, n]), -1, 0) b = tf.reshape(b, [1, 1, n, n]) w = w*b + -1e9*(1-b)
tensorflow.nn.dropout
8,087
from tensorflow.python.ops import array_ops # Use static shape if known. num_predictions = predictions_2d.get_shape().as_list()[0] # Otherwise use dynamic shape. if num_predictions is None: num_predictions = array_ops.shape(predictions_2d)[0] thresh_tiled = array_ops.tile( array_ops.expand_dims(array_ops.constant(thresholds), [1]), array_ops.pack([1, num_predictions])) # Tile the predictions after thresholding them across different thresholds. pred_is_pos = math_ops.greater( array_ops.tile(array_ops.transpose(predictions_2d), [num_thresholds, 1]), thresh_tiled) pred_is_neg = math_ops.logical_not(pred_is_pos) # Tile labels by number of thresholds
tensorflow.python.ops.array_ops.pack
8,088
import tensorflow as tf with tf.device('/gpu:0'): c = tf.matmul(a,b) c = tf.reshape(c, [-1]) with tf.device('/gpu:1'): d = tf.matmul(b, a) flat_d = tf.reshape(d, [-1]) combined = tf.multiply(c, flat_d) print(sess.run(combined))
tensorflow.multiply
8,089
import tensorflow as tf imgs = random_apply(color_drop, imgs, self._aug_color_drop_prob) return tf.stop_gradient(imgs) aug_images, aug_generated = augment(images), augment(generated) # concat all images all_images = tf.concat([images, generated, aug_images, aug_generated], 0) if self.conditional: all_y = tf.concat([y, sampled_y, y, sampled_y], axis=0) # Compute discriminator output for real and fake images in one batch. d_all, d_all_logits, d_latents = self.discriminator( x=all_images, y=all_y, is_training=is_training) z_projs = self._latent_projections(d_latents)
tensorflow.concat
8,090
import tensorflow as tf if FLAGS.num_gpus > len(gpus): raise ValueError('Invalid num_gpus') raw_data = reader.ptb_raw_data(FLAGS.data_path) train_data, valid_data, test_data, _ = raw_data config = get_config() eval_config = get_config() eval_config.batch_size = 1 eval_config.num_steps = 1 train_graph = tf.Graph() eval_graph = tf.Graph() infer_graph = tf.Graph() with train_graph.as_default(): initializer = tf.random_uniform_initializer(-config.init_scale, config.init_scale) with tf.name_scope('Train'): train_input = DataInput(config=config, data=train_data, name='TrainInput') with tf.variable_scope('Model', reuse=None, initializer=initializer): m = Model(is_training=True, config=config, input_=train_input, graph=train_graph)
tensorflow.Graph
8,091
import tensorflow as tf def test_discriminator_grad_norm_progress(self): stable_stage_num_images = 2 transition_stage_num_images = 3 current_image_id_ph = tf.placeholder(tf.int32, []) progress = networks.compute_progress( current_image_id_ph, stable_stage_num_images,
tensorflow.placeholder
8,092
import tensorflow as tf matched_label = tf.gather(groundtruth_labels, matched_gt_indices) matched_is_foreground = tf.cast(matched_label[:,0] <= 0, tf.float32) matched_anchor_indices = match.matched_column_indices() unmatched_ignored_anchor_indices=match.unmatched_or_ignored_column_indices() unmatched_ignored_reg_weights = tf.gather(reg_weights, unmatched_ignored_anchor_indices) reg_weights= tf.dynamic_stitch( [matched_anchor_indices, unmatched_ignored_anchor_indices], [matched_is_foreground, unmatched_ignored_reg_weights])
tensorflow.gather
8,093
import tensorflow as tf decoder=decoders[1], training=training, encoders=decoders[:1] ) target_weights = get_weights(targets[1][:, 1:], utils.EOS_ID, include_first_eos=True) xent_loss += reconstruction_weight * sequence_loss(logits=reconstructed_outputs, targets=targets[1][:, 1:], weights=target_weights) max_src_len = tf.shape(reconstructed_weights)[1] batch_size = tf.shape(reconstructed_weights)[0] attn_loss = tf.matmul(reconstructed_weights, attention_weights) - tf.eye(max_src_len) src_mask = tf.sequence_mask(encoder_input_length[0], maxlen=max_src_len, dtype=tf.float32) src_mask = tf.einsum('ij,ik->ijk', src_mask, src_mask) attn_loss *= tf.to_float(src_mask) # don't take padding words into account attn_loss = tf.norm(attn_loss) / tf.to_float(batch_size) xent_loss += reconstruction_attn_weight * attn_loss attention_weights = [attention_weights, reconstructed_weights]
tensorflow.matmul
8,094
import tensorflow.contrib.eager as tfe if policy['type'] == 'gcnn': # load model sys.path.insert(0, os.path.abspath(f"models/{policy['name']}")) import model importlib.reload(model) del sys.path[0] policy['model'] = model.GCNPolicy() policy['model'].restore_state(f"trained_models/{args.problem}/{policy['name']}/{seed}/best_params.pkl") policy['model'].call = tfe.defun(policy['model'].call, input_signature=policy['model'].input_signature) policy['batch_datatypes'] = [tf.float32, tf.int32, tf.float32, tf.float32, tf.int32, tf.int32, tf.int32, tf.int32, tf.int32, tf.float32] policy['batch_fun'] = load_batch_gcnn else: # load feature normalization parameters try: with open(f"trained_models/{args.problem}/{policy['name']}/{seed}/normalization.pkl", 'rb') as f:
tensorflow.contrib.eager.defun
8,095
import tensorflow as tf " batch_shape=()" " event_shape=()" " dtype=float16>") chi2 = tfd.Chi2(df=np.float32([1., 2.]), name="silly") self.assertEqual( repr(chi2), "<tfp.distributions.Chi2" " 'silly/'" # What a silly name that is! " batch_shape=(2,)" " event_shape=()" " dtype=float32>") # There's no notion of partially known shapes in eager mode, so exit # early. if tf.executing_eagerly(): return exp = tfd.Exponential(rate=tf.placeholder_with_default( input=1., shape=None)) self.assertEqual( repr(exp), "<tfp.distributions.Exponential" " 'Exponential/'" " batch_shape=<unknown>" " event_shape=()" " dtype=float32>") def testReprWorksCorrectlyMultivariate(self): mvn_static = tfd.MultivariateNormalDiag(
tensorflow.executing_eagerly
8,096
import tensorflow as tf with tf.variable_scope(args.name): model = HredModel(data, args, embed) model.print_parameters() latest_dir = '%s/checkpoint_latest' % args.model_dir best_dir = '%s/checkpoint_best' % args.model_dir if tf.train.get_checkpoint_state(latest_dir) and args.restore == "last": print("Reading model parameters from %s" % latest_dir) model.latest_saver.restore(sess, tf.train.latest_checkpoint(latest_dir)) else: if tf.train.get_checkpoint_state(best_dir) and args.restore == "best": print('Reading model parameters from %s' % best_dir) model.best_saver.restore(sess, tf.train.latest_checkpoint(best_dir)) else: print("Created model with fresh parameters.") global_variable = [gv for gv in tf.global_variables() if args.name in gv.name] sess.run(tf.variables_initializer(global_variable)) return model
tensorflow.train.get_checkpoint_state
8,097
import tensorflow as tf def update(self, state, target, sess=None): sess = sess or tf.get_default_session() for st_idx in range(len(state)): state[st_idx]=featurize_state(state[st_idx]); feed_dict = { self.state: state, self.target: target } _, loss = sess.run([self.train_op, self.loss], feed_dict) return loss """ 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
tensorflow.random_normal_initializer
8,098
import tensorflow as tf **self.policy_kwargs) # Initialize Placeholders self.observations_ph = self.policy_tf.obs_ph # Normalized observation for pixels self.processed_obs_ph = self.policy_tf.processed_obs self.next_observations_ph = self.target_policy.obs_ph self.processed_next_obs_ph = self.target_policy.processed_obs self.action_target = self.target_policy.action_ph self.terminals_ph = tf.placeholder(tf.float32, shape=(None, 1), name='terminals') self.rewards_ph = tf.placeholder(tf.float32, shape=(None, 1), name='rewards') self.is_demo_ph = tf.placeholder(tf.float32, shape=(None, 1), name='is_demonstrations') self.weight_ph = tf.placeholder(tf.float32, shape=(None, 1), name='importance_weight') self.actions_ph = tf.placeholder(tf.float32, shape=(None,) + self.action_space.shape, name='actions') self.learning_rate_ph = tf.placeholder(tf.float32, [], name="learning_rate_ph") if self.n_step: self.next_observations_ph_n = self.target_policy.obs_ph self.processed_next_obs_ph_n = self.target_policy.processed_obs self.rewards_ph_n = tf.placeholder(tf.float32, shape=(None, 1), name='n_step_rewards') self.terminals_ph_n = tf.placeholder(tf.float32, shape=(None, 1), name='n_step_terminals')
tensorflow.placeholder
8,099