seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
import tensorflow as tf
y1_valid = tf.to_float(
tf.less_equal(y1, max_y) & tf.greater_equal(y1, 0))
z0_valid = tf.to_float(
tf.less_equal(z0, max_z) & tf.greater_equal(z0, 0))
z1_valid = tf.to_float(
tf.less_equal(z1, max_z) & tf.greater_equal(z1, 0))
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) *
| tensorflow.expand_dims | 500 |
import tensorflow as tf
'conv17', conv16, filters=512, size=1, stride=1, bn=self.BN, act='lrelu')
conv18 = self._conv_layer(
'conv18', conv17, filters=1024, size=3, stride=1, bn=self.BN, act='lrelu')
with tf.variable_scope('detector') as scope:
conv19 = self._conv_layer(
'conv19', conv18, filters=1024, size=3, stride=1, bn=self.BN, act='lrelu')
conv20 = self._conv_layer(
| tensorflow.variable_scope | 501 |
import tensorflow as tf
W_deps = tf.get_variable("embed_W_deps", [deps_vocab_size, embedding_size], initializer=initializer)
embedded_deps = tf.nn.embedding_lookup(W_deps, self.input_deps)
| tensorflow.nn.embedding_lookup | 502 |
import tensorflow as tf
import layers
import networks
def _get_grad_norm(ys, xs):
"""Compute 2-norm of dys / dxs."""
return tf.sqrt(
tf.add_n([tf.reduce_sum(tf.square(g)) for g in tf.gradients(ys, xs)]))
def _num_filters_stub(block_id):
return networks.num_filters(block_id, 8, 1, 8)
class NetworksTest(tf.test.TestCase):
| tensorflow.gradients | 503 |
from tensorflow.python.framework import ops
array_ops.zeros([self._target_column.num_label_columns]),
collections=[self._centered_bias_weight_collection,
ops.GraphKeys.VARIABLES],
name="centered_bias_weight")
logging_ops.scalar_summary(
["centered_bias_%d" % cb for cb in range(
self._target_column.num_label_columns)],
array_ops.reshape(centered_bias, [-1]))
return centered_bias
def _centered_bias_step(self, targets, features):
centered_bias = ops.get_collection(self._centered_bias_weight_collection)
batch_size = array_ops.shape(targets)[0]
logits = array_ops.reshape(
array_ops.tile(centered_bias[0], [batch_size]),
[batch_size, self._target_column.num_label_columns])
loss = self._target_column.loss(logits, targets, features)
# Learn central bias by an optimizer. 0.1 is a convervative lr for a single
# variable.
return training.AdagradOptimizer(0.1).minimize(loss, var_list=centered_bias)
def _logits(self, features, is_training=False):
| tensorflow.python.framework.ops.get_collection | 504 |
import tensorflow as tf
id_to_char = tf.contrib.lookup.index_to_string_table_from_tensor(chars, " ")
return char_to_id, id_to_char
def characters(filename, batch_size, sequence_size):
"""Returns a dataset of characters from the given file."""
def _to_chars(line):
"""string scalar -> Dataset of characters (string scalars)."""
chars, = tf.py_func(_split_string, [line + "\n"], [tf.string])
chars.set_shape([None])
return tf.data.Dataset.from_tensor_slices(chars)
return (tf.data.TextLineDataset([filename])
.flat_map(_to_chars)
.repeat()
.batch(tf.to_int64(sequence_size))
.shuffle(1000)
.batch(tf.to_int64(batch_size)))
| tensorflow.data.TextLineDataset | 505 |
import tensorflow as tf
conv(self._attention(tf.concat([self.enc[1], self.enc[2]], axis=-1), name="attn1"), 1, bias=False,
name="start_pointer"), -1)
end_logits = tf.squeeze(
conv(self._attention(tf.concat([self.enc[1], self.enc[3]], axis=-1), name="attn2"), 1, bias=False,
name="end_pointer"), -1)
else:
start_logits = tf.squeeze(
conv(tf.concat([self.enc[1], self.enc[2]], axis=-1), 1, bias=False, name="start_pointer"), -1)
end_logits = tf.squeeze(
conv(tf.concat([self.enc[1], self.enc[3]], axis=-1), 1, bias=False, name="end_pointer"), -1)
self.logits = [mask_logits(start_logits, mask=tf.reshape(self.c_mask, [N, -1])),
mask_logits(end_logits, mask=tf.reshape(self.c_mask, [N, -1]))]
self.logits1, self.logits2 = [l for l in self.logits]
outer = tf.matmul(tf.expand_dims(tf.nn.softmax(self.logits1), axis=2),
tf.expand_dims(tf.nn.softmax(self.logits2), axis=1))
| tensorflow.concat | 506 |
from tensorflow.contrib.rnn.python.ops.core_rnn_cell import _Linear
@property
def output_size(self):
return self._num_units
def __call__(self, inputs, state, att_score):
return self.call(inputs, state, att_score)
def call(self, inputs, state, att_score=None):
"""Gated recurrent unit (GRU) with nunits cells."""
if self._gate_linear is None:
bias_ones = self._bias_initializer
if self._bias_initializer is None:
bias_ones = init_ops.constant_initializer(1.0, dtype=inputs.dtype)
with vs.variable_scope("gates"): # Reset gate and update gate.
self._gate_linear = _Linear(
[inputs, state],
2 * self._num_units,
True,
bias_initializer=bias_ones,
kernel_initializer=self._kernel_initializer)
value = math_ops.sigmoid(self._gate_linear([inputs, state]))
r, u = array_ops.split(value=value, num_or_size_splits=2, axis=1)
r_state = r * state
if self._candidate_linear is None:
with vs.variable_scope("candidate"):
self._candidate_linear = _Linear(
[inputs, r_state],
| tensorflow.contrib.rnn.python.ops.core_rnn_cell._Linear | 507 |
import tensorflow as tf
def __init__(self, is_training, config, input_):
self._is_training = is_training
self._input = input_
self._rnn_params = None
self._cell = None
self.batch_size = input_.batch_size
self.num_steps = input_.num_steps
size = config.hidden_size
vocab_size = config.vocab_size
with tf.device("/cpu:0"):
embedding = tf.get_variable(
"embedding", [vocab_size, size], dtype=data_type())
inputs = tf.nn.embedding_lookup(embedding, input_.input_data)
if is_training and config.keep_prob < 1:
inputs = tf.nn.dropout(inputs, config.keep_prob)
output, state = self._build_rnn_graph(inputs, config, is_training)
| tensorflow.device | 508 |
import tensorflow as tf
class_true = tf.reshape(y_true[..., 15], [num_batch * num_prior, 1])
# define filter mask: class_true = 1 (pos), 0 (neg), -1 (ignore)
# landm_valid = 1 (w landm), 0 (w/o landm)
mask_pos = tf.equal(class_true, 1)
mask_neg = tf.equal(class_true, 0)
mask_landm = tf.logical_and(tf.equal(landm_valid, 1), mask_pos)
| tensorflow.equal | 509 |
import tensorflow as tf
constraint_tf[key] = (tf.constant(low, dtype=tf.float64),
tf.constant(high, dtype=tf.float64))
print("N.B.: using direct data entry")
likelihood = sum_pdf(data, nsig, sigmean, sigwidth, nbkg, m0, argpar, constraint_tf['mes'][0], constraint_tf['mes'][1])
nll = tf.neg(tf.reduce_sum(tf.log(likelihood)), name="nll")
variables = tf.all_variables()
grads = tf.gradients(nll, variables)
# ### build constraint inequalities
inequalities = []
for key, (lower, upper) in constraint_tf.iteritems():
if key != 'mes':
inequalities.append(vdict[key] - lower)
inequalities.append(upper - vdict[key])
# ### build bounds instead of inequalities (only for L-BFGS-B, TNC and SLSQP)
# N.B.: order important! Also supply variables to be sure the orders match.
| tensorflow.gradients | 510 |
import tensorflow as tf
for x in output
], axis=0)
return output
def process(policy, dataloader, top_k):
mean_kacc = np.zeros(len(top_k))
n_samples_processed = 0
for batch in dataloader:
if policy['type'] == 'gcnn':
c, ei, ev, v, n_cs, n_vs, n_cands, cands, best_cands, cand_scores = batch
pred_scores = policy['model']((c, ei, ev, v, tf.reduce_sum(n_cs, keepdims=True), tf.reduce_sum(n_vs, keepdims=True)), tf.convert_to_tensor(False))
# filter candidate variables
pred_scores = tf.expand_dims(tf.gather(tf.squeeze(pred_scores, 0), cands), 0)
elif policy['type'] == 'ml-competitor':
cand_feats, n_cands, best_cands, cand_scores = batch
# move to numpy
cand_feats = cand_feats.numpy()
n_cands = n_cands.numpy()
# feature normalization
cand_feats = (cand_feats - policy['feat_shift']) / policy['feat_scale']
| tensorflow.convert_to_tensor | 511 |
import tensorflow as tf
stddev=0.02, data_format='NDHWC') :
with tf.variable_scope(name) :
assert(data_format == 'NDHWC')
self.w = tf.get_variable('w', [k_t, k_h, k_w, input_dim, output_dim],
initializer=tf.truncated_normal_initializer(stddev=stddev))
self.b = tf.get_variable('b',[output_dim], initializer=tf.constant_initializer(0.0))
self.strides = [d_t,d_h,d_w]
def __call__(self,input_var,name=None,w=None,b=None,**kwargs) :
| tensorflow.truncated_normal_initializer | 512 |
import tensorflow as tf
features["label_ids"] = create_int_feature(feature.label_ids)
tf_example = tf.train.Example(features=tf.train.Features(feature=features))
writer.write(tf_example.SerializeToString())
def file_based_input_fn_builder(input_file, seq_length, is_training, drop_remainder):
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([seq_length], tf.int64),
}
def _decode_record(record, name_to_features):
example = tf.parse_single_example(record, name_to_features)
for name in list(example.keys()):
| tensorflow.FixedLenFeature | 513 |
import tensorflow as tf
def embed(X, we):
#X [-1,,2]
we = convert_gradient_to_tensor(we)
e = tf.gather(we, X)
h = tf.reduce_sum(e, 2)
return h
def clf(x, ny, w_init=tf.random_normal_initializer(stddev=0.02), b_init=tf.constant_initializer(0), train=False):
with tf.variable_scope('clf'):
nx = shape_list(x)[-1]
w = tf.get_variable("w", [nx, ny], initializer=w_init)
b = tf.get_variable("b", [ny], initializer=b_init)
return tf.matmul(x, w)+b
def model(X, M, Y, train=False, reuse=False):
with tf.variable_scope('model', reuse=reuse):
we = tf.get_variable("we", [n_vocab+n_special+n_ctx, n_embd], initializer=tf.random_normal_initializer(stddev=0.02))
we = dropout(we, embd_pdrop, train)
#X:[n_batch_train, 2, n_ctx, 2] -> [n_batch_train*2,n_ctx,2]
X = tf.reshape(X, [-1, n_ctx, 2])
M = tf.reshape(M, [-1, n_ctx])
| tensorflow.get_variable | 514 |
from tensorflow import ConfigProto
self._num_classes = num_classes
self._score_threshold = score_threshold
self._image_sz = image_sz[0:2]
self._config = ConfigProto()
self._config.gpu_options.allow_growth = True
self._graph = tf.Graph()
| tensorflow.ConfigProto | 515 |
import tensorflow as tf
def export_ops(self, name):
self._name = name
ops = {self.with_prefix(self._name, 'cost'): self._cost}
if self._is_training:
ops.update(lr=self._lr, new_lr=self._new_lr, lr_update=self._lr_update)
if self._rnn_params:
ops.update(rnn_params=self._rnn_params)
for name, op in ops.items():
tf.add_to_collection(name, op)
self._initial_state_name = self.with_prefix(self._name, 'initial')
self._final_state_name = self.with_prefix(self._name, 'final')
for state_tuple in self._initial_state:
tf.add_to_collection(self._initial_state_name, state_tuple.c)
tf.add_to_collection(self._initial_state_name, state_tuple.h)
for state_tuple in self._final_state:
tf.add_to_collection(self._final_state_name, state_tuple.c)
tf.add_to_collection(self._final_state_name, state_tuple.h)
def import_state_tuples(self, state_tuples, name, num_replicas):
restored = []
for i in range(len(state_tuples) * num_replicas):
c = tf.get_collection_ref(name)[2 * i + 0]
h = tf.get_collection_ref(name)[2 * i + 1]
| tensorflow.add_to_collection | 516 |
import tensorflow as tf
with tf.variable_scope('conditional_1'):
output, state = update(state, input_)
elif decoder.update_first:
output, state = update(state, input_, None, ids)
elif decoder.generate_first:
output, state = tf.cond(tf.equal(time, 0),
lambda: (output, state),
lambda: update(state, input_, context, ids))
context, new_weights = look(time, output, input_, pos=pos, prev_weights=prev_weights, context=context)
if decoder.conditional_rnn:
with tf.variable_scope('conditional_2'):
output, state = update(state, context)
elif not decoder.generate_first:
output, state = update(state, input_, context, ids)
logits = generate(output, input_, context)
pos = tf.expand_dims(pos, axis=1)
state = tf.concat([state, context, pos, new_weights], axis=1)
return state, logits
def _time_step(time, input_, input_symbol, pos, state, output, outputs, states, weights, attns, prev_weights,
| tensorflow.variable_scope | 517 |
from tensorflow.contrib.learn.python.learn.estimators import head as head_lib
config=config,
params={
"head":
head_lib._regression_head( # pylint: disable=protected-access
label_dimension=label_dimension,
weight_column_name=weight_column_name,
| tensorflow.contrib.learn.python.learn.estimators.head._regression_head | 518 |
import tensorflow as tf
# tgt2 = tf.slice(batch2, [0, 1], [num_sam, 1])
# loss = compute_contra_loss(pred1, pred2, tgt1, tgt2)
# print(loss)
# return loss
i = tf.constant(0)
loss = tf.constant(0.)
final_loss = tf.while_loop(lambda l, i: i < resample, sample_compute, [loss, i])[0]
# final_loss = tf.scan(sample_compute, tf.range(resample), loss)[-1]
# final_loss = tf.map_fn(fn=lambda inp: sample_compute(inp), elems= tf.range(resample), dtype=tf.float32, parallel_iterations=1)
# print('final', final_loss)
# final_loss = loss
| tensorflow.constant | 519 |
import tensorflow as tf
beta_list.append(beta)
with tf.variable_scope('lstm', reuse=(t!=0)):
_, (c, h) = lstm_cell(inputs=tf.concat(axis=1, values=[x, context]), state=[c, h])
logits = self._decode_lstm(x, h, context, reuse=(t!=0))
sampled_word = tf.argmax(logits, 1)
sampled_word_list.append(sampled_word)
alphas = tf.transpose(tf.stack(alpha_list), (1, 0, 2)) # (N, T, L)
betas = tf.transpose(tf.squeeze(beta_list), (1, 0)) # (N, T)
sampled_captions = tf.transpose(tf.stack(sampled_word_list), (1, 0)) # (N, max_len)
return alphas, betas, sampled_captions
| tensorflow.stack | 520 |
import tensorflow as tf
add=True,
transpose=transpose)
else:
y = sbnet_module.sparse_scatter(
q,
indices.bin_counts,
indices.active_block_indices,
x,
dynamic_bsize=tf.constant(block_params.bsize_out, dtype=tf.int32),
dynamic_bstride=tf.constant(block_params.bsize_out, dtype=tf.int32),
dynamic_boffset=tf.constant([0, 0], dtype=tf.int32),
add=True,
transpose=transpose)
return y
def sparse_conv2d_matmul(x, w, blk_indices, strides, padding):
"""
Performs 2D convolution using matrix multiplication on a sparse feature map.
Naive python implementation of sparse convolution using gather and scatter.
| tensorflow.constant | 521 |
import tensorflow as tf
self.n_steps = len(X_train[0]) # 128 time_steps per series
# Training
self.learning_rate = 0.0025
self.lambda_loss_amount = 0.0015
self.training_epochs = 300
self.batch_size = 1000
# LSTM structure
self.n_inputs = len(X_train[0][0]) # Features count is of 9: three 3D sensors features over time
self.n_hidden = N_HIDDEN_CONFIG # nb of neurons inside the neural network
self.n_classes = 6 # Final output classes
self.W = {
'hidden': tf.Variable(tf.random_normal([self.n_inputs, self.n_hidden])), # [9, 32]
'output': tf.Variable(tf.random_normal([self.n_hidden, self.n_classes])) # [32, 6]
}
self.biases = {
'hidden': tf.Variable(tf.random_normal([self.n_hidden], mean=1.0)), # [32]
'output': tf.Variable(tf.random_normal([self.n_classes])) # [6]
}
config = Config(X_train, X_test)
# print("Some useful info to get an insight on dataset's shape and normalisation:")
# print("features shape, labels shape, each features mean, each features standard deviation")
# print(X_test.shape, y_test.shape,
# np.mean(X_test), np.std(X_test))
# print("the dataset is therefore properly normalised, as expected.")
#
| tensorflow.random_normal | 522 |
import tensorflow as tf
if not callable(else_expression):
def else_expression_fn():
return else_expression
else:
else_expression_fn = else_expression
x = tf.cond(condition, then_expression_fn, else_expression_fn)
return x
def normalize_batch_in_training(x, gamma, beta, reduction_axes, epsilon=1e-3):
"""Computes mean and std for batch then apply batch_normalization on batch.
| tensorflow.cond | 523 |
import tensorflow as tf
gtboxes_and_label_r = tf.reshape(gtboxes_and_label_r, [-1, 6])
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)
| tensorflow.cast | 524 |
import tensorflow as tf
with tf.control_dependencies(_maybe_validate_rightmost_transposed_ndims(
rightmost_transposed_ndims, validate_args)):
rightmost_transposed_ndims = tf.identity(rightmost_transposed_ndims)
perm = tf.range(
start=rightmost_transposed_ndims - 1,
limit=-1,
delta=-1,
name='perm')
else: # perm is not None:
perm = tf.convert_to_tensor(value=perm, dtype=np.int32, name='perm')
rightmost_transposed_ndims = tf.size(
input=perm, name='rightmost_transposed_ndims')
rightmost_transposed_ndims_ = tf.get_static_value(
rightmost_transposed_ndims)
with tf.control_dependencies(_maybe_validate_perm(perm, validate_args)):
perm = tf.identity(perm)
# TODO(b/110828604): If bijector base class ever supports dynamic
# `min_event_ndims`, then this class already works dynamically and the
# following five lines can be removed.
| tensorflow.size | 525 |
import tensorflow as tf
(gt_boxes_width, gt_boxes_height,
gt_boxes_urx, gt_boxes_ury) = get_width_upright(gt_boxes)
if variances is None:
variances = [1., 1.]
targets_dx = (gt_boxes_urx - bboxes_urx)/(bboxes_width * variances[0])
targets_dy = (gt_boxes_ury - bboxes_ury)/(bboxes_height * variances[0])
targets_dw = tf.log(gt_boxes_width / bboxes_width) / variances[1]
targets_dh = tf.log(gt_boxes_height / bboxes_height) / variances[1]
targets = tf.concat(
[targets_dx, targets_dy, targets_dw, targets_dh], axis=1)
return targets
def decode(roi, deltas, variances=None):
with tf.name_scope('BoundingBoxTransform/decode'):
| tensorflow.log | 526 |
import tensorflow as tf
n_bins = 2**n_bits
rgb_out = rgb
# discretization noise
if add_dequantization_noise:
shape = tf.shape(rgb_out)
rgb_out += tf.random_uniform(shape=shape)*(1/n_bins)
return rgb_out
| tensorflow.shape | 527 |
import tensorflow as tf
total_examples = tf.reduce_sum(tf.cast(final_mask, tf.float32))
# add mask for glabels and cls_pred here
glabels = tf.boolean_mask(tf.clip_by_value(glabels, 0, FLAGS.num_classes), tf.stop_gradient(final_mask))
cls_pred = tf.boolean_mask(cls_pred, tf.stop_gradient(final_mask))
location_pred = tf.boolean_mask(location_pred, tf.stop_gradient(positive_mask))
| tensorflow.clip_by_value | 528 |
import tensorflow as tf
end_loss = tf.nn.softmax_cross_entropy_with_logits(
logits=self.logits2, labels=end_label)
self.loss = tf.reduce_mean(start_loss + end_loss)
else:
start_loss = focal_loss(tf.nn.softmax(self.logits1, -1), start_label)
end_loss = focal_loss(tf.nn.softmax(self.logits2, -1), end_label)
self.loss = tf.reduce_mean(start_loss + end_loss)
self.logger.info("loss type %s" % self.config.loss_type)
self.all_params = tf.trainable_variables()
| tensorflow.nn.softmax | 529 |
import tensorflow as tf
if direction is None:
direct_mask_un = tf.not_equal(unhead_idxs, undep_idxs) # [bs, sluh, sld]
else:
if direction == 'forward':
direct_mask_un = tf.greater(unhead_idxs, undep_idxs) # [bs, sluh, sld]
else:
direct_mask_un = tf.less(unhead_idxs, undep_idxs) # [bs, sluh, sld]
# [bs, sluh, sld]
rep_mask_tile_un = tf.logical_and(tf.expand_dims(rep_dep_mask, 1), tf.expand_dims(rep_unhead_mask, 2))
pooling_mask = tf.logical_and(direct_mask_un, rep_mask_tile_un) # [bs, sluh, sld]
# data for pooling
pooling_data = tf.tile(tf.expand_dims(rep_dep_tensor, 1), [1, sl_unhead, 1, 1]) # bs,sluh,sld,hn
# execute mean pooling based on pooling_mask[bs, sluh, sld] and pooling_data[bs,sluh,sld,hn]
pooling_data = mask_for_high_rank(pooling_data, pooling_mask) # [bs,sluh,sld,hn]
pooling_data_sum = tf.reduce_sum(pooling_data, -2) # [bs,sluh,hn]
pooling_den = tf.reduce_sum(tf.cast(pooling_mask, tf.int32), -1, keep_dims=True) # [bs,sluh]
pooling_den = tf.where(tf.equal(pooling_den, 0), tf.ones_like(pooling_den), pooling_den)
pooling_result = pooling_data_sum / tf.cast(pooling_den, tf.float32)
return pooling_result
def scaled_tanh(x, scale=5.):
return scale * tf.nn.tanh(1./scale * x) | tensorflow.expand_dims | 530 |
import tensorflow as tf
# Reshape patches.
p = tf.reshape(p, [blk_shape[0], blk_shape[1], blk_shape[2], -1])
# Convolution on patches.
q = tf.nn.conv2d(p, w, strides, 'VALID', use_cudnn_on_gpu=True)
# Paste convolution results.
q_shape = tf.shape(q)
def _strides_gt_one():
# Calculate output indices when strides > 1.
blk_indices_crop = tf.strided_slice(blk_indices, [0, 0, 0, 0], [
blk_shape[0], q_shape[1] * strides[1], q_shape[2] * strides[2], 3
], strides)
blk_indices_crop = blk_indices_crop // tf.stack([1, strides[1], strides[2]])
return blk_indices_crop
def _strides_one():
# Calculate otuput indices when strides = 1.
return blk_indices[:, :q_shape[1], :q_shape[2], :]
strides_gt_one = tf.logical_or(tf.greater(strides[1], 1), tf.greater(strides[2], 1))
| tensorflow.strided_slice | 531 |
import tensorflow as tf
return scale * tf.nn.tanh(1. / scale * x)
bs, sl, vec = tf.shape(rep_tensor)[0], tf.shape(rep_tensor)[1], tf.shape(rep_tensor)[2]
ivec = hn or rep_tensor.get_shape().as_list()[2]
input_dim = rep_tensor.get_shape().as_list()[2]
with tf.variable_scope(scope or 'block_simple'):
# @1. split sequence
with tf.variable_scope('split_seq'):
block_num = tf.cast(tf.ceil(tf.divide(tf.cast(sl, tf.float32), tf.cast(block_len, tf.float32))), tf.int32)
comp_len = block_num * block_len - sl
rep_tensor_comp = tf.concat([rep_tensor, tf.zeros([bs, comp_len, input_dim], tf.float32)], 1)
rep_mask_comp = tf.concat([rep_mask, tf.cast(tf.zeros([bs, comp_len], tf.int32), tf.bool)], 1)
rep_tensor_split = tf.reshape(rep_tensor_comp, [bs, block_num, block_len, input_dim]) # bs,bn,bl,d
rep_mask_split = tf.reshape(rep_mask_comp, [bs, block_num, block_len]) # bs,bn,bl
| tensorflow.cast | 532 |
import tensorflow as tf
# ============================================================================OUT
# print('VNET Out:', X.get_shape().as_list())
# if self.args.mode == 'adapt':
return X, X_EARLY, X_MIDDLE, X_LATE, prediction
# else:
# return X, prediction
def D_4(self, X, reuse):
def discrim_conv(name, X, out_channels, filtersize, stride=1, norm='', nonlin=True, init_stddev=-1):
with tf.variable_scope(name) as scope:
if init_stddev <= 0.0:
init = tf.contrib.layers.variance_scaling_initializer(dtype=tf.float32)
else:
init = tf.truncated_normal_initializer(stddev=init_stddev)
X = tf.layers.conv2d(X, out_channels, kernel_size=filtersize, strides=(stride, stride), padding="valid",
kernel_initializer=init)
if norm == 'I':
X = tf.contrib.layers.instance_norm(X, scope=scope, reuse=reuse, epsilon=0.001)
elif norm == 'B':
X = tf.layers.batch_normalization(X, reuse=reuse, training=True)
| tensorflow.variable_scope | 533 |
import tensorflow as tf
# add by wangxiao
# define the inputs of signature
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,
| tensorflow.placeholder | 534 |
import tensorflow as tf
return tf.reshape(tf.concat(axis=1, values=h), [-1, nh])
else:
return tf.reshape(tf.stack(values=h, axis=1), [-1])
| tensorflow.stack | 535 |
from tensorflow.python.framework import ops
return g.extra_inputs
else:
return []
def get_extra_args():
"""Returns the corresponding function arguments for the captured inputs.
Returns:
If the default graph is being used to define a function, the
returned list of place holders are those used inside the function
body corresponding those returned by get_extra_inputs(). Otherwise,
returns an empty list.
"""
g = ops.get_default_graph()
if isinstance(g, _FuncGraph):
return g.extra_args
else:
return []
class _DefinedFunction(object):
"""_DefinedFunction encapsulates a function definition and its properties.
Attributes:
name: The function name.
definition: The definition of this function. A FunctionDef proto.
grad_func_name: If not None, the name of this function's gradient function.
| tensorflow.python.framework.ops.get_default_graph | 536 |
import tensorflow as tf
with tf.control_dependencies([assert_op]):
barrier = tf.no_op(name)
| tensorflow.no_op | 537 |
import tensorflow as tf
tile_multiples.insert(index_c, 1)
weights = tf.tile(weights, tile_multiples)
| tensorflow.tile | 538 |
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 | 539 |
import tensorflow as tf
scores,
classes,
min_score_thresh=0.65,
min_iou_thresh=0.5,
is_class_agnostic=False)
nms_masks_expected2 = tf.constant(1.0, shape=[0, 2, 2], dtype=tf.float32)
nms_scores_expected2 = tf.constant([], dtype=tf.float32)
nms_classes_expected2 = tf.constant([], dtype=tf.int32)
self.assertAllEqual(nms_masks1.numpy(), nms_masks_expected1.numpy())
self.assertAllClose(nms_scores1.numpy(), nms_scores_expected1.numpy())
self.assertAllEqual(nms_classes1.numpy(), nms_classes_expected1.numpy())
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())
| tensorflow.constant | 540 |
import tensorflow as tf
def f(a, b):
batch_size = tf.shape(a)[0]
return a + b, tf.tile([batch_size], [batch_size])
output = f(tf.constant([[1, 3]]), tf.constant([2]))
tf.train.start_queue_runners()
| tensorflow.constant | 541 |
import tensorflow as tf
atten_hidden = tf.tanh(
tf.add(
tf.matmul(self.position_emb, W),
tf.matmul(output, U)))
alpha = tf.nn.softmax(
tf.reshape(tf.matmul(atten_hidden, V), [-1, shape[1], 1]), axis=1)
output = tf.reshape(output, [-1, shape[1], 2 * self.config.hidden_size])
C = tf.multiply(alpha, output)
return tf.concat([output, C], axis=-1)
def _train_epoch(self, train_batches, dropout):
"""
:param train_batches:
:param dropout:
:return:
| tensorflow.concat | 542 |
import tensorflow as tf
average_across_batch=True)
# Update the cost
self._cost = tf.reduce_sum(loss)
self._final_state = state
if not is_training:
return
self._lr = tf.Variable(0.0, trainable=False)
tvars = tf.trainable_variables()
grads, _ = tf.clip_by_global_norm(tf.gradients(self._cost, tvars),
config.max_grad_norm)
optimizer = tf.train.GradientDescentOptimizer(self._lr)
self._train_op = optimizer.apply_gradients(
zip(grads, tvars),
global_step=tf.train.get_or_create_global_step())
| tensorflow.Variable | 543 |
import tensorflow as tf
output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt")
with tf.gfile.GFile(output_eval_file, "w") as writer:
tf.logging.info("***** Eval results *****")
| tensorflow.gfile.GFile | 544 |
import tensorflow as tf
print((sess.run(custom_polynomial(tf, 11))))
alpha = 0.1
val = tf.constant([[2, 3], [1, 4]], dtype=tf.float32)
l1 = tf.contrib.layers.l1_regularizer(alpha)(val)
l2 = tf.contrib.layers.l2_regularizer(alpha)(val)
A = [[0.8, 0.6, 0.3], [0.1, 0.6, 0.4]]
B = [1, 1]
top_k = tf.nn.top_k(A, 2)
in_top_k = tf.nn.in_top_k(A, B, 1)
| tensorflow.contrib.layers.l2_regularizer | 545 |
import tensorflow as tf
save_pb_at_end = config.get("save_pb", 0)
))
# summary hook
if config["save_summaries"]:
save_steps_summaries = self._get_steps(config["save_summaries_period"], self._time_reference_str)
self.set_summaries()
summary_hooks = [tf.train.SummarySaverHook(save_steps=save_steps_summaries,
output_dir=self._tensorboard_dir+sn.name,
summary_op=sn,
summary_writer=fw)
for sk in self.summary_keys for sn,fw in zip(self.summary_nodes[sk], self.summary_writers[sk])]
hooks += summary_hooks
# images input hook
| tensorflow.train.SummarySaverHook | 546 |
import tensorflow as tf
# Host call fns are executed FLAGS.iterations_per_loop times after one
# TPU loop is finished, setting max_queue value to the same as number of
# iterations will make the summary writer only flush the data to storage
# once per loop.
with (tf.contrib.summary.create_file_writer(
params['model_dir'],
max_queue=params['iterations_per_loop']).as_default()):
with tf.contrib.summary.always_record_summaries():
tf.contrib.summary.scalar(
'total_loss', tf.reduce_mean(total_loss), step=global_step)
tf.contrib.summary.scalar(
'total_rpn_loss', tf.reduce_mean(total_rpn_loss),
step=global_step)
tf.contrib.summary.scalar(
'rpn_score_loss', tf.reduce_mean(rpn_score_loss),
step=global_step)
tf.contrib.summary.scalar(
'rpn_box_loss', tf.reduce_mean(rpn_box_loss), step=global_step)
tf.contrib.summary.scalar(
'total_fast_rcnn_loss', tf.reduce_mean(total_fast_rcnn_loss),
step=global_step)
tf.contrib.summary.scalar(
| tensorflow.reduce_mean | 547 |
import tensorflow as tf
# inputs = tf.unstack(inputs, num=num_steps, axis=1)
# outputs, state = tf.contrib.rnn.static_rnn(cell, inputs,
# initial_state=self._initial_state)
outputs = []
with tf.variable_scope("RNN"):
for time_step in range(self.num_steps):
if time_step > 0: tf.get_variable_scope().reuse_variables()
(cell_output, state) = cell(inputs[:, time_step, :], state)
outputs.append(cell_output)
output = tf.reshape(tf.concat(outputs, 1), [-1, config.hidden_size])
return output, state
| tensorflow.get_variable_scope | 548 |
import tensorflow as tf
#print(image.shape)
#print(label.shape)
images,labels=tf.train.shuffle_batch([image,label],
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):
images,labels=tf.train.batch([image,label],batch_size=batch_size)
return tf.reshape(images,[batch_size,4096]),tf.reshape(labels,[batch_size])
class trainwork(object):
def __init__(self):
with tf.variable_scope('scop'):
self.w1=tf.get_variable('w1', [4096,1024],initializer=tf.contrib.layers.xavier_initializer_conv2d())
self.w2=tf.get_variable('w2', [1024,classnum],initializer=tf.contrib.layers.xavier_initializer_conv2d())
self.b1 = tf.get_variable('b1', [1024],initializer=tf.constant_initializer(0.0))
self.b2 = tf.get_variable('b2', [classnum],initializer=tf.constant_initializer(0.0))
| tensorflow.train.batch | 549 |
import tensorflow as tf
def TestModel(seq2seq):
with self.test_session(graph=tf.Graph()) as sess:
tf.set_random_seed(111)
random.seed(111)
np.random.seed(111)
enc_inp = [tf.constant(i + 1, tf.int32, shape=[batch_size])
for i in range(num_enc_timesteps)]
dec_inp_fp_true = [tf.constant(i, tf.int32, shape=[batch_size])
for i in range(num_dec_timesteps)]
dec_inp_holder_fp_false = [tf.placeholder(tf.int32, shape=[batch_size])
for _ in range(num_dec_timesteps)]
| tensorflow.constant | 550 |
import tensorflow as tf
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
def _selector(self, context, h, reuse=False):
| tensorflow.nn.softmax | 551 |
import tensorflow as tf
if is_training:
# I.e., 0.1 dropout
output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
logits = tf.matmul(output_layer, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
probabilities = tf.nn.softmax(logits, axis=-1)
log_probs = tf.nn.log_softmax(logits, axis=-1)
one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)
| tensorflow.nn.bias_add | 552 |
import tensorflow as tf
fname = 'model.tf'
dst_nodes = ['output/predictions']
saver = tf.train.Saver()
| tensorflow.train.Saver | 553 |
import tensorflow as tf
tf.broadcast_to(self.unk_id, tf.shape(tokens)),
tokens)
# Create initial candidate list.
candidates = tf.map_fn(
self._MergeTokens, (tokens[:-1], tokens[1:]), dtype=tokens.dtype)
def _ShouldMerge(unused_tokens, candidates):
"""Merge until not possible, or we abort early according to merge_prob."""
return tf.logical_and(
tf.reduce_any(tf.not_equal(candidates, NO_TOKEN)),
tf.random.uniform([]) < self._merge_prob)
def _MergeOneToken(tokens, i):
return tf.expand_dims(
self._MergeTokens((tokens[i], tokens[i + 1])), axis=-1)
def _MergeCandidates(tokens, candidates):
"""Merge in the reverse binary tree."""
best_id = tf.argmin(candidates, output_type=tf.int32)
# Perform the merge at position best_id.
| tensorflow.random.uniform | 554 |
import tensorflow as tf
def relu(inputdata, name=None):
"""
:param name:
:param inputdata:
:return:
"""
return tf.nn.relu(features=inputdata, name=name)
@staticmethod
def sigmoid(inputdata, name=None):
"""
:param name:
| tensorflow.nn.relu | 555 |
import tensorflow as tf
self.obs_space = N_S
self.act_space = N_A
self.k = 16
self.g_dim = 256
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))
# 其中传送的是local—net的actor和critic的参数梯度grads,具体计算在上面定义
# apply_gradients是tf.train.Optimizer中自带的功能函数,将求得的梯度参数更新到global中
self.inc_step = self.global_step.assign_add(tf.shape(self.obs)[0])
self.train_op = tf.group(self.update_params_op, self.inc_step)
# GLOBALE_STEP += tf.shape(self.obs)[0]
def build_model(self):
"""
| tensorflow.name_scope | 556 |
import tensorflow as tf
file_based_convert_examples_to_features(predict_examples, label_list,
FLAGS.max_seq_length, tokenizer,
predict_file)
tf.logging.info("***** Running prediction*****")
tf.logging.info(" Num examples = %d (%d actual, %d padding)",
len(predict_examples), num_actual_predict_examples,
len(predict_examples) - num_actual_predict_examples)
tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size)
predict_drop_remainder = True if FLAGS.use_tpu else False
predict_input_fn = file_based_input_fn_builder(
input_file=predict_file,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=predict_drop_remainder)
| tensorflow.logging.info | 557 |
import tensorflow as tf
----------
x: input tensor.
Returns
-------
A tensor.
"""
zero = _to_tensor(0., x.dtype.base_dtype)
inf = _to_tensor(np.inf, x.dtype.base_dtype)
x = tf.clip_by_value(x, zero, inf)
return tf.sqrt(x)
def var(x, axis=None, keepdims=False):
"""Variance of a tensor, alongside the specified axis.
Parameters
----------
| tensorflow.clip_by_value | 558 |
import tensorflow as tf
with self.test_session(graph=tf.Graph()) as sess:
# Restores from MetaGraphDef.
new_saver = tf.train.import_meta_graph(filename)
# Generates a new MetaGraphDef.
new_saver.export_meta_graph()
# 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]
| tensorflow.constant | 559 |
import tensorflow as tf
step_model: (DQNPolicy) Policy for evaluation
"""
n_actions = ac_space.nvec if isinstance(ac_space, MultiDiscrete) else ac_space.n
with tf.variable_scope("input", reuse=reuse):
stochastic_ph = tf.placeholder(tf.bool, (), name="stochastic")
update_eps_ph = tf.placeholder(tf.float32, (), name="update_eps")
| tensorflow.variable_scope | 560 |
import tensorflow as tf
# Zero out entries of the loss where labels_difference zero (so loss is only
# computed on pairs with different labels).
loss = tf.reduce_mean(tf.abs(labels_difference) * weighted_loss, 0) * 0.5
loss = tf.reshape(loss, original_shape)
return loss, {}
| tensorflow.abs | 561 |
import tensorflow as tf
tt_rank = tt_rank.astype(int)
var = np.prod(tt_rank)
# Empirically entries of a TT tensor with cores initialized from N(0, 1)
# will have variances np.prod(tt_rank) and mean 0.
# We scale each TT-core to obtain the desired stddev
cr_exponent = -1.0 / (2 * num_dims)
var = np.prod(tt_rank ** cr_exponent)
core_stddev = stddev ** (1.0 / num_dims) * var
with tf.name_scope(name):
tt = matrix_with_random_cores(shape, tt_rank=tt_rank, stddev=core_stddev,
dtype=dtype)
if np.abs(mean) < 1e-8:
return tt
else:
raise NotImplementedError('non-zero mean is not supported yet')
def random_matrix_batch(shape, tt_rank=2, batch_size=1, mean=0., stddev=1.,
| tensorflow.name_scope | 562 |
import tensorflow as tf
num_convs = 2
decoder_features = slim.repeat(
tf.concat(decoder_features_list, 3),
num_convs,
| tensorflow.concat | 563 |
import tensorflow as tf
# Calculate manager output g
x = tf.expand_dims(self.s, [0])
self.manager_lstm = SingleStepLSTM(x,
self.g_dim,
step_size=tf.shape(self.obs)[:1])
g_hat = self.manager_lstm.output
self.g = tf.nn.l2_normalize(g_hat, dim=1)
self.manager_vf = self.build_value(g_hat)
def build_worker(self):
with tf.variable_scope('worker'):
| tensorflow.nn.l2_normalize | 564 |
import tensorflow as tf
def _evaluate_spherical_harmonics_branch(degree,
order,
theta,
phi,
sign_order,
var_type=tf.float64):
sqrt_2 = tf.constant(1.41421356237, dtype=var_type)
order_float = tf.cast(order, dtype=var_type)
tmp = sqrt_2 * _spherical_harmonics_normalization(
degree, order, var_type) * evaluate_legendre_polynomial(
degree, order, tf.cos(theta))
positive = tmp * tf.cos(order_float * phi)
negative = tmp * tf.sin(order_float * phi)
return tf.where(tf.greater(sign_order, 0), positive, negative)
def evaluate_spherical_harmonics(
degree_l: TensorLike,
order_m: TensorLike,
theta: TensorLike,
phi: TensorLike,
name: str = "spherical_harmonics_evaluate_spherical_harmonics") -> TensorLike: # pylint: disable=line-too-long
| tensorflow.cos | 565 |
import tensorflow as tf
# now we wait for all workers to finish
# we create an empty dataset and wait
# until we collected as many observations in it
# as there were points in the batch
all_new_data = Dataset(
tf.zeros((0, initial_data.query_points.shape[1]), tf.float64),
tf.zeros((0, initial_data.observations.shape[1]), tf.float64),
)
while len(all_new_data) < num_workers:
# this line blocks the process until new data is available in the queue
| tensorflow.zeros | 566 |
import tensorflow as tf
outer = tf.matrix_band_part(outer, 0, self.max_a_len)
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 | 567 |
import tensorflow as tf
"input_ids": tf.FixedLenFeature([FLAGS.max_seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([FLAGS.max_seq_length], tf.int64),
"segment_ids": tf.FixedLenFeature([FLAGS.max_seq_length], tf.int64),
"label_ids": tf.FixedLenFeature([], tf.int64),
| tensorflow.FixedLenFeature | 568 |
import tensorflow as tf
sigma*(2*pi)^(1/2)
'''
def gaussian_pdf(mean, loc_std, sample):
Z = 1.0 / (loc_std * tf.sqrt(2.0 * np.pi))
a = - tf.square(sample - mean) / (2.0 * tf.square(loc_std))
return Z * tf.exp(a)
class ACNet:
| tensorflow.square | 569 |
import tensorflow as tf
1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1, 5, 10, 15, 20, 25, 30, 35, 100, 1e3, 1e4, 1e5, 1e6
]
gaussian_kernel = partial(util.gaussian_kernel_matrix, sigmas=tf.constant(sigmas))
loss_value = maximum_mean_discrepancy(source_samples, target_samples, kernel=gaussian_kernel)
loss_value = tf.maximum(1e-4, loss_value) * weight
assert_op = tf.Assert(tf.is_finite(loss_value), [loss_value])
with tf.control_dependencies([assert_op]):
tag = 'MMD_Loss'
barrier = tf.no_op(tag)
| tensorflow.maximum | 570 |
import tensorflow as tf
truthoutput_z_ = lrelu(linear(tgtimg_z, self.gf_dim*8*s_h16*s_w16, 'd_h0_lin'))
truthoutput_h0 = tf.reshape(truthoutput_z_, [-1, s_h16, s_w16, self.gf_dim * 8])
truthoutput_h1 = lrelu(deconv2d(tf.concat([truthoutput_h0, tgtctx_h3], 3),
[self.batch_size, s_h8, s_w8, self.gf_dim*4], name='d_h1'))
truthoutput_h2 = lrelu(deconv2d(tf.concat([truthoutput_h1, tgtctx_h2], 3),
[self.batch_size, s_h4, s_w4, self.gf_dim*2], name='d_h2'))
truthoutput_h3 = lrelu(deconv2d(tf.concat([truthoutput_h2, tgtctx_h1], 3),
[self.batch_size, s_h2, s_w2, self.gf_dim*1], name='d_h3'))
truthoutput_h4 = deconv2d(tf.concat([truthoutput_h3, tgtctx_h0], 3),
[self.batch_size, s_h, s_w, self.c_dim], name='d_h4')
self.simloss = tf.reduce_mean((trans_z - tgtimg_z) ** 2) * 1e3
mean, var = tf.nn.moments(tgtimg_z, axes=[0])
print(var.get_shape())
# self.simloss /= tf.reduce_mean(var)
print(tgtimg_z.get_shape())
| tensorflow.concat | 571 |
from tensorflow.python.platform import tf_logging as logging
return False
if latest_path is not None and latest_path == self._latest_path:
logging.debug("Skipping evaluation due to same checkpoint %s for step %d "
"as for step %d.", latest_path, step,
| tensorflow.python.platform.tf_logging.debug | 572 |
import tensorflow as tf
pred_posi_dif = tf.where(geq, pred_dif, -pred_dif)
loss = tf.maximum(0., tgt_posi_dif - pred_posi_dif)
cstr_pct = tf.math.count_nonzero(loss, dtype=tf.float32) / tf.cast(tf.reduce_prod(tf.shape(loss)), tf.float32)
final_loss = tf.reduce_mean(loss)
return final_loss, cstr_pct
def contra_traj_lossV7(pred, tgt, horizon=12, temp=100):
horizon_pred, horizon_tgt = horizon_sumV1(pred, horizon), horizon_sumV1(tgt, horizon)
# horizon_pred, horizon_tgt = horizon_sumV2(pred, tgt, horizon)
pred_flat1, pred_flat2 = tf.reshape(horizon_pred, [-1, 1]), tf.reshape(horizon_pred, [1, -1])
tgt_flat1, tgt_flat2 = tf.reshape(horizon_tgt, [-1, 1]), tf.reshape(horizon_tgt, [1, -1])
tgt_dif = tgt_flat1 - tgt_flat2
pred_dif = pred_flat1 - pred_flat2
geq = tf.cast(tgt_dif > 0, tf.bool)
tgt_posi_dif = tf.where(geq, tgt_dif, -tgt_dif)
pred_posi_dif = tf.where(geq, pred_dif, -pred_dif)
loss = tf.maximum(0., tgt_posi_dif - pred_posi_dif)
cstr_pct = tf.math.count_nonzero(loss, dtype=tf.float32) / tf.cast(tf.reduce_prod(tf.shape(loss)), tf.float32)
unorm_w = tf.exp((tgt_flat1 + tgt_flat2)/temp)
| tensorflow.reshape | 573 |
import tensorflow as tf
d_real=d_real, d_fake=d_fake, d_real_logits=d_real_logits,
d_fake_logits=d_fake_logits)
penalty_loss = penalty_lib.get_penalty_loss(
x=images, x_fake=generated, y=y, is_training=is_training,
discriminator=self.discriminator, architecture=self._architecture)
self.d_loss += self._lambda * penalty_loss
z_projs = tf.concat([z_projs_real, z_projs_fake], 0)
z_aug_projs = tf.concat([z_aug_projs_real, z_aug_projs_fake], 0)
sims_logits = tf.matmul(z_projs, z_aug_projs, transpose_b=True)
logits_max = tf.reduce_max(sims_logits,1)
sims_logits = sims_logits - tf.reshape(logits_max, [-1, 1])
sims_probs = tf.nn.softmax(sims_logits)
| tensorflow.concat | 574 |
import tensorflow as tf
input_size = inputs.get_shape()[2].value
dtype = inputs.dtype
x = inputs
x0 = tf.transpose(x, perm=[1, 2,0]) # (num_nodes, total_arg_size, batch_size)
x0 = tf.reshape(x0, shape=[self._num_nodes, input_size * batch_size])
x = tf.expand_dims(x0, axis=0)
scope = tf.get_variable_scope()
with tf.variable_scope(scope):
if self._max_diffusion_step == 0:
pass
| tensorflow.expand_dims | 575 |
import tensorflow as tf
# 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.reduce_sum | 576 |
import tensorflow as tf
# a_fc3_ = tf.layers.dense(a_fc2_, 64, tf.nn.relu, kernel_initializer=w_initializer,
# bias_initializer=b_initializer, name='agent_fc3_t')
self.q_next = tf.layers.dense(a_fc1_, self.num_a, kernel_initializer=w_initializer,
bias_initializer=b_initializer, name='q_t')
# [batch*n_agents, 1]
self.q_selected = tf.reduce_sum(tf.multiply(self.q_eval, self.a), axis=1)
# ------------------ build mixing_net ------------------
with tf.variable_scope('mixing_net'):
# [batch, n_agents]
self.q_concat = tf.reshape(self.q_selected, [-1, self.n_agents])
self.q_concat_ =tf.reshape(self.q_m_, [-1, self.n_agents])
with tf.variable_scope('eval_hyper'):
self.Q_tot = Qmix_mixer(self.q_concat, self.S, self.num_global_s, self.n_agents, 32)
with tf.variable_scope('target_hyper'):
| tensorflow.variable_scope | 577 |
import tensorflow as tf
# activation
conv = activation(conv)
conv = tf.squeeze(conv, squeeze_dims=[2])
convolutions.append(conv)
| tensorflow.squeeze | 578 |
import tensorflow as tf
flattened_image_features = slim.dropout(flattened_image_features,
keep_prob=self._dropout_keep_prob,
is_training=self._is_training)
with slim.arg_scope(self._fc_hyperparams):
box_encodings = slim.fully_connected(
flattened_image_features,
self._num_classes * self._box_code_size,
activation_fn=None,
scope='BoxEncodingPredictor')
class_predictions_with_background = slim.fully_connected(
flattened_image_features,
self._num_classes + 1,
activation_fn=None,
scope='ClassPredictor')
box_encodings = tf.reshape(
box_encodings, [-1, 1, self._num_classes, self._box_code_size])
class_predictions_with_background = tf.reshape(
class_predictions_with_background, [-1, 1, self._num_classes + 1])
predictions_dict = {
BOX_ENCODINGS: box_encodings,
CLASS_PREDICTIONS_WITH_BACKGROUND: class_predictions_with_background
}
if self._predict_instance_masks:
with slim.arg_scope(self._conv_hyperparams):
upsampled_features = tf.image.resize_bilinear(
image_features,
| tensorflow.reshape | 579 |
import tensorflow as tf
differences = self.generator_out - self.real_pc
interpolates = self.real_pc + (alpha * differences)
with tf.variable_scope('discriminator') as scope:
gradients = tf.gradients(self.discriminator(interpolates, reuse=True, scope=scope, **disc_kwargs)[1], [interpolates])[0]
# Reduce over all but the first dimension
slopes = tf.sqrt(tf.reduce_sum(tf.square(gradients), reduction_indices=list(range(1, ndims))))
gradient_penalty = tf.reduce_mean((slopes - 1.) ** 2)
self.loss_d_rot += lam * gradient_penalty
train_vars = tf.trainable_variables()
d_params = [v for v in train_vars if v.name.startswith(name + '/discriminator/')]
g_params = [v for v in train_vars if v.name.startswith(name + '/generator/')]
| tensorflow.square | 580 |
import tensorflow as tf
c = util.shape(top_antecedents, 1)
feature_emb_list = []
if self.config["use_metadata"]:
top_antecedent_speaker_ids = tf.gather(top_span_speaker_ids, top_antecedents) # [k, c]
same_speaker = tf.equal(tf.expand_dims(top_span_speaker_ids, 1), top_antecedent_speaker_ids) # [k, c]
speaker_pair_emb = tf.gather(tf.get_variable("same_speaker_emb", [2, self.config["feature_size"]]), tf.to_int32(same_speaker)) # [k, c, emb]
feature_emb_list.append(speaker_pair_emb)
tiled_genre_emb = tf.tile(tf.expand_dims(tf.expand_dims(genre_emb, 0), 0), [k, c, 1]) # [k, c, emb]
feature_emb_list.append(tiled_genre_emb)
if self.config["use_features"]:
antecedent_distance_buckets = self.bucket_distance(top_antecedent_offsets) # [k, c]
antecedent_distance_emb = tf.gather(tf.get_variable("antecedent_distance_emb", [10, self.config["feature_size"]]), antecedent_distance_buckets) # [k, c]
feature_emb_list.append(antecedent_distance_emb)
feature_emb = tf.concat(feature_emb_list, 2) # [k, c, emb]
feature_emb = tf.nn.dropout(feature_emb, self.dropout) # [k, c, emb]
| tensorflow.expand_dims | 581 |
from tensorflow.python.ops import array_ops
ids, math_ops.equal(ids.values, selected_id))
# TODO(ptucker): Make this more efficient, maybe add a sparse version of
# tf.equal and tf.reduce_any?
# Shape of filled IDs is the same as `ids` with the last dim collapsed to 1.
ids_shape = array_ops.shape(ids, out_type=dtypes.int64)
ids_last_dim = array_ops.size(ids_shape) - 1
filled_selected_id_shape = math_ops.reduced_shape(
ids_shape, array_ops.reshape(ids_last_dim, [1]))
# Intersect `ids` with the selected ID.
filled_selected_id = array_ops.fill(
filled_selected_id_shape, math_ops.to_int64(selected_id))
result = set_ops.set_intersection(filled_selected_id, ids)
return ops.SparseTensor(
indices=result.indices, values=result.values, shape=ids_shape)
| tensorflow.python.ops.array_ops.reshape | 582 |
import tensorflow as tf
self.encoder_1 = self.conv2
self.encoder_2 = self.conv3
self.encoder_3 = self.conv4
self.encoder_4 = self.conv5
print("\nEncoder RESNET is built successfully\n\n")
@timeit
def load_pretrained_weights(self, sess):
print("Loading pretrained weights of resnet18")
all_vars = tf.trainable_variables()
all_vars += tf.get_collection('mu_sigma_bn')
for v in all_vars:
if v.op.name in self.pretrained_weights.keys():
assign_op = v.assign(self.pretrained_weights[v.op.name])
sess.run(assign_op)
print(v.op.name + " - loaded successfully")
print("All pretrained weights of resnet18 is loaded")
def _residual_block(self, name, x, filters, pool_first=False, strides=1, dilation=1):
| tensorflow.trainable_variables | 583 |
import tensorflow as tf
)
dialogue_state_size = conv3.size + \
3 * histories_embedding_size * conv_mul
dialogue_state = tf.nn.relu(dialogue_state)
dialogue_state = dropout(dialogue_state, self.dropout_keep_prob)
# action prediction
| tensorflow.nn.relu | 584 |
import tensorflow as tf
self.opt_pred = self.optimizer(lr_pred, beta, self.real_pc_rot_loss, rot_params, batch) #only use real pics to update
self.saver = tf.train.Saver(tf.global_variables(), max_to_keep=None)
self.init = tf.global_variables_initializer()
#Launch the session
config = tf.ConfigProto(allow_soft_placement = True)
config.gpu_options.allow_growth = True
self.sess = tf.Session(config=config, graph=self.graph)
self.sess.run(self.init)
| tensorflow.ConfigProto | 585 |
import tensorflow as tf
im = (im + 1.0) * 128
im = tf.clip_by_value(im, 0, 255)
| tensorflow.clip_by_value | 586 |
import tensorflow as tf
loss = tf.math.reduce_mean(
distance_utils.compute_gaussian_kl_divergence(
means, stddevs, rhs_means=prior_mean, rhs_stddevs=prior_stddev))
weighted_loss = loss_weight * loss
summaries = {
'regularization_loss/KL/PriorMean/Mean':
tf.math.reduce_mean(tf.constant(prior_mean)),
'regularization_loss/KL/PriorVar/Mean':
tf.math.reduce_mean(tf.constant(prior_stddev)**2),
'regularization_loss/KL/Loss/Original':
loss,
'regularization_loss/KL/Loss/Weighted':
weighted_loss,
'regularization_loss/KL/Loss/Weight':
tf.constant(loss_weight),
}
return weighted_loss, summaries
def compute_positive_pairwise_loss(anchor_embeddings,
positive_embeddings,
loss_weight,
distance_fn=functools.partial(
distance_utils.compute_l2_distances,
squared=True)):
"""Computes anchor/positive pairwise (squared L2) loss.
Args:
| tensorflow.constant | 587 |
import tensorflow as tf
"""
s = sqrt_diag if diag else sqrt
kl_batch = gauss_kl(mu,s,K if shared_k else K_batch)
kl_sum = []
for n in range(Datum.N):
kl_sum.append(gauss_kl(mu[:, n][:,None], # M x 1
sqrt_diag[:, n][:, None] if diag else sqrt[n, :, :][None, :, :], # 1 x M x M or M x 1
K if shared_k else K_batch[n, :, :][None,:,:])) # 1 x M x M or M x M
kl_sum =tf.reduce_sum(kl_sum)
assert_almost_equal(kl_sum.eval(), kl_batch.eval())
def tf_kl_1d(q_mu, q_sigma, p_var=1.0):
p_var = tf.ones_like(q_sigma) if p_var is None else p_var
q_var = tf.square(q_sigma)
kl = 0.5 * (q_var / p_var + tf.square(q_mu) / p_var - 1 + tf.log(p_var / q_var))
return tf.reduce_sum(kl)
@pytest.mark.parametrize('white', [True, False])
def test_oned(session_tf, white, mu, sqrt, K_batch):
"""
Check that the KL divergence matches a 1D by-hand calculation.
"""
m = 0
mu1d = mu[m,:][None,:] # 1 x N
s1d = sqrt[:,m,m][:,None,None] # N x 1 x 1
K1d = K_batch[:,m,m][:,None,None] # N x 1 x 1
kl = gauss_kl(mu1d,s1d,K1d if not white else None)
| tensorflow.log | 588 |
import tensorflow as tf
img_batch=tf.expand_dims(img[0, :, :, :], axis=0),
boxes=gtboxes_and_label_h[0, :, :-1],
labels=gtboxes_and_label_h[0, :, -1],
method=0)
tf.summary.image('Compare/gtboxes_h_gpu:%d' % i, gtboxes_in_img_h)
if cfgs.ADD_BOX_IN_TENSORBOARD:
detections_in_img = self.drawer.draw_boxes_with_categories_and_scores(
| tensorflow.summary.image | 589 |
import tensorflow as tf
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
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', loss_entropy)
tf.summary.scalar('Loss/Total', loss)
tf.summary.scalar('Var/Epsilon', epsilon_decay)
tf.summary.scalar('Var/Policy Mode', tf.reduce_mean(pi.mode()))
tf.summary.scalar('Var/Policy Sigma', tf.reduce_mean(pi.stddev()))
tf.summary.scalar('Var/Value', tf.reduce_mean(self.vf))
self.summarise = tf.summary.merge(tf.get_collection(tf.GraphKeys.SUMMARIES))
# AC net
| tensorflow.summary.scalar | 590 |
import tensorflow as tf
decoder_features = _split_separable_conv2d(
tf.concat(decoder_features_list, 3),
| tensorflow.concat | 591 |
import tensorflow as tf
if isinstance(facts, tuple):
# In case of Bi-RNN, concatenate the forward and the backward RNN outputs.
facts = tf.concat(facts, 2)
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_trans_shine' + stag)
query = prelu(query)
queries = tf.tile(query, [1, tf.shape(facts)[1]])
queries = tf.reshape(queries, tf.shape(facts))
din_all = tf.concat([queries, facts, queries-facts, queries*facts], axis=-1)
| tensorflow.ones_like | 592 |
import tensorflow as tf
if not reader:
reader = tf.TFRecordReader
keys_to_features = {
'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''),
'image/format': tf.FixedLenFeature((), tf.string, default_value='png'),
'image/class/label': tf.FixedLenFeature(
[], tf.int64, default_value=tf.zeros([], dtype=tf.int64)),
}
| tensorflow.FixedLenFeature | 593 |
import tensorflow as tf
elif ord == 2:
red_ind = list(range(1, len(x.get_shape())))
avoid_zero_div = 1e-8
square = tf.maximum(avoid_zero_div,
reduce_sum(tf.square(grad),
reduction_indices=red_ind,
keepdims=True))
normalized_grad = old_div(grad, tf.sqrt(square))
else:
normalized_grad = tf.sign(grad)
normalized_grad = tf.stop_gradient(normalized_grad)
scaled_grad = eps * normalized_grad
#目标是让loss下降
adv_x = x - scaled_grad
if (clip_min is not None) and (clip_max is not None):
adv_x = tf.clip_by_value(adv_x, clip_min, clip_max)
| tensorflow.stop_gradient | 594 |
import tensorflow as tf
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"):
with tf.variable_scope(name):
deconv = tf.layers.conv2d_transpose(input_data, filters, kernel_size, (stride, stride), padding, activation = None)
| tensorflow.layers.conv2d_transpose | 595 |
from tensorflow.python.framework import tensor_shape
if input_shape.ndims is None:
return [tensor_shape.unknown_shape()]
| tensorflow.python.framework.tensor_shape.unknown_shape | 596 |
import tensorflow as tf
box_wh = tf.exp(box_wh) * anchors
box_x1y1 = box_xy - box_wh / 2.
box_x2y2 = box_xy + box_wh / 2.
box = tf.concat([box_x1y1, box_x2y2], axis=-1)
boxes.append(tf.reshape(box, (x_shape[0], -1, 1, 4)))
objects.append(tf.reshape(obj, (x_shape[0], -1, 1)))
classes.append(tf.reshape(cls, (x_shape[0], -1, num_classes)))
boxes = tf.concat(boxes, axis=1)
objects = tf.concat(objects, axis=1)
classes = tf.concat(classes, axis=1)
scores = objects * classes
boxes, scores, classes, valid = tf.image.combined_non_max_suppression(
boxes=boxes,
scores=scores,
max_output_size_per_class=max_outputs,
max_total_size=max_outputs,
| tensorflow.concat | 597 |
import tensorflow as tf
tf.flags.DEFINE_string(
"tpu_zone", None,
"[Optional] GCE zone where the Cloud TPU is located in. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
tf.flags.DEFINE_string(
"gcp_project", None,
"[Optional] Project name for the Cloud TPU-enabled project. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
flags.DEFINE_integer(
"num_tpu_cores", 8,
"Only used if `use_tpu` is True. Total number of TPU cores to use.")
class InputExample(object):
def __init__(self, unique_id, text):
self.unique_id = unique_id
self.text = text
| tensorflow.flags.DEFINE_string | 598 |
import tensorflow as tf
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.metrics.accuracy | 599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.