seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
import tensorflow as tf
training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(
decoder=training_decoder,
impute_finished=True,
maximum_iterations=tf.reduce_max(seq_lens),
)
self.Y_hat = training_decoder_output.rnn_output
out_decoder2 = tf.reshape(self.Y_hat, [tf.shape(self.Y_hat)[0], -1, n_mels])
dec = conv1d_banks(out_decoder2, K=decoder_num_banks, is_training=self.training)
dec = tf.layers.max_pooling1d(dec, pool_size=2, strides=1, padding="same")
dec = tf.layers.conv1d(dec, embed_size // 2, 3, name="decoder-conv1-1", padding="SAME")
dec = tf.nn.relu(tf.layers.batch_normalization(dec, training=self.training))
dec = tf.layers.conv1d(dec, embed_size // 2, 3, name="decoder-conv1-2", padding="SAME")
dec = tf.layers.batch_normalization(dec, training=self.training)
dec = tf.layers.dense(dec, embed_size // 2)
for i in range(4):
dec = highwaynet(
dec, num_units=embed_size // 2, scope="decoder-highwaynet-{}".format(i)
)
with tf.variable_scope("decoder-gru", reuse=False):
cell = tf.contrib.rnn.GRUCell(embed_size // 2)
cell_bw = tf.contrib.rnn.GRUCell(embed_size // 2)
|
tensorflow.layers.batch_normalization
| 7,600 |
import tensorflow as tf
def test_maximum_batch_size(self):
with self.test_session() as session:
@dynamic_batching.batch_fn_with_options(maximum_batch_size=2)
def f(a, b):
batch_size = tf.shape(a)[0]
return a + b, tf.tile([batch_size], [batch_size])
outputs = [
f(tf.constant([1]), tf.constant([2])),
f(tf.constant([1]), tf.constant([2])),
f(tf.constant([1]), tf.constant([2])),
f(tf.constant([1]), tf.constant([2])),
f(tf.constant([1]), tf.constant([2])),
]
tf.train.start_queue_runners()
results = session.run(outputs)
for value, batch_size in results:
self.assertEqual(3, value)
self.assertGreaterEqual(2, batch_size)
def test_static_shape(self):
assertions_triggered = [0]
@dynamic_batching.batch_fn_with_options(minimum_batch_size=1,
maximum_batch_size=2)
def f0(a):
self.assertEqual(None, a.shape[0].value)
|
tensorflow.train.start_queue_runners
| 7,601 |
import tensorflow as tf
def example_reading_spec(self):
data_fields = {"inputs": tf.VarLenFeature(tf.int64), "targets": tf.VarLenFeature(tf.int64)}
data_items_to_decoders = None
|
tensorflow.VarLenFeature
| 7,602 |
import tensorflow as tf
return float(
self.sess.run(self.cross_entropy, feed_dict={self.x: xs, self.y_: ys})
)
def grad(self, xs, ys):
"""Computes the gradients of the network."""
return self.sess.run(
self.cross_entropy_grads, feed_dict={self.x: xs, self.y_: ys}
)
@ray.remote
class NetActor(object):
def __init__(self, xs, ys):
os.environ["CUDA_VISIBLE_DEVICES"] = ""
with tf.device("/cpu:0"):
self.net = LinearModel([784, 10])
self.xs = xs
self.ys = ys
# Compute the loss on a batch of data.
def loss(self, theta):
net = self.net
net.variables.set_flat(theta)
return net.loss(self.xs, self.ys)
# Compute the gradient of the loss on a batch of data.
def grad(self, theta):
net = self.net
net.variables.set_flat(theta)
|
tensorflow.device
| 7,603 |
import tensorflow as tf
beta1=beta1).minimize(supervised_encoder_loss,
var_list=en_var)
init = tf.global_variables_initializer()
# Reshape immages to display them
input_images = tf.reshape(x_input, [-1, 28, 28, 1])
generated_images = tf.reshape(decoder_output, [-1, 28, 28, 1])
# Tensorboard visualization
tf.summary.scalar(name='Autoencoder Loss', tensor=autoencoder_loss)
tf.summary.scalar(name='Discriminator gauss Loss', tensor=dc_g_loss)
tf.summary.scalar(name='Discriminator categorical Loss', tensor=dc_c_loss)
tf.summary.scalar(name='Generator Loss', tensor=generator_loss)
tf.summary.scalar(name='Supervised Encoder Loss', tensor=supervised_encoder_loss)
tf.summary.histogram(name='Encoder Gauss Distribution', values=encoder_output_latent)
tf.summary.histogram(name='Real Gauss Distribution', values=real_distribution)
tf.summary.histogram(name='Encoder Categorical Distribution', values=encoder_output_label)
tf.summary.histogram(name='Real Categorical Distribution', values=categorial_distribution)
tf.summary.image(name='Input Images', tensor=input_images, max_outputs=10)
tf.summary.image(name='Generated Images', tensor=generated_images, max_outputs=10)
summary_op = tf.summary.merge_all()
# Saving the model
saver = tf.train.Saver()
step = 0
with tf.Session() as sess:
if train_model:
|
tensorflow.summary.scalar
| 7,604 |
import tensorflow as tf
deconv = tf.layers.batch_normalization(deconv, momentum = 0.9)
if activation_function == "relu":
deconv = tf.nn.relu(deconv, name = 'relu')
if activation_function == "leakyrelu":
deconv = tf.nn.leaky_relu(deconv, alpha=relu_factor)
if activation_function == "elu":
deconv = tf.nn.elu(deconv, name = 'elu')
return deconv
|
tensorflow.nn.leaky_relu
| 7,605 |
import tensorflow as tf
half_1 = tf.nn.avg_pool(X, ksize=(1, 1, 1, 1), strides=(1, 2, 2, 1), padding='VALID')
shifted_X = tf.pad(X, ((0, 0), (0, 1), (0, 1), (0, 0)))[:, 1:, 1:, :]
half_2 = tf.nn.avg_pool(shifted_X, ksize=(1, 1, 1, 1), strides=(1, 2, 2, 1), padding='VALID')
|
tensorflow.nn.avg_pool
| 7,606 |
import tensorflow as tf
zs = tf.map_fn(loop_hyper_encoder, ys, dtype=tf.float32, parallel_iterations=1, back_prop=False)
print("Hyper Encoder")
z_hats, _ = entropy_bottleneck(zs, False)
print("Quantize hyperprior")
def loop_hyper_deocder(z):
z = tf.expand_dims(z, 0)
loc, scale = hyper_decoder(z)
return tf.squeeze(loc, [0]), tf.squeeze(scale, [0])
locs, scales = tf.map_fn(loop_hyper_deocder, z_hats, dtype=(tf.float32, tf.float32),
parallel_iterations=1, back_prop=False)
lower_bound = 1e-9# TODO
|
tensorflow.expand_dims
| 7,607 |
import tensorflow as tf
return return_dict
def get_race_loss(FLAGS, features, is_training):
"""Loss for downstream multi-choice QA tasks such as RACE."""
bsz_per_core = tf.shape(features["input_ids"])[0]
def _transform_features(feature):
out = tf.reshape(feature, [bsz_per_core, 4, -1])
out = tf.transpose(out, [2, 0, 1])
out = tf.reshape(out, [-1, bsz_per_core * 4])
return out
inp = _transform_features(features["input_ids"])
seg_id = _transform_features(features["segment_ids"])
inp_mask = _transform_features(features["input_mask"])
label = tf.reshape(features["label_ids"], [bsz_per_core])
xlnet_config = xlnet.XLNetConfig(json_path=FLAGS.model_config_path)
run_config = xlnet.create_run_config(is_training, True, FLAGS)
|
tensorflow.transpose
| 7,608 |
import tensorflow as tf
def testAddCollectionDefFails(self):
with self.test_session():
# Creates a graph.
v0 = tf.Variable(10.0, name="v0")
# Creates a saver.
save = tf.train.Saver({"v0": v0})
|
tensorflow.Variable
| 7,609 |
import tensorflow as tf
def _process_and_truncate(text, trunc, max_len):
if data_status != compat.DataStatus.PROJECTED:
text = self._multilingual_dp.encode(
text, is_processed=(data_status == compat.DataStatus.PROCESSED))
if mode == compat.ModeKeys.TRAIN and trunc and max_len:
if compat.is_tf_tensor(text):
text = tf.cond(
tf.less_equal(tf.size(text), max_len), lambda: text,
lambda: tf.concat([text[:(max_len - 1)], text[-1:]], axis=0))
elif len(text) > max_len:
text = text[:(max_len - 1)] + text[-1:]
return text
def _process_lang(lang):
|
tensorflow.size
| 7,610 |
import tensorflow as tf
# Make a matrix where each row contains [0, 1, ..., max_sequence_len]
r = tf.range(0, max_sequence_len, 1)
range_row = tf.expand_dims(r, 0)
range_tiled = tf.tile(range_row, [batch_size, 1])
# Use the logical operations to create a mask
indicator = tf.less(range_tiled, lengths_tiled)
sz = [batch_size, max_sequence_len]
self._mask = tf.select(indicator, tf.ones(sz), tf.zeros(sz))
def _DoPredictions(self, in_size, mats, class_weights=None):
"""Takes in an array of states and calculates predictions.
Get the cross-entropy for each example in the vector self._xent.
Args:
in_size: size of the hidden state vectors
|
tensorflow.ones
| 7,611 |
import tensorflow as tf
with tf.name_scope('accuracy'):
correct_prediction_action = tf.equal(
tf.argmax(one_hot_labels_action, 1),
tf.argmax(self.predictions_action, 1)
)
self.accuracy_action = tf.reduce_mean(tf.cast(correct_prediction_action, 'float'))
tf.scalar_summary('accuracy_action', self.accuracy_action)
correct_prediction_arguments = tf.equal(tf.argmax(one_hot_labels_arguments, 2),
tf.argmax(self.predictions_arguments, 2))
self.accuracy_arguments = tf.reduce_mean(tf.cast(correct_prediction_arguments, 'float'))
tf.scalar_summary('accuracy_arguments', self.accuracy_arguments)
|
tensorflow.argmax
| 7,612 |
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:
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
tf.logging.info("**** Trainable Variables ****")
for var in tvars:
init_string = ""
if var.name in initialized_variable_names:
init_string = ", *INIT_FROM_CKPT*"
tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
init_string)
output_spec = None
if mode == tf.estimator.ModeKeys.TRAIN:
train_op = optimization.create_optimizer(
total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
|
tensorflow.train.init_from_checkpoint
| 7,613 |
from tensorflow.python.ops import math_ops
keep_prob = ops.convert_to_tensor(
keep_prob, dtype=x.dtype, name="keep_prob")
keep_prob.get_shape().assert_is_compatible_with(tensor_shape.scalar())
noise_shape = noise_shape or array_ops.shape(x)
# uniform [keep_prob, 1.0 + keep_prob)
random_tensor = keep_prob
random_tensor += random_ops.random_uniform(
noise_shape, seed=seed, dtype=x.dtype)
# 0. if [keep_prob, 1.0) and 1. if [1.0, 1.0 + keep_prob)
binary_tensor = math_ops.floor(random_tensor)
ret = x * math_ops.inv(keep_prob) * binary_tensor
ret.set_shape(x.get_shape())
return ret
def top_k(input, k=1, sorted=True, name=None):
"""Finds values and indices of the `k` largest entries for the last dimension.
If the input is a vector (rank-1), finds the `k` largest entries in the vector
and outputs their values and indices as vectors. Thus `values[j]` is the
`j`-th largest entry in `input`, and its index is `indices[j]`.
|
tensorflow.python.ops.math_ops.inv
| 7,614 |
import tensorflow as tf
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
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)
out = tf.matmul(l1, self.w2)+self.b2
return out
def softmax_loss(self,predicts,labels):
|
tensorflow.matmul
| 7,615 |
import tensorflow as tf
max_num_pos = int(positive_fraction * sample_size)
sampled_pos_idx = subsample_indicator(positive_idx, max_num_pos)
num_sampled_pos = tf.reduce_sum(tf.cast(sampled_pos_idx, tf.int32))
if sample_size is None:
negative_positive_ratio = (1 - positive_fraction) / positive_fraction
max_num_neg = tf.cast(negative_positive_ratio * tf.cast(num_sampled_pos, dtype=tf.float32),
dtype=tf.int32)
else:
max_num_neg = sample_size - num_sampled_pos
sampled_neg_idx = subsample_indicator(negative_idx, max_num_neg)
return tf.logical_or(sampled_pos_idx, sampled_neg_idx)
def batch_sample_balanced_positive_negative(indicators,
sample_size,
labels,
positive_fraction=0.5,
dtype=tf.float32):
"""Subsamples minibatches to a desired balance of positives and negatives.
Arguments:
|
tensorflow.logical_or
| 7,616 |
import tensorflow as tf
layers = tf.keras.layers
def parse(line):
"""Parse a line from the colors dataset."""
# Each line of the dataset is comma-separated and formatted as
# color_name, r, g, b
# so `items` is a list [color_name, r, g, b].
items = tf.string_split([line], ",").values
rgb = tf.string_to_number(items[1:], out_type=tf.float32) / 255.
# Represent the color name as a one-hot encoded character sequence.
color_name = items[0]
chars = tf.one_hot(tf.decode_raw(color_name, tf.uint8), depth=256)
# The sequence length is needed by our RNN.
length = tf.cast(tf.shape(chars)[0], dtype=tf.int64)
return rgb, chars, length
def maybe_download(filename, work_directory, source_url):
"""Download the data from source url, unless it's already here.
|
tensorflow.string_to_number
| 7,617 |
import tensorflow as tf
label_id = label_map[example.label]
if ex_index < 5:
tf.logging.info("*** Example ***")
tf.logging.info("guid: %s" % (example.guid))
tf.logging.info("tokens: %s" % " ".join(
[tokenization.printable_text(x) for x in tokens]))
tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
tf.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
tf.logging.info("label: %s (id = %d)" % (example.label, label_id))
feature = InputFeatures(
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
label_id=label_id,
is_real_example=True)
return feature
|
tensorflow.logging.info
| 7,618 |
import tensorflow as tf
# If you want to use the token-level output, use model.get_sequence_output()
# instead.
output_layer = model.get_pooled_output()
hidden_size = output_layer.shape[-1].value
output_weights = tf.get_variable(
"output_weights", [num_labels, hidden_size],
initializer=tf.truncated_normal_initializer(stddev=0.02))
output_bias = tf.get_variable(
"output_bias", [num_labels], initializer=tf.zeros_initializer())
with tf.variable_scope("loss"):
if is_training:
# I.e., 0.1 dropout
output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
logits = tf.matmul(output_layer, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
probabilities = tf.nn.softmax(logits, axis=-1)
log_probs = tf.nn.log_softmax(logits, axis=-1)
|
tensorflow.zeros_initializer
| 7,619 |
from tensorflow.contrib import metrics as metrics_lib
logits = array_ops.concat(1, [array_ops.zeros_like(logits), logits])
if proba:
return nn.softmax(logits)
else:
return math_ops.argmax(logits, 1)
def _default_eval_metrics(self):
if self._num_label_columns == 1:
return _get_default_binary_metrics_for_eval(thresholds=[.5])
return {}
def get_eval_ops(self, features, logits, targets, metrics=None):
loss = self.loss(logits, targets, features)
result = {"loss": metrics_lib.streaming_mean(loss)}
# Adds default metrics.
if metrics is None:
# TODO(b/29366811): This currently results in both an "accuracy" and an
# "accuracy/threshold_0.500000_mean" metric for binary classification.
metrics = {("accuracy", "classes"): metrics_lib.streaming_accuracy}
predictions = math_ops.sigmoid(logits)
targets_float = math_ops.to_float(targets)
default_metrics = self._default_eval_metrics()
for metric_name, metric_op in default_metrics.items():
result[metric_name] = metric_op(predictions, targets_float)
|
tensorflow.contrib.metrics.streaming_mean
| 7,620 |
import tensorflow as tf
tf.flags.DEFINE_string("data_dir", "/scratch1/ram095/nips20/paris_street", "path to dataset")
tf.flags.DEFINE_float("learning_rate", "1e-4", "Learning rate for Adam Optimizer")
|
tensorflow.flags.DEFINE_float
| 7,621 |
import tensorflow as tf
with tf.variable_scope('source2token_self_attn'):
inter_block_logits = bn_dense_layer(self_attn_result, ivec, True, 0., 'bn_dense_map', 'linear',
False, wd, keep_prob, is_train) # bs,bn,bl,vec
inter_block_logits_masked = exp_mask_for_high_rank(inter_block_logits, rep_mask_split) # bs,bn,bl,vec
inter_block_soft = tf.nn.softmax(inter_block_logits_masked, 2) # bs,bn,bl,vec
inter_block_attn_output = tf.reduce_sum(self_attn_result * inter_block_soft, 2) # bs,bn,vec
with tf.variable_scope('self_attn_inter_block'):
inter_block_attn_output_mask = tf.cast(tf.ones([bs, bn], tf.int32), tf.bool)
block_ct_res = directional_attention_with_dense(
|
tensorflow.reduce_sum
| 7,622 |
import tensorflow as tf
"inputs": observations,
"epoch": tf.constant(epoch + 1),
"input_action": tf.zeros(obs_shape[:2] + [1], dtype=tf.int32),
"input_reward": tf.zeros(obs_shape[:2] + [1], dtype=tf.int32),
"targets": tf.zeros(obs_shape[:1] + [num_target_frames] + obs_shape[2:]),
"target_action": tf.zeros(
obs_shape[:1] + [num_target_frames, 1], dtype=tf.int32),
"target_reward": tf.zeros(
obs_shape[:1] + [num_target_frames, 1], dtype=tf.int32),
"target_policy": tf.zeros(
obs_shape[:1] + [num_target_frames] + [action_space.n]),
"target_value": tf.zeros(
obs_shape[:1] + target_value_shape_suffix)
}
model.distributional_value_size = max(distributional_size, 1)
model.use_epochs = hparams.use_epochs
with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):
t2t_model.create_dummy_vars()
|
tensorflow.zeros
| 7,623 |
import tensorflow as tf
img = img - img.min()
img *= 255.0/img.max()
file_name = 'heatmap_{}_{}.jpg'.format(save_image_with_heatmap.counter, ind)
imsave(os.path.join(config.DEBUG_DIR, file_name), img.astype(np.uint8))
return save_image_with_heatmap.counter
def get_keypoint(image, targets, predictions, heatmap_size, height, width, category, clip_at_zero=True, data_format='channels_last', name=None):
predictions = tf.reshape(predictions, [1, -1, heatmap_size*heatmap_size])
pred_max = tf.reduce_max(predictions, axis=-1)
pred_indices = tf.argmax(predictions, axis=-1)
pred_x, pred_y = tf.cast(tf.floormod(pred_indices, heatmap_size), tf.float32), tf.cast(tf.floordiv(pred_indices, heatmap_size), tf.float32)
width, height = tf.cast(width, tf.float32), tf.cast(height, tf.float32)
pred_x, pred_y = pred_x * width / tf.cast(heatmap_size, tf.float32), pred_y * height / tf.cast(heatmap_size, tf.float32)
if clip_at_zero:
pred_x, pred_y = pred_x * tf.cast(pred_max>0, tf.float32), pred_y * tf.cast(pred_max>0, tf.float32)
pred_x = pred_x * tf.cast(pred_max>0, tf.float32) + tf.cast(pred_max<=0, tf.float32) * (width / 2.)
pred_y = pred_y * tf.cast(pred_max>0, tf.float32) + tf.cast(pred_max<=0, tf.float32) * (height / 2.)
if config.PRED_DEBUG:
|
tensorflow.floormod
| 7,624 |
import tensorflow as tf
# Build another graph with 2 nodes, initialized
# differently, and a Restore node for them.
with self.test_session(graph=tf.Graph()) as sess:
v0_2 = tf.Variable(1000.0, name="v0")
v1_2 = tf.Variable(2000.0, name="v1")
save2 = tf.train.Saver([v0_2, v1_2])
|
tensorflow.Variable
| 7,625 |
import tensorflow as tf
self.assertEqual((2, 4), res[0].shape)
res = sess.run([mem])
self.assertEqual((2, 2), res[0].shape)
def testDynamicAttentionDecoder2(self):
with self.test_session() as sess:
with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)):
cell = tf.nn.rnn_cell.GRUCell(2)
inp = tf.constant(0.5, shape=[2, 2, 2])
enc_outputs, enc_state = tf.nn.dynamic_rnn(cell, inp, dtype=tf.float32)
attn_states = enc_outputs
dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3
dec, mem = tf.nn.seq2seq.attention_decoder(
dec_inp, enc_state,
attn_states, cell, output_size=4,
num_heads=2)
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 testAttentionDecoderStateIsTuple(self):
|
tensorflow.nn.seq2seq.attention_decoder
| 7,626 |
import tensorflow as tf
with tf.variable_scope('rnd_pred_act'):
# rnd_pred_act = act_limit * mlp(x_ph, list(hidden_sizes) + [act_dim], activation, output_activation)
rnd_pred_act_in_dim = x_ph.shape.as_list()[1]
rnd_pred_act_dropout_mask_generator = DropoutMaskGenerator(rnd_pred_act_in_dim,
hidden_sizes, model_prob=1.0 - dropout_rate)
rnd_pred_act_dropout_mask_phs = rnd_pred_act_dropout_mask_generator.generate_dropout_mask_placeholders()
rnd_pred_act, rnd_pred_act_reg = mlp_variational(x_ph, rnd_pred_act_dropout_mask_phs,
list(hidden_sizes) + [act_dim], activation,
output_activation, dropout_rate)
rnd_pred_act = act_limit * rnd_pred_act
with tf.variable_scope('rnd_targ_cri'):
rnd_targ_cri = tf.squeeze(mlp(tf.concat([x_ph, a_ph], axis=-1), list(hidden_sizes) + [1], activation, None), axis=1)
with tf.variable_scope('rnd_pred_cri'):
rnd_pred_cri = tf.squeeze(mlp(tf.concat([x_ph, a_ph], axis=-1), list(hidden_sizes) + [1], activation, None),
axis=1)
rnd_pred_cri_in_ph = tf.concat([x_ph, a_ph], axis=-1)
rnd_pred_cri_in_dim = rnd_pred_cri_in_ph.shape.as_list()[1]
rnd_pred_cri_dropout_mask_generator = DropoutMaskGenerator(rnd_pred_cri_in_dim,
hidden_sizes, model_prob=1.0 - dropout_rate)
rnd_pred_cri_dropout_mask_phs = rnd_pred_cri_dropout_mask_generator.generate_dropout_mask_placeholders()
rnd_pred_cri, rnd_pred_cri_reg = mlp_variational(rnd_pred_cri_in_ph, rnd_pred_cri_dropout_mask_phs,
list(hidden_sizes) + [1],
|
tensorflow.concat
| 7,627 |
import tensorflow as tf
if FLAGS.mode == 'train':
train_dataset_reader = dataset.BatchDatset(train_records, image_options)
validation_dataset_reader = dataset.BatchDatset(valid_records, image_options)
sess = tf.Session()
print("Setting up Saver...")
saver = tf.train.Saver()
# create two summary writers to show training loss and validation loss in the same graph
# need to create two folders 'train' and 'validation' inside FLAGS.logs_dir
train_writer = tf.summary.FileWriter(osp.join(FLAGS.logs_dir , 'train'), sess.graph)
validation_writer = tf.summary.FileWriter(osp.join(FLAGS.logs_dir , 'validation'))
sess.run(tf.global_variables_initializer())
ckpt = tf.train.get_checkpoint_state(FLAGS.logs_dir)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess, ckpt.model_checkpoint_path)
print("Model restored...")
if FLAGS.mode == "train":
for itr in xrange(MAX_ITERATION):
train_images, train_annotations = train_dataset_reader.next_batch(FLAGS.batch_size)
feed_dict = {image: train_images, annotation: train_annotations, keep_probability: 0.85}
sess.run(train_op, feed_dict=feed_dict)
if itr % 10 == 0:
|
tensorflow.global_variables_initializer
| 7,628 |
import tensorflow as tf
correct = tf.equal(tf.arg_max(logits,1), tf.arg_max(labels,1))
correct = tf.cast(correct, tf.int32)
n_correct = tf.reduce_sum(correct)
return n_correct
def optimize(loss, learning_rate, global_step):
'''
Optimization, use Gradient Descent as default
'''
with tf.name_scope('optimizer'):
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss, global_step=global_step)
return train_op
def print_all_variables(train_only=True):
'''
Print all trainable and non-trainable variables
'''
|
tensorflow.name_scope
| 7,629 |
import tensorflow as tf
def testSeqAE(self):
FLAGS.use_seq2seq_autoencoder = True
graphs.VatxtModel().language_model_training()
def testBidirLM(self):
graphs.VatxtBidirModel().language_model_graph()
def testBidirClassifier(self):
at_methods = [None, 'rp', 'at', 'vat', 'atvat']
for method in at_methods:
FLAGS.adv_training_method = method
with tf.Graph().as_default():
graphs.VatxtBidirModel().classifier_graph()
# Ensure variables have been reused
# Embedding + 2 LSTM layers + hidden layers + logits layer
expected_num_vars = 1 + 2 * 2 * FLAGS.rnn_num_layers + 2 * (
FLAGS.cl_num_layers) + 2
self.assertEqual(len(tf.trainable_variables()), expected_num_vars)
def testEvalGraph(self):
_, _ = graphs.VatxtModel().eval_graph()
|
tensorflow.Graph
| 7,630 |
import tensorflow as tf
"""Preprocess a single raw image."""
image = tf.image.decode_image(encoded_image, channels=shape[-1])
image.set_shape(shape)
return tf.cast(image, dtype)
def serving_input_receiver_fn():
image_bytes_list = tf.placeholder(
shape=[None],
dtype=tf.string,
)
images = tf.map_fn(
_preprocess_image, image_bytes_list, back_prop=False, dtype=dtype)
return tf.estimator.export.TensorServingInputReceiver(
features=images, receiver_tensors=image_bytes_list)
return serving_input_receiver_fn
def _encode_image(image_array, fmt='PNG'):
"""encodes an (numpy) image array to string.
Args:
image_array: (numpy) image array
fmt: image format to use
|
tensorflow.estimator.export.TensorServingInputReceiver
| 7,631 |
import tensorflow as tf
class TFRecordDataset(TFDataset):
def get_num_partitions(self):
self.train_rdd.getNumPartitions()
def __init__(self, file_path, parse_fn, batch_size,
batch_per_thread, hard_code_batch_size=False, validation_file_path=None):
import tensorflow as tf
g = tf.Graph()
with g.as_default():
serialized_example = tf.placeholder(dtype=tf.string, shape=[])
results = parse_fn(serialized_example)
flattened = nest.flatten(results)
output_names = [tf.cast(t, dtype=tf.float32).name for t in flattened]
serialized_graph = bytearray(g.as_graph_def().SerializeToString())
sc = getOrCreateSparkContext()
train_rdd = callBigDlFunc("float", "createRDDFromTFRecords",
file_path, sc, serialized_graph,
serialized_example.name, output_names)
|
tensorflow.placeholder
| 7,632 |
import tensorflow as tf
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.cast
| 7,633 |
import tensorflow.contrib.eager as tfe
x_dim=hparams.x_dim,
minus_loglikelihood_fn=energy_fn,
n_steps=hparams.n_steps,
eps=hparams.eps)
optimizer = tf.train.AdamOptimizer(learning_rate=hparams.learning_rate)
step_fn = tfe.defun(step) if defun else step
# Warmup to reduce initialization effect when timing
warmup(
dynamics,
|
tensorflow.contrib.eager.defun
| 7,634 |
from tensorflow.contrib.metrics.python.ops import metric_ops
if proba:
return nn.softmax(logits)
else:
return math_ops.argmax(logits, 1)
def _default_eval_metrics(self):
if self._num_label_columns == 1:
return get_default_binary_metrics_for_eval(thresholds=[.5])
return {}
def get_eval_ops(self, features, logits, labels, metrics=None):
loss = self.loss(logits, labels, features)
result = {"loss": metric_ops.streaming_mean(loss)}
# Adds default metrics.
if metrics is None:
# TODO(b/29366811): This currently results in both an "accuracy" and an
# "accuracy/threshold_0.500000_mean" metric for binary classification.
metrics = {("accuracy", "classes"): metric_ops.streaming_accuracy}
predictions = math_ops.sigmoid(logits)
labels_float = math_ops.to_float(labels)
default_metrics = self._default_eval_metrics()
for metric_name, metric_op in default_metrics.items():
|
tensorflow.contrib.metrics.python.ops.metric_ops.streaming_mean
| 7,635 |
import tensorflow as tf
for i in range(n_iters):
loss, samples = step_fn(dynamics, optimizer, samples)
if verbose:
print("Iteration %d: loss %.4f" % (i, loss))
if logdir:
with summary_writer.as_default():
with tf.contrib.summary.always_record_summaries():
tf.contrib.summary.scalar("loss", loss)
class L2hmcTest(tf.test.TestCase):
"""Unit tests for l2hmc in both eager and graph mode."""
def test_apply_transition(self):
"""Testing function `Dynamics.apply_transition` in graph and eager mode."""
|
tensorflow.contrib.summary.scalar
| 7,636 |
import tensorflow as tf
activation_fn=tf.nn.relu,
normalizer_fn=slim.batch_norm,
padding='SAME',
stride=1,
reuse=reuse):
with slim.arg_scope([slim.batch_norm], **batch_norm_params):
with tf.variable_scope(_DECODER_SCOPE, _DECODER_SCOPE, [features]):
feature_list = feature_extractor.networks_to_feature_maps[
model_variant][feature_extractor.DECODER_END_POINTS]
if feature_list is None:
tf.logging.info('Not found any decoder end points.')
return features
else:
decoder_features = features
for i, name in enumerate(feature_list):
decoder_features_list = [decoder_features]
feature_name = '{}/{}'.format(
feature_extractor.name_scope[model_variant], name)
decoder_features_list.append(
slim.conv2d(
|
tensorflow.logging.info
| 7,637 |
import tensorflow as tf
if not no_moving_average:
moving_mean = self._make_var('moving_mean', (in_ch,), trainable=False, init_constant=0)
moving_variance = self._make_var('moving_variance', (in_ch,), trainable=False, init_constant=1)
if is_train:
# For training, do batch norm with batch mean & variance
# Update moving averages if training
(X, mean, variance) = tf.nn.fused_batch_norm(X, scale, offset, epsilon=epsilon, is_training=True)
update_mean = moving_averages.assign_moving_average(moving_mean, mean, decay)
update_variance = moving_averages.assign_moving_average(moving_variance, variance, decay)
with tf.control_dependencies([update_mean, update_variance]):
X = tf.identity(X)
else:
# For prediction, do batch norm with computed moving mean & variance from training
# Don't update moving averages if predicting
|
tensorflow.nn.fused_batch_norm
| 7,638 |
import tensorflow as tf
f2 = tf.reduce_sum(half(masked, 1), 2) / tf.reduce_sum(half(mask, 1))
return tf.concat([x, f1, f2], 1)
|
tensorflow.concat
| 7,639 |
import tensorflow as tf
with tf.variable_scope('train'):
self._train_op = tf.train.RMSPropOptimizer(self.lr).minimize(self.loss)
|
tensorflow.train.RMSPropOptimizer
| 7,640 |
import tensorflow as tf
dynamic_size=True,
element_shape=(facts[:, 0, :].get_shape()))
_, output_op, _ = tf.while_loop(cond, body, [facts, output_ta, 0])
self_attention = output_op.stack()
|
tensorflow.while_loop
| 7,641 |
from tensorflow.python.framework import ops
with ops.control_dependencies([assign_op]):
copy_op = array[:size].assign(old_value[:size])
# return value needs to be the same dtype as no_op() for cond
with ops.control_dependencies([copy_op]):
return control_flow_ops.no_op()
new_size = size + batch_size
array_size = array_ops.shape_internal(array, optimize=False)[0]
maybe_reallocate_op = control_flow_ops.cond(
new_size > array_size, reallocate, control_flow_ops.no_op)
with ops.control_dependencies([maybe_reallocate_op]):
append_values_op = array[size:new_size].assign(batch_values)
with ops.control_dependencies([append_values_op]):
update_op = size.assign(new_size)
if metrics_collections:
ops.add_to_collections(metrics_collections, value)
if updates_collections:
ops.add_to_collections(updates_collections, update_op)
|
tensorflow.python.framework.ops.control_dependencies
| 7,642 |
import tensorflow as tf
with tf.variable_scope("cls/seq_relationship"):
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)
batch_size = sequence_shape[0]
seq_length = sequence_shape[1]
width = sequence_shape[2]
|
tensorflow.one_hot
| 7,643 |
import tensorflow as tf
with tf.control_dependencies(control_inputs=deltas):
|
tensorflow.control_dependencies
| 7,644 |
import tensorflow as tf
for t in threads:
t.join()
vals = p.eval()
ones = np.ones((1024, 1024)).astype(np.float32)
self.assertTrue((vals >= ones).all())
self.assertTrue((vals <= ones * 20).all())
def testParallelAssignWithoutLocking(self):
with self.test_session() as sess:
ones_t = tf.fill([1024, 1024], float(1))
p = tf.Variable(tf.zeros([1024, 1024]))
assigns = [tf.assign(p, tf.mul(ones_t, float(i)), False)
for i in range(1, 21)]
tf.initialize_all_variables().run()
def run_assign(assign_op):
sess.run(assign_op)
threads = [self.checkedThread(target=run_assign, args=(assign_op,))
for assign_op in assigns]
for t in threads:
t.start()
|
tensorflow.zeros
| 7,645 |
import tensorflow as tf
for input_pattern in FLAGS.input_file.split(","):
input_files.extend(tf.gfile.Glob(input_pattern))
|
tensorflow.gfile.Glob
| 7,646 |
import tensorflow as tf
]
print_obj(
"build_discriminator_layers",
"conv_block_tensors",
conv_block_tensors
)
with tf.control_dependencies(control_inputs=conv_block_tensors):
# Build logits layer internals using call.
logits_tensor = self.build_discriminator_logits_layer(
params=params
)
print_obj(
"build_discriminator_layers",
|
tensorflow.control_dependencies
| 7,647 |
import tensorflow as tf
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:
|
tensorflow.concat
| 7,648 |
import tensorflow as tf
fc = tf.nn.bias_add(tf.matmul(x, weights), biases)
tf.summary.histogram('weight', weights)
tf.summary.histogram('bias', biases)
return fc
|
tensorflow.summary.histogram
| 7,649 |
import tensorflow as tf
pmm1 = tf.where(tf.less_equal(n, l), pmn, pmm1)
n += 1
return x, n, l, m, pmm, pmm1
def _evaluate_legendre_polynomial_loop(x, m, l, pmm, pmm1):
n = m + 2
x, n, l, m, pmm, pmm1 = tf.while_loop(
cond=_evaluate_legendre_polynomial_loop_cond,
body=_evaluate_legendre_polynomial_loop_body,
loop_vars=[x, n, l, m, pmm, pmm1])
return pmm1
|
tensorflow.while_loop
| 7,650 |
from tensorflow.python.framework import ops
name: `String`. The name to give this op.
Returns:
ndims: Scalar number of dimensions associated with a `Tensor`.
"""
with self._name_scope(name, values=[x]):
x = ops.convert_to_tensor(x, name="x")
ndims = x.get_shape().ndims
if ndims is None:
return array_ops.rank(x, name="ndims")
return ops.convert_to_tensor(ndims, dtype=dtypes.int32, name="ndims")
|
tensorflow.python.framework.ops.convert_to_tensor
| 7,651 |
import tensorflow as tf
params.train.iterations_per_loop,
num_cores_per_replica=num_cores_per_replica,
input_partition_dims=input_partition_dims,
per_host_input_for_training=tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2 # pylint: disable=line-too-long
)
run_config = tf.contrib.tpu.RunConfig(
cluster=tpu_cluster_resolver,
evaluation_master=params.platform.eval_master,
model_dir=params.model_dir,
log_step_count_steps=params.train.iterations_per_loop,
tpu_config=tpu_config,
|
tensorflow.contrib.tpu.RunConfig
| 7,652 |
import tensorflow as tf
])
src_features = tf.gather(src_features, indices, axis=0)
src_features = tf.stop_gradient(src_features)
src_labels = tf.gather(src_labels, indices)
inst_weights = bs * inst_weights / tf.reduce_sum(inst_weights)
src_one_hot_labels = tf.one_hot(tf.cast(src_labels, tf.int64), num_classes)
src_logits, dst_logits = get_model_logits(src_features, finetune_features,
mode, num_classes,
|
tensorflow.reduce_sum
| 7,653 |
import tensorflow as tf
o_d1 = self.general_deconv2d(o_c5, self.base_number_of_features * 8, 3, stride = 2, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_deconv2d_1')
o_me1 = tf.concat([o_d1, o_c4], 3) # Skip connection
o_d2 = self.general_deconv2d(o_me1, self.base_number_of_features * 4, 3, stride = 2, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_deconv2d_2')
o_me2 = tf.concat([o_d2, o_c3], 3) # Skip connection
o_d3 = self.general_deconv2d(o_me2, self.base_number_of_features * 2, 3, stride = 2, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_deconv2d_3')
o_me3 = tf.concat([o_d3, o_c2], 3) # Skip connection
o_d4 = self.general_deconv2d(o_me3, self.base_number_of_features, 3, stride = 2, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_deconv2d_4')
o_me4 = tf.concat([o_d4, o_c1], 3) # Skip connection
logits = tf.layers.conv2d(o_me4, self.args.num_classes, 1, 1, 'SAME', activation = None)
prediction = tf.nn.softmax(logits, name = name + '_softmax')
return logits, prediction
def general_conv2d(self, input_data, filters = 64, kernel_size = 7, stride = 1, stddev = 0.02, activation_function = "relu", padding = "VALID", do_norm=True, relu_factor = 0, name="conv2d"):
with tf.variable_scope(name):
conv = tf.layers.conv2d(input_data, filters, kernel_size, stride, padding, activation=None)
if do_norm:
conv = tf.layers.batch_normalization(conv, momentum=0.9)
if activation_function == "relu":
conv = tf.nn.relu(conv, name = 'relu')
if activation_function == "leakyrelu":
conv = tf.nn.leaky_relu(conv, alpha=relu_factor)
if activation_function == "elu":
conv = tf.nn.elu(conv, name = 'elu')
return conv
def general_deconv2d(self, input_data, filters = 64, kernel_size = 7, stride = 1, stddev = 0.02, activation_function = "relu", padding = "VALID", do_norm = True, relu_factor = 0, name="deconv2d"):
|
tensorflow.layers.conv2d
| 7,654 |
import tensorflow as tf
else: #was used to train LM
c = tf.nn.conv1d(x, w, stride=1, padding=pad)+b
|
tensorflow.nn.conv1d
| 7,655 |
import tensorflow as tf
batch_size = sequence_shape[0]
seq_length = sequence_shape[1]
width = sequence_shape[2]
flat_offsets = tf.reshape(
tf.range(0, batch_size, dtype=tf.int32) * seq_length, [-1, 1])
flat_positions = tf.reshape(positions + flat_offsets, [-1])
flat_sequence_tensor = tf.reshape(sequence_tensor,
[batch_size * seq_length, width])
output_tensor = tf.gather(flat_sequence_tensor, flat_positions)
return output_tensor
def input_fn_builder(input_files,
max_seq_length,
max_predictions_per_seq,
is_training,
num_cpu_threads=4):
|
tensorflow.gather
| 7,656 |
import tensorflow as tf
def nin(x, num_units, **kwargs):
s = tf.shape(x)
sh = x.get_shape().as_list()
x = tf.reshape(x, [tf.reduce_prod(s[:-1]), sh[-1]])
x = dense(x, num_units, **kwargs)
return tf.reshape(x, [-1] + sh[1:-1] + [num_units])
|
tensorflow.reduce_prod
| 7,657 |
from tensorflow.python.ops import state_ops
predictions = array_ops.reshape(predictions, [-1])
labels_rank = labels.get_shape().ndims
if labels_rank > 1:
labels = array_ops.reshape(labels, [-1])
weights = _mask_weights(ignore_mask, weights)
if weights is not None:
weights_rank = weights.get_shape().ndims
if weights_rank > 1:
weights = array_ops.reshape(weights, [-1])
# Accumulate the prediction to current confusion matrix.
current_cm = confusion_matrix_ops.confusion_matrix(
predictions, labels, num_classes, weights=weights, dtype=cm_dtype)
update_op = state_ops.assign_add(total_cm, current_cm)
def compute_mean_iou(name):
"""Compute the mean intersection-over-union via the confusion matrix."""
sum_over_row = math_ops.to_float(math_ops.reduce_sum(total_cm, 0))
sum_over_col = math_ops.to_float(math_ops.reduce_sum(total_cm, 1))
cm_diag = math_ops.to_float(array_ops.diag_part(total_cm))
denominator = sum_over_row + sum_over_col - cm_diag
# If the value of the denominator is 0, set it to 1 to avoid
# zero division.
denominator = math_ops.select(
math_ops.greater(denominator, 0),
denominator,
array_ops.ones_like(denominator))
|
tensorflow.python.ops.state_ops.assign_add
| 7,658 |
import tensorflow as tf
'bar': tf.convert_to_tensor([0, 2, 0, 2]),
}
boundaries_foo = tf.expand_dims(tf.convert_to_tensor([.5, 1.5]), axis=0)
boundaries_bar = tf.expand_dims(tf.convert_to_tensor([.1, .2]), axis=0)
outputs = {}
|
tensorflow.convert_to_tensor
| 7,659 |
import tensorflow as tf
encoding_stage.AdaptiveEncodingStageInterface))
# Calling the method again should create a new instance.
new_stage = self.default_encoding_stage()
self.assertIsNot(stage, new_stage)
def test_encoding_stage_constructor_does_not_modify_graph(self):
"""Tests that the constructor of encoding stage does not modify graph."""
graph_def = tf.get_default_graph().as_graph_def()
self.default_encoding_stage()
new_graph_def = tf.get_default_graph().as_graph_def()
tf.test.assert_equal_graph_def(graph_def, new_graph_def)
def test_encoding_stage_name(self):
"""Tests that the `name` property returns a string."""
|
tensorflow.get_default_graph
| 7,660 |
import tensorflow as tf
for i in range(num_gpu):
with tf.device('/gpu:%d' % i):
with tf.name_scope('tower_%d' % i):
with slim.arg_scope(
[slim.model_variable, slim.variable],
device='/device:CPU:0'):
with slim.arg_scope([slim.conv2d, slim.conv2d_in_plane,
slim.conv2d_transpose, slim.separable_conv2d,
slim.fully_connected],
weights_regularizer=weights_regularizer,
biases_regularizer=biases_regularizer,
biases_initializer=tf.constant_initializer(0.0)):
gtboxes_and_label_h, gtboxes_and_label_q = tf.py_func(self.get_gtboxes_and_label,
inp=[inputs_list[i][1],
inputs_list[i][2],
inputs_list[i][3]],
Tout=[tf.float32, tf.float32])
gtboxes_and_label_h = tf.reshape(gtboxes_and_label_h, [cfgs.BATCH_SIZE, -1, 5])
# Unnecessary, if you have already sorted when making tfrecord and no data augmentation.
gtboxes_and_label_q = tf.py_func(func=re_order,
|
tensorflow.constant_initializer
| 7,661 |
import tensorflow as tf
pq.put(np.atleast_2d(point.numpy()))
while points_observed < num_observations:
# keep asking queue for new observations until one arrives
try:
new_data = oq.get_nowait()
print(f"Process {pid}: Main : received data {new_data}", flush=True)
except:
continue
# new_data is a tuple of (point, observation value)
# here we turn it into a Dataset and tell of it Trieste
points_observed += 1
new_data = Dataset(
query_points=tf.constant(new_data[0], dtype=tf.float64),
observations=tf.constant(new_data[1], dtype=tf.float64),
)
async_bo.tell(new_data)
# now we can ask Trieste for one more point
# and feed that back into the points queue
point = async_bo.ask()
print(f"Process {pid}: Main : acquired point {point}", flush=True)
pq.put(np.atleast_2d(point))
finally:
terminate_processes(observer_processes)
stop = timeit.default_timer()
|
tensorflow.constant
| 7,662 |
import tensorflow as tf
# Run a linear projection of `hidden_size` then add a residual
# with `layer_input`.
with tf.variable_scope("output"):
attention_output = dense_layer_3d_proj(
|
tensorflow.variable_scope
| 7,663 |
from tensorflow.python.platform import tf_logging as logging
# Exports depend on saved checkpoints for constructing the graph and
# getting the global step from the graph instance saved in the checkpoint.
# If the checkpoint is stale with respect to current step, the global step
# is taken to be the last saved checkpoint's global step and exporter
# doesn't export the same checkpoint again with the following error.
logging.info("Skipping exporting because the existing checkpoint has "
"already been exported. "
"Consider exporting less frequently.")
def end(self, session=None):
super(ExportMonitor, self).end(session=session)
latest_path = saver_lib.latest_checkpoint(self._estimator.model_dir)
if latest_path is None:
logging.info("Skipping export at the end since model has not been saved "
"yet.")
return
try:
self._last_export_dir = self._estimator.export(
self.export_dir,
exports_to_keep=self.exports_to_keep,
signature_fn=self.signature_fn,
input_fn=self._input_fn,
default_batch_size=self._default_batch_size,
input_feature_key=self._input_feature_key,
use_deprecated_input_fn=self._use_deprecated_input_fn)
except RuntimeError:
|
tensorflow.python.platform.tf_logging.info
| 7,664 |
import tensorflow as tf
self.epsilon = epsilon
def __call__(self,input_var,name=None,**kwargs) :
def _init():
v_norm = tf.nn.l2_normalize(self.v,axis=[0,1,2])
t = tf.nn.conv2d(input_var,v_norm,self.strides,self.padding,data_format='NHWC')
mu,var = tf.nn.moments(t,axes=[0,1,2])
std = tf.sqrt(var+self.epsilon)
return [tf.assign(self.g,1/std),tf.assign(self.b,-1.*mu/std)]
require_init = tf.reduce_any(tf.is_nan(self.g))
init_ops = tf.cond(require_init,_init,lambda : [self.g,self.b])
with tf.control_dependencies(init_ops):
w = tf.reshape(self.g,[1,1,1,tf.shape(self.v)[-1]]) * tf.nn.l2_normalize(self.v,axis=[0,1,2])
return tf.nn.bias_add(
tf.nn.conv2d(input_var, w,data_format='NHWC',
strides=self.strides, padding=self.padding),
self.b,data_format='NHWC',name=name)
def get_variables(self):
#TODO: self.v should be l2-normalized or not? / currently not.
return {'v':self.v,'b':self.b,'g':self.g}
class DepthConv2d(object) :
def __init__(self,name,input_dim,channel_multiplier,k_h=4,k_w=4,d_h=2,d_w=2,
stddev=0.02, data_format='NCHW', padding='SAME') :
with tf.variable_scope(name) :
|
tensorflow.nn.l2_normalize
| 7,665 |
import tensorflow as tf
top_antecedents = tf.maximum(raw_top_antecedents, 0) # [k, c]
top_fast_antecedent_scores = tf.expand_dims(top_span_mention_scores, 1) + tf.gather(top_span_mention_scores, top_antecedents) # [k, c]
top_fast_antecedent_scores += tf.log(tf.to_float(top_antecedents_mask)) # [k, c]
|
tensorflow.gather
| 7,666 |
import tensorflow as tf
# Step-wise contrastive loss
horizon_pred, horizon_tgt = horizon_sumV2(pred, tgt, horizon)
# pred1, pred2 = tf.split(horizon_pred, 2, axis=0)
# tgt1, tgt2 = tf.split(horizon_tgt, 2, axis=0)
even = [2 * i for i in range(25)]
odd = [2 * i + 1 for i in range(25)]
pred1 = tf.gather(horizon_pred, even)
pred2 = tf.gather(horizon_pred, odd)
tgt1 = tf.gather(horizon_tgt, even)
tgt2 = tf.gather(horizon_tgt, odd)
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)
return loss
def apply_optimizers(objectives, trainer, config):
# Make sure all losses are computed and apply loss scales.
processed = []
values = [ob.value for ob in objectives]
for ob in objectives:
loss = {min: ob.value, max: -ob.value}[ob.goal]
|
tensorflow.where
| 7,667 |
import tensorflow as tf
sess = tf.get_default_session()
sess.run(tf.global_variables_initializer())
|
tensorflow.global_variables_initializer
| 7,668 |
import tensorflow as tf
true_image_shapes: int32 tensor of shape [batch, 3] where each row is
of the form [height, width, channels] indicating the shapes
of true images in the resized images, as resized images can be padded
with zeros.
Returns:
prediction_dict: a dictionary holding prediction tensors to be
passed to the Loss or Postprocess functions.
"""
flattened_inputs = tf.contrib.layers.flatten(preprocessed_inputs)
class_prediction = tf.contrib.layers.fully_connected(
flattened_inputs, self._num_classes)
box_prediction = tf.contrib.layers.fully_connected(flattened_inputs, 4)
return {
'class_predictions_with_background': tf.reshape(
class_prediction, [-1, 1, self._num_classes]),
'box_encodings': tf.reshape(box_prediction, [-1, 1, 4])
|
tensorflow.contrib.layers.flatten
| 7,669 |
import tensorflow as tf
Returns:
A new tensor where all rows have been scaled as necessary
'''
axis_norms = tf.sqrt(tf.reduce_sum(tf.square(var_matrix), 1))
scaling = maxnorm / tf.maximum(axis_norms, maxnorm)
return var_matrix * tf.expand_dims(scaling, 1)
|
tensorflow.square
| 7,670 |
import tensorflow as tf
X = self.conv('d_1', X, 512, size=1, stride=1, padding="SAME")
X = tf.nn.leaky_relu(X, 0.2)
X = self.conv('d_2', X, 512, size=1, stride=1, padding="SAME")
X = tf.nn.leaky_relu(X, 0.2)
X = self.conv('d_3', X, 512, size=1, stride=1, padding="SAME")
X = tf.nn.leaky_relu(X, 0.2)
X = self.conv('d_out', X, 1, size=1, stride=1, padding="SAME")
print('D out:', X.get_shape().as_list())
|
tensorflow.nn.leaky_relu
| 7,671 |
import tensorflow as tf
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
output_bias = tf.get_variable(
"output_bias",
shape=[bert_config.vocab_size],
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)
label_ids = tf.reshape(label_ids, [-1])
label_weights = tf.reshape(label_weights, [-1])
one_hot_labels = tf.one_hot(
label_ids, depth=bert_config.vocab_size, dtype=tf.float32)
# The `positions` tensor might be zero-padded (if the sequence is too
# short to have the maximum number of predictions). The `label_weights`
# tensor has a value of 1.0 for every real prediction and 0.0 for the
# padding predictions.
per_example_loss = -tf.reduce_sum(log_probs * one_hot_labels, axis=[-1])
numerator = tf.reduce_sum(label_weights * per_example_loss)
denominator = tf.reduce_sum(label_weights) + 1e-5
loss = numerator / denominator
return (loss, per_example_loss, log_probs)
|
tensorflow.one_hot
| 7,672 |
import tensorflow as tf
if use_hvd:
d = d.shard(hvd.size(), hvd.rank()) #TODO only for Horovod, shard to mimic single_GPU = False
print("Data shard: %s %s" % (hvd.size(), hvd.rank()))
d = d.repeat()
d = d.shuffle(buffer_size=len(input_files))
# `cycle_length` is the number of parallel files that get read.
cycle_length = min(num_cpu_threads, len(input_files))
# `sloppy` mode means that the interleaving is not exact. This adds
# even more randomness to the training pipeline.
d = d.apply(
tf.contrib.data.parallel_interleave(
tf.data.TFRecordDataset,
sloppy=is_training,
cycle_length=cycle_length))
d = d.shuffle(buffer_size=100)
else:
d = tf.data.TFRecordDataset(input_files)
# Since we evaluate for a fixed number of steps we don't want to encounter
# out-of-range exceptions.
# d = d.repeat()
# We must `drop_remainder` on training because the TPU requires fixed
# size dimensions. For eval, we assume we are evaluating on the CPU or GPU
|
tensorflow.contrib.data.parallel_interleave
| 7,673 |
import tensorflow as tf
output_bias = tf.get_variable(
"output_bias",
shape=[bert_config.vocab_size],
initializer=tf.zeros_initializer())
logits = tf.matmul(input_tensor, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
if clip:
log_probs = tf.log(tf.clip_by_value(tf.nn.softmax(logits, axis=-1), 1e-6, 1.0 - 1e-6))
else:
log_probs = tf.nn.log_softmax(logits, axis=-1)
label_ids = tf.reshape(label_ids, [-1])
label_weights = tf.reshape(label_weights, [-1])
one_hot_labels = tf.one_hot(
label_ids, depth=bert_config.vocab_size, dtype=tf.float32)
# The `positions` tensor might be zero-padded (if the sequence is too
|
tensorflow.nn.log_softmax
| 7,674 |
import tensorflow as tf
loss_vf = 0.5 * tf.reduce_mean(tf.square(batch['rewards'] - self.vf))
self.a_grads = tf.gradients(loss_pg, self.pi_params)
self.c_grads = tf.gradients(loss_vf, self.vf_params)
self.a_grads, _ = tf.clip_by_global_norm(self.a_grads, 20.0)
self.c_grads, _ = tf.clip_by_global_norm(self.c_grads, 20.0)
opt = tf.train.AdamOptimizer(self.LR)
self.update_a_op = opt.apply_gradients(zip(self.a_grads, self.pi_params))
self.update_c_op = opt.apply_gradients(zip(self.c_grads, self.vf_params))
self.sess.run(tf.global_variables_initializer())
# Tensorboard
if summary_dir is not None:
self.writer = tf.summary.FileWriter(summary_dir)
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)
|
tensorflow.summary.scalar
| 7,675 |
import tensorflow as tf
if ex_index % 10000 == 0:
tf.logging.info("Writing example %d of %d" % (ex_index, len(examples)))
feature = convert_single_example(ex_index, example, label_list,
max_seq_length, tokenizer)
features.append(feature)
return features
def serving_input_fn():
label_ids = tf.placeholder(tf.int32, [None], name='label_ids')
input_ids = tf.placeholder(tf.int32, [None, FLAGS.max_seq_length], name='input_ids')
input_mask = tf.placeholder(tf.int32, [None, FLAGS.max_seq_length], name='input_mask')
segment_ids = tf.placeholder(tf.int32, [None, FLAGS.max_seq_length], name='segment_ids')
input_fn = tf.estimator.export.build_raw_serving_input_receiver_fn({
'label_ids': label_ids,
'input_ids': input_ids,
'input_mask': input_mask,
'segment_ids': segment_ids,
})()
return input_fn
|
tensorflow.placeholder
| 7,676 |
import tensorflow as tf
if 'batch_normalization' not in v.name])
total_loss = tf.identity(loss, name='total_loss')
if mode == tf.estimator.ModeKeys.TRAIN:
global_step = tf.train.get_or_create_global_step()
lr_values = [params['learning_rate'] * decay for decay in params['lr_decay_factors']]
learning_rate = tf.train.piecewise_constant(tf.cast(global_step, tf.int32),
|
tensorflow.train.get_or_create_global_step
| 7,677 |
import tensorflow as tf
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.latest_checkpoint
| 7,678 |
import tensorflow as tf
self.c = 10
self.vf_hidden_size = 128 # for value function network
self.alpha = 0.5 # for build loss
self.batch_processor = FeudalBatchProcessor(self.c)
self.build_model() # build feudal policy model
with tf.name_scope('local_grad'):
grads = tf.gradients(self.loss, self.var_list)
grads, _ = tf.clip_by_global_norm(grads, 40)
with tf.name_scope('sync'): # worker和global的同步过程
with tf.name_scope('pull'): # 获取global参数,复制到local—net
self.pull_params_op = tf.group(*[v1.assign(v2)
for v1, v2 in zip(self.var_list, globalAC.var_list)])
with tf.name_scope('push'): # 将参数传送到gloabl中去
self.update_params_op = OPT.apply_gradients(zip(grads, globalAC.var_list))
|
tensorflow.clip_by_global_norm
| 7,679 |
import tensorflow as tf
aux_logits = self._add_aux_head(*layers[-1], K, is_train)
aux_logits_list.append(aux_logits)
# Global average pooling
(X, w, h, ch) = layers[-1]
X = self._add_global_avg_pool(X, w, h, ch)
# Add dropout if training
if is_train:
X = tf.nn.dropout(X, dropout_keep_prob)
# Compute logits from X
with tf.variable_scope('fully_connected'):
logits = self._add_fully_connected(X, (ch,), K)
return (logits, aux_logits_list)
def _optimize(self, loss, step, **knobs):
opt_momentum = knobs['opt_momentum'] # Momentum optimizer momentum
grad_clip_norm = knobs['grad_clip_norm'] # L2 norm to clip gradients by
# Compute learning rate, gradients
tf_trainable_vars = tf.trainable_variables()
lr = self._get_learning_rate(step, **knobs)
|
tensorflow.variable_scope
| 7,680 |
import tensorflow as tf
layer = conv(inp, 'resconv1'+nom, size=3, strides=first_stride, out_channels=out_num_filters, alpha=alpha, padding='SAME')
layer = batch_norm(layer, 'batch_norm_resconv1'+nom, phase=phase)
layer = conv(layer, 'resconv2'+nom, size=3, strides=[1, 1, 1, 1], out_channels=out_num_filters, apply_relu=False,alpha=alpha, padding='SAME')
layer = batch_norm(layer, 'batch_norm_resconv2'+nom, phase=phase)
if increase_dim:
projection = conv(inp, 'projconv'+nom, size=1, strides=[1, 2, 2, 1], out_channels=out_num_filters, alpha=alpha, apply_relu=False,padding='SAME',bias=False)
projection = batch_norm(projection, 'batch_norm_projconv'+nom, phase=phase)
if last:
block = layer + projection
else:
block = layer + projection
block = tf.nn.relu(block, name='relu')
else:
if last:
block = layer + inp
else:
block = layer + inp
block = tf.nn.relu(block, name='relu')
return block
# First conv
#layer = batch_norm(inp, 'batch_norm_0', phase=phase)
|
tensorflow.nn.relu
| 7,681 |
import tensorflow as tf
dec, mem = tf.nn.seq2seq.attention_decoder(
dec_inp, enc_state,
attn_states, cell, output_size=4,
num_heads=2)
sess.run([tf.global_variables_initializer()])
res = sess.run(dec)
self.assertEqual(3, len(res))
self.assertEqual((2, 4), res[0].shape)
|
tensorflow.global_variables_initializer
| 7,682 |
import tensorflow as tf
return True
def example_reading_spec(self):
data_fields = {"dist_targets": tf.VarLenFeature(tf.int64)}
if self.has_inputs:
|
tensorflow.VarLenFeature
| 7,683 |
import tensorflow as tf
"""Convert indices to one-hot."""
shape = input_.get_shape().as_list()
n_elem = numpy.prod(shape)
indices = tf.range(n_elem)
indices = tf.cast(indices, tf.int64)
indices_input = tf.concat(axis=0, values=[indices, tf.reshape(input_, [-1])])
|
tensorflow.range
| 7,684 |
import tensorflow as tf
total_fast_rcnn_loss_t = tf.reshape(total_fast_rcnn_loss, [1])
fast_rcnn_class_loss_t = tf.reshape(fast_rcnn_class_loss, [1])
fast_rcnn_box_loss_t = tf.reshape(fast_rcnn_box_loss, [1])
mask_loss_t = tf.reshape(mask_loss, [1])
learning_rate_t = tf.reshape(learning_rate, [1])
host_call = (host_call_fn,
|
tensorflow.reshape
| 7,685 |
import tensorflow as tf
Run ``sess.run(tf.global_variables_initializer())`` for TF 0.12+ or
``sess.run(tf.initialize_all_variables())`` for TF 0.11.
Parameters
----------
sess : Session
TensorFlow session.
"""
assert sess is not None
# try: # TF12+
sess.run(tf.global_variables_initializer())
# except: # TF11
# sess.run(tf.initialize_all_variables())
class Layer(object):
"""The basic :class:`Layer` class represents a single layer of a neural network.
It should be subclassed when implementing new types of layers.
Because each layer can keep track of the layer(s) feeding into it, a
network's output :class:`Layer` instance can double as a handle to the full
network.
|
tensorflow.global_variables_initializer
| 7,686 |
import tensorflow as tf
used = tf.sign(tf.reduce_max(tf.abs(data), axis=2))
length = tf.reduce_sum(used, axis=1)
|
tensorflow.reduce_sum
| 7,687 |
import tensorflow as tf
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
sess = tf.Session(config=config)
# data input pipeline
with tf.variable_scope(self.data_scope):
iterator = self.build_dataset_train()
|
tensorflow.Session
| 7,688 |
import tensorflow as tf
feature_emb = tf.concat(feature_emb_list, 2) # [k, c, emb]
feature_emb = tf.nn.dropout(feature_emb, self.dropout) # [k, c, emb]
target_emb = tf.expand_dims(top_span_emb, 1) # [k, 1, emb]
similarity_emb = top_antecedent_emb * target_emb # [k, c, emb]
target_emb = tf.tile(target_emb, [1, c, 1]) # [k, c, emb]
|
tensorflow.expand_dims
| 7,689 |
import tensorflow as tf
features[movielens.ITEM_COLUMN], rconst.ITEM_DTYPE), (batch_size,))
def decode_binary(data_bytes):
# tf.decode_raw does not support bool as a decode type. As a result it is
# necessary to decode to int8 (7 of the bits will be ignored) and then
# cast to bool.
return tf.reshape(tf.cast(tf.decode_raw(data_bytes, tf.int8), tf.bool),
(batch_size,))
if self._is_training:
mask_start_index = tf.decode_raw(
features[rconst.MASK_START_INDEX], tf.int32)[0]
valid_point_mask = tf.less(tf.range(batch_size), mask_start_index)
return {
movielens.USER_COLUMN: users,
movielens.ITEM_COLUMN: items,
rconst.VALID_POINT_MASK: valid_point_mask,
}, decode_binary(features["labels"])
return {
movielens.USER_COLUMN: users,
movielens.ITEM_COLUMN: items,
rconst.DUPLICATE_MASK: decode_binary(features[rconst.DUPLICATE_MASK]),
|
tensorflow.range
| 7,690 |
import tensorflow as tf
horizon_tgt = tf.matmul(tgt, cur_weights)
return horizon_pred, horizon_tgt
def contra_traj_lossV2(pred, tgt, horizon=9):
# Step-wise contrastive loss
horizon_pred = horizon_sumV1(pred, horizon)
horizon_tgt = horizon_sumV1(tgt, horizon)
pred1, pred2 = tf.split(horizon_pred, 2, axis=0)
tgt1, tgt2 = tf.split(horizon_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)
return loss
# randrom horizon
def contra_traj_lossV3(pred, tgt, horizon=12):
# Step-wise contrastive loss
horizon_pred, horizon_tgt = horizon_sumV2(pred, tgt, horizon)
|
tensorflow.where
| 7,691 |
import tensorflow as tf
model.build_graph()
op = model.predictions.op
logit, = op.inputs
if RCE_train==True:
logit = -logit
if tsne_logits==True:
return tf.nn.softmax(logit), model.t_SNE_logits
if logits==True:
return tf.nn.softmax(logit), logit
return tf.nn.softmax(logit)
class models_carlini:
def __init__(self,hps):
self.image_size = image_size
self.num_channels = num_channel############MNIST and CIFAR10 are different ar here
self.num_labels = num_classes
|
tensorflow.nn.softmax
| 7,692 |
import tensorflow as tf
tf.app.flags.DEFINE_integer('max-steps', 10000,
'Number of mini-batches to train on. (default: %(default)d)')
tf.app.flags.DEFINE_integer('log-frequency', 10,
'Number of steps between logging results to the console and saving summaries (default: %(default)d)')
|
tensorflow.app.flags.DEFINE_integer
| 7,693 |
import tensorflow as tf
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]],
dtype=tf.float32)
mask2 = tf.constant([[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 1, 1, 1, 1],
[0, 0, 0, 0, 1, 1, 1, 1]],
dtype=tf.float32)
masks = tf.stack([mask0, mask1, mask2])
return masks
def test_map_labels_to_0_to_n1(self):
labels = tf.constant([[-1, 2, 5],
[0, 9, 1]], dtype=tf.int32)
labels_0_n = isu.map_labels_to_0_to_n(labels)
expected_labels_0_n = tf.constant([[-1, 2, 3],
[0, 4, 1]], dtype=tf.int32)
self.assertAllEqual(labels_0_n.numpy(), expected_labels_0_n.numpy())
def test_map_labels_to_0_to_n2(self):
labels = tf.constant([[-1, 1, 2],
[1, 1, 2]], dtype=tf.int32)
labels_0_n = isu.map_labels_to_0_to_n(labels)
expected_labels_0_n = tf.constant([[-1, 0, 1],
[0, 0, 1]], dtype=tf.int32)
self.assertAllEqual(labels_0_n.numpy(), expected_labels_0_n.numpy())
|
tensorflow.constant
| 7,694 |
import tensorflow as tf
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
def build_cnet(self, state_in, name, reuse=False, batch_size=64):
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)
lstm_c = tf.nn.rnn_cell.LSTMCell(num_units=256)
lstm_c = tf.nn.rnn_cell.DropoutWrapper(lstm_c, output_keep_prob=self.keep_prob)
|
tensorflow.clip_by_value
| 7,695 |
import tensorflow as tf
# Zero-pad up to the sequence length.
while len(input_ids) < max_seq_length:
input_ids.append(0)
input_mask.append(0)
segment_ids.append(0)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
label_id = label_map[example.label]
if ex_index < 5:
tf.logging.info("*** Example ***")
tf.logging.info("guid: %s" % (example.guid))
tf.logging.info("tokens: %s" % " ".join(
[tokenization.printable_text(x) for x in tokens]))
tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
tf.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
tf.logging.info("label: %s (id = %d)" % (example.label, label_id))
feature = InputFeatures(
input_ids=input_ids,
input_mask=input_mask,
|
tensorflow.logging.info
| 7,696 |
import tensorflow as tf
self.yp1 = tf.argmax(tf.reduce_max(outer, axis=2), axis=1)
self.yp2 = tf.argmax(tf.reduce_max(outer, axis=1), axis=1)
|
tensorflow.reduce_max
| 7,697 |
import tensorflow as tf
tf.app.flags.DEFINE_string('pm', '66661', 'pooling scheme across scales. Each number specifies the number of scales remaining at each layer. The first number has to be the same as used in --num_scales.')
tf.app.flags.DEFINE_integer('conv_kernel', 5, 'Size of convolutional kernel')
tf.app.flags.DEFINE_integer('pool_kernel', 3, 'Size of spatial pooling kernel')
tf.app.flags.DEFINE_integer('feats_per_layer', 32, 'Number of feature channels at each layer')
tf.app.flags.DEFINE_boolean('total_pool', True, 'If true, pool all feature maps to 1x1 size in final layer')
tf.app.flags.DEFINE_integer('pool_stride', '1', 'If 2, we get progressive pooling - with overlap pooling, AlexNet style')
|
tensorflow.app.flags.DEFINE_integer
| 7,698 |
import tensorflow as tf
rep_mask_split = tf.reshape(rep_mask_comp, [bs, block_num, block_len]) # bs,bn,bl
# non-linear
rep_map = bn_dense_layer(rep_tensor_split, ivec, True, 0., 'bn_dense_map', activation,
False, wd, keep_prob, is_train) # bs,bn,bl,vec
rep_map_tile = tf.tile(tf.expand_dims(rep_map, 2), [1, 1, block_len, 1, 1]) # bs,bn,bl,bl,vec
# rep_map_dp = dropout(rep_map, keep_prob, is_train)
bn = block_num
bl = block_len
with tf.variable_scope('self_attention'):
# @2.self-attention in block
# mask generation
sl_indices = tf.range(block_len, dtype=tf.int32)
sl_col, sl_row = tf.meshgrid(sl_indices, sl_indices)
if direction == 'forward':
direct_mask = tf.greater(sl_row, sl_col) # bl,bl
else:
direct_mask = tf.greater(sl_col, sl_row) # bl,bl
direct_mask_tile = tf.tile(
tf.expand_dims(tf.expand_dims(direct_mask, 0), 0), [bs, bn, 1, 1]) # bs,bn,bl,bl
rep_mask_tile_1 = tf.tile(tf.expand_dims(rep_mask_split, 2), [1, 1, bl, 1]) # bs,bn,bl,bl
rep_mask_tile_2 = tf.tile(tf.expand_dims(rep_mask_split, 3), [1, 1, 1, bl]) # bs,bn,bl,bl
rep_mask_tile = tf.logical_and(rep_mask_tile_1, rep_mask_tile_2)
attn_mask = tf.logical_and(direct_mask_tile, rep_mask_tile, name='attn_mask') # bs,bn,bl,bl
# attention
f_bias = tf.get_variable('f_bias', [ivec], tf.float32, tf.constant_initializer(0.))
|
tensorflow.meshgrid
| 7,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.