seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
import tensorflow as tf
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)
elif norm == 'G':
X = tf.contrib.layers.group_norm(X, groups=16, scope=scope, reuse=reuse)
| tensorflow.layers.batch_normalization | 14,200 |
import tensorflow as tf
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]
restored.append(tf.contrib.rnn.LSTMStateTuple(c, h))
return tuple(restored)
| tensorflow.add_to_collection | 14,201 |
import tensorflow as tf
masked_lm_example_loss = tf.reshape(masked_lm_example_loss, [-1])
masked_lm_ids = tf.reshape(masked_lm_ids, [-1])
masked_lm_weights = tf.reshape(masked_lm_weights, [-1])
masked_lm_accuracy = tf.metrics.accuracy(
labels=masked_lm_ids,
predictions=masked_lm_predictions,
weights=masked_lm_weights)
masked_lm_mean_loss = tf.metrics.mean(
values=masked_lm_example_loss, weights=masked_lm_weights)
next_sentence_log_probs = tf.reshape(
next_sentence_log_probs, [-1, next_sentence_log_probs.shape[-1]])
next_sentence_predictions = tf.argmax(
next_sentence_log_probs, axis=-1, output_type=tf.int32)
next_sentence_labels = tf.reshape(next_sentence_labels, [-1])
next_sentence_accuracy = tf.metrics.accuracy(
labels=next_sentence_labels, predictions=next_sentence_predictions)
next_sentence_mean_loss = tf.metrics.mean(
values=next_sentence_example_loss)
return {
"masked_lm_accuracy": masked_lm_accuracy,
"masked_lm_loss": masked_lm_mean_loss,
"next_sentence_accuracy": next_sentence_accuracy,
"next_sentence_loss": next_sentence_mean_loss,
}
eval_metrics = metric_fn(
| tensorflow.reshape | 14,202 |
import tensorflow as tf
predict_image_weight = predict_image_train_weight if training else 0.0
mask_begin = tf.ones_like(flat)
mask_begin = tf.cast(mask_begin, tf.float32) * predict_image_weight
mask_end = tf.cast(tf.ones_like(tgt), tf.float32)
new_features['mask'] = tf.concat([mask_begin, mask_end], axis=0)
return new_features, flat_with_target
if training:
| tensorflow.concat | 14,203 |
import tensorflow as tf
offset = get_variable("offset", shape=[channels], dtype=tf.float32, initializer=tf.constant_initializer(0.0))
scale = get_variable("scale", shape=[channels], dtype=tf.float32, initializer=tf.constant_initializer(1.0), regularizer=tf.nn.l2_loss)
mean, variance = tf.nn.moments(inp, axes=[0, 1, 2], shift=moving_mean)
mean_op = moving_mean.assign(decay * moving_mean + (1 - decay) * mean)
| tensorflow.nn.moments | 14,204 |
from tensorflow.python.ops import math_ops
if self._n_classes < 2:
loss_vec = math_ops.square(logits - math_ops.to_float(target))
elif self._n_classes == 2:
loss_vec = nn.sigmoid_cross_entropy_with_logits(logits,
math_ops.to_float(target))
else:
loss_vec = nn.sparse_softmax_cross_entropy_with_logits(
logits, array_ops.reshape(target, [-1]))
| tensorflow.python.ops.math_ops.to_float | 14,205 |
import tensorflow as tf
channels = 3
rows = height
if likelihood == common_image_attention.DistributionType.CAT:
cols = channels * width
else:
cols = width
hparams = tf.contrib.training.HParams(
hidden_size=2,
likelihood=likelihood,
mode=tf.estimator.ModeKeys.TRAIN,
num_mixtures=num_mixtures,
)
decoder_output = tf.random_normal([batch, rows, cols, hparams.hidden_size])
targets = tf.random_uniform([batch, height, width, channels],
minval=-1., maxval=1.)
output = common_image_attention.create_output(
decoder_output, rows, cols, targets, hparams)
if hparams.likelihood == common_image_attention.DistributionType.CAT:
self.assertEqual(output.shape, (batch, height, width, channels, depth))
else:
self.assertEqual(output.shape, (batch, height, width, depth))
if __name__ == "__main__":
tf.test.main()
| tensorflow.random_uniform | 14,206 |
import tensorflow as tf
with tf.variable_scope('fully_connected'):
bottom = out
bottom_shape = bottom.get_shape().as_list()
reshape = tf.reshape(
bottom,
[-1, bottom_shape[1] * bottom_shape[2] * bottom_shape[3] * bottom_shape[4]])
| tensorflow.reshape | 14,207 |
import tensorflow as tf
offset = tf.get_variable('offset',[x.get_shape()[-1]],initializer=tf.constant_initializer(0.0))
out = scale*tf.div(x-mean, tf.sqrt(var+epsilon)) + offset
| tensorflow.sqrt | 14,208 |
import tensorflow as tf
l1=tf.nn.relu(l1)
out = tf.matmul(l1, self.w2)+self.b2
return out
def test_inference(self,images):
images=tf.cast(images,tf.float32)/255.0
l1 = tf.matmul(images, self.w1)+self.b1
l1=tf.nn.relu(l1)
out = tf.matmul(l1, self.w2)+self.b2
return out
def valid_inference(self,images):
images=tf.cast(images,tf.float32)/255.0
l1 = tf.matmul(images, self.w1)+self.b1
| tensorflow.nn.relu | 14,209 |
import tensorflow as tf
b = tf.get_variable('b', [num_classes], initializer=tf.constant_initializer(1.0))
self.fc3 = tf.matmul(self.fc2, w) + b
| tensorflow.matmul | 14,210 |
import tensorflow as tf
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 ')
tf.app.flags.DEFINE_float('blur', 5.0, 'Max sigma value for Gaussian blur applied to training set')
tf.app.flags.DEFINE_boolean('new_blur', False, 'Use data augmentation as blur info')
| tensorflow.app.flags.DEFINE_integer | 14,211 |
import tensorflow as tf
batch_size = tf.shape(policy.obs_ph)[0]
n_actions = ac_space.nvec if isinstance(ac_space, MultiDiscrete) else ac_space.n
random_actions = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=n_actions, dtype=tf.int64)
chose_random = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=1, dtype=tf.float32) < eps
stochastic_actions = tf.where(chose_random, random_actions, deterministic_actions)
output_actions = tf.cond(stochastic_ph, lambda: stochastic_actions, lambda: deterministic_actions)
update_eps_expr = eps.assign(tf.cond(update_eps_ph >= 0, lambda: update_eps_ph, lambda: eps))
_act = tf_util.function(inputs=[policy.obs_ph, stochastic_ph, update_eps_ph],
outputs=output_actions,
givens={update_eps_ph: -1.0, stochastic_ph: True},
updates=[update_eps_expr])
def act(obs, stochastic=True, update_eps=-1):
return _act(obs, stochastic, update_eps)
| tensorflow.cond | 14,212 |
import tensorflow as tf
wvs_weighted_reshaped = tf.reshape(wvs_weighted, wvs.get_shape())
wvsum = tf.reduce_sum(wvs_weighted_reshaped,0)
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 for each tweet.
def GetWordPred(o_):
| tensorflow.get_variable | 14,213 |
import tensorflow as tf
# 4. Return EstimatorSpec
return tf.estimator.EstimatorSpec(
mode = mode,
| tensorflow.estimator.EstimatorSpec | 14,214 |
import tensorflow as tf
sampler_cls=sampler_cls, sampler_args=sampler_args)
def initialize_tf_vars(self):
"""Initialize all uninitialized variables in session."""
with tf.name_scope('initialize_tf_vars'):
uninited_set = [
e.decode()
for e in self.sess.run(tf.report_uninitialized_variables())
]
self.sess.run(
tf.variables_initializer([
v for v in tf.global_variables()
if v.name.split(':')[0] in uninited_set
]))
def _start_worker(self):
"""Start Plotter and Sampler workers."""
self.sampler.start_worker()
if self.plot:
from garage.tf.plotter import Plotter
self.plotter = Plotter(self.env, self.policy)
self.plotter.start()
| tensorflow.global_variables | 14,215 |
import tensorflow as tf
# Compute epsilon from {n_samples} standard Gaussian
# epsilon = tf.random_normal([n_samples, 1, n_out*2, n_out])
epsilon = tf.random_uniform([n_samples, 1, n_basis, n_out])
hyp_params = tf.get_variable('hyp_params_layer'+str(h),
shape=[2],
initializer=tf.random_normal_initializer())
l1, l2 = tf.nn.sigmoid(hyp_params[0]), tf.exp(hyp_params[1])
epsilon = tf.sinh(epsilon*l2)/tf.cosh(epsilon*l2)**l1/l2
# Compute A_{h+1}
A = tf.tile(alpha_mean+epsilon*alpha_std, [1, tf.shape(X)[0], 1, 1])
# Compute z_{h}A_{h+1}
Z1 = tf.matmul(Z, A[:,:,:n_basis//2,:])/tf.sqrt(n_basis*.5)
Z2 = tf.matmul(Z, A[:,:,n_basis//2:,:])/tf.sqrt(n_basis*.5)
# Compute u_{h+1} and v_{h+1}
U, V = tf.cos(Z1)+tf.cos(Z2), tf.sin(Z1)+tf.sin(Z2)
Z = tf.concat([U, V], 3)/tf.sqrt(n_out*1.)
KL += tf.reduce_mean(alpha_std**2+alpha_mean**2-2*alpha_logstd-1)/2.
# Output layer
else:
F = tf.squeeze(tf.layers.dense(Z, n_out), [2])
return F, KL | tensorflow.matmul | 14,216 |
from tensorflow.python.framework import ops
with ops.name_scope(
name, 'expand_and_tile', (tensor, multiple, dim)) as scope:
# Sparse.
if isinstance(tensor, ops.SparseTensorValue):
tensor = ops.SparseTensor.from_value(tensor)
if isinstance(tensor, ops.SparseTensor):
if dim < 0:
expand_dims = array_ops.reshape(
| tensorflow.python.framework.ops.SparseTensor.from_value | 14,217 |
import tensorflow as tf
parser.add_argument('--batch_size', type=int, default=32, help='batch size')
parser.add_argument('--max_train_step', type=int, default=50000, help='the maximum training step')
parser.add_argument('--model_path', type=str, default='', help='the path of checkpoint file')
args = parser.parse_args()
def model():
x = tf.placeholder(tf.float32, [None, 784], name='x')
gt = tf.placeholder(tf.float32, [None, 10], name='groundtruth')
with tf.variable_scope('layer1'):
w1 = tf.get_variable('weight1', [784, 1024], initializer=tf.random_normal_initializer())
b1 = tf.get_variable('bias1', [1024], initializer=tf.constant_initializer(0.0))
h1 = tf.nn.relu(tf.matmul(x, w1) + b1)
with tf.variable_scope('layer2'):
w2 = tf.get_variable('weight2', [1024, 1024], initializer=tf.random_normal_initializer())
b2 = tf.get_variable('bias2', [1024], initializer=tf.constant_initializer(0.0))
h2 = tf.nn.relu(tf.matmul(h1, w2) + b2)
with tf.variable_scope('layer3'):
w3 = tf.get_variable('weight3', [1024, 10], initializer=tf.random_normal_initializer())
b3 = tf.get_variable('bias3', [10], initializer=tf.constant_initializer(0.0))
y = tf.matmul(h2, w3) + b3
| tensorflow.constant_initializer | 14,218 |
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]),
lambda: tf.no_op())
with tf.control_dependencies([p]):
return tf.reduce_mean(loss)
| tensorflow.no_op | 14,219 |
import tensorflow as tf
with tf.control_dependencies([update_op]):
clear_ops = [tf.assign(s, tf.zeros_like(s)) for s in slots]
return tf.group(*clear_ops, name='update_grad')
pred = tf.equal(tf.mod(counter, self._niter), 0)
with tf.control_dependencies([update_slot_op]):
if name is None:
name = 'cond_update_grad'
op = tf.cond(pred, update_grad, tf.no_op, name=name).op
return op
| tensorflow.control_dependencies | 14,220 |
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)
| tensorflow.contrib.tpu.TPUEstimatorSpec | 14,221 |
import tensorflow as tf
def tf_store(self, states, internals, actions, terminal, reward):
# Memory indices to overwrite.
num_instances = tf.shape(input=terminal)[0]
with tf.control_dependencies([tf.assert_less_equal(num_instances, self.capacity)]):
indices = tf.range(self.memory_index, self.memory_index + num_instances) % self.capacity
# Remove episode indices.
num_episodes = tf.count_nonzero(
input_tensor=tf.gather(params=self.terminal_memory, indices=indices),
axis=0,
dtype=util.tf_dtype('int')
)
num_episodes = tf.minimum(x=num_episodes, y=self.episode_count)
assignment = tf.assign(
ref=self.episode_indices[:self.episode_count - num_episodes],
value=self.episode_indices[num_episodes: self.episode_count]
)
# Decrement episode count.
with tf.control_dependencies(control_inputs=(assignment,)):
assignment = tf.assign_sub(ref=self.episode_count, value=num_episodes)
# Assign new observations.
with tf.control_dependencies(control_inputs=(assignment,)):
assignments = list()
for name in sorted(states):
| tensorflow.assign | 14,222 |
import tensorflow as tf
test(model, eval_data)
print("Colorbot is ready to generate colors!")
while True:
try:
color_name = six.moves.input(
"Give me a color name (or press enter to exit): ")
except EOFError:
return
if not color_name:
return
_, chars, length = parse(color_name)
with tf.device(device):
(chars, length) = (tf.identity(chars), tf.identity(length))
chars = tf.expand_dims(chars, 0)
length = tf.expand_dims(length, 0)
preds = tf.unstack(model((chars, length), training=False)[0])
# Predictions cannot be negative, as they are generated by a ReLU layer;
# they may, however, be greater than 1.
clipped_preds = tuple(min(float(p), 1.0) for p in preds)
rgb = tuple(int(p * 255) for p in clipped_preds)
print("rgb:", rgb)
data = [[clipped_preds]]
if HAS_MATPLOTLIB:
plt.imshow(data)
plt.title(color_name)
plt.show()
| tensorflow.identity | 14,223 |
import tensorflow as tf
shape=shape,
dtype=dtype,
initializer=initializer,
collections=collections,
trainable=trainable)
finally:
tf.get_variable_scope().set_partitioner(partitioner)
# Using the absolute value enforces nonnegativity.
dual_value = tf.abs(dual_variable)
if trainable:
# To reverse the gradient on the dual variable, multiply the gradient by
# -dual_rate_factor
dual_value = (tf.stop_gradient(
(1.0 + dual_rate_factor) * dual_value) - dual_rate_factor * dual_value)
return dual_value, dual_variable
def maybe_create_label_priors(label_priors, labels, weights, variables_collections):
"""Creates moving average ops to track label priors, if necessary.
Args:
label_priors: As required in e.g. precision_recall_auc_loss.
labels: A `Tensor` of shape [batch_size] or [batch_size, num_labels].
weights: As required in e.g. precision_recall_auc_loss.
variables_collections: Optional list of collections for the variables, if
any must be created.
| tensorflow.stop_gradient | 14,224 |
from tensorflow.contrib.metrics.python.ops import metric_ops
return logits
def get_eval_ops(self, features, logits, labels, metrics=None):
loss = self.loss(logits, labels, features)
result = {"loss": metric_ops.streaming_mean(loss)}
if metrics:
predictions = self.logits_to_predictions(logits, proba=False)
result.update(
| tensorflow.contrib.metrics.python.ops.metric_ops.streaming_mean | 14,225 |
import tensorflow as tf
y_as_list = tf.unstack(y, num=num_steps, axis=1)
losses = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y,logits=logits)
total_loss = tf.reduce_mean(losses)
train_step = tf.train.AdagradOptimizer(learning_rate).minimize(total_loss)
'''训练网络'''
def train_rnn(num_epochs, num_steps, state_size=4, verbose=True):
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
#sess = tf_debug.LocalCLIDebugWrapperSession(sess)
training_losses = []
for idx, epoch in enumerate(gen_epochs(num_epochs, num_steps)):
training_loss = 0
training_state = np.zeros((batch_size, state_size)) # ->(200, 4)
if verbose:
| tensorflow.Session | 14,226 |
import tensorflow as tf
def _meshgrid(depth, height, width, z_near, z_far):
with tf.variable_scope('_meshgrid'):
x_t = tf.reshape(
tf.tile(tf.linspace(-1.0, 1.0, width), [height * depth]),
[depth, height, width])
y_t = tf.reshape(
tf.tile(tf.linspace(-1.0, 1.0, height), [width * depth]),
[depth, width, height])
y_t = tf.transpose(y_t, [0, 2, 1])
sample_grid = tf.tile(
tf.linspace(float(z_near), float(z_far), depth), [width * height])
z_t = tf.reshape(sample_grid, [height, width, depth])
z_t = tf.transpose(z_t, [2, 0, 1])
z_t = 1 / z_t
d_t = 1 / z_t
x_t /= z_t
| tensorflow.transpose | 14,227 |
import tensorflow as tf
Returns:
tuple (final output, loss)
'''
y = output
if add_bias:
bias = tf.Variable([0.0])
y = output + bias
sig_y = tf.clip_by_value(tf.sigmoid(y), 0.001, 0.999) # avoid NaNs
loss = -tf.reduce_sum(target*tf.log(sig_y) + (1-target)*tf.log(1-sig_y))
return sig_y, loss
def ranking_margin_objective(output, margin=1.0):
''' Create final model output and loss for pairwise ranking margin objective
| tensorflow.sigmoid | 14,228 |
import tensorflow as tf
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)
one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)
per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
loss = tf.reduce_mean(per_example_loss)
return (loss, per_example_loss, logits, probabilities)
def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps, use_tpu,
use_one_hot_embeddings, do_serve):
"""Returns `model_fn` closure for TPUEstimator."""
| tensorflow.nn.log_softmax | 14,229 |
import tensorflow as tf
num_decoder_symbols=classes, embedding_size=24)
targets = [dec_inp[i+1] for i in range(len(dec_inp) - 1)] + [0]
return tf.nn.seq2seq.model_with_buckets(
enc_inp, dec_inp, targets, weights, buckets, GRUSeq2Seq,
per_example_loss=per_example_loss)
# Now we construct the copy model.
inp = [tf.placeholder(tf.int32, shape=[None]) for _ in range(8)]
out = [tf.placeholder(tf.int32, shape=[None]) for _ in range(8)]
weights = [tf.ones_like(inp[0], dtype=tf.float32) for _ in range(8)]
with tf.variable_scope("root"):
_, losses1 = SampleGRUSeq2Seq(inp, out, weights, per_example_loss=False)
# Now check that we did not accidentally set reuse.
self.assertEqual(False, tf.get_variable_scope().reuse)
# Construct one more model with per-example loss.
tf.get_variable_scope().reuse_variables()
_, losses2 = SampleGRUSeq2Seq(inp, out, weights, per_example_loss=True)
# First loss is scalar, the second one is a 1-dimensinal tensor.
self.assertEqual([], losses1[0].get_shape().as_list())
self.assertEqual([None], losses2[0].get_shape().as_list())
def testModelWithBuckets(self):
"""Larger tests that does full sequence-to-sequence model training."""
# We learn to copy 10 symbols in 2 buckets: length 4 and length 8.
classes = 10
buckets = [(4, 4), (8, 8)]
perplexities = [[], []] # Results for each bucket.
tf.set_random_seed(111)
random.seed(111)
np.random.seed(111)
| tensorflow.get_variable_scope | 14,230 |
import tensorflow as tf
partitioner = tf.get_variable_scope().partitioner
try:
tf.get_variable_scope().set_partitioner(None)
dual_variable = tf.contrib.framework.model_variable(
name=name,
shape=shape,
dtype=dtype,
initializer=initializer,
collections=collections,
trainable=trainable)
finally:
tf.get_variable_scope().set_partitioner(partitioner)
# Using the absolute value enforces nonnegativity.
dual_value = tf.abs(dual_variable)
if trainable:
# To reverse the gradient on the dual variable, multiply the gradient by
# -dual_rate_factor
dual_value = (tf.stop_gradient(
(1.0 + dual_rate_factor) * dual_value) - dual_rate_factor * dual_value)
return dual_value, dual_variable
| tensorflow.get_variable_scope | 14,231 |
import tensorflow as tf
table_values = np.arange(len(vocab), dtype=np.int64)
table = tf.lookup.StaticVocabularyTable(
tf.lookup.KeyValueTensorInitializer(vocab, table_values),
num_oov_buckets=1)
def to_ids(example):
sentence = tf.reshape(example['tokens'], shape=[1])
words = tf.strings.split(sentence, sep=' ').values
truncated_words = words[:max_seq_len]
tokens = table.lookup(truncated_words) + 1
tokens = tf.cond(
tf.less(tf.size(tokens), max_seq_len),
lambda: tf.concat([tokens, [eos]], 0), lambda: tokens)
| tensorflow.reshape | 14,232 |
import tensorflow as tf
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):
print('Building residual unit: %s' % name)
with tf.variable_scope(name):
# get input channels
in_channel = x.shape.as_list()[-1]
# Shortcut connection
shortcut = tf.identity(x)
if pool_first:
if in_channel == filters:
if strides == 1:
| tensorflow.variable_scope | 14,233 |
import tensorflow as tf
negative: 2-D `tensor` [batch_size, embedding_size], the embeddings for the negative images.
alpha: positive to negative triplet distance margin
Returns:
the triplet loss.
"""
with tf.name_scope(name):
pos_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, positive)), 1)
neg_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, negative)), 1)
basic_loss = tf.add(tf.subtract(pos_dist, neg_dist), alpha)
loss = tf.reduce_mean(tf.maximum(basic_loss, 0.0), 0)
return loss
def decov_loss(xs, name='decov_loss'):
"""Decov loss as described in https://arxiv.org/pdf/1511.06068.pdf 'Reducing
| tensorflow.subtract | 14,234 |
import tensorflow as tf
eval_metric_ops=eval_metric_ops
)
assert mode == tf.estimator.ModeKeys.TRAIN
with tf.variable_scope('learning_rate'):
global_step = tf.train.get_global_step()
learning_rate = tf.train.cosine_decay(
params['initial_learning_rate'],
global_step, decay_steps=params['num_steps']
)
tf.summary.scalar('learning_rate', learning_rate)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops), tf.variable_scope('optimizer'):
optimizer = tf.train.AdamOptimizer(learning_rate)
grads_and_vars = optimizer.compute_gradients(total_loss)
train_op = optimizer.apply_gradients(grads_and_vars, global_step)
for g, v in grads_and_vars:
tf.summary.histogram(v.name[:-2] + '_hist', v)
tf.summary.histogram(v.name[:-2] + '_grad_hist', g)
with tf.control_dependencies([train_op]), tf.name_scope('ema'):
ema = tf.train.ExponentialMovingAverage(decay=MOVING_AVERAGE_DECAY, num_updates=global_step)
train_op = ema.apply(tf.trainable_variables())
| tensorflow.variable_scope | 14,235 |
from tensorflow.python.framework import ops
array_ops.ones_like(count),
name=name)
return math_ops.truediv(total, non_zero_count, name=name)
mean = compute_mean(total, count, 'value')
with ops.control_dependencies([total_compute_op, count_compute_op]):
update_op = compute_mean(total, count, 'update_op')
if metrics_collections:
ops.add_to_collections(metrics_collections, mean)
| tensorflow.python.framework.ops.control_dependencies | 14,236 |
import tensorflow as tf
if q_sqrt is not None:
if q_sqrt.get_shape().ndims == 2:
LTA = A * tf.expand_dims(tf.transpose(q_sqrt), 2) # R x M x N
elif q_sqrt.get_shape().ndims == 3:
L = tf.matrix_band_part(q_sqrt, -1, 0) # R x M x M
A_tiled = tf.tile(tf.expand_dims(A, 0), tf.stack([num_func, 1, 1]))
LTA = tf.matmul(L, A_tiled, transpose_a=True) # R x M x N
else: # pragma: no cover
raise ValueError("Bad dimension for q_sqrt: %s" %
| tensorflow.matrix_band_part | 14,237 |
import tensorflow as tf
@under_name_scope()
def area(boxes):
"""
Args:
boxes: nx4 floatbox
Returns:
n
"""
x_min, y_min, x_max, y_max = tf.split(boxes, 4, axis=1)
return tf.squeeze((y_max - y_min) * (x_max - x_min), [1])
@under_name_scope()
def pairwise_intersection(boxlist1, boxlist2):
"""Compute pairwise intersection areas between boxes.
Args:
boxlist1: Nx4 floatbox
boxlist2: Mx4
| tensorflow.split | 14,238 |
import tensorflow as tf
KK = tf.matmul(K, K, transpose_b=True)
K_trace = tf.expand_dims(tf.expand_dims(tf.trace(KK), -1), -1)
K_loss = tf.reduce_mean(tf.abs(KK / K_trace - tf.eye(2)))
| tensorflow.eye | 14,239 |
import tensorflow as tf
boxes = tf.gather(gt_boxes, best_target_per_prior_index)
return boxes, labels
class MatchPrior(object):
def __init__(self, center_form_priors, center_variance, size_variance, iou_threshold):
self.center_form_priors = center_form_priors
self.corner_form_priors = center_form_to_corner_form(center_form_priors)
self.center_variance = center_variance
self.size_variance = size_variance
self.iou_threshold = iou_threshold
def __call__(self, gt_boxes, gt_labels):
if type(gt_boxes) is np.ndarray:
gt_boxes = tf.convert_to_tensor(gt_boxes)
if type(gt_labels) is np.ndarray:
gt_labels = tf.convert_to_tensor(gt_labels)
boxes, labels = assign_priors(gt_boxes, gt_labels, self.corner_form_priors, self.iou_threshold)
boxes = corner_form_to_center_form(boxes)
locations = convert_boxes_to_locations(boxes, self.center_form_priors, self.center_variance, self.size_variance)
return locations, labels | tensorflow.convert_to_tensor | 14,240 |
from tensorflow.python.framework import ops
returned_shape = []
for i, dim in enumerate(input_shape.dims):
if i != dimension:
returned_shape.append(dim)
return [tensor_shape.TensorShape(returned_shape)]
else:
raise ValueError(
"dimension (%d) must be in the range [0, %d), where %d is the number "
"of dimensions in the input"
% (dimension, input_shape.ndims, input_shape.ndims))
@ops.RegisterShape("All")
@ops.RegisterShape("Any")
@ops.RegisterShape("Max")
@ops.RegisterShape("Mean")
@ops.RegisterShape("Min")
@ops.RegisterShape("Prod")
@ops.RegisterShape("Sum")
def _ReductionShape(op):
"""Common shape function for reduction ops."""
input_shape = op.inputs[0].get_shape()
reduction_indices = tensor_util.ConstantValue(op.inputs[1])
keep_dims = op.get_attr("keep_dims")
| tensorflow.python.framework.ops.RegisterShape | 14,241 |
import tensorflow as tf
beta1_t = math_ops.cast(self._beta1_t, var.dtype.base_dtype)
beta2_t = math_ops.cast(self._beta2_t, var.dtype.base_dtype)
if var.dtype.base_dtype == tf.float16:
eps = 1e-7 # Can't use 1e-8 due to underflow -- not sure if it makes a big difference.
else:
eps = 1e-8
v = self.get_slot(var, "v")
v_t = v.assign(beta2_t * v + (1. - beta2_t) * tf.square(grad))
m = self.get_slot(var, "m")
m_t = m.assign(beta1_t * m + (1. - beta1_t) * grad)
v_t_hat = tf.div(v_t, 1. - beta2_t)
m_t_hat = tf.div(m_t, 1. - beta1_t)
g_t = tf.div(m_t_hat, tf.sqrt(v_t_hat) + eps)
g_t_1 = self.get_slot(var, "g")
| tensorflow.square | 14,242 |
import tensorflow as tf
time_steps = input_shape[1]
scope_name = 'decoder_{}'.format(decoder.name)
scope_name += '/' + '_'.join(encoder.name for encoder in encoders)
def embed(input_):
embedded_input = tf.nn.embedding_lookup(embedding, input_)
if decoder.use_dropout and decoder.word_keep_prob is not None:
noise_shape = [1, 1] if decoder.pervasive_dropout else [tf.shape(input_)[0], 1]
embedded_input = tf.nn.dropout(embedded_input, keep_prob=decoder.word_keep_prob, noise_shape=noise_shape)
if decoder.use_dropout and decoder.embedding_keep_prob is not None:
| tensorflow.nn.embedding_lookup | 14,243 |
import tensorflow as tf
target_modality = self._problem_hparams.target_modality
with tf.variable_scope(target_modality.name):
| tensorflow.variable_scope | 14,244 |
import tensorflow as tf
pq.put(np.atleast_2d(point.numpy()))
while points_observed < num_observations:
# keep asking queue for new observations until one arrives
try:
new_data = oq.get_nowait()
print(f"Process {pid}: Main : received data {new_data}", flush=True)
except:
continue
# new_data is a tuple of (point, observation value)
# here we turn it into a Dataset and tell of it Trieste
points_observed += 1
new_data = Dataset(
query_points=tf.constant(new_data[0], dtype=tf.float64),
observations=tf.constant(new_data[1], dtype=tf.float64),
)
async_bo.tell(new_data)
# now we can ask Trieste for one more point
# and feed that back into the points queue
point = async_bo.ask()
print(f"Process {pid}: Main : acquired point {point}", flush=True)
pq.put(np.atleast_2d(point))
finally:
terminate_processes(observer_processes)
stop = timeit.default_timer()
# Collect the observations, compute the running time
async_lp_observations = async_bo.to_result().try_get_final_dataset().observations - SCALED_BRANIN_MINIMUM
| tensorflow.constant | 14,245 |
import tensorflow as tf
tf.summary.scalar('Loss/Total', loss)
tf.summary.scalar('Var/Epsilon', epsilon_decay)
tf.summary.scalar('Var/Policy Mode', tf.reduce_mean(pi.mode()))
tf.summary.scalar('Var/Policy Sigma', tf.reduce_mean(pi.stddev()))
tf.summary.scalar('Var/Value', tf.reduce_mean(self.vf))
self.summarise = tf.summary.merge(tf.get_collection(tf.GraphKeys.SUMMARIES))
# AC net
def build_anet(self, state_in, name, reuse=False):
reg = tf.contrib.layers.l2_regularizer(1e-3)
with tf.variable_scope(name, reuse=reuse):
layer_a1 = tf.layers.dense(state_in, 512, tf.nn.relu, kernel_regularizer=reg)
layer_a2 = tf.layers.dense(layer_a1, 256, tf.nn.relu, kernel_regularizer=reg)
mu = tf.layers.dense(layer_a2, self.a_dim, tf.nn.tanh, kernel_regularizer=reg)
# sigma = tf.layers.dense(layer_a2, self.a_dim, tf.nn.softplus, kernel_regularizer=reg)
sigma = tf.get_variable(name='pi_sigma', shape=self.a_dim, initializer=tf.constant_initializer(0.5))
sigma = tf.clip_by_value(sigma, 0.0, 1.0)
norm_dist = tf.distributions.Normal(loc=mu * self.a_bound, scale=sigma)
params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=name)
return norm_dist, params
def build_cnet(self, state_in, name, reuse=False):
| tensorflow.layers.dense | 14,246 |
import tensorflow as tf
return image
def validation_mapper(byte):
image = tf.image.decode_jpeg(
tf.reshape(byte, shape=[]), 3, **JPEG_OPT)
image = resize_shortest_edge(image, tf.shape(image), 256)
image = center_crop(image, 224)
image = tf.reverse(image, axis=[2]) # to BGR
return image
def training_mapper(byte):
jpeg_shape = tf.image.extract_jpeg_shape(byte) # hwc
bbox_begin, bbox_size, distort_bbox = tf.image.sample_distorted_bounding_box(
jpeg_shape,
bounding_boxes=tf.zeros(shape=[0, 0, 4]),
min_object_covered=0,
aspect_ratio_range=[0.75, 1.33],
area_range=[0.08, 1.0],
max_attempts=10,
use_image_if_no_bounding_boxes=True)
is_bad = tf.reduce_sum(tf.cast(tf.equal(bbox_size, jpeg_shape), tf.int32)) >= 2
def good():
offset_y, offset_x, _ = tf.unstack(bbox_begin)
target_height, target_width, _ = tf.unstack(bbox_size)
crop_window = tf.stack([offset_y, offset_x, target_height, target_width])
| tensorflow.zeros | 14,247 |
import tensorflow as tf
optimizer = tf.train.MomentumOptimizer(learning_rate=truncated_learning_rate,
momentum=params['momentum'])
# Batch norm requires update_ops to be added as a train_op dependency.
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
train_op = optimizer.minimize(loss, global_step)
else:
train_op = None
return tf.estimator.EstimatorSpec(
| tensorflow.control_dependencies | 14,248 |
import tensorflow as tf
fname = os.path.join(tf.resource_loader.get_data_files_path(),
'samples/configs/' + model_name + '.config')
label_map_path = os.path.join(tf.resource_loader.get_data_files_path(),
'data/pet_label_map.pbtxt')
| tensorflow.resource_loader.get_data_files_path | 14,249 |
import tensorflow as tf
+ self.b_out
return new_output
def rnn_step_scan(self, state, rnn_in):
if self.dale_ratio:
new_state = (1-self.alpha) * state \
+ self.alpha * (
tf.matmul(
tf.nn.relu(state),
tf.matmul(
tf.abs(self.W_rec) * self.rec_Connectivity,
self.Dale_rec, name="in_1"),
transpose_b=True, name="1")
+ tf.matmul(
rnn_in,
tf.abs(self.W_in) * self.input_Connectivity,
transpose_b=True, name="2")
+ self.b_rec) \
+ np.sqrt(2.0 * self.alpha * self.rec_noise * self.rec_noise)\
* tf.random_normal(state.get_shape(), mean=0.0, stddev=1.0)
else:
new_state = ((1 - self.alpha) * state) \
| tensorflow.abs | 14,250 |
import tensorflow as tf
x = tf.reshape(x, x_shape[:-2] + [-1])
dropout = getattr(self.hparams, "dropout_ppo", 0.0)
with tf.variable_scope("feed_forward_cnn_small"):
x = tf.cast(x, tf.float32) / 255.0
| tensorflow.variable_scope | 14,251 |
import tensorflow as tf
:param name:
:param inputdata:
:param keep_prob:
:param noise_shape:
:return:
"""
return tf.nn.dropout(inputdata, keep_prob=keep_prob, noise_shape=noise_shape, name=name)
@staticmethod
def fullyconnect(inputdata, out_dim, w_init=None, b_init=None,
use_bias=True, name=None):
"""
| tensorflow.nn.dropout | 14,252 |
import tensorflow as tf
def tensorflow_session(gpu_memory_fraction):
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.gpu_options.per_process_gpu_memory_fraction = gpu_memory_fraction
| tensorflow.ConfigProto | 14,253 |
import tensorflow as tf
max_predictions_per_seq=FLAGS.max_predictions_per_seq,
is_training=True,
)
eval_input_fn = input_fn_builder(
input_files=input_files,
max_seq_length=FLAGS.max_seq_length,
max_predictions_per_seq=FLAGS.max_predictions_per_seq,
is_training=False,
)
tf.estimator.train_and_evaluate(
estimator,
train_spec=tf.estimator.TrainSpec(input_fn=train_input_fn, max_steps=100),
eval_spec=tf.estimator.EvalSpec(input_fn=eval_input_fn, steps=10),
)
# if FLAGS.do_train:
# tf.logging.info("***** Running training *****")
# tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
# train_input_fn = input_fn_builder(
# input_files=input_files,
# max_seq_length=FLAGS.max_seq_length,
# max_predictions_per_seq=FLAGS.max_predictions_per_seq,
# is_training=True)
| tensorflow.estimator.TrainSpec | 14,254 |
import tensorflow as tf
w1 = tf.Variable(tf.random_normal([hidden_size, attention_size], stddev=0.1))
w2 = tf.Variable(tf.random_normal([input_size, attention_size], stddev=0.1))
b = tf.Variable(tf.random_normal([attention_size], stddev=0.1))
v = tf.Variable(tf.random_normal([attention_size], stddev=0.1))
with tf.name_scope('v'):
# Applying fully connected layer with non-linear activation to each of the B*T timestamps;
# the shape of `tmp` is (B,T,D)*(D,A)=(B,T,A), where A=attention_size
tmp1 = tf.tensordot(facts, w1, axes=1)
tmp2 = tf.tensordot(query, w2, axes=1)
| tensorflow.name_scope | 14,255 |
import tensorflow as tf
def mgpu_train(*xs):
gpu_ops = []
gpu_grads = []
xs = (tf.split(x, n_gpu, 0) for x in xs)
for i, xs in enumerate(zip(*xs)):
do_reuse = True if i > 0 else None
with tf.device(assign_to_gpu(i, "/gpu:0")), tf.variable_scope(tf.get_variable_scope(), reuse=do_reuse):
| tensorflow.split | 14,256 |
import tensorflow as tf
tf.Summary.Value(tag="Tacotron_eval_model/eval_stats/eval_loss", simple_value=loss),
]
if linear_loss is not None:
values.append(tf.Summary.Value(tag="Tacotron_eval_model/eval_stats/eval_linear_loss",
simple_value=linear_loss))
test_summary = tf.Summary(value=values)
| tensorflow.Summary.Value | 14,257 |
import tensorflow as tf
)
# add l2 regularization
with tf.name_scope('weight_decay'):
add_weight_decay(params['weight_decay'])
regularization_loss = tf.losses.get_regularization_loss()
| tensorflow.name_scope | 14,258 |
import tensorflow as tf
v1 = tf.Variable(20.0, name="v1")
save = tf.train.Saver([v0, v1])
tf.initialize_all_variables().run()
| tensorflow.initialize_all_variables | 14,259 |
import tensorflow as tf
apply_attack_loop(hps)
elif FLAGS.mode == 'tSNE_logits':
if is_carliniL2 == True:
tSNE_visual_carliniLi(hps,num_batch)
else:
tSNE_visual(hps,num_batch)
if __name__ == '__main__':
tf.logging.set_verbosity(tf.logging.INFO)
tf.app.run() | tensorflow.app.run | 14,260 |
import tensorflow as tf
# segment.
#
# If you want to use the token-level output, use model_bak.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)
| tensorflow.truncated_normal_initializer | 14,261 |
import tensorflow as tf
if k:
return tf.transpose(split_states(x, n), [0, 2, 3, 1])
else:
return tf.transpose(split_states(x, n), [0, 2, 1, 3])
def merge_heads(x):
#[-1,head,n_ctx,emb]
return merge_states(tf.transpose(x, [0, 2, 1, 3]))
def conv1d(x, scope, nf, rf, w_init=tf.random_normal_initializer(stddev=0.02), b_init=tf.constant_initializer(0), pad='VALID', train=False):
with tf.variable_scope(scope):
#x = [-1,n_ctx,512]
nx = shape_list(x)[-1]
#rf = 1,nx=emb,nf=3*emb
| tensorflow.transpose | 14,262 |
import tensorflow as tf
A `TestData` tuple containing numpy values representing the results.
"""
def _adaptive_one_to_many_encode_decode(state):
"""Implementation of the method for `AdaptiveEncodingStageInterface`."""
server_graph = tf.Graph()
with server_graph.as_default():
x = input_fn()
shape = py_utils.static_or_dynamic_shape(x)
if state is None:
| tensorflow.Graph | 14,263 |
import tensorflow as tf
def conv2d(x, shape, name, bias=False, stride=2, padding='SAME'):
with tf.variable_scope(name):
W = weight_variable(shape)
h = tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding=padding)
if bias:
b = bias_variable([shape[-1]])
h = h + b
return h
def deconv2d(x, shape, output_shape, name, bias=False, stride=2, padding='SAME'):
with tf.variable_scope(name):
W = weight_variable(shape)
h = tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, stride, stride, 1], padding=padding)
if bias:
b = bias_variable([shape[-2]])
h = h + b
return h
def conv3d(x, shape, name, bias=False, stride=2, padding='SAME'):
with tf.variable_scope(name):
W = weight_variable(shape)
| tensorflow.variable_scope | 14,264 |
import tensorflow as tf
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import tensorflow as tf
import tensorflow.contrib.metrics as metrics
import tensorflow.contrib.rnn as rnn
tf.logging.set_verbosity(tf.logging.INFO)
SEQ_LEN = 10
DEFAULTS = [[0.0] for x in range(0, SEQ_LEN)]
BATCH_SIZE = 20
TIMESERIES_INPUT_LAYER = 'rawdata'
TIMESERIES_COL = '{}_input'.format(TIMESERIES_INPUT_LAYER)
# In each sequence, column index 0 to N_INPUTS - 1 are features, and column index N_INPUTS to SEQ_LEN are labels
| tensorflow.logging.set_verbosity | 14,265 |
import tensorflow as tf
key_masks = mask # [B, 1, T]
# key_masks = tf.expand_dims(mask, 1) # [B, 1, T]
paddings = tf.ones_like(v_dot_tmp) * (-2 ** 32 + 1)
v_dot_tmp = tf.where(key_masks, v_dot_tmp, paddings) # [B, 1, T]
alphas = tf.nn.softmax(v_dot_tmp, name='alphas') # (B,T) shape
# Output of (Bi-)RNN is reduced with attention vector; the result has (B,D) shape
#output = tf.reduce_sum(facts * tf.expand_dims(alphas, -1), 1)
output = facts * tf.expand_dims(alphas, -1)
output = tf.reshape(output, tf.shape(facts))
# output = output / (facts.get_shape().as_list()[-1] ** 0.5)
if not return_alphas:
return output
else:
return output, alphas
| tensorflow.expand_dims | 14,266 |
import tensorflow as tf
grid = tf.expand_dims(tf.stack(grid, axis=-1), axis=2) # [gx, gy, 1, 2]
box_xy = (box_xy + tf.cast(grid, dtype)) * stride
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,
| tensorflow.reshape | 14,267 |
import tensorflow as tf
w_c = tf.get_variable('w_c', [self.D, self.H], initializer=self.weight_initializer)
b_c = tf.get_variable('b_c', [self.H], initializer=self.const_initializer)
c = tf.nn.tanh(tf.matmul(features_mean, w_c) + b_c)
return c, h
| tensorflow.matmul | 14,268 |
import tensorflow as tf
"output_weights",
shape=[2, bert_config.hidden_size],
initializer=modeling.create_initializer(bert_config.initializer_range))
output_bias = tf.get_variable(
"output_bias", shape=[2], initializer=tf.zeros_initializer())
logits = tf.matmul(input_tensor, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
log_probs = tf.nn.log_softmax(logits, axis=-1)
labels = tf.reshape(labels, [-1])
one_hot_labels = tf.one_hot(labels, depth=2, dtype=tf.float32)
per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
| tensorflow.matmul | 14,269 |
import tensorflow as tf
def circuit_input(self, h2, layer, var_scope, layer_idx):
"""Calculate gain and inh horizontal activities."""
gain_kernels = getattr(self, 'gain_kernels_%s' % layer)
gain_bias = getattr(self, 'gain_bias_%s' % layer)
horizontal_kernels = getattr(self, 'horizontal_kernels_%s' % layer)
# h_bias = getattr(self, 'h_bias_%s' % layer)
g1_intermediate = self.conv_3d_op(
data=h2,
weights=gain_kernels,
strides=[1, 1, 1, 1, 1],
symmetric_weights=self.symmetric_gate_weights,
dilations=self.hgru_dilations[layer_idx])
with tf.variable_scope(
'%s/g1_bn' % var_scope,
reuse=self.scope_reuse) as scope:
g1_intermediate = tf.contrib.layers.batch_norm(
inputs=g1_intermediate + gain_bias,
scale=True,
center=False,
fused=True,
renorm=False,
param_initializers=self.param_initializer,
updates_collections=None,
scope=scope,
| tensorflow.variable_scope | 14,270 |
import tensorflow as tf
if self._apply_sigmoid_to_scores:
class_predictions_with_background = tf.sigmoid(
class_predictions_with_background)
combined_feature_map_shape = shape_utils.combined_static_and_dynamic_shape(
image_features)
box_encodings = tf.reshape(
box_encodings, tf.stack([combined_feature_map_shape[0],
combined_feature_map_shape[1] *
combined_feature_map_shape[2] *
num_predictions_per_location,
1, self._box_code_size]))
class_predictions_with_background = tf.reshape(
class_predictions_with_background,
| tensorflow.stack | 14,271 |
import tensorflow as tf
def build_training_model(self, x, y):
"""
This method will be called once by all data owners
to create a local gradient computation on their machine.
"""
_, _, grads = self._build_model(x, y)
return grads
def _build_validation_model(self, x, y):
predictions, loss, _ = self._build_model(x, y)
most_likely = tf.argmax(predictions, axis=1)
return most_likely, loss
def _build_data_pipeline(self):
def normalize(image, label):
image = tf.cast(image, tf.float32) / 255.0
return image, label
dataset = tf.data.TFRecordDataset(["./data/train.tfrecord"])
| tensorflow.argmax | 14,272 |
import tensorflow as tf
for key, value in metrics.items():
key = 'metrics_{}_{}'.format(name, key)
mean = tools.StreamingMean((), tf.float32, key)
means.append(mean)
updates.append(mean.submit(value))
with tf.control_dependencies(updates):
# message = 'step/' + '/'.join(metrics.keys()) + ' = '
message = '{}: step/{} ='.format(name, '/'.join(metrics.keys()))
gs = tf.train.get_or_create_global_step()
print_metrics = tf.cond(
tf.equal(step % every, 0),
lambda: tf.print(message, [gs] + [mean.clear() for mean in means]),
tf.no_op)
return print_metrics
| tensorflow.train.get_or_create_global_step | 14,273 |
import tensorflow as tf
return v
if init:
x = tf.nn.conv2d_transpose(x, tf.nn.l2_normalize(V.initialized_value(), [0, 1, 3]), target_shape, [1] + list(stride) + [1], padding=pad)
init_scale = .01
m_init, v_init = tf.nn.moments(x, [0, 1, 2])
scale_init = init_scale / tf.sqrt(v_init + 1e-10)
with tf.control_dependencies([g.assign(g * scale_init), b.assign_add(-m_init * scale_init)]):
x = tf.reshape(scale_init, [1, 1, 1, num_filters]) * (x - tf.reshape(m_init, [1, 1, 1, num_filters]))
else:
V = maybe_avg(V)
g = maybe_avg(g)
| tensorflow.sqrt | 14,274 |
import tensorflow as tf
mask_ratio = mask_ratio * update_mask
with tf.variable_scope('parconv'):
x = tf.nn.conv2d(input, filters, strides=[1, stride, stride, 1], padding="SAME", name='zero-conv_' + id,
| tensorflow.variable_scope | 14,275 |
import tensorflow as tf
test_data = dh.load_data_and_labels(args.test_file, args.word2vec_file, data_aug_flag=False)
logger.info("Data padding...")
x_test_content, x_test_question, x_test_option, y_test = dh.pad_data(test_data, args.pad_seq_len)
# Load tarnn model
OPTION = dh.option(pattern=1)
if OPTION == 'B':
logger.info("Loading best model...")
checkpoint_file = cm.get_best_checkpoint(BEST_CPT_DIR, select_maximum_value=True)
else:
logger.info("Loading latest model...")
checkpoint_file = tf.train.latest_checkpoint(CPT_DIR)
logger.info(checkpoint_file)
graph = tf.Graph()
with graph.as_default():
session_conf = tf.ConfigProto(
allow_soft_placement=args.allow_soft_placement,
log_device_placement=args.log_device_placement)
session_conf.gpu_options.allow_growth = args.gpu_options_allow_growth
sess = tf.Session(config=session_conf)
with sess.as_default():
# Load the saved meta graph and restore variables
saver = tf.train.import_meta_graph("{0}.meta".format(checkpoint_file))
saver.restore(sess, checkpoint_file)
# Get the placeholders from the graph by name
input_x_content = graph.get_operation_by_name("input_x_content").outputs[0]
input_x_question = graph.get_operation_by_name("input_x_question").outputs[0]
| tensorflow.Graph | 14,276 |
import tensorflow as tf
if K.backend() == 'tensorflow':
import tensorflow as tf
I, J = tf.meshgrid(i, j, indexing=indexing)
else:
| tensorflow.meshgrid | 14,277 |
import tensorflow as tf
def LSGAN_losses(real, fake):
d_real = tf.reduce_mean(tf.squared_difference(real, 1), name='d_real')
| tensorflow.squared_difference | 14,278 |
import tensorflow as tf
self.g_variables = [var for var in trainable_variables if 'generator' in var.name]
print ('Variable printing start :' )
for var in self.d_variables:
print(var.name)
self.test_image_A = tf.placeholder(tf.float32,[None, self.image_size,self.image_size,self.input_dim], name='test_A')
self.test_image_B = tf.placeholder(tf.float32,[None, self.image_size, self.image_size,self.output_c_dim], name='test_B')
self.saver = tf.train.Saver()
def train_network(self):
self.learning_rate = tf.placeholder(tf.float32)
| tensorflow.placeholder | 14,279 |
from tensorflow.python.ops import array_ops
return array_ops.reshape(
math_ops.to_float(features[self._weight_column_name]), shape=(-1,))
@property
def problem_type(self):
return self._problem_type
def _weighted_loss(self, loss, weight_tensor):
"""Returns cumulative weighted loss."""
unweighted_loss = array_ops.reshape(loss, shape=(-1,))
weighted_loss = math_ops.multiply(unweighted_loss,
array_ops.reshape(
weight_tensor, shape=(-1,)))
return weighted_loss
def training_loss(self, logits, target, features, name="training_loss"):
"""Returns training loss tensor for this head.
Training loss is different from the loss reported on the tensorboard as we
should respect the example weights when computing the gradient.
L = sum_{i} w_{i} * l_{i} / B
| tensorflow.python.ops.array_ops.reshape | 14,280 |
import tensorflow as tf
'layer_depth': [-1, -1, 512, 256, 256, 128],
'use_explicit_padding': self._use_explicit_padding,
'use_depthwise': self._use_depthwise,
}
with slim.arg_scope(self._conv_hyperparams_fn()):
with tf.variable_scope('InceptionV2',
reuse=self._reuse_weights) as scope:
_, image_features = inception_v2.inception_v2_base(
ops.pad_to_multiple(preprocessed_inputs, self._pad_to_multiple),
final_endpoint='Mixed_5c',
min_depth=self._min_depth,
| tensorflow.variable_scope | 14,281 |
import tensorflow as tf
"""
class PolicyEstimator_Pendulum():
def __init__(self, entropy_beta=0.01, learning_rate=0.01, par_idx=0,scope="policy_estimator"):
w_init = tf.random_normal_initializer(0.,.1);
with tf.variable_scope(scope+"_"+str(par_idx)):
# state, target and action
self.state = tf.placeholder(tf.float32, [None,num_state], name="state")
self.target = tf.placeholder(tf.float32,[None,1], name="target")
self.a_his = tf.placeholder(tf.float32, [None, num_action], name="action_hist")
# layers
l_a = tf.layers.dense(self.state, 200, tf.nn.relu6, kernel_initializer=w_init, name='la')
self.mu = tf.layers.dense(l_a, num_action, tf.nn.tanh, kernel_initializer=w_init, name='mu') # estimated action value
self.sigma = tf.layers.dense(l_a, num_action, tf.nn.softplus, kernel_initializer=w_init, name='sigma') # estimated variance
# wrap output
self.mu = self.mu * action_bound[1];
self.sigma = self.sigma + 1e-4
# get action from distribution
self.normal_dist = tf.contrib.distributions.Normal(self.mu, self.sigma)
self.action = tf.squeeze(self.normal_dist.sample(1),axis=0);
self.action = tf.clip_by_value(self.action, action_bound[0], action_bound[1])
# Loss and train op
self.loss = -self.normal_dist.log_prob(self.a_his) * self.target
# Add cross entropy cost to encourage exploration
| tensorflow.layers.dense | 14,282 |
from tensorflow.python.training import saver
supervisor_master=self._config.master,
feed_fn=feed_fn,
max_steps=steps)
return eval_results
def _infer_model(self, x, batch_size=None, axis=None, proba=False):
# Converts inputs into tf.DataFrame / tf.Series.
batch_size = -1 if batch_size is None else batch_size
input_fn, feed_fn = _get_predict_input_fn(x, batch_size)
checkpoint_path = saver.latest_checkpoint(self._model_dir)
with ops.Graph().as_default() as g:
random_seed.set_random_seed(self._config.tf_random_seed)
contrib_framework.create_global_step(g)
features, _ = input_fn()
feed_dict = feed_fn() if feed_fn is not None else None
predictions = self._get_predict_ops(features)
if not isinstance(predictions, dict):
predictions = {'predictions': predictions}
# TODO(ipolosukhin): Support batching
| tensorflow.python.training.saver.latest_checkpoint | 14,283 |
import tensorflow as tf
x = self.__conv2d("conv_1", x, filter_depth=64,
kernel_size=7, stride=2, padding='valid')
x = self.__batch_norm("bn_1", x)
x = tf.nn.relu(x)
x = tf.keras.layers.MaxPool2D(pool_size = 3, strides = 2, padding = 'same')(x)
x = self.__conv_block(stage=0, block=0, inputs=x,
filter_depths=[32, 32, 128],
kernel_size=3, stride=1)
x = self.__identity_block(stage=0, block=1, inputs=x,
| tensorflow.keras.layers.MaxPool2D | 14,284 |
import tensorflow as tf
else:
groundtruth_confidences = tf.ones_like(
zero_indexed_groundtruth_classes, dtype=tf.float32)
tensor_dict[fields.InputDataFields.groundtruth_confidences] = (
tensor_dict[fields.InputDataFields.groundtruth_classes])
if merge_multiple_boxes:
merged_boxes, merged_classes, merged_confidences, _ = (
util_ops.merge_boxes_with_multiple_labels(
tensor_dict[fields.InputDataFields.groundtruth_boxes],
zero_indexed_groundtruth_classes,
groundtruth_confidences,
num_classes))
merged_classes = tf.cast(merged_classes, tf.float32)
tensor_dict[fields.InputDataFields.groundtruth_boxes] = merged_boxes
tensor_dict[fields.InputDataFields.groundtruth_classes] = merged_classes
tensor_dict[fields.InputDataFields.groundtruth_confidences] = (
merged_confidences)
if fields.InputDataFields.groundtruth_boxes in tensor_dict:
tensor_dict[fields.InputDataFields.num_groundtruth_boxes] = tf.shape(
tensor_dict[fields.InputDataFields.groundtruth_boxes])[0]
return tensor_dict
def pad_input_data_to_static_shapes(tensor_dict, max_num_boxes, num_classes,
| tensorflow.cast | 14,285 |
import tensorflow as tf
# FIXME: augment error:tensorflow.python.framework.errors_impl.InvalidArgumentError: indices[0] = 0 is not in [0, 0)
tf.logging.info('Starting a training cycle.')
fashionAI.train(input_fn=lambda : input_pipeline(True, model_scope, epochs_per_eval), hooks=[logging_hook], max_steps=(steps_per_epoch*train_epochs))
tf.logging.info('Starting to evaluate.')
eval_results = fashionAI.evaluate(input_fn=lambda : input_pipeline(False, model_scope, 1))
tf.logging.info(eval_results)
tf.logging.info('Finished model {}.'.format(model_scope))
| tensorflow.logging.info | 14,286 |
import tensorflow as tf
gcnn_models += ['mean_convolution', 'no_prenorm']
result_file = f"results/{args.problem}_test_{time.strftime('%Y%m%d-%H%M%S')}"
result_file = result_file + '.csv'
os.makedirs('results', exist_ok=True)
### TENSORFLOW SETUP ###
if args.gpu == -1:
os.environ['CUDA_VISIBLE_DEVICES'] = ''
else:
os.environ['CUDA_VISIBLE_DEVICES'] = f'{args.gpu}'
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
tf.enable_eager_execution(config)
tf.executing_eagerly()
test_files = list(pathlib.Path(f"data/samples/{problem_folder}/test").glob('sample_*.pkl'))
test_files = [str(x) for x in test_files]
print(f"{len(test_files)} test samples")
evaluated_policies = [['gcnn', model] for model in gcnn_models] + \
[['ml-competitor', model] for model in other_models]
fieldnames = [
'policy',
'seed',
| tensorflow.enable_eager_execution | 14,287 |
import tensorflow as tf
self.assertAllEqual(
padded_tensor_dict[fields.InputDataFields.image].shape.as_list(),
[None, None, 3])
def test_images_and_additional_channels(self):
input_tensor_dict = {
fields.InputDataFields.image:
tf.placeholder(tf.float32, [None, None, 5]),
fields.InputDataFields.image_additional_channels:
tf.placeholder(tf.float32, [None, None, 2]),
}
padded_tensor_dict = inputs.pad_input_data_to_static_shapes(
tensor_dict=input_tensor_dict,
max_num_boxes=3,
| tensorflow.placeholder | 14,288 |
import tensorflow as tf
Return the input tensor, offset by a certain value
:param input_tensor: (TensorFlow Tensor) The input tensor
:param idx: (int) The index offset
:return: (TensorFlow Tensor) the offset tensor
"""
assert len(input_tensor.get_shape()) == 2
assert len(idx.get_shape()) == 1
idx_flattened = tf.range(0, input_tensor.shape[0], dtype=tf.int64) * input_tensor.shape[1] + idx
offset_tensor = tf.gather(tf.reshape(input_tensor, [-1]), # flatten input
idx_flattened) # use flattened indices
return offset_tensor
def strip(var, n_envs, n_steps, flat=False):
"""
Removes the last step in the batch
| tensorflow.reshape | 14,289 |
import tensorflow as tf
'''
pass
def loss(logits, labels):
'''
Compute loss
'''
with tf.name_scope('loss') as scope:
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=labels, name='cross-entropy')
loss = tf.reduce_mean(cross_entropy, name='loss')
tf.summary.scalar(scope+'/loss', loss)
return loss
| tensorflow.name_scope | 14,290 |
import tensorflow as tf
# loss = tf.maximum(0.0, tf.math.abs(tgt_larg - pred_larg) - tf.math.abs(tgt_small - pred_small))
loss = tf.reduce_mean(loss)
return loss
def contra_step_lossV5(pred, tgt, resample=1):
# p = tf.print('begin loss v5', [resample, pred.shape,tgt.shape])
# with tf.control_dependencies([p]):
pred_flat = tf.reshape(pred, [-1])
tgt_flat = tf.reshape(tgt, [-1])
batch = tf.stack([pred_flat, tgt_flat], 1)
num_sam = tools.shape(batch)[0]
index = tf.range(num_sam)
divider = tf.constant(resample, dtype=tf.float32)
def sample_compute(cur_loss, i):
batch1 = tf.gather(batch, tf.random.shuffle(index))
batch2 = tf.gather(batch, tf.random.shuffle(index))
| tensorflow.reshape | 14,291 |
import tensorflow as tf
initializer=tf.constant_initializer(self.dale_out),
trainable=False)
# Connectivity weight matrices:
self.input_Connectivity = tf.get_variable('input_Connectivity', [N_rec, N_in],
initializer=tf.constant_initializer(
self.input_connectivity_mask),
trainable=False)
self.rec_Connectivity = tf.get_variable('rec_Connectivity', [N_rec, N_rec],
initializer=tf.constant_initializer(
self.recurrent_connectivity_mask),
trainable=False)
self.output_Connectivity = tf.get_variable('output_Connectivity', [N_out, N_rec],
initializer=tf.constant_initializer(
self.output_connectivity_mask),
trainable=False)
# ------------------------------------------------
| tensorflow.constant_initializer | 14,292 |
import tensorflow as tf
elif encoder.cell_type.lower() == 'dropoutgru':
cell = DropoutGRUCell(encoder.cell_size, reuse=reuse, layer_norm=encoder.layer_norm,
input_size=input_size, input_keep_prob=encoder.rnn_input_keep_prob,
state_keep_prob=encoder.rnn_state_keep_prob)
else:
cell = GRUCell(encoder.cell_size, reuse=reuse, layer_norm=encoder.layer_norm)
if encoder.use_dropout and encoder.cell_type.lower() != 'dropoutgru':
cell = DropoutWrapper(cell, input_keep_prob=encoder.rnn_input_keep_prob,
output_keep_prob=encoder.rnn_output_keep_prob,
state_keep_prob=encoder.rnn_state_keep_prob,
variational_recurrent=encoder.pervasive_dropout,
dtype=tf.float32, input_size=input_size)
return cell
batch_size = tf.shape(encoder_inputs_)[0]
time_steps = tf.shape(encoder_inputs_)[1]
if embeddings is not None:
flat_inputs = tf.reshape(encoder_inputs_, [tf.multiply(batch_size, time_steps)])
flat_inputs = tf.nn.embedding_lookup(embeddings, flat_inputs)
encoder_inputs_ = tf.reshape(flat_inputs,
tf.stack([batch_size, time_steps, flat_inputs.get_shape()[1].value]))
if pos_embeddings is not None:
pos_inputs_ = tf.range(time_steps, dtype=tf.int32)
pos_inputs_ = tf.nn.embedding_lookup(pos_embeddings, pos_inputs_)
pos_inputs_ = tf.tile(tf.expand_dims(pos_inputs_, axis=0), [batch_size, 1, 1])
encoder_inputs_ = tf.concat([encoder_inputs_, pos_inputs_], axis=2)
if other_inputs is not None:
| tensorflow.shape | 14,293 |
import tensorflow as tf
if FLAGS.do_train:
train_file = os.path.join(FLAGS.output_dir, "train.tf_record")
if not tf.gfile.Exists(train_file) or not FLAGS.data_converted:
file_based_convert_examples_to_features(
train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file)
tf.logging.info("***** Running training *****")
tf.logging.info(" Num examples = %d", len(train_examples))
tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
tf.logging.info(" Num steps = %d", num_train_steps)
train_input_fn = file_based_input_fn_builder(
input_file=train_file,
seq_length=FLAGS.max_seq_length,
is_training=True,
drop_remainder=True)
| tensorflow.logging.info | 14,294 |
import tensorflow as tf
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(masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids,
masked_lm_weights, next_sentence_example_loss,
next_sentence_log_probs, next_sentence_labels):
"""Computes the loss and accuracy of the model."""
masked_lm_log_probs = tf.reshape(masked_lm_log_probs,
[-1, masked_lm_log_probs.shape[-1]])
masked_lm_predictions = tf.argmax(
masked_lm_log_probs, axis=-1, output_type=tf.int32)
masked_lm_example_loss = tf.reshape(masked_lm_example_loss, [-1])
masked_lm_ids = tf.reshape(masked_lm_ids, [-1])
masked_lm_weights = tf.reshape(masked_lm_weights, [-1])
masked_lm_accuracy = tf.metrics.accuracy(
labels=masked_lm_ids,
predictions=masked_lm_predictions,
weights=masked_lm_weights)
| tensorflow.reshape | 14,295 |
import tensorflow as tf
self.vars=self.vars[-1*NUM_VARS:];
self.train_op = self.optimizer.apply_gradients(
self.grads_and_vars, global_step=tf.contrib.framework.get_global_step())
def predict(self, state, sess=None):
sess = sess or tf.get_default_session()
return sess.run(self.action, { self.state: [state] })[0]
def update(self, state, target, a_his, sess=None):
sess = sess or tf.get_default_session()
feed_dict = { self.state: state, self.target: target, self.a_his: a_his }
_, loss = sess.run([self.train_op, self.loss], feed_dict)
return loss
class ValueEstimator_Pendulum():
def __init__(self, learning_rate=0.1, par_idx=0,scope="value_estimator"):
w_init = tf.random_normal_initializer(0.,.1);
with tf.variable_scope(scope+"_"+str(par_idx)):
| tensorflow.get_default_session | 14,296 |
import tensorflow as tf
status = True
if status:
box_limits_x = [100, -100]
# box_limits_y = [100, -100]
box_limits_z = [100, -100]
for i in range(labeled_translations.shape[0]):
rot = tf.reshape(tf.gather(labeled_rotations[i], [0, 2, 6, 8]), [2, 2])
min_x = tf.cast(0.0 - labeled_sizes[i][0] / 2.0, dtype=tf.float32)
max_x = tf.cast(0.0 + labeled_sizes[i][0] / 2.0, dtype=tf.float32)
# min_y = tf.cast(0.0 - labeled_sizes[i][1] / 2.0, dtype=tf.float32)
# max_y = tf.cast(0.0 + labeled_sizes[i][1] / 2.0, dtype=tf.float32)
min_z = tf.cast(0.0 - labeled_sizes[i][2] / 2.0, dtype=tf.float32)
max_z = tf.cast(0.0 + labeled_sizes[i][2] / 2.0, dtype=tf.float32)
translation = tf.reshape([labeled_translations[i][0],
labeled_translations[i][2]], [2, 1])
| tensorflow.cast | 14,297 |
import tensorflow as tf
def get_mention_scores(self, span_emb):
with tf.variable_scope("mention_scores"):
| tensorflow.variable_scope | 14,298 |
import tensorflow as tf
with tf.variable_scope(scope):
shape = tf.shape(inputs)
dim = inputs.get_shape().as_list()[-1]
out_shape = [shape[idx] for idx in range(
len(inputs.get_shape().as_list()) - 1)] + [hidden]
flat_inputs = tf.reshape(inputs, [-1, dim])
W = tf.get_variable("W", [dim, hidden])
res = tf.matmul(flat_inputs, W)
if use_bias:
b = tf.get_variable(
"b", [hidden], initializer=tf.constant_initializer(0.))
res = tf.nn.bias_add(res, b)
res = tf.reshape(res, out_shape)
return res
| tensorflow.reshape | 14,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.