seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
import tensorflow as tf
org_ivec = rep_tensor.get_shape().as_list()[2]
ivec = hn or org_ivec
with tf.variable_scope(scope or 'directional_attention_%s' % direction or 'diag'):
# non-linear
rep_map = bn_dense_layer(rep_tensor, ivec, True, 0., 'bn_dense_map', activation,
False, wd, keep_prob, is_train)
# ensure the seletion is right
dep_selection = tf.logical_and(rep_mask, dep_selection)
head_selection = tf.logical_and(rep_mask, head_selection)
rep_dep_tensor, rep_dep_mask, dep_org_idx = reduce_data_rep_max_len(rep_map, dep_selection)
rep_head_tensor,rep_head_mask, head_org_idx = reduce_data_rep_max_len(rep_map, head_selection)
sl_dep, sl_head = tf.shape(rep_dep_tensor)[1], tf.shape(rep_head_tensor)[1]
if keep_unselected:
unhead_selection = tf.logical_and(rep_mask, tf.logical_not(head_selection))
rep_unhead_tensor, rep_unhead_mask, unhead_org_idx = reduce_data_rep_max_len(rep_map, unhead_selection)
sl_unhead = tf.shape(rep_unhead_tensor)[1]
| tensorflow.logical_and | 6,200 |
import tensorflow as tf
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,
method = 'L-BFGS-B',
options = {'maxiter': 50000,
'maxfun': 50000,
'maxcor': 50,
'maxls': 50,
'ftol' : 1.0 * np.finfo(float).eps})
| tensorflow.square | 6,201 |
import tensorflow as tf
tile_multiples = [1, t, w, h]
tile_multiples.insert(index_c, 1)
weights = tf.tile(weights, tile_multiples)
weights = tf.nn.sigmoid(weights)
return tf.multiply(weights, input_tensor)
def s3dg_base(inputs,
first_temporal_kernel_size=3,
| tensorflow.multiply | 6,202 |
import tensorflow as tf
with self.assertRaisesOpError("Condition x > 0"):
pareto = tfd.Pareto(concentration, scale, validate_args=True)
self.evaluate(pareto.concentration)
def testParetoLogPdf(self):
batch_size = 6
scale = tf.constant([3.] * batch_size)
scale_v = 3.
concentration = tf.constant([2.])
concentration_v = 2.
x = [3., 3.1, 4., 5., 6., 7.]
pareto = tfd.Pareto(concentration, scale)
log_prob = pareto.log_prob(x)
self.assertEqual(log_prob.shape, (6,))
self.assertAllClose(
self.evaluate(log_prob),
| tensorflow.constant | 6,203 |
import tensorflow as tf
with tf.variable_scope("translate") as scope:
trans_h0 = lrelu(linear(tf.nn.dropout(tf.concat([srcimg_z, tgtctx_z], 1), keep_prob), featsize, 'trans_h0'))
trans_z = linear(tf.nn.dropout(trans_h0, keep_prob), featsize, 'trans_z')
self.translated_z = trans_z
s_h, s_w = self.output_height, self.output_width
s_h0, s_h1, s_h2, s_h3 = \
int(s_h/ns0), int(s_h/ns0/ns1), int(s_h/ns0/ns1/ns2), int(s_h/ns0/ns1/ns2/ns3)
s_w0, s_w1, s_w2, s_w3 = \
int(s_w/ns0), int(s_w/ns0/ns1), int(s_w/ns0/ns1/ns2), int(s_w/ns0/ns1/ns2/ns3)
def decode(z, skip_h3, skip_h2, skip_h1, skip_h0):
z_ = lrelu(linear(tf.nn.dropout(z, keep_prob), nf3*s_h3*s_w3, 'd_h0_lin'))
h0 = tf.nn.dropout(tf.reshape(z_, [-1, s_h3, s_w3, nf3]), keep_prob)
h1 = lrelu(deconv2d(tf.concat([h0, skip_h3], 3),
[self.batch_size, s_h2, s_w2, nf2], name='d_h1', d_h=ns3, d_w=ns3))
h2 = lrelu(deconv2d(tf.concat([h1, skip_h2], 3),
[self.batch_size, s_h1, s_w1, nf1], name='d_h2', d_h=ns2, d_w=ns2))
h3 = lrelu(deconv2d(tf.concat([h2, skip_h1], 3),
[self.batch_size, s_h0, s_w0, nf0], name='d_h3', d_h=ns1, d_w=ns1))
print(h3.get_shape())
h4 = deconv2d(tf.concat([h3, skip_h0], 3),
[self.batch_size, s_h, s_w, self.c_dim], name='d_h4', d_h=ns0, d_w=ns0)
return h4
with tf.variable_scope("deconv") as scope:
output_h4 = decode(trans_z, tgtctx_h3, tgtctx_h2, tgtctx_h1, tgtctx_h0)
scope.reuse_variables()
truthoutput_h4 = decode(tgtimg_z, tgtctx_h3, tgtctx_h2, tgtctx_h1, tgtctx_h0)
| tensorflow.concat | 6,204 |
import tensorflow as tf
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.))
dependent_head = linear(
rep_map, 2 * ivec, False, 0., 'linear_dependent_head', False, wd, keep_prob, is_train) # bs,bn,bl,2vec
dependent, head = tf.split(dependent_head, 2, 3)
dependent_etd = tf.expand_dims(dependent, 2) # bs,bn,1,bl,vec
head_etd = tf.expand_dims(head, 3) # bs,bn,bl,1,vec
logits = scaled_tanh(dependent_etd + head_etd + f_bias, 5.0) # bs,bn,bl,bl,vec
logits_masked = exp_mask_for_high_rank(logits, attn_mask)
attn_score = tf.nn.softmax(logits_masked, 3) # bs,bn,bl,bl,vec
attn_score = mask_for_high_rank(attn_score, attn_mask) # bs,bn,bl,bl,vec
self_attn_result = tf.reduce_sum(attn_score * rep_map_tile, 3) # bs,bn,bl,vec
with tf.variable_scope('source2token_self_attn'):
inter_block_logits = bn_dense_layer(self_attn_result, ivec, True, 0., 'bn_dense_map', 'linear',
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
| tensorflow.expand_dims | 6,205 |
import tensorflow as tf
valid_image_batch,valid_label_batch=get_valid_batch(valid_image,valid_label,validnum)
valid_inf=work.valid_inference(valid_image_batch)
valid_labels=tf.one_hot(valid_label_batch,classnum)
#train_step=tf.train.GradientDescentOptimizer(0.001).minimize(cross_entropy)
valid_pre = tf.reshape(valid_inf, [validnum, classnum])
valid_correct_prediction=tf.equal(tf.argmax(valid_inf,1),tf.argmax(valid_labels,1))
valid_accuracy=tf.reduce_mean(tf.cast(valid_correct_prediction,tf.float32))
valid_pre = tf.argmax(valid_pre, 1)
valid_true = tf.argmax(valid_labels, 1)
target_names = ['class sg', 'class bm', 'class wd', 'class wt', 'class wj', 'class wo', 'class ym', 'class shq', 'class shj',
'class no', 'class yh', 'class fb']
init = tf.initialize_all_variables()
config=tf.ConfigProto()
config.gpu_options.allow_growth=True
| tensorflow.argmax | 6,206 |
import tensorflow as tf
embedding = tf.matmul(embedding, W_proj_cnn) + b_proj_cnn
# reshape back to (batch_size, tokens, dim)
if use_highway or use_proj:
shp = tf.concat([batch_size_n_tokens, [projection_dim]], axis=0)
embedding = tf.reshape(embedding, shp)
# at last assign attributes for remainder of the model
| tensorflow.concat | 6,207 |
import tensorflow as tf
tf.app.flags.DEFINE_string('net', 'f100-f3', 'model configuration')
tf.app.flags.DEFINE_string('model', 'noise', 'Type of the model to use: Autoencoder (ae)'
'WhatWhereAe (ww) U-netAe (u)')
tf.app.flags.DEFINE_string('postfix', '', 'Postfix for the training folder')
tf.app.flags.DEFINE_float('alpha', 10, 'Predictive reconstruction loss weight')
tf.app.flags.DEFINE_float('beta', 0.0005, 'Reconstruction from noisy data loss weight')
tf.app.flags.DEFINE_float('epsilon', 0.000001,
'Diameter of epsilon sphere comparing to distance to a neighbour. <= 0.5')
tf.app.flags.DEFINE_float('gamma', 50., 'Loss weight for large distances')
tf.app.flags.DEFINE_float('distance', 0.01, 'Maximum allowed interpoint distance')
tf.app.flags.DEFINE_float('delta', 1., 'Loss weight for stacked objective')
tf.app.flags.DEFINE_string('comment', '', 'Comment to leave by the model')
tf.app.flags.DEFINE_float('test_max', 10000, 'max number of examples in the test set')
tf.app.flags.DEFINE_integer('max_epochs', 0, 'Train for at most this number of epochs')
tf.app.flags.DEFINE_integer('save_every', 250, 'Save model state every INT epochs')
tf.app.flags.DEFINE_integer('eval_every', 25, 'Save encoding and visualizations every')
tf.app.flags.DEFINE_integer('visualiza_max', 10, 'Max pairs to show on visualization')
tf.app.flags.DEFINE_boolean('load_state', True, 'Load state if possible ')
tf.app.flags.DEFINE_boolean('kill_depth', False, 'Ignore depth information')
tf.app.flags.DEFINE_boolean('dev', False, 'Indicate development mode')
tf.app.flags.DEFINE_integer('batch_size', 128, 'Batch size')
tf.app.flags.DEFINE_float('learning_rate', 0.0001, 'Create visualization of ')
| tensorflow.app.flags.DEFINE_string | 6,208 |
import tensorflow as tf
[6, 5, 4, 0, 1], #
[6, 6, 5, 4, 0], #
]
]
self.assertAllEqual(
expected,
relative_pos_gen.make_relative_att_ids(
seq_len=5, batch_size=tf.shape(dummy_batch)[0]))
def test_overwrite_relative_att_ids_outside_segments(self):
# batch_size = 2, seq_len = 5, max_distance = 3
rel_att_ids = [
[
| tensorflow.shape | 6,209 |
import tensorflow as tf
# Weighted sum
if mode == 'SUM':
output = tf.matmul(scores, facts) # [B, 1, H]
# output = tf.reshape(output, [-1, tf.shape(facts)[-1]])
else:
scores = tf.reshape(scores, [-1, tf.shape(facts)[1]])
output = facts * tf.expand_dims(scores, -1)
output = tf.reshape(output, tf.shape(facts))
return output
def din_fcn_attention(query, facts, attention_size, mask, stag='null', mode='SUM', softmax_stag=1, time_major=False, return_alphas=False, forCnn=False):
if isinstance(facts, tuple):
# In case of Bi-RNN, concatenate the forward and the backward RNN outputs.
facts = tf.concat(facts, 2)
if len(facts.get_shape().as_list()) == 2:
facts = tf.expand_dims(facts, 1)
if time_major:
# (T,B,D) => (B,T,D)
facts = tf.array_ops.transpose(facts, [1, 0, 2])
# Trainable parameters
mask = tf.equal(mask, tf.ones_like(mask))
facts_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer
querry_size = query.get_shape().as_list()[-1]
query = tf.layers.dense(query, facts_size, activation=None, name='f1' + stag)
query = prelu(query)
queries = tf.tile(query, [1, tf.shape(facts)[1]])
| tensorflow.concat | 6,210 |
import tensorflow as tf
def dot_attention(inputs, memory, mask, hidden, keep_prob=1.0, is_train=None, scope="dot_attention"):
with tf.variable_scope(scope):
d_inputs = dropout(inputs, keep_prob=keep_prob, is_train=is_train)
d_memory = dropout(memory, keep_prob=keep_prob, is_train=is_train)
JX = tf.shape(inputs)[1]
with tf.variable_scope("attention"):
inputs_ = tf.nn.relu(
dense(d_inputs, hidden, use_bias=False, scope="inputs"))
memory_ = tf.nn.relu(
dense(d_memory, hidden, use_bias=False, scope="memory"))
outputs = tf.matmul(inputs_, tf.transpose(
memory_, [0, 2, 1])) / (hidden ** 0.5)
mask = tf.tile(tf.expand_dims(mask, axis=1), [1, JX, 1])
logits = tf.nn.softmax(softmax_mask(outputs, mask))
| tensorflow.variable_scope | 6,211 |
from tensorflow.python.framework import ops
new_value = array_ops.zeros(next_shape, dtype=values.dtype)
old_value = array.value()
assign_op = state_ops.assign(array, new_value, validate_shape=False)
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(
| tensorflow.python.framework.ops.control_dependencies | 6,212 |
import tensorflow as tf
head_rel_mult = tf.batch_matmul(head_embed_row, rel_embed_square)
# Output needs a squeeze into a 1d vector
raw_output = tf.squeeze(tf.batch_matmul(head_rel_mult, tail_embed_col))
self.output, self.loss = self._create_output_and_loss(raw_output)
| tensorflow.batch_matmul | 6,213 |
import tensorflow as tf
def __init__(self, env, summary_dir='./', gpu=False):
self.LR = 1e-4
self.MINIBATCH = 64
self.EPOCHS = 8
self.EPSILON = 0.2
self.EPS_LEN = 100000
# GPU setup
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False, device_count={'GPU': gpu})
config.gpu_options.allow_growth = True
config.gpu_options.per_process_gpu_memory_fraction = 0.5
# Placeholders
self.sess = tf.Session(config=config)
self.s_dim, self.a_dim = env.observation_space.shape, env.action_space.shape[0]
self.a_bound = (env.action_space.high - env.action_space.low) / 2
self.actions = tf.placeholder(tf.float32, [None, self.a_dim], 'action')
self.state = tf.placeholder(tf.float32, [None, self.s_dim[0]], 'state')
| tensorflow.ConfigProto | 6,214 |
import tensorflow as tf
features["label_ids"] = create_int_feature([feature.label_id])
features["is_real_example"] = create_int_feature(
[int(feature.is_real_example)])
tf_example = tf.train.Example(features=tf.train.Features(feature=features))
writer.write(tf_example.SerializeToString())
writer.close()
def file_based_input_fn_builder(input_file, seq_length, is_training,
drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_length], tf.int64),
"segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
"label_ids": tf.FixedLenFeature([], tf.int64),
"is_real_example": tf.FixedLenFeature([], tf.int64),
}
def _decode_record(record, name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
| tensorflow.FixedLenFeature | 6,215 |
import tensorflow as tf
net = _blur_expand(net)
FLAGS.blur = 0.
return net
def _init_optimizer(self):
self.loss_total = tf.add_n(self.losses, 'loss_total')
self.optimizer = self.optimizer_constructor(learning_rate=FLAGS.learning_rate)
self._train = self.optimizer.minimize(self.loss_total, global_step=self.step)
| tensorflow.add_n | 6,216 |
import tensorflow as tf
# key_masks = tf.expand_dims(mask, 1) # [B, 1, T]
paddings = tf.ones_like(v_dot_tmp) * (-2 ** 32 + 1)
| tensorflow.ones_like | 6,217 |
import tensorflow as tf
self.assertAllEqual(nms_masks2.numpy(), nms_masks_expected2.numpy())
self.assertAllClose(nms_scores2.numpy(), nms_scores_expected2.numpy())
self.assertAllEqual(nms_classes2.numpy(), nms_classes_expected2.numpy())
def test_instance_non_maximum_suppression_2d_scores(self):
mask0 = tf.constant([[1, 0],
[0, 1]], dtype=tf.float32)
mask1 = tf.constant([[1, 1],
[0, 1]], dtype=tf.float32)
mask2 = tf.constant([[1, 0],
[1, 1]], dtype=tf.float32)
mask3 = tf.constant([[1, 1],
[1, 1]], dtype=tf.float32)
mask4 = tf.constant([[0, 0],
| tensorflow.constant | 6,218 |
import tensorflow as tf
output_sizes = [
int((list_size+1)/2) + 1,
int((list_size+1)/4) + 1,
1
]
for i in range(len(output_sizes)):
expand_W = tf.get_variable("W_%d" % i, [current_size, output_sizes[i]])
expand_b = tf.get_variable("b_%d" % i, [output_sizes[i]])
output_data = tf.nn.bias_add(tf.matmul(output_data, expand_W), expand_b)
output_data = tf.nn.elu(output_data)
current_size = output_sizes[i]
#expand_W = tf.get_variable("final_W", [current_size, 1])
| tensorflow.get_variable | 6,219 |
from tensorflow.python.ops import math_ops
predictions, normalizer = tensor_util.remove_squeezable_dimensions(
predictions, normalizer)
predictions.get_shape().assert_is_compatible_with(normalizer.get_shape())
relative_errors = math_ops.select(
math_ops.equal(normalizer, 0.0),
array_ops.zeros_like(labels),
math_ops.div(math_ops.abs(labels - predictions), normalizer))
return streaming_mean(relative_errors, weights, metrics_collections,
| tensorflow.python.ops.math_ops.equal | 6,220 |
import tensorflow as tf
#from keras import backend as K
def din_attention(query, facts, attention_size, mask=None, stag='null', mode='SUM', softmax_stag=1, time_major=False, return_alphas=False):
if isinstance(facts, tuple):
# In case of Bi-RNN, concatenate the forward and the backward RNN outputs.
facts = tf.concat(facts, 2)
print ("query_size mismatch")
query = tf.concat(values = [
query,
query,
| tensorflow.concat | 6,221 |
from tensorflow.python.framework import ops
"""
with ops.op_scope([x], name, "Tanh") as name:
x = ops.convert_to_tensor(x, name="x")
return gen_math_ops._tanh(x, name=name)
ops.RegisterShape("Abs")(common_shapes.unchanged_shape)
ops.RegisterShape("Ceil")(common_shapes.unchanged_shape)
ops.RegisterShape("Conj")(common_shapes.unchanged_shape)
ops.RegisterShape("Cos")(common_shapes.unchanged_shape)
ops.RegisterShape("Exp")(common_shapes.unchanged_shape)
ops.RegisterShape("Floor")(common_shapes.unchanged_shape)
ops.RegisterShape("Imag")(common_shapes.unchanged_shape)
ops.RegisterShape("Inv")(common_shapes.unchanged_shape)
ops.RegisterShape("IsFinite")(common_shapes.unchanged_shape)
ops.RegisterShape("IsInf")(common_shapes.unchanged_shape)
ops.RegisterShape("IsNan")(common_shapes.unchanged_shape)
ops.RegisterShape("Log")(common_shapes.unchanged_shape)
ops.RegisterShape("LogicalNot")(common_shapes.unchanged_shape)
ops.RegisterShape("Neg")(common_shapes.unchanged_shape)
ops.RegisterShape("Real")(common_shapes.unchanged_shape)
ops.RegisterShape("Rsqrt")(common_shapes.unchanged_shape)
ops.RegisterShape("Sign")(common_shapes.unchanged_shape)
ops.RegisterShape("Sin")(common_shapes.unchanged_shape)
| tensorflow.python.framework.ops.RegisterShape | 6,222 |
import tensorflow as tf
h = h + b
return h
def deconv3d(x, shape, output_shape, name, bias=False, stride=2, padding='SAME'):
with tf.variable_scope(name):
W = weight_variable(shape)
h = tf.nn.conv3d_transpose(x, W, output_shape, strides=[1, stride, stride, stride, 1], padding=padding)
if bias:
b = bias_variable([shape[-2]])
h = h + b
return h
def phase_shift_3d(x, r):
batch_size, d, h, w, c = x.get_shape().as_list()
x = tf.reshape(x, (batch_size, d, h, w, r, r, r))
for ns in [d, h, w]:
x = tf.split(x, ns, 1)
x = tf.concat([tf.squeeze(v, 1) for v in x], 3)
return tf.reshape(x, (batch_size, d*r, h*r, w*r, 1))
def subpixel_conv3d(x, r, out_channels):
x = tf.split(x, out_channels, 4)
x = tf.concat([phase_shift_3d(v, r) for v in x], 4)
return x
def pixel_shuffler_3d(x, r, k, out_channels, name):
in_channels = x.get_shape.as_list()[4]
with tf.variable_scope(name):
| tensorflow.reshape | 6,223 |
import tensorflow as tf
hparams["type"] = "natural_exp_decay"
hparams["kwargs"] = {
"decay_steps": 1,
"decay_rate": 0.5
}
ned_lr_decay_fn = opt.get_learning_rate_decay_fn(hparams)
ned_lr = ned_lr_decay_fn(learning_rate=1., global_step=global_step)
ned_lr_true = tf.train.natural_exp_decay(
1., global_step-hparams["start_decay_step"],
hparams["kwargs"]["decay_steps"], hparams["kwargs"]["decay_rate"])
with self.test_session() as sess:
sess.run(tf.global_variables_initializer())
pc_lr_, pc_lr_true_, ned_lr_, ned_lr_true_ = sess.run(
| tensorflow.train.natural_exp_decay | 6,224 |
import tensorflow as tf
logit, = op.inputs
if FLAGS.RCE_train==True:
logit = -logit
if tsne_logits==True:
return logit,model.t_SNE_logits
return logit
def adv_craft_func(hps, images, method, eps=0.01,RCE_train=False, target_labels=None):
if method=='fgsm':
print('Attacking method is fgsm')
adversarial_sample = attacks.fgsm.fgsm(models, images, hps, RCE_train,
eps=eps, epochs=1, clip_min=-0.5, clip_max=0.5)
elif method=='random':
print('Attacking method is random')
adversarial_sample = tf.clip_by_value(images + tf.random_uniform((hps.batch_size,image_size,image_size,num_channel),
minval=-eps, maxval=eps), clip_value_min=-0.5, clip_value_max=0.5)
elif method=='bim':
print('Attacking method is bim')
adversarial_sample = attacks.fgsm.fgsm(models, images, hps, RCE_train,
eps=eps/10, epochs=10, clip_min=-0.5, clip_max=0.5)
elif method=='tgsm':
print('Attacking method is tgsm')
adversarial_sample = attacks.tgsm.tgsm(models, images, hps, RCE_train, y=None,
eps=eps/10, epochs=10, clip_min=-0.5, clip_max=0.5)
elif method=='jsma':
print('Attacking method is jsma')
if target_labels==None:
| tensorflow.random_uniform | 6,225 |
import tensorflow as tf
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,2048],initializer=tf.contrib.layers.xavier_initializer_conv2d())
self.w2=tf.get_variable('w2', [2048,3072],initializer=tf.contrib.layers.xavier_initializer_conv2d())
self.w3=tf.get_variable('w3', [3072,512],initializer=tf.contrib.layers.xavier_initializer_conv2d())
self.w4=tf.get_variable('w4', [512,classnum],initializer=tf.contrib.layers.xavier_initializer_conv2d())
self.b1 = tf.get_variable('b1', [2048],initializer=tf.constant_initializer(0.0))
self.b2 = tf.get_variable('b2', [3072],initializer=tf.constant_initializer(0.0))
self.b3 = tf.get_variable('b3', [512],initializer=tf.constant_initializer(0.0))
self.b4 = tf.get_variable('b4', [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)
l2 = tf.matmul(l1, self.w2)+self.b2
l2=tf.nn.relu(l2)
l3=tf.matmul(l2, self.w3)+self.b3
l3=tf.nn.relu(l3)
out=tf.matmul(l3, self.w4)+self.b4
| tensorflow.constant_initializer | 6,226 |
import tensorflow as tf
self.t_replace_counter += 1
def choose_action(self, s):
s = s[np.newaxis, :] # single state
return self.sess.run(self.a, feed_dict={S: s})[0] # single action
def add_grad_to_graph(self, a_grads):
with tf.variable_scope('policy_grads'):
# ys = policy;
# xs = policy's parameters;
# self.a_grads = the gradients of the policy to get more Q
# tf.gradients will calculate dys/dxs with a initial gradients for ys, so this is dq/da * da/dparams
self.policy_grads_and_vars = tf.gradients(ys=self.a, xs=self.e_params, grad_ys=a_grads)
with tf.variable_scope('A_train'):
opt = tf.train.RMSPropOptimizer(-self.lr) # (- 1_tensorflow_new rate) for ascent policy
self.train_op = opt.apply_gradients(zip(self.policy_grads_and_vars, self.e_params), global_step=GLOBAL_STEP)
############################### Critic ####################################
class Critic(object):
def __init__(self, sess, state_dim, action_dim, learning_rate, gamma, t_replace_iter, a, a_):
self.sess = sess
| tensorflow.gradients | 6,227 |
import tensorflow as tf
"""Returns the loss function."""
loss = tf.losses.softmax_cross_entropy(
| tensorflow.losses.softmax_cross_entropy | 6,228 |
import tensorflow as tf
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.estimator.export.build_raw_serving_input_receiver_fn | 6,229 |
import tensorflow as tf
ls = [-1] + l.get_shape().as_list()[1:]
xs = ls[:-1] + [3]
# unpack parameters
logit_probs = l[:, :, :, :nr_mix]
l = tf.reshape(l[:, :, :, nr_mix:], xs + [nr_mix * 3])
# sample mixture indicator from softmax
sel = tf.one_hot(tf.argmax(logit_probs - tf.log(-tf.log(tf.random_uniform(
tf.shape(logit_probs), minval=1e-5, maxval=1. - 1e-5))), 3), depth=nr_mix, dtype=tf.float32)
| tensorflow.reshape | 6,230 |
import tensorflow as tf
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)
state_init_c = lstm_c.zero_state(batch_size=batch_size, dtype=tf.float32)
lstm_cin = tf.expand_dims(layer_c2, axis=1)
out_c, state_final_c = tf.nn.dynamic_rnn(cell=lstm_c, inputs=lstm_cin, initial_state=state_init_c)
cell_out_c = tf.reshape(out_c, [-1, 256])
vf = tf.layers.dense(cell_out_c, 1, kernel_regularizer=reg)
params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=name)
return vf, params, state_init_c, state_final_c
# Update the network
def train(self, rollout):
start = time()
self.sess.run([self.pi_new_params, self.vf_new_params])
for _ in range(self.EPOCHS):
| tensorflow.layers.dense | 6,231 |
import tensorflow as tf
with tf.Graph().as_default() as graph, tf.device('/cpu:0'):
num_gpu = len(cfgs.GPU_GROUP.strip().split(','))
global_step = slim.get_or_create_global_step()
lr = self.warmup_lr(cfgs.LR, global_step, cfgs.WARM_SETP, num_gpu)
tf.summary.scalar('lr', lr)
optimizer = tf.train.MomentumOptimizer(lr, momentum=cfgs.MOMENTUM)
r3det_gwd = build_whole_network.DetectionNetworkR3DetGWD(cfgs=self.cfgs,
is_training=True)
with tf.name_scope('get_batch'):
if cfgs.IMAGE_PYRAMID:
shortside_len_list = tf.constant(cfgs.IMG_SHORT_SIDE_LEN)
shortside_len = tf.random_shuffle(shortside_len_list)[0]
else:
shortside_len = cfgs.IMG_SHORT_SIDE_LEN
img_name_batch, img_batch, gtboxes_and_label_batch, num_objects_batch, img_h_batch, img_w_batch = \
self.reader.next_batch(dataset_name=cfgs.DATASET_NAME,
batch_size=cfgs.BATCH_SIZE * num_gpu,
shortside_len=shortside_len,
is_training=True)
# data processing
inputs_list = []
for i in range(num_gpu):
| tensorflow.random_shuffle | 6,232 |
import tensorflow as tf
Args:
in_size: size of the hidden state vectors
mats: list of hidden state vectors
"""
pred_mat = tf.get_variable('pred_mat',
[in_size, self._out_vocab_size])
pred_bias = tf.get_variable('pred_bias', [self._out_vocab_size])
# Make a prediction on every word.
def GetWordPred(o_):
logits = tf.nn.xw_plus_b(o_, pred_mat, pred_bias)
return tf.nn.softmax(logits)
self.preds_by_word = tf.pack([GetWordPred(o_) for o_ in mats])
self.cs = self._mask / tf.reduce_sum(self._mask, 1, keep_dims=True)
# The final prediction is the average of the predictions for each word
# weighted by the individual confidence/utility scores.
preds_weighted = tf.mul(tf.reshape(tf.transpose(self.cs), [-1, 1]),
tf.reshape(self.preds_by_word,
[-1, self._out_vocab_size]))
| tensorflow.nn.xw_plus_b | 6,233 |
import tensorflow as tf
:return [Tensor] [N, H+Ph, W+Pw, C]. Padded input tensor.
"""
x_shape = tf.shape(x)
if padding == 'SAME':
pad_h0, pad_h1, pad_w0, pad_w1 = calc_padding_4d(x_shape, ksize, strides, padding)
if bstrides is not None:
# Here we do not use the standard padding on the right hand side.
# If the convolution results is larger than expected, the scatter function will not use
# out-of-boundary points.
assert bsize is not None, 'Must pass in bsize and bstrides together.'
h = x_shape[1] + pad_h0 + pad_h1
w = x_shape[2] + pad_w0 + pad_w1
pad_h1 += tf.mod(-h + bsize[1], bstrides[1])
pad_w1 += tf.mod(-w + bsize[2], bstrides[2])
return tf.pad(x, [[0, 0], [pad_h0, pad_h1], [pad_w0, pad_w1], [0, 0]])
else:
if bstrides is not None:
assert bsize is not None, 'Must pass in bsize and bstrides together.'
h = x_shape[1]
w = x_shape[2]
pad_h1 = tf.mod(-h + bsize[1], bstrides[1])
pad_w1 = tf.mod(-w + bsize[2], bstrides[2])
return tf.cond(
tf.logical_or(tf.greater(pad_h1, 0), tf.greater(pad_w1, 0)),
lambda: tf.pad(x, [[0, 0], [0, pad_h1], [0, pad_w1], [0, 0]]), lambda: x)
else:
return x
| tensorflow.mod | 6,234 |
from tensorflow import keras
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
lstm_cell = rnn.BasicLSTMCell(LSTM_SIZE, forget_bias = 1.0)
| tensorflow.keras.layers.Dense | 6,235 |
import tensorflow as tf
def euclidean_loss_layer(a, b, multiplier=100.0, use_l1=False, eps=0.01):
""" Math: out = (action - mlp_out)'*precision*(action-mlp_out)
= (u-uhat)'*A*(u-uhat)"""
multiplier = tf.constant(multiplier, dtype='float') #for bc #10000
uP =a*multiplier-b*multiplier
if use_l1:
return tf.reduce_mean(eps*tf.square(uP) + tf.abs(uP))
return tf.reduce_mean(tf.square(uP))
def conv2d(img, w, b, strides=[1, 1, 1, 1], is_dilated=False):
if is_dilated:
layer = tf.nn.atrous_conv2d(img, w, rate=2, padding='SAME') + b
else:
| tensorflow.square | 6,236 |
import tensorflow as tf
out = tf.reshape(input_, [-1, np.prod(self.inp_modes)])
self.image_max_size = max(self.image_max_size, np.prod(self.inp_modes))
out = tf.transpose(out, [1, 0])
for i in range(dim):
out = tf.reshape(out, [self.mat_ranks[i] * self.inp_modes[i], -1])
out = tf.matmul(self.mat_cores[i], out)
out = tf.reshape(out, [self.out_modes[i], -1])
out = tf.transpose(out, [1, 0])
out = tf.reshape(out, [-1, np.prod(self.out_modes)])
# self.image_max_size = max(self.image_max_size, np.prod([val.value for val in out.get_shape()[1:]]))
if self.use_bias:
out = tf.add(out, self.bias, name='out')
| tensorflow.transpose | 6,237 |
import tensorflow as tf
batch_size=batch_size,num_threads=10,capacity=10000,min_after_dequeue=200)
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):
| tensorflow.train.batch | 6,238 |
import tensorflow as tf
outputs.append(output)
# The outputs of this layer are the inputs of the subsequent layer.
chars = tf.stack(outputs, axis=0)
if training:
| tensorflow.stack | 6,239 |
import tensorflow as tf
h = h + b
return h
def deconv3d(x, shape, output_shape, name, bias=False, stride=2, padding='SAME'):
with tf.variable_scope(name):
W = weight_variable(shape)
h = tf.nn.conv3d_transpose(x, W, output_shape, strides=[1, stride, stride, stride, 1], padding=padding)
if bias:
b = bias_variable([shape[-2]])
h = h + b
return h
| tensorflow.nn.conv3d_transpose | 6,240 |
import tensorflow as tf
ratio = tf.maximum(pi.prob(batch['actions']), 1e-6) / tf.maximum(pi_old.prob(batch['actions']), 1e-6)
ratio = tf.clip_by_value(ratio, 0, 10)
surr1 = batch['advantage'] * ratio
surr2 = batch['advantage'] * tf.clip_by_value(ratio, 1 - epsilon_decay, 1 + epsilon_decay)
loss_pg = - 2.0 * tf.reduce_mean(tf.minimum(surr1, surr2))
loss_vf = 0.5 * tf.reduce_mean(tf.square(batch['rewards'] - self.vf))
loss_entropy = - 0.01 * tf.reduce_mean(pi.entropy())
loss = loss_pg + loss_vf + loss_entropy
opt = tf.train.AdamOptimizer(self.LR)
self.train_op = opt.minimize(loss, global_step=self.global_step, var_list=pi_params + vf_params)
self.pi_new_params = [oldp.assign(p) for p, oldp in zip(pi_params, pi_old_params)]
self.vf_new_params = [oldp.assign(p) for p, oldp in zip(vf_params, vf_old_params)]
self.sess.run(tf.global_variables_initializer())
# Tensorboard
| tensorflow.train.AdamOptimizer | 6,241 |
from tensorflow.python.framework import ops
with ops.name_scope(name) as scope:
with ops.device(v.device or ops.get_default_graph().get_default_device()):
if callable(init):
assert v.get_shape().is_fully_defined(), "Variable shape unknown."
# TODO(mrry): Convert to v.shape when the property and
# accessor are reconciled (and all initializers support
# tf.TensorShape objects).
value = init(v.get_shape().as_list(), v.dtype.base_dtype)
value = ops.convert_to_tensor(value, name="value")
return assign(v, value, name=scope)
else:
init = ops.convert_to_tensor(init, name="init")
return assign(v, init, name=scope)
@ops.RegisterShape("Assign")
| tensorflow.python.framework.ops.convert_to_tensor | 6,242 |
import tensorflow as tf
if self._trg_lang_tag_position in ["src", "source"]:
src = tf.concat([tf.expand_dims(batch_of_data["trg_lang"], axis=1), src], axis=1)
if self._with_src_lang_tag:
src = tf.concat([tf.expand_dims(batch_of_data["src_lang"], axis=1), src], axis=1)
input_dict = {"src": src,
"src_length": deduce_text_length(src, self._multilingual_dp.meta["pad_id"],
self._multilingual_dp.meta["padding_mode"])}
if self._trg_lang_tag_position in ["trg", "target"]:
target_bos = batch_of_data["trg_lang"]
else:
target_bos = tf.tile([tf.convert_to_tensor(
self._multilingual_dp.meta["bos_id"], dtype=tf.int64)], [tf.shape(src)[0]])
if mode == compat.ModeKeys.INFER:
input_dict["trg_input"] = target_bos
else:
input_dict["trg"] = batch_of_data["label"]
input_dict["trg_length"] = deduce_text_length(batch_of_data["label"],
self._multilingual_dp.meta["pad_id"],
self._multilingual_dp.meta["padding_mode"])
input_dict["trg_input"] = tf.concat([tf.expand_dims(target_bos, axis=1),
batch_of_data["label"][:, :-1]], axis=1)
| tensorflow.convert_to_tensor | 6,243 |
import tensorflow as tf
tf.GraphKeys.VARIABLES],
initializer=tf.ones_initializer(),
trainable=False)
self._moving_variance = tf.sub(self._moving_second_moment,
tf.square(self._moving_mean),
name="moving_variance")
def build_batch_stats():
"""Builds the batch statistics calculation ops."""
# Copy for better stability.
# We use the moving mean as an estimate of the mean in order to perform
# a more numerically stable calculation of the batch mean.
shift = tf.add(self._moving_mean, 0)
counts, shifted_sum_x, shifted_sum_x2, _ = tf.nn.sufficient_statistics(
input_batch,
reduction_indices,
keep_dims=True,
shift=shift,
name="batch_norm_ss")
mean, variance = tf.nn.normalize_moments(counts,
shifted_sum_x,
shifted_sum_x2,
shift,
name="normalize_moments")
second_moment = variance + tf.square(mean)
| tensorflow.add | 6,244 |
from tensorflow.python.eager import context
initial_output = tf.slice(initial_output, [0, 0, 0, 0],
common_layers.shape_list(initial_output))
target_modality = self._problem_hparams.target_modality
if target_modality.is_class_modality:
decode_length = 1
else:
decode_length = common_layers.shape_list(
features["inputs"])[1] + decode_length
# Initial values of result, logits and loss.
result = initial_output
# tensor of shape [batch_size, time, 1, 1, vocab_size]
logits = tf.zeros((batch_size, 0, 1, 1, target_modality.top_dimensionality))
if not context.in_eager_mode():
logits.set_shape([None, None, None, None, None])
loss = 0.0
def while_exit_cond(result, logits, loss): # pylint: disable=unused-argument
"""Exit the loop either if reach decode_length or EOS."""
length = common_layers.shape_list(result)[1]
not_overflow = length < decode_length
if self._problem_hparams.stop_at_eos:
| tensorflow.python.eager.context.in_eager_mode | 6,245 |
import tensorflow as tf
inter = tf.reshape(values, [self.resolution,
self.resolution,
self.resolution])
inter = tf.transpose(tf.reduce_max(inter, axis=a))
im = axs[fig_obj_count, 4].matshow(inter.numpy())
plt.colorbar(im, ax=axs[fig_obj_count, 4])
print(mtype, fig_obj_count, 2)
fig_obj_count += 1
intersection = tf.reduce_sum(tf.math.sign(tf.nn.relu(sdf_values - 1)))
union = tf.reduce_sum(tf.math.sign(sdf_values))
iou = intersection / union
if not tf.math.is_nan(iou):
ious.append(iou)
status3 = False
if status3:
_ = plt.figure(figsize=(5, 5))
plt.clf()
# mask = (sdf_values.numpy() > 0)[:, 0]
# plt.scatter(samples_world.numpy()[mask, 0],
# samples_world.numpy()[mask, 1],
# marker='.', c=sdf_values.numpy()[mask, 0])
plt.scatter(samples_world.numpy()[:, 0],
| tensorflow.math.is_nan | 6,246 |
import tensorflow as tf
img = inputs_list[i][0]
img_shape = inputs_list[i][-2:]
img = tf.image.crop_to_bounding_box(image=img,
offset_height=0,
offset_width=0,
target_height=tf.cast(img_shape[0], tf.int32),
target_width=tf.cast(img_shape[1], tf.int32))
outputs = r3det_gwd.build_whole_detection_network(input_img_batch=img,
gtboxes_batch_h=gtboxes_and_label_h,
gtboxes_batch_r=gtboxes_and_label_r,
gpu_id=i)
gtboxes_in_img_h = self.drawer.draw_boxes_with_categories(img_batch=img,
| tensorflow.cast | 6,247 |
import tensorflow as tf
valid_correct_prediction=tf.equal(tf.argmax(valid_inf,1),tf.argmax(valid_labels,1))
valid_accuracy=tf.reduce_mean(tf.cast(valid_correct_prediction,tf.float32))
valid_pre = tf.argmax(valid_pre, 1)
valid_true = tf.argmax(valid_labels, 1)
target_names = ['class sg', 'class bm', 'class wd', 'class wt', 'class wj', 'class wo', 'class ym', 'class shq', 'class shj',
'class no', 'class yh', 'class fb']
init = tf.initialize_all_variables()
config=tf.ConfigProto()
config.gpu_options.allow_growth=True
#init=tf.initialize_all_variables()
def train(train_num=64,test_num=32,lr=1e-4,loop_count=10000,report_step=100,save_step=1000,restore=False):
with tf.Session(config=config) as sess:
sess.run(init)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
| tensorflow.ConfigProto | 6,248 |
import tensorflow as tf
def cw_sampling(X, y=None):
def phi_sampling(s, D):
return tf.pow(1.0 + 4.0*s/(2.0*D-3), -0.5)
D = tf.cast(tf.shape(X)[1], tf.float32)
N = tf.cast(tf.shape(X)[0], tf.float32)
D_int = tf.cast(D, tf.int32)
N_int = tf.cast(N, tf.int32)
if y is None:
y = silverman_rule_of_thumb(N)
| tensorflow.shape | 6,249 |
import tensorflow as tf
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)
def get_next_sentence_output(bert_config, input_tensor, labels, clip):
"""Get loss and log probs for the next sentence prediction."""
# Simple binary classification. Note that 0 is "next sentence" and 1 is
| tensorflow.reduce_sum | 6,250 |
import tensorflow as tf
flags.DEFINE_integer("iterations_per_loop", 1000,
"How many steps to make in each estimator call.")
flags.DEFINE_integer("max_eval_steps", None, "Maximum number of eval steps.")
flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
tf.flags.DEFINE_string(
"tpu_name", None,
"The Cloud TPU to use for training. This should be either the name "
"used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 "
"url.")
tf.flags.DEFINE_string(
"tpu_zone", None,
| tensorflow.flags.DEFINE_string | 6,251 |
import tensorflow as tf
Args:
x: Batch of encoder continuous latent states sliced/projected into
shape [-1, num_blocks, block_dim].
means: Embedding means of shape.
Returns:
Tensor with nearest element in mean encoded in one-hot notation.
"""
x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keep_dims=True)
means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keep_dims=True)
scalar_prod = tf.matmul(
tf.transpose(x, perm=[1, 0, 2]), tf.transpose(means, perm=[0, 2, 1]))
scalar_prod = tf.transpose(scalar_prod, perm=[1, 0, 2])
dist = x_norm_sq + tf.transpose(
means_norm_sq, perm=[2, 0, 1]) - 2 * scalar_prod
if self.hparams.soft_em:
nearest_idx = tf.stack(
[
tf.multinomial(
-dist[:, i, :], num_samples=self.hparams.num_samples)
for i in range(self.hparams.num_blocks)
| tensorflow.transpose | 6,252 |
import tensorflow as tf
# with tf.variable_scope('q_target'):
with tf.variable_scope('loss'):
self.loss = tf.reduce_mean(tf.squared_difference(self.q_target, tf.squeeze(self.Q_tot), name='TD_error'))
# self.loss = tf.reduce_mean(tf.squared_difference(self.q_target, self.Q_tot, name='TD_error'))
with tf.variable_scope('train'):
self._train_op = tf.train.RMSPropOptimizer(self.lr).minimize(self.loss)
def act(self, state):
if np.random.uniform() > self.epsilon :# pick the argmax action
s = np.array(state)
| tensorflow.variable_scope | 6,253 |
import tensorflow as tf
ch_emb = tf.reshape(ch_emb, [N * self.max_p_num, PL, -1])
qh_emb = tf.reshape(qh_emb, [N * self.max_p_num, QL, -1])
c_emb = tf.nn.dropout(tf.nn.embedding_lookup(self.word_mat, self.c), 1.0 - self.dropout)
q_emb = tf.nn.dropout(tf.nn.embedding_lookup(self.word_mat, self.q), 1.0 - self.dropout)
c_emb = tf.concat([c_emb, ch_emb], axis=2)
q_emb = tf.concat([q_emb, qh_emb], axis=2)
self.c_emb = highway(c_emb, size=d, scope="highway", dropout=self.dropout, reuse=None)
self.q_emb = highway(q_emb, size=d, scope="highway", dropout=self.dropout, reuse=True)
def _encode(self):
N, PL, QL, CL, d, dc, nh = self._params()
| tensorflow.concat | 6,254 |
import tensorflow as tf
def read_and_decode(filename_queue):
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(
serialized_example,
# Defaults are not specified since both keys are required.
features={
'image_raw': tf.FixedLenFeature([], tf.string),
'label': tf.FixedLenFeature([], tf.int64),
})
if FLAGS.contrast_norm == 'areafactor':
image = tf.decode_raw(features['image_raw'], tf.float32)
else:
image = tf.decode_raw(features['image_raw'], tf.uint8)
image = tf.cast(image, tf.float32) * (1. / 255)
image.set_shape(np.prod([FLAGS.num_scales, FLAGS.crop_size, FLAGS.crop_size]))
image = tf.reshape(image, [FLAGS.num_scales, FLAGS.crop_size, FLAGS.crop_size, 1])
image = image - 0.5
# Convert label from a scalar uint8 tensor to an int32 scalar.
label = tf.cast(features['label'], tf.int32)
return image, label
def inputs(name, batch_size, num_epochs):
"""Reads input data num_epochs times.
| tensorflow.cast | 6,255 |
import tensorflow as tf
pct = tf.math.count_nonzero(loss, dtype=tf.float32) / tf.size(loss, out_type=tf.float32)
p = tf.cond(tf.random_uniform((), dtype=tf.float32) < 1e-4,
lambda: tf.print('csrt acc ', [pct]),
| tensorflow.random_uniform | 6,256 |
import tensorflow as tf
features_flat = tf.reshape(features, [-1, self.D])
features_proj = tf.matmul(features_flat, w)
features_proj = tf.reshape(features_proj, [-1, self.L, self.D])
return features_proj
def _attention_layer(self, features, features_proj, h, reuse=False):
with tf.variable_scope('attention_layer', reuse=reuse):
w = tf.get_variable('w', [self.H, self.D], initializer=self.weight_initializer)
b = tf.get_variable('b', [self.D], initializer=self.const_initializer)
w_att = tf.get_variable('w_att', [self.D, 1], initializer=self.weight_initializer)
h_att = tf.nn.relu(features_proj + tf.expand_dims(tf.matmul(h, w), 1) + b) # (N, L, D)
out_att = tf.reshape(tf.matmul(tf.reshape(h_att, [-1, self.D]), w_att), [-1, self.L]) # (N, L)
alpha = tf.nn.softmax(out_att)
context = tf.reduce_sum(features * tf.expand_dims(alpha, 2), 1, name='context') #(N, D)
return context, alpha
| tensorflow.get_variable | 6,257 |
import tensorflow as tf
tmp2 = tf.tensordot(query, w2, axes=1)
tmp2 = tf.reshape(tmp2, [-1, 1, tf.shape(tmp2)[-1]])
tmp = tf.tanh((tmp1 + tmp2) + b)
| tensorflow.tanh | 6,258 |
import tensorflow as tf
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)
| tensorflow.layers.dense | 6,259 |
import tensorflow as tf
# Restores from checkpoint.
new_saver.restore(sess, saver0_ckpt)
# Addes loss and train.
labels = tf.constant(0, tf.int32, shape=[100], name="labels")
batch_size = tf.size(labels)
labels = tf.expand_dims(labels, 1)
indices = tf.expand_dims(tf.range(0, batch_size), 1)
concated = tf.concat(1, [indices, labels])
onehot_labels = tf.sparse_to_dense(
concated, tf.pack([batch_size, 10]), 1.0, 0.0)
logits = tf.get_collection("logits")[0]
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits,
onehot_labels,
name="xentropy")
loss = tf.reduce_mean(cross_entropy, name="xentropy_mean")
tf.scalar_summary(loss.op.name, loss)
# Creates the gradient descent optimizer with the given learning rate.
optimizer = tf.train.GradientDescentOptimizer(0.01)
| tensorflow.get_collection | 6,260 |
import tensorflow as tf
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]
return top_antecedents, top_antecedents_mask, top_fast_antecedent_scores, top_antecedent_offsets
def get_predictions_and_loss(self, tokens, context_word_emb, head_word_emb, lm_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids):
self.dropout = self.get_dropout(self.config["dropout_rate"], is_training)
self.lexical_dropout = self.get_dropout(self.config["lexical_dropout_rate"], is_training)
self.lstm_dropout = self.get_dropout(self.config["lstm_dropout_rate"], is_training)
num_sentences = tf.shape(context_word_emb)[0]
max_sentence_length = tf.shape(context_word_emb)[1]
context_emb_list = [context_word_emb]
head_emb_list = [head_word_emb]
if self.config["char_embedding_size"] > 0:
char_emb = tf.gather(tf.get_variable("char_embeddings", [len(self.char_dict), self.config["char_embedding_size"]]), char_index) # [num_sentences, max_sentence_length, max_word_length, emb]
flattened_char_emb = tf.reshape(char_emb, [num_sentences * max_sentence_length, util.shape(char_emb, 2), util.shape(char_emb, 3)]) # [num_sentences * max_sentence_length, max_word_length, emb]
flattened_aggregated_char_emb = util.cnn(flattened_char_emb, self.config["filter_widths"], self.config["filter_size"]) # [num_sentences * max_sentence_length, emb]
| tensorflow.shape | 6,261 |
import tensorflow as tf
if mode == tf.estimator.ModeKeys.TRAIN:
train_op = optimization.create_optimizer(
total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
train_op=train_op,
scaffold_fn=scaffold_fn)
elif mode == tf.estimator.ModeKeys.EVAL:
def metric_fn(per_example_loss, label_ids, logits, is_real_example):
predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)
accuracy = tf.metrics.accuracy(
labels=label_ids, predictions=predictions, weights=is_real_example)
loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example)
return {
"eval_accuracy": accuracy,
"eval_loss": loss,
}
eval_metrics = (metric_fn,
[per_example_loss, label_ids, logits, is_real_example])
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
| tensorflow.argmax | 6,262 |
import tensorflow as tf
# Get the binary representation
num_bits = int(self.hparams.z_size // self.hparams.num_blocks)
x_means_bits = self.int_to_bit(x_means_idx, num_bits=num_bits, base=2)
x_discrete = self.bit_to_int(
tf.to_int32(x_means_bits), num_bits=self.hparams.z_size, base=2)
# Reshape x_discrete
shape_x = common_layers.shape_list(x)
| tensorflow.to_int32 | 6,263 |
import tensorflow as tf
* images is a float tensor with shape [batch_size, FLAGS.num_scales, FLAGS.crop_size, FLAGS.crop_size]
* labels is an int32 tensor with shape [batch_size] with the true label,
a number in the range [0, NUM_CLASSES()).
Note that an tf.train.QueueRunner is added to the graph, which
must be run using e.g. tf.train.start_queue_runners().
"""
if not num_epochs: num_epochs = None
filename = os.path.join(FLAGS.train_dir, 'data',
'{}_{}.tfrecords'.format(name, records.tfrecord_name()))
with tf.name_scope('input'):
filename_queue = tf.train.string_input_producer(
[filename], num_epochs=num_epochs)
# Even when reading in multiple threads, share the filename
# queue.
image, label = read_and_decode(filename_queue)
# Shuffle the examples and collect them into batch_size batches.
# (Internally uses a RandomShuffleQueue.)
# We run this in two threads to avoid being a bottleneck.
images, sparse_labels = tf.train.shuffle_batch(
| tensorflow.train.string_input_producer | 6,264 |
import tensorflow as tf
cols[0] / width,
cols[3] / height,
cols[2] / width], axis=1)
# add batch dimension (assume batch_size==1)
#assert image.get_shape()[0] == 1
boxes = tf.expand_dims(boxes, dim=0)
image = tf.image.draw_bounding_boxes(image, boxes) # 在image上画gt_truth
return tf.summary.image('ground_truth', image)
| tensorflow.expand_dims | 6,265 |
import tensorflow as tf
block_ct_res_tile = tf.tile(tf.expand_dims(block_ct_res, 2), [1, 1, bl, 1])#[bs,bn,vec]->[bs,bn,bl,vec]
with tf.variable_scope('combination'):
# input:1.rep_map[bs,bn,bl,vec]; 2.self_attn_result[bs,bn,bl,vec]; 3.rnn_res_tile[bs,bn,bl,vec]
rep_tensor_with_ct = tf.concat([rep_map, self_attn_result, block_ct_res_tile], -1) # [bs,bn,bl,3vec]
new_context_and_gate = linear(rep_tensor_with_ct, 2 * ivec, True, 0., 'linear_new_context_and_gate',
False, wd, keep_prob, is_train) # [bs,bn,bl,2vec]
new_context, gate = tf.split(new_context_and_gate, 2, 3) # bs,bn,bl,vec
if activation == "relu":
new_context_act = tf.nn.relu(new_context)
elif activation == "elu":
new_context_act = tf.nn.elu(new_context)
elif activation == "linear":
new_context_act = tf.identity(new_context)
else:
raise RuntimeError
gate_sig = tf.nn.sigmoid(gate)
combination_res = gate_sig * new_context_act + (1 - gate_sig) * rep_map # bs,bn,bl,vec
| tensorflow.nn.relu | 6,266 |
import tensorflow as tf
conv1_bn = tf.nn.relu(tf.layers.batch_normalization(conv1, training=train))
pool1 = tf.layers.max_pooling2d(
| tensorflow.layers.max_pooling2d | 6,267 |
import tensorflow as tf
embedding_output = modeling.embedding_postprocessor(
input_tensor=word_embedding_output,
use_token_type=True,
token_type_ids=segment_ids,
token_type_vocab_size=config.type_vocab_size,
token_type_embedding_name="token_type_embeddings",
use_position_embeddings=True,
position_embedding_name="position_embeddings",
initializer_range=config.initializer_range,
max_position_embeddings=config.max_position_embeddings,
dropout_prob=config.hidden_dropout_prob)
with tf.variable_scope("bilstm"):
sequence_output = modeling.bilstm_fused(
inputs=embedding_output,
sequence_lengths=_true_length,
lstm_size=config.lstm_size,
bilstm_dropout_rate=config.bilstm_dropout_rate,
is_training=is_training,
num_layers=config.num_bilstm)
# with tf.variable_scope("bilstm"):
# sequence_output, _ = modeling.cudnn_rnn(
# inputs=embedding_output,
| tensorflow.variable_scope | 6,268 |
import tensorflow as tf
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)
| tensorflow.cond | 6,269 |
import tensorflow as tf
l = tf.cast(l, dtype=var_type)
m = tf.cast(m, dtype=var_type)
numerator = (2.0 * l + 1.0) * factorial(l - tf.abs(m))
denominator = 4.0 * np.pi * factorial(l + tf.abs(m))
return tf.sqrt(numerator / denominator)
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,
| tensorflow.constant | 6,270 |
import tensorflow as tf
if FLAGS.num_gpus > 1:
soft_placement = True
util.auto_parallel(metagraph, m)
with tf.Graph().as_default():
tf.train.import_meta_graph(metagraph)
for model in models.values():
model.import_ops()
sv = tf.train.Supervisor(logdir=FLAGS.save_path)
config_proto = tf.ConfigProto(allow_soft_placement=soft_placement)
with sv.managed_session(config=config_proto) as session:
for i in range(config.max_max_epoch):
lr_decay = config.lr_decay ** max(i + 1 - config.max_epoch, 0.0)
m.assign_lr(session, config.learning_rate * lr_decay)
print("Epoch: %d Learning rate: %.3f" % (i + 1, session.run(m.lr)))
| tensorflow.train.Supervisor | 6,271 |
import tensorflow as tf
n_valid = len(vaY)
n_batch_train = n_batch*n_gpu
n_updates_total = (n_train//n_batch_train)*n_iter
X_train = tf.placeholder(tf.int32, [n_batch_train, 2, n_ctx, 2])
M_train = tf.placeholder(tf.float32, [n_batch_train, 2, n_ctx])
X = tf.placeholder(tf.int32, [None, 2, n_ctx, 2])
M = tf.placeholder(tf.float32, [None, 2, n_ctx])
Y_train = tf.placeholder(tf.int32, [n_batch_train])
Y = tf.placeholder(tf.int32, [None])
train, logits, clf_losses, lm_losses = mgpu_train(X_train, M_train, Y_train)
clf_loss = tf.reduce_mean(clf_losses)
| tensorflow.placeholder | 6,272 |
from tensorflow.python.framework import ops
ops.RegisterShape("Ceil")(common_shapes.unchanged_shape)
ops.RegisterShape("Conj")(common_shapes.unchanged_shape)
ops.RegisterShape("Cos")(common_shapes.unchanged_shape)
ops.RegisterShape("Exp")(common_shapes.unchanged_shape)
ops.RegisterShape("Floor")(common_shapes.unchanged_shape)
ops.RegisterShape("Imag")(common_shapes.unchanged_shape)
ops.RegisterShape("Inv")(common_shapes.unchanged_shape)
ops.RegisterShape("IsFinite")(common_shapes.unchanged_shape)
ops.RegisterShape("IsInf")(common_shapes.unchanged_shape)
ops.RegisterShape("IsNan")(common_shapes.unchanged_shape)
ops.RegisterShape("Log")(common_shapes.unchanged_shape)
ops.RegisterShape("LogicalNot")(common_shapes.unchanged_shape)
ops.RegisterShape("Neg")(common_shapes.unchanged_shape)
ops.RegisterShape("Real")(common_shapes.unchanged_shape)
ops.RegisterShape("Rsqrt")(common_shapes.unchanged_shape)
ops.RegisterShape("Sign")(common_shapes.unchanged_shape)
ops.RegisterShape("Sin")(common_shapes.unchanged_shape)
ops.RegisterShape("Sqrt")(common_shapes.unchanged_shape)
ops.RegisterShape("Square")(common_shapes.unchanged_shape)
ops.RegisterShape("Sigmoid")(common_shapes.unchanged_shape)
ops.RegisterShape("Tanh")(common_shapes.unchanged_shape)
ops.RegisterShape("Cast")(common_shapes.unchanged_shape)
ops.RegisterShape("ComplexAbs")(common_shapes.unchanged_shape)
@ops.RegisterShape("Add")
| tensorflow.python.framework.ops.RegisterShape | 6,273 |
import tensorflow as tf
w_z0_y0_x0 = tf.expand_dims(((x1_f - x) * (y1_f - y) *
(z1_f - z) * x1_valid * y1_valid * z1_valid),
1)
w_z0_y0_x1 = tf.expand_dims(((x - x0_f) * (y1_f - y) *
(z1_f - z) * x0_valid * y1_valid * z1_valid),
1)
w_z0_y1_x0 = tf.expand_dims(((x1_f - x) * (y - y0_f) *
(z1_f - z) * x1_valid * y0_valid * z1_valid),
1)
w_z0_y1_x1 = tf.expand_dims(((x - x0_f) * (y - y0_f) *
(z1_f - z) * x0_valid * y0_valid * z1_valid),
1)
w_z1_y0_x0 = tf.expand_dims(((x1_f - x) * (y1_f - y) *
(z - z0_f) * x1_valid * y1_valid * z0_valid),
1)
w_z1_y0_x1 = tf.expand_dims(((x - x0_f) * (y1_f - y) *
(z - z0_f) * x0_valid * y1_valid * z0_valid),
1)
w_z1_y1_x0 = tf.expand_dims(((x1_f - x) * (y - y0_f) *
(z - z0_f) * x1_valid * y0_valid * z0_valid),
1)
w_z1_y1_x1 = tf.expand_dims(((x - x0_f) * (y - y0_f) *
(z - z0_f) * x0_valid * y0_valid * z0_valid),
1)
| tensorflow.expand_dims | 6,274 |
import tensorflow as tf
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)
# pred1, pred2 = tf.split(horizon_pred, 2, axis=0)
| tensorflow.where | 6,275 |
import tensorflow as tf
})
return model_outputs
if params['use_bfloat16']:
with tf.contrib.tpu.bfloat16_scope():
model_outputs = _model_outputs()
def cast_outputs_to_float(d):
for k, v in sorted(six.iteritems(d)):
| tensorflow.contrib.tpu.bfloat16_scope | 6,276 |
import tensorflow as tf
"input_ids":
tf.constant(
all_input_ids, shape=[num_examples, seq_length],
dtype=tf.int32),
"input_mask":
tf.constant(
all_input_mask,
shape=[num_examples, seq_length],
dtype=tf.int32),
"segment_ids":
tf.constant(
all_segment_ids,
shape=[num_examples, seq_length],
dtype=tf.int32),
"label_ids":
tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32),
})
if is_training:
d = d.repeat()
| tensorflow.constant | 6,277 |
import tensorflow as tf
# Embedding matrices for entities and relationship types
head_init = tf.truncated_normal([head_cnt, self.embedding_size], stddev=init_sd)
rel_init = tf.truncated_normal([rel_cnt, self.embedding_size], stddev=init_sd)
tail_init = tf.truncated_normal([tail_cnt, self.embedding_size], stddev=init_sd)
if self.maxnorm is not None:
# Ensure maxnorm constraints are initially satisfied
head_init = dense_maxnorm(head_init, self.maxnorm)
rel_init = dense_maxnorm(rel_init, self.maxnorm)
tail_init = dense_maxnorm(tail_init, self.maxnorm)
self.head_embedding_vars = tf.Variable(head_init)
self.rel_embedding_vars = tf.Variable(rel_init)
self.tail_embedding_vars = tf.Variable(tail_init)
# Embedding layer for each (head, rel, tail) triple being fed in as input
head_embed = tf.nn.embedding_lookup(self.head_embedding_vars, self.head_input)
rel_embed = tf.nn.embedding_lookup(self.rel_embedding_vars, self.rel_input)
tail_embed = tf.nn.embedding_lookup(self.tail_embedding_vars, self.tail_input)
# Model output
raw_output = tf.reduce_sum(tf.mul(tf.mul(head_embed, rel_embed), tail_embed), 1)
| tensorflow.Variable | 6,278 |
import tensorflow as tf
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.)
| tensorflow.cast | 6,279 |
from tensorflow.python.ops import math_ops
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)
class_metrics = {}
proba_metrics = {}
for name, metric_op in six.iteritems(metrics):
if isinstance(name, tuple):
if len(name) != 2:
raise ValueError("Ignoring metric {}. It returned a tuple with "
"len {}, expected 2.".format(name, len(name)))
else:
if name[1] not in ["classes", "probabilities"]:
| tensorflow.python.ops.math_ops.to_float | 6,280 |
import tensorflow as tf
# define path to save the embeddings
dirs = ["./emb/embeddings_AVspeech/"]
for d in dirs:
if not os.path.exists(d):
os.makedirs(d)
print("Folder created:", d)
with tf.Graph().as_default():
with tf.Session() as sess:
# Load the model
facenet.load_model(args.model_dir)
# Get input and output tensors
| tensorflow.Graph | 6,281 |
import tensorflow as tf
best_target_per_prior = tf.math.reduce_max(ious, axis=1)
best_target_per_prior_index = tf.math.argmax(ious, axis=1)
# size: num_targets
best_prior_per_target = tf.math.reduce_max(ious, axis=0)
best_prior_per_target_index = tf.math.argmax(ious, axis=0)
targets = tf.range(tf.shape(best_prior_per_target_index)[0], dtype='int64')
best_target_per_prior_index = tf.tensor_scatter_nd_update(best_target_per_prior_index, tf.expand_dims(best_prior_per_target_index, 1), targets)
# 2.0 is used to make sure every target has a prior assigned
best_target_per_prior = tf.tensor_scatter_nd_update(best_target_per_prior, tf.expand_dims(best_prior_per_target_index, 1), tf.ones_like(best_prior_per_target_index, dtype=tf.float32)*2.0)
# size: num_priors
| tensorflow.shape | 6,282 |
import tensorflow as tf
[1, 1, 0, 0, 0, 0, 0, 0],
[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())
| tensorflow.stack | 6,283 |
import tensorflow as tf
pass
else:
tf.set_random_seed(i)
np.random.seed(i)
| tensorflow.set_random_seed | 6,284 |
import tensorflow as tf
import vat
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('device', '/gpu:0', "device")
tf.app.flags.DEFINE_string('dataset', 'cifar10', "{cifar10, svhn}")
tf.app.flags.DEFINE_string('log_dir', "", "log_dir")
tf.app.flags.DEFINE_integer('seed', 1, "initial random seed")
tf.app.flags.DEFINE_bool('validation', False, "")
tf.app.flags.DEFINE_integer('batch_size', 32, "the number of examples in a batch")
tf.app.flags.DEFINE_integer('ul_batch_size', 128, "the number of unlabeled examples in a batch")
tf.app.flags.DEFINE_integer('eval_batch_size', 100, "the number of eval examples in a batch")
tf.app.flags.DEFINE_integer('eval_freq', 5, "")
tf.app.flags.DEFINE_integer('num_epochs', 120, "the number of epochs for training")
tf.app.flags.DEFINE_integer('epoch_decay_start', 80, "epoch of starting learning rate decay")
tf.app.flags.DEFINE_integer('num_iter_per_epoch', 400, "the number of updates per epoch")
tf.app.flags.DEFINE_float('learning_rate', 0.001, "initial leanring rate")
tf.app.flags.DEFINE_float('mom1', 0.9, "initial momentum rate")
tf.app.flags.DEFINE_float('mom2', 0.5, "momentum rate after epoch_decay_start")
tf.app.flags.DEFINE_string('method', 'vat', "{vat, vatent, baseline}")
| tensorflow.app.flags.DEFINE_integer | 6,285 |
import tensorflow as tf
layer_id, tf.matmul(next_h[-1], self.w_attn_1))
def _condition(layer_id, *args):
return tf.less(layer_id, self.num_cells + 2)
def _body(layer_id, inputs, prev_c, prev_h, anchors, anchors_w_1, arc_seq,
entropy, log_prob):
indices = tf.range(0, layer_id, dtype=tf.int32)
start_id = 4 * (layer_id - 2)
prev_layers = []
for i in range(2): # index_1, index_2
next_c, next_h = stack_lstm(inputs, prev_c, prev_h, self.w_lstm)
prev_c, prev_h = next_c, next_h
query = anchors_w_1.gather(indices)
| tensorflow.range | 6,286 |
import tensorflow as tf
"""
with tf.variable_scope(scope, reuse=reuse):
observations_ph = U.ensure_tf_input(make_obs_ph("observation"))
stochastic_ph = tf.placeholder(tf.bool, (), name="stochastic")
update_eps_ph = tf.placeholder(tf.float32, (), name="update_eps")
eps = tf.get_variable("eps", (), initializer=tf.constant_initializer(0.0))
| tensorflow.placeholder | 6,287 |
from tensorflow.python.ops import array_ops
else:
loss_vec = nn.sparse_softmax_cross_entropy_with_logits(
logits, array_ops.reshape(target, [-1]))
if weight_tensor is None:
return math_ops.reduce_mean(loss_vec, name="loss")
else:
loss_vec = array_ops.reshape(loss_vec, shape=(-1,))
loss_vec = math_ops.mul(
loss_vec, array_ops.reshape(weight_tensor, shape=(-1,)))
return math_ops.div(
math_ops.reduce_sum(loss_vec),
math_ops.to_float(math_ops.reduce_sum(weight_tensor)),
name="loss")
| tensorflow.python.ops.array_ops.reshape | 6,288 |
from tensorflow.python.framework import ops
value: A `Tensor` with type `float`, `double`, `int64`, `int32`, `uint8`,
`int16`, `int8`, or `complex64`.
bias: A 1-D `Tensor` with size matching the last dimension of `value`.
Must be the same type as `value` unless `value` is a quantized type,
in which case a different quantized type may be used.
name: A name for the operation (optional).
Returns:
A `Tensor` with the same type as `value`.
"""
with ops.op_scope([value, bias], name, "BiasAddV1") as name:
value = ops.convert_to_tensor(value, name="input")
bias = ops.convert_to_tensor(bias, dtype=value.dtype, name="bias")
return gen_nn_ops._bias_add_v1(value, bias, name=name)
ops.RegisterShape("BiasAddV1")(common_shapes.bias_add_shape)
ops.RegisterShape("BiasAddGradV1")(common_shapes.bias_add_grad_shape)
def relu6(features, name=None):
| tensorflow.python.framework.ops.convert_to_tensor | 6,289 |
import tensorflow as tf
def load_and_align_data(image_paths, image_size, margin, gpu_memory_fraction):
print('Creating networks and loading parameters')
with tf.Graph().as_default():
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
with sess.as_default():
pnet, rnet, onet = align.detect_face.create_mtcnn(sess, None)
| tensorflow.Graph | 6,290 |
import tensorflow as tf
def mgpu_predict(*xs):
gpu_ops = []
xs = (tf.split(x, n_gpu, 0) for x in xs)
for i, xs in enumerate(zip(*xs)):
with tf.device(assign_to_gpu(i, "/gpu:0")), tf.variable_scope(tf.get_variable_scope(), reuse=True):
clf_logits, clf_losses, lm_losses = model(*xs, train=False, reuse=True)
gpu_ops.append([clf_logits, clf_losses, lm_losses])
ops = [tf.concat(op, 0) for op in zip(*gpu_ops)]
return ops
| tensorflow.get_variable_scope | 6,291 |
import tensorflow as tf
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))
return NetworkOutput(policy, value, lambda a: tf.clip_by_value(a, -2., 2))
| tensorflow.layers.dense | 6,292 |
import tensorflow as tf
with tf.name_scope(name):
| tensorflow.name_scope | 6,293 |
import tensorflow as tf
def get_weight_initializer(params):
initializer = []
scope = tf.get_variable_scope()
scope.reuse_variables()
for layer, value in params.items():
op = tf.get_variable('%s' % layer).assign(value)
initializer.append(op)
| tensorflow.get_variable_scope | 6,294 |
from tensorflow.python.ops import gen_math_ops
x = ops.convert_to_tensor(x, name="x")
return gen_math_ops._sigmoid(x, name=name)
| tensorflow.python.ops.gen_math_ops._sigmoid | 6,295 |
import tensorflow as tf
def get_width_upright(bboxes):
with tf.name_scope('BoundingBoxTransform/get_width_upright'):
bboxes = tf.cast(bboxes, tf.float32)
x1, y1, x2, y2 = tf.split(bboxes, 4, axis=1)
width = x2 - x1 + 1.
height = y2 - y1 + 1.
| tensorflow.cast | 6,296 |
import tensorflow as tf
"""
return tf.variable_scope('resnet_model',
custom_getter=self._custom_dtype_getter)
| tensorflow.variable_scope | 6,297 |
from tensorflow.python.framework import ops
event_start = array_ops.where(
self._batch_ndims_is_0, 2, 1 + self.batch_ndims)
event_shape = array_ops.slice(s, (event_start,), (self.event_ndims,))
new_shape = array_ops.concat(0, (sample_shape, batch_shape, event_shape))
x = array_ops.reshape(x, shape=new_shape)
return x
@contextlib.contextmanager
def _name_scope(self, name=None, values=None):
"""Helper function to standardize op scope."""
with ops.name_scope(self.name):
with ops.name_scope(name, values=(
(values or []) + [self.batch_ndims, self.event_ndims])) as scope:
yield scope
def _is_all_constant_helper(self, *args):
"""Helper which returns True if all inputs are constant_value."""
return all(tensor_util.constant_value(x) is not None for x in args)
def _assert_non_negative_int32_scalar(self, x):
| tensorflow.python.framework.ops.name_scope | 6,298 |
import tensorflow as tf
reinforce_weights = get_weights(samples, utils.EOS_ID, include_first_eos=True)
reinforce_loss = sequence_loss(logits=outputs, targets=samples, weights=reinforce_weights,
rewards=baseline_rewards)
trg_mask = get_weights(targets[:, 1:], utils.EOS_ID, include_first_eos=True)
xent_loss = sequence_loss(logits=outputs, targets=targets[:, 1:], weights=trg_mask)
if monotonicity_weight:
monotonicity_dist = monotonicity_dist or 1.0
batch_size = tf.shape(attention_weights)[0]
src_len = tf.shape(attention_weights)[2]
trg_len = tf.shape(attention_weights)[1]
src_indices = tf.tile(tf.reshape(tf.range(src_len), shape=[1, 1, src_len]), [batch_size, trg_len, 1])
trg_indices = tf.tile(tf.reshape(tf.range(trg_len), shape=[1, trg_len, 1]), [batch_size, 1, src_len])
source_length = encoder_input_length[0]
target_length = tf.to_int32(tf.reduce_sum(trg_mask, axis=1))
true_src_len = tf.reshape(source_length, shape=[batch_size, 1, 1]) - 1
true_trg_len = tf.reshape(target_length, shape=[batch_size, 1, 1]) - 1
src_mask = tf.to_float(tf.sequence_mask(source_length, maxlen=src_len))
mask = tf.matmul(tf.expand_dims(trg_mask, axis=2), tf.expand_dims(src_mask, axis=1))
| tensorflow.shape | 6,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.