seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
import tensorflow as tf
tf.less(
matched_iou, self._config_dict['background_iou_high_threshold']))
ignored_matches = tf.logical_and(
tf.less(matched_iou, 0.0),
tf.greater_equal(
matched_iou, self._config_dict['background_iou_high_threshold']))
ignored_matches = tf.logical_and(
ignored_matches,
tf.less(
matched_iou, self._config_dict['foreground_iou_threshold']))
background_indicator = tf.logical_or(negative_matches, ignored_matches)
# re-assign negatively matched boxes to the background class.
matched_gt_boxes = tf.where(
tf.tile(tf.expand_dims(background_indicator, -1), [1, 1, 4]),
tf.zeros_like(matched_gt_boxes),
matched_gt_boxes)
matched_gt_classes = tf.where(
background_indicator,
tf.zeros_like(matched_gt_classes),
matched_gt_classes)
| tensorflow.logical_or | 12,500 |
import tensorflow as tf
# GPU setup
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False, device_count={'GPU': gpu})
config.gpu_options.allow_growth = True
config.gpu_options.per_process_gpu_memory_fraction = 0.5
# Placeholders
self.sess = tf.Session(config=config)
self.s_dim, self.a_dim = env.observation_space.shape, env.action_space.shape[0]
self.a_bound = (env.action_space.high - env.action_space.low) / 2
self.actions = tf.placeholder(tf.float32, [None, self.a_dim], 'action')
self.state = tf.placeholder(tf.float32, [None, self.s_dim[0]], 'state')
self.advantage = tf.placeholder(tf.float32, [None, 1], 'advantage')
self.rewards = tf.placeholder(tf.float32, [None, 1], 'rewards')
self.keep_prob = tf.placeholder(tf.float32, name='dropout_keep_prob')
# Dateset with experiennce replay
self.dataset = tf.data.Dataset.from_tensor_slices({'state': self.state, 'actions': self.actions,
'rewards': self.rewards, 'advantage': self.advantage})
self.dataset = self.dataset.batch(self.MINIBATCH, drop_remainder=True)
| tensorflow.placeholder | 12,501 |
import tensorflow as tf
:return:
"""
with tf.variable_scope(name):
inputdata = tf.transpose(inputdata, [0, 3, 1, 2])
n, c, h, w = inputdata.get_shape().as_list()
group_size = min(group_size, c)
inputdata = tf.reshape(inputdata, [-1, group_size, c // group_size, h, w])
mean, var = tf.nn.moments(inputdata, [2, 3, 4], keep_dims=True)
inputdata = (inputdata - mean) / tf.sqrt(var + esp)
# 每个通道的gamma和beta
gamma = tf.Variable(tf.constant(1.0, shape=[c]), dtype=tf.float32, name='gamma')
beta = tf.Variable(tf.constant(0.0, shape=[c]), dtype=tf.float32, name='beta')
gamma = tf.reshape(gamma, [1, c, 1, 1])
beta = tf.reshape(beta, [1, c, 1, 1])
| tensorflow.sqrt | 12,502 |
import tensorflow as tf
if kh > 255 or kw > 255:
return 1.0
elif kh == 3 and kw == 3:
return 9.0 * 7.0 / 64.0
elif kh == 5 and kw == 5:
return 25.0 * 10.0 / 256.0
elif kh == 6 and kw == 6:
return 36.0 * 7.0 / 256.0
elif kh == 7 and kw == 7:
return 49.0 * 21.0 / 1024.0
elif kh == 14 and kw == 14:
return 196.0 * 21.0 / 4096.0
else:
rec = tf.cast(kw * kh, tf.float32)
n_max = 7 + tf.math.ceil(tf.math.log(rec) / tf.math.log(2.))
ns = tf.range(0., n_max)
ns_pow = tf.pow(2., ns)
ks = tf.round(ns_pow / rec)
diffs = tf.math.abs(ks / ns_pow - 1 / rec)
n = tf.argmin(diffs)
k = ks[n]
scale = k / tf.pow(2., tf.cast(n, tf.float32))
scale *= rec
return scale
| tensorflow.cast | 12,503 |
import tensorflow as tf
pmm *= tf.cast(
tf.pow(-ones, m) * double_factorial(2 * m - 1),
dtype=pmm.dtype)
return pmm
def _evaluate_legendre_polynomial_loop_cond(x, n, l, m, pmm, pmm1):
return tf.cast(tf.math.count_nonzero(n <= l), tf.bool)
def _evaluate_legendre_polynomial_loop_body(x, n, l, m, pmm, pmm1):
n_float = tf.cast(n, dtype=x.dtype)
m_float = tf.cast(m, dtype=x.dtype)
pmn = (x * (2.0 * n_float - 1.0) * pmm1 - (n_float + m_float - 1) * pmm) / (
n_float - m_float)
pmm = tf.where(tf.less_equal(n, l), pmm1, pmm)
pmm1 = tf.where(tf.less_equal(n, l), pmn, pmm1)
n += 1
return x, n, l, m, pmm, pmm1
def _evaluate_legendre_polynomial_loop(x, m, l, pmm, pmm1):
n = m + 2
x, n, l, m, pmm, pmm1 = tf.while_loop(
| tensorflow.cast | 12,504 |
import tensorflow as tf
# build regularized distance objective
dist_loss1 = self._distance_loss(models[1].encode - models[0].encode)
dist_loss2 = self._distance_loss(models[1].encode - models[2].encode)
# Stitch it all together and train
self.loss_reco = tf.add_n(reco_losses)
self.loss_pred = pred_loss_0 + pred_loss_2
self.loss_dist = dist_loss1 + dist_loss2
self.losses = [self.loss_reco, self.loss_pred]
def _distance_loss(self, distances):
| tensorflow.add_n | 12,505 |
import tensorflow as tf
normalizer_fn=None,
biases_initializer=None,
data_format=data_format,
weights_initializer=trunc_normal(0.01),
scope=scope + '/self_gating/transformer_W')
tile_multiples = [1, t, w, h]
tile_multiples.insert(index_c, 1)
weights = tf.tile(weights, tile_multiples)
weights = tf.nn.sigmoid(weights)
return tf.multiply(weights, input_tensor)
def s3dg_base(inputs,
first_temporal_kernel_size=3,
temporal_conv_startat='Conv2d_2c_3x3',
gating_startat='Conv2d_2c_3x3',
| tensorflow.nn.sigmoid | 12,506 |
import tensorflow as tf
def scheduled_sampling(hparams, problem_hparams, dp, sharded_logits, losses,
sharded_features, transformed_features, model):
"""Scheduled sampling."""
target_modality = problem_hparams.target_modality
def sample(x):
"""Multinomial sampling from a n-dimensional tensor."""
vocab_size = target_modality.top_dimensionality
samples = tf.multinomial(tf.reshape(x, [-1, vocab_size]), 1)
reshaped_samples = tf.reshape(samples, common_layers.shape_list(x)[:-1])
return tf.to_int32(reshaped_samples)
def mix_gold_sampled(gold_targets, sampled_targets):
return tf.where(
tf.less(
tf.random_uniform(common_layers.shape_list(sampled_targets)),
hparams.scheduled_sampling_gold_mixin_prob), gold_targets,
| tensorflow.reshape | 12,507 |
from tensorflow.python.ops import state_ops
def _apply_sparse_shared(self, grad, var, indices, scatter_add):
lr_t = math_ops.cast(self._lr_t, var.dtype.base_dtype)
mu_t = math_ops.cast(self._mu_t, var.dtype.base_dtype)
vstar = self.get_slot(var, "vstar")
gold = self.get_slot(var, "gold") # glod is not sparse
v_diff = state_ops.assign(vstar, mu_t * (var - vstar), use_locking=self._use_locking)
with ops.control_dependencies([v_diff]): # run v_diff operation before scatter_add
scaled_grad = scatter_add(vstar, indices, grad)
var_update = state_ops.assign_sub(var, lr_t * (scaled_grad + gold))
return control_flow_ops.group(*[var_update, ])
| tensorflow.python.ops.state_ops.assign | 12,508 |
import tensorflow as tf
# loss = None
with tf.name_scope(name, "click_loglikelihood"):
ob_prob=tf.nn.softmax(propensity)
rel_prob=tf.nn.softmax(train_output)
click_prob=ob_prob*rel_prob
click_prob_norm=click_prob/tf.reduce_sum(click_prob,axis=1,keep_dims=True)
label_dis = labels/ tf.reduce_sum(labels, 1, keep_dims=True)
| tensorflow.nn.softmax | 12,509 |
import tensorflow as tf
entropy = - tf.reduce_sum(prob_tf * log_prob_tf)
bs = tf.to_float(tf.shape(pi.x)[0])
self.loss = pi_loss + 0.5 * vf_loss - entropy * 0.01
# 20 represents the number of "local steps": the number of timesteps
# we run the policy before we update the parameters.
# The larger local steps is, the lower is the variance in our policy gradients estimate
# on the one hand; but on the other hand, we get less frequent parameter updates, which
# slows down learning. In this code, we found that making local steps be much
# smaller than 20 makes the algorithm more difficult to tune and to get to work.
self.runner = RunnerThread(env, pi, 20)
grads = tf.gradients(self.loss, pi.var_list)
tf.summary.scalar("model/policy_loss", pi_loss / bs)
tf.summary.scalar("model/value_loss", vf_loss / bs)
tf.summary.scalar("model/entropy", entropy / bs)
tf.summary.image("model/state", pi.x)
tf.summary.scalar("model/grad_global_norm", tf.global_norm(grads))
tf.summary.scalar("model/var_global_norm", tf.global_norm(pi.var_list))
self.summary_op = tf.summary.merge_all()
grads, _ = tf.clip_by_global_norm(grads, 40.0)
# copy weights from the parameter server to the local model
self.sync = tf.group(*[v1.assign(v2) for v1, v2 in zip(pi.var_list, self.network.var_list)])
grads_and_vars = list(zip(grads, self.network.var_list))
self.inc_step = self.global_step.assign_add(tf.shape(pi.x)[0])
| tensorflow.summary.scalar | 12,510 |
import tensorflow as tf
self.prev_g = tf.placeholder(tf.float32, (None, None, self.g_dim))
self.ri = tf.placeholder(tf.float32, (None,))
self.s_diff = tf.placeholder(tf.float32, (None, self.g_dim))
def build_perception(self):
self._obs = tf.expand_dims(self.obs, -1) # !
self._obs = tf.expand_dims(self._obs, -1) # !
conv1 = tf.layers.conv2d(inputs=self._obs,
filters=16,
kernel_size=[2, 1], # ! kernel_size = [8,8]
activation=tf.nn.elu,
strides=1) # ! strides = 4
| tensorflow.expand_dims | 12,511 |
import tensorflow as tf
resize_b_x = tf.compat.v1.image.resize_bilinear(squeeze_b_x, [y_size_new, z_size_new], align_corners=align)
resume_b_x = tf.reshape(resize_b_x, [-1, x_size, y_size_new, z_size_new, c_size], name='resume_bx')
# Reorient
reoriented = tf.transpose(resume_b_x, [0, 3, 2, 1, 4])
# squeeze and 2d resize
squeeze_b_z = tf.reshape(reoriented, [-1, y_size_new, x_size, c_size], name='reshape_bz')
| tensorflow.transpose | 12,512 |
import tensorflow as tf
min_iou_thresh=0.5,
is_class_agnostic=True)
nms_masks_expected1 = tf.stack([mask0, mask5, mask4])
nms_scores_expected1 = tf.constant([1.0, 0.8, 0.7], dtype=tf.float32)
nms_classes_expected1 = tf.constant([1, 2, 2], dtype=tf.int32)
(nms_masks2,
nms_scores2,
nms_classes2) = isu.instance_non_maximum_suppression_2d_scores(
| tensorflow.constant | 12,513 |
from tensorflow.python.ops import check_ops
def _log_prob(self, x):
x = control_flow_ops.with_dependencies([check_ops.assert_positive(x)] if
self.validate_args else [], x)
| tensorflow.python.ops.check_ops.assert_positive | 12,514 |
import tensorflow as tf
self.n_output = gan_kwargs.get('n_out') #(1024, 3)
self.flags = gan_kwargs.get('flags')
self.batch_size = gan_kwargs.get('batch_size_value', 32)
batch = tf.Variable(0)
self.noise_dim = gan_kwargs.get('noise_dim')
self.init_lr = gan_kwargs.get('init_lr')
| tensorflow.Variable | 12,515 |
import tensorflow as tf
from tensor2tensor.data_generators import algorithmic
from tensor2tensor.data_generators import problem as problem_module
from tensor2tensor.data_generators import problem_hparams
from tensor2tensor.layers import modalities
from tensor2tensor.utils import test_utils
import tensorflow as tf
tf.compat.v1.enable_eager_execution()
def assert_tensors_equal(sess, t1, t2, n):
"""Compute tensors `n` times and ensure that they are equal."""
for _ in range(n):
| tensorflow.compat.v1.enable_eager_execution | 12,516 |
import tensorflow as tf
'The path to a checkpoint from which to fine-tune.')
tf.app.flags.DEFINE_string(
| tensorflow.app.flags.DEFINE_string | 12,517 |
import tensorflow as tf
conv2 = tf.layers.conv2d(pool1, filters=64*amp_factor, kernel_size=[5, 1],
data_format='channels_last', padding= "same",
strides=(2, 1),
activation=tf.nn.relu)
pool2 = conv2
conv3 = tf.layers.conv2d(pool2, filters=128*amp_factor, kernel_size=[5, 1],
data_format='channels_last', padding= "same",
strides=(2, 1),
activation=tf.nn.relu)
pool3 = conv3
| tensorflow.layers.conv2d | 12,518 |
import tensorflow as tf
# hardware related configuration
tf.app.flags.DEFINE_integer(
'num_readers', 16,
'The number of parallel readers that read data from the dataset.')
| tensorflow.app.flags.DEFINE_integer | 12,519 |
from tensorflow.python.framework import ops
input_shape.assert_is_fully_defined()
filter_shape = graph_util.tensor_shape_from_node_def_name(graph,
node.input[1])
filter_shape.assert_is_fully_defined()
output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name)
output_shape.assert_is_fully_defined()
filter_height = int(filter_shape[0])
filter_width = int(filter_shape[1])
filter_in_depth = int(filter_shape[2])
filter_out_depth = int(filter_shape[3])
return ops.OpStats("weight_parameters", (filter_height * filter_width *
filter_in_depth * filter_out_depth))
@ops.RegisterStatistics("BiasAdd", "flops")
def _calc_bias_add_flops(graph, node):
"""Calculates the computing needed for BiasAdd."""
input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0])
input_shape.assert_is_fully_defined()
input_count = np.prod(input_shape.as_list())
return ops.OpStats("flops", input_count)
@ops.RegisterStatistics("BiasAdd", "weight_parameters")
def _calc_bias_add_weight_params(graph, node):
"""Calculates the on-disk weight parameters for BiasAdd."""
bias_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[1])
bias_shape.assert_is_fully_defined()
| tensorflow.python.framework.ops.RegisterStatistics | 12,520 |
import tensorflow as tf
if self.temperature is not None:
logits /= self.temperature
if self.tanh_constant is not None:
op_tanh = self.tanh_constant / self.op_tanh_reduce
logits = op_tanh * tf.tanh(logits)
if use_bias:
logits += self.b_soft_no_learn
op_id = tf.multinomial(logits, 1)
op_id = tf.to_int32(op_id)
op_id = tf.reshape(op_id, [1])
arc_seq = arc_seq.write(start_id + 2 * i + 1, op_id)
curr_log_prob = tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=logits, labels=op_id)
log_prob += curr_log_prob
curr_ent = tf.stop_gradient(tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=tf.nn.softmax(logits)))
entropy += curr_ent
inputs = tf.nn.embedding_lookup(self.w_emb, op_id)
next_c, next_h = stack_lstm(inputs, prev_c, prev_h, self.w_lstm)
anchors = anchors.write(layer_id, next_h[-1])
anchors_w_1 = anchors_w_1.write(layer_id, tf.matmul(next_h[-1], self.w_attn_1))
| tensorflow.nn.sparse_softmax_cross_entropy_with_logits | 12,521 |
import tensorflow as tf
return out
def d_layer(layer_input,filters,f_size=4,stride=2,norm=True,name='d_layer'):
"""Discriminator layer"""
with tf.variable_scope(name):
if reuse:
tf.get_variable_scope().reuse_variables()
else:
assert tf.get_variable_scope().reuse is False
| tensorflow.variable_scope | 12,522 |
import tensorflow as tf
# In this notebook we demonstrate Trieste's ability to perform asynchronous Bayesian optimisation, as is suitable for scenarios where the objective function can be run for several points in parallel but where observations might return back at different times. To avoid wasting resources waiting for the evaluation of the whole batch, we immediately request the next point asynchronously, taking into account points that are still being evaluated. Besides saving resources, asynchronous approach also can potentially [improve sample efficiency](https://arxiv.org/abs/1901.10452) in comparison with synchronous batch strategies, although this is highly dependent on the use case.
#
# To contrast this approach with regular [batch optimization](batch_optimization.ipynb), this notebook also shows how to run parallel synchronous batch approach.
# %%
# silence TF warnings and info messages, only print errors
# https://stackoverflow.com/questions/35911252/disable-tensorflow-debugging-information
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
import tensorflow as tf
tf.get_logger().setLevel("ERROR")
import numpy as np
import time
import timeit
# %% [markdown]
# First, let's define a simple objective that will emulate evaluations taking variable time. We will be using a classic Bayesian optimisation benchmark function [Branin](https://www.sfu.ca/~ssurjano/branin.html) with a sleep call inserted in the middle of the calculation to emulate delay. Our sleep delay is a scaled sum of all input values to make sure delays are uneven.
# %%
from trieste.objectives import scaled_branin
| tensorflow.get_logger | 12,523 |
import tensorflow as tf
wd=weight_decay)
outputs = tf.nn.conv1d(inputs, kernel,
| tensorflow.nn.conv1d | 12,524 |
import tensorflow as tf
if self.maxnorm is not None:
# Ensure maxnorm constraints are initially satisfied
head_init = dense_maxnorm(head_init, self.maxnorm)
rel_init = dense_maxnorm(rel_init, self.maxnorm)
tail_init = dense_maxnorm(tail_init, self.maxnorm)
self.head_embedding_vars = tf.Variable(head_init)
self.rel_embedding_vars = tf.Variable(rel_init)
self.tail_embedding_vars = tf.Variable(tail_init)
# Embedding layer for each (head, rel, tail) triple being fed in as input
head_embed = tf.nn.embedding_lookup(self.head_embedding_vars, self.head_input)
rel_embed = tf.nn.embedding_lookup(self.rel_embedding_vars, self.rel_input)
tail_embed = tf.nn.embedding_lookup(self.tail_embedding_vars, self.tail_input)
# Model output
raw_output = tf.reduce_sum(tf.mul(tf.mul(head_embed, rel_embed), tail_embed), 1)
| tensorflow.Variable | 12,525 |
import tensorflow as tf
# Assign to yet another shape
data2 = tf.fill([10, 10], 1)
a2 = tf.assign(p, data2, validate_shape=False)
a2.op.run()
self.assertAllEqual(p.eval(), data2.eval())
def testInitRequiredAssignAdd(self):
with self.test_session():
p = tf.Variable(tf.fill([1024, 1024], 1),
tf.int32)
a = tf.assign_add(p, tf.fill([1024, 1024], 0))
with self.assertRaisesOpError("use uninitialized"):
a.op.run()
def testInitRequiredAssignSub(self):
with self.test_session():
p = tf.Variable(tf.fill([1024, 1024], 1),
| tensorflow.fill | 12,526 |
import tensorflow as tf
for idx, (x, m) in enumerate(zip(xs, ms)):
c = c*(1-m)
h = h*(1-m)
z = _ln(tf.matmul(x, wx), gx, bx) + _ln(tf.matmul(h, wh), gh, bh) + b
i, f, o, u = tf.split(axis=1, num_or_size_splits=4, value=z)
i = tf.nn.sigmoid(i)
f = tf.nn.sigmoid(f)
o = tf.nn.sigmoid(o)
u = tf.tanh(u)
c = f*c + i*u
h = o*tf.tanh(_ln(c, gc, bc))
xs[idx] = h
s = tf.concat(axis=1, values=[c, h])
| tensorflow.nn.sigmoid | 12,527 |
import tensorflow as tf
def dann_loss(source_samples, target_samples, weight, name='dann_loss'):
"""Adds the domain adversarial (DANN) loss.
Args:
source_samples: a tensor of shape [num_samples, num_features].
target_samples: a tensor of shape [num_samples, num_features].
weight: the weight of the loss.
scope: optional name scope for summary tags.
Returns:
a scalar tensor representing the correlation loss value.
"""
with tf.variable_scope(name):
batch_size = tf.shape(source_samples)[0]
samples = tf.concat(values=[source_samples, target_samples], axis=0)
samples = flatten(samples)
domain_selection_mask = tf.concat(
values=[tf.zeros((batch_size, 1)), tf.ones((batch_size, 1))], axis=0)
grl = gradient_reverse(samples)
grl = tf.reshape(grl, (-1, samples.get_shape().as_list()[1]))
grl = fc(grl, 100, True, None, activation=relu, name='fc1')
logits = fc(grl, 1, True, None, activation=None, name='fc2')
| tensorflow.variable_scope | 12,528 |
import tensorflow as tf
with tf.device('/cpu:0'), tf.name_scope("embedding_tags"):
W_tags = tf.get_variable("embed_W_tags", [tags_vocab_size, embedding_size], initializer=initializer)
embedded_tags = tf.nn.embedding_lookup(W_tags, self.input_tags)
embedded_tags_expanded = tf.expand_dims(embedded_tags, -1)
with tf.device('/cpu:0'), tf.name_scope("embedding_deps"):
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)
embedded_deps_expanded = tf.expand_dims(embedded_deps, -1)
with tf.device('/cpu:0'), tf.name_scope("embedding_head"):
W_head = tf.get_variable("embed_W_head", [num_quantized_chars, embedding_size], initializer=initializer)
embedded_head = tf.nn.embedding_lookup(W_head, self.input_head)
embedded_head_expanded = tf.expand_dims(embedded_head, -1)
cnn_inputs = tf.concat(
[embedded_text_expand, embedded_tags_expanded, embedded_deps_expanded, embedded_head_expanded], -1)
print("-" * 20)
print("Embedded Lookup:", cnn_inputs.get_shape())
print("-" * 20)
self.layers = []
# Temp(First) Conv Layer
with tf.variable_scope("temp_conv") as scope:
| tensorflow.expand_dims | 12,529 |
import tensorflow.contrib.layers as layers
with tf.variable_scope(scope, reuse=reuse):
out = img_in
with tf.variable_scope("convnet"):
# original architecture
out = layers.convolution2d(out, num_outputs=32, kernel_size=8, stride=4, activation_fn=tf.nn.relu)
out = layers.convolution2d(out, num_outputs=64, kernel_size=4, stride=2, activation_fn=tf.nn.relu)
out = layers.convolution2d(out, num_outputs=64, kernel_size=3, stride=1, activation_fn=tf.nn.relu)
out = layers.flatten(out)
| tensorflow.contrib.layers.convolution2d | 12,530 |
import tensorflow as tf
self.block4_1 = self.res_block_3_layers(self.pool4, [512, 512, 2048], "res5a", True)# 7*7
self.block4_2 = self.res_block_3_layers(self.block4_1, [512, 512, 2048], "res5b")# 7*7
self.block4_3 = self.res_block_3_layers(self.block4_2, [512, 512, 2048], "res5c")# 7*7
# upsample layer begins
self.deconv_1 = self.deconv_bn_relu(self.block4_3, name = 'deconv_1',kernel_size = 3, output_channels = 1024,
initializer = tf.contrib.layers.variance_scaling_initializer(), stride=2, bn=True, training=self.is_training)# 14*14
self.deconv_2 = self.deconv_bn_relu(self.deconv_1, name = 'deconv_2',kernel_size = 3, output_channels = 512,
initializer = tf.contrib.layers.variance_scaling_initializer(), stride=2, bn=True, training=self.is_training)# 28*28
self.deconv_3 = self.deconv_bn_relu(self.deconv_2, name = 'deconv_3',kernel_size = 3, output_channels = 256,
initializer = tf.contrib.layers.variance_scaling_initializer(), stride=2, bn=True, training=self.is_training)# 56*56
| tensorflow.contrib.layers.variance_scaling_initializer | 12,531 |
import tensorflow as tf
return weighted_average, weights
def local_attention(state, hidden_states, encoder, encoder_input_length, pos=None, scope=None, context=None, **kwargs):
batch_size = tf.shape(state)[0]
attn_length = tf.shape(hidden_states)[1]
if context is not None and encoder.use_context:
state = tf.concat([state, context], axis=1)
state_size = state.get_shape()[1].value
with tf.variable_scope(scope or 'attention_{}'.format(encoder.name)):
encoder_input_length = tf.to_float(tf.expand_dims(encoder_input_length, axis=1))
if pos is not None:
pos = tf.reshape(pos, [-1, 1])
pos = tf.minimum(pos, encoder_input_length - 1)
if pos is not None and encoder.attn_window_size > 0:
# `pred_edits` scenario, where we know the aligned pos
# when the windows size is non-zero, we concatenate consecutive encoder states
# and map it to the right attention vector size.
weights = tf.to_float(tf.one_hot(tf.to_int32(tf.squeeze(pos, axis=1)), depth=attn_length))
weighted_average = []
| tensorflow.expand_dims | 12,532 |
import tensorflow as tf
w0 = self.w0.read_value()
b0 = self.b0.read_value()
w1 = self.w1.read_value()
b1 = self.b1.read_value()
params = (w0, b0, w1, b1)
layer0 = tf.matmul(x, w0) + b0
layer1 = tf.nn.sigmoid(layer0)
layer2 = tf.matmul(layer1, w1) + b1
predictions = layer2
loss = tf.reduce_mean(tf.losses.sparse_softmax_cross_entropy(logits=predictions, labels=y))
grads = tf.gradients(ys=loss, xs=params)
return predictions, loss, grads
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
| tensorflow.losses.sparse_softmax_cross_entropy | 12,533 |
from tensorflow.python.ops import nn
`false_positives` variables appropriately, and whose value matches
`precision`.
Raises:
ValueError: If `ignore_mask` is not `None` and its shape doesn't match
`predictions`, or if `weights` is not `None` and its shape doesn't match
`predictions`, or if either `metrics_collections` or `updates_collections`
are not a list or tuple.
"""
default_name = _at_k_name('precision', k, class_id=class_id)
with ops.name_scope(name, default_name,
(predictions, labels, ignore_mask, weights)) as scope:
_, top_k_idx = nn.top_k(predictions, k)
return _streaming_sparse_precision_at_k(
top_k_idx=top_k_idx,
labels=labels,
k=k,
class_id=class_id,
ignore_mask=ignore_mask,
weights=weights,
metrics_collections=metrics_collections,
updates_collections=updates_collections,
name=scope)
| tensorflow.python.ops.nn.top_k | 12,534 |
import tensorflow as tf
with variable_scope.variable_scope("AttnOutputProjection"):
output_t = linear([cell_output] + [context_t], options.gen_hidden_size, True)
with tf.variable_scope('output_projection'):
w = tf.get_variable('w', [options.gen_hidden_size, vocab.vocab_size+1], dtype=tf.float32)
b = tf.get_variable('b', [vocab.vocab_size +1], dtype=tf.float32)
# vocab_scores is the vocabulary distribution before applying softmax.
# Each entry on the list corresponds to one decoder step
vocab_score_t = tf.nn.xw_plus_b(output_t, w, b) # apply the linear layer
vocab_score_t = tf.nn.softmax(vocab_score_t)
# For pointer-generator model, calc final distribution from copy distribution and vocabulary distribution
if options.pointer_gen:
vocab_score_t = self.merge_prob_dist_for_one_step(vocab_score_t, attn_dist, p_gen, passage_word_idx, passage_mask)
vocab_score_t = _clip_and_normalize(vocab_score_t, 1e-6)
return (state_t, context_t, coverage_t, attn_dist, p_gen, vocab_score_t)
| tensorflow.nn.softmax | 12,535 |
import tensorflow as tf
'The size of the input image for the model to use.')
tf.app.flags.DEFINE_integer(
'heatmap_size', 96,
'The size of the output heatmap of the model.')
tf.app.flags.DEFINE_string(
'backbone', 'seresnext50',#or seresnext50 seresnet50
'The backbone network to use for feature pyramid.')
tf.app.flags.DEFINE_float(
'heatmap_sigma', 1.,
'The sigma of Gaussian which generate the target heatmap.')
tf.app.flags.DEFINE_float(
'bbox_border', 25.,
'The nearest distance of the crop border to al keypoints.')
tf.app.flags.DEFINE_integer(
'train_epochs', 50,
'The number of epochs to use for training.')
tf.app.flags.DEFINE_integer(
'epochs_per_eval', 20,
'The number of training epochs to run between evaluations.')
tf.app.flags.DEFINE_integer(
'batch_size', 10,
'Batch size for training and evaluation.')
tf.app.flags.DEFINE_integer(
'xt_batch_size', 10,
'Batch size for training and evaluation.')
tf.app.flags.DEFINE_boolean(
| tensorflow.app.flags.DEFINE_integer | 12,536 |
import tensorflow as tf
def testGlobalPoolUnknownImageShape(self):
tf.reset_default_graph()
batch_size = 1
height, width = 250, 300
num_classes = 1000
input_np = np.random.uniform(0, 1, (batch_size, height, width, 3))
with self.test_session() as sess:
inputs = tf.placeholder(tf.float32, shape=(batch_size, None, None, 3))
logits, end_points = mobilenet_v1.mobilenet_v1(inputs, num_classes,
global_pool=True)
self.assertTrue(logits.op.name.startswith('MobilenetV1/Logits'))
self.assertListEqual(logits.get_shape().as_list(),
[batch_size, num_classes])
pre_pool = end_points['Conv2d_13_pointwise']
| tensorflow.placeholder | 12,537 |
from tensorflow.python.framework import ops
init: Tensor to assign to v,
Or an object convertible to Tensor e.g. nparray,
Or an Initializer that generates a tensor given the shape and type of v.
An "Initializer" is a callable that returns a tensor that "v" should be
set to. It will be called as init(shape, dtype).
name: Optional name for the op.
Returns:
The operation that initializes v.
"""
with ops.op_scope([v, init], None, v.op.name + "/"):
with ops.name_scope(name) as scope:
with ops.device(v.device or ops.get_default_graph().get_default_device()):
if callable(init):
assert v.get_shape().is_fully_defined(), "Variable shape unknown."
# TODO(mrry): Convert to v.shape when the property and
# accessor are reconciled (and all initializers support
# tf.TensorShape objects).
value = init(v.get_shape().as_list(), v.dtype.base_dtype)
value = ops.convert_to_tensor(value, name="value")
| tensorflow.python.framework.ops.op_scope | 12,538 |
import tensorflow as tf
identity = (registry.Modalities.GENERIC, None)
if self.has_inputs:
p.input_modality["inputs_segmentation"] = identity
p.input_modality["inputs_position"] = identity
p.input_modality["targets_segmentation"] = identity
p.input_modality["targets_position"] = identity
def example_reading_spec(self):
data_fields = {"targets": tf.VarLenFeature(tf.int64)}
if self.has_inputs:
data_fields["inputs"] = tf.VarLenFeature(tf.int64)
if self.packed_length:
if self.has_inputs:
data_fields["inputs_segmentation"] = tf.VarLenFeature(tf.int64)
data_fields["inputs_position"] = tf.VarLenFeature(tf.int64)
| tensorflow.VarLenFeature | 12,539 |
import tensorflow as tf
features_proj = tf.matmul(features_flat, w)
features_proj = tf.reshape(features_proj, [-1, self.L, self.D])
return features_proj
def _attention_layer(self, features, features_proj, h, reuse=False):
with tf.variable_scope('attention_layer', reuse=reuse):
w = tf.get_variable('w', [self.H, self.D], initializer=self.weight_initializer)
b = tf.get_variable('b', [self.D], initializer=self.const_initializer)
w_att = tf.get_variable('w_att', [self.D, 1], initializer=self.weight_initializer)
h_att = tf.nn.relu(features_proj + tf.expand_dims(tf.matmul(h, w), 1) + b) # (N, L, D)
out_att = tf.reshape(tf.matmul(tf.reshape(h_att, [-1, self.D]), w_att), [-1, self.L]) # (N, L)
alpha = tf.nn.softmax(out_att)
context = tf.reduce_sum(features * tf.expand_dims(alpha, 2), 1, name='context') #(N, D)
return context, alpha
| tensorflow.get_variable | 12,540 |
import tensorflow as tf
outer = tf.matmul(tf.expand_dims(tf.nn.softmax(self.logits1), axis=2),
tf.expand_dims(tf.nn.softmax(self.logits2), axis=1))
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)
def _compute_loss(self):
def focal_loss(logits, labels, weights=None, alpha=0.25, gamma=2):
logits = tf.nn.sigmoid(logits)
zeros = array_ops.zeros_like(logits, dtype=logits.dtype)
pos_p_sub = array_ops.where(labels > zeros, labels - logits, zeros)
neg_p_sub = array_ops.where(labels > zeros, zeros, logits)
cross_ent = - alpha * (pos_p_sub ** gamma) * tf.log(tf.clip_by_value(logits, 1e-8, 1.0)) \
- (1 - alpha) * (neg_p_sub ** gamma) * tf.log(tf.clip_by_value(1.0 - logits, 1e-8, 1.0))
return tf.reduce_sum(cross_ent, 1)
start_label = tf.one_hot(self.start_label, tf.shape(self.logits1)[1], axis=1)
end_label = tf.one_hot(self.end_label, tf.shape(self.logits2)[1], axis=1)
if self.config.loss_type == 'cross_entropy':
start_loss = tf.nn.softmax_cross_entropy_with_logits(
logits=self.logits1, labels=start_label)
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)
| tensorflow.clip_by_value | 12,541 |
import tensorflow as tf
'image/width':
tf.io.FixedLenFeature((), tf.int64),
'image/object/bbox/xmin':
tf.io.VarLenFeature(tf.float32),
'image/object/bbox/xmax':
tf.io.VarLenFeature(tf.float32),
'image/object/bbox/ymin':
tf.io.VarLenFeature(tf.float32),
'image/object/bbox/ymax':
tf.io.VarLenFeature(tf.float32),
'image/object/class/label':
tf.io.VarLenFeature(tf.int64),
'image/object/area':
tf.io.VarLenFeature(tf.float32),
'image/object/is_crowd':
tf.io.VarLenFeature(tf.int64),
}
if include_mask:
self._keys_to_features.update({
'image/object/mask':
tf.io.VarLenFeature(tf.string),
})
def _decode_image(self, parsed_tensors):
"""Decodes the image and set its static shape."""
image = tf.io.decode_image(parsed_tensors['image/encoded'], channels=3)
| tensorflow.io.VarLenFeature | 12,542 |
import tensorflow as tf
# TODO: tf.ones acts as an overridable placeholder but this is still awkward
target_weights_nunroll = tf.ones([batch_size, rnn_nunroll], dtype)
| tensorflow.ones | 12,543 |
import tensorflow as tf
qh_emb = conv(qh_emb, d,
bias=True, activation=tf.nn.relu, kernel_size=5, name="char_conv", reuse=True)
ch_emb = tf.reduce_max(ch_emb, axis=1)
qh_emb = tf.reduce_max(qh_emb, axis=1)
| tensorflow.reduce_max | 12,544 |
import tensorflow as tf
class ValueEstimator_MountainCarContinuous():
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.random_normal_initializer | 12,545 |
import tensorflow as tf
decoder_inputs: [batch_size, max_dec_steps].
answer_batch: [batch_size, max_dec_steps]
'''
options = self.options
input_shape = tf.shape(encoder_states)
batch_size = input_shape[0]
passage_len = input_shape[1]
# map decoder inputs to word embeddings
| tensorflow.shape | 12,546 |
import tensorflow as tf
logits,
label_ids):
"""Computes the loss and accuracy of the model."""
sentence_log_probs = tf.reshape(
logits, [-1, logits.shape[-1]])
sentence_predictions = tf.argmax(
logits, axis=-1, output_type=tf.int32)
sentence_labels = tf.reshape(label_ids, [-1])
sentence_accuracy = tf.metrics.accuracy(
labels=label_ids, predictions=sentence_predictions)
sentence_mean_loss = tf.metrics.mean(
values=per_example_loss)
sentence_f = tf_metrics.f1(label_ids,
sentence_predictions,
| tensorflow.reshape | 12,547 |
import tensorflow as tf
rotations_y = tf.concat([tf_utils.euler_from_rotation_matrix(
tf.reshape(detections['rotations_3d'][i], [3, 3]),
1) for i in range(num_boxes)], axis=0)
rotations_y = tf.reshape(rotations_y, [-1, 1])
predicted_boxes = tf.concat([detections['translations_3d'],
detections['sizes_3d'],
rotations_y], axis=1)
| tensorflow.concat | 12,548 |
from tensorflow.contrib.eager.python import tfe
default=0.5,
help="Keep probability for dropout between layers.")
parser.add_argument(
"--learning_rate",
type=float,
default=0.01,
help="Learning rate to be used during training.")
parser.add_argument(
"--no_gpu",
action="store_true",
default=False,
help="Disables GPU usage even if a GPU is available.")
FLAGS, unparsed = parser.parse_known_args()
tfe.run(main=main, argv=[sys.argv[0]] + unparsed)
| tensorflow.contrib.eager.python.tfe.run | 12,549 |
import tensorflow as tf
var_names.append(key)
tf.logging.info('Warm-starting tensors: %s', sorted(var_names))
vars_to_warm_start = var_names
warm_start_settings = tf.estimator.WarmStartSettings(
ckpt_to_initialize_from=checkpoint_path,
vars_to_warm_start=vars_to_warm_start)
else:
warm_start_settings = None
l2tl_classifier = tf.estimator.Estimator(
train_model_fn, config=config, warm_start_from=warm_start_settings)
def make_input_dataset():
"""Return input dataset."""
def _merge_datasets(train_batch, finetune_batch, target_batch):
"""Merge different splits."""
train_features, train_labels = train_batch['image'], train_batch['label']
finetune_features, finetune_labels = finetune_batch[
'image'], finetune_batch['label']
| tensorflow.estimator.Estimator | 12,550 |
import tensorflow as tf
'''
image += cfg.FLAGS2["pixel_means"]
# bgr to rgb (opencv uses bgr)
channels = tf.unstack(image, axis=-1)
image = tf.stack([channels[2], channels[1], channels[0]], axis=-1)
# dims for normalization
| tensorflow.unstack | 12,551 |
import tensorflow as tf
return None, self._loss, sampled_words
def calculate_encoder_features(self, encoder_states, encoder_dim):
options = self.options
input_shape = tf.shape(encoder_states)
batch_size = input_shape[0]
passage_len = input_shape[1]
| tensorflow.shape | 12,552 |
import tensorflow as tf
print("Preprocessing and Initializing...")
# Compute number of nodes
num_nodes = adj.shape[0]
# If features are not used, replace feature matrix by identity matrix
if not FLAGS.features:
features = sp.identity(adj.shape[0])
# Preprocessing on node features
features = sparse_to_tuple(features)
num_features = features[2][1]
features_nonzero = features[1].shape[0]
# Define placeholders
placeholders = {
'features': tf.sparse_placeholder(tf.float32),
'adj': tf.sparse_placeholder(tf.float32),
'adj_orig': tf.sparse_placeholder(tf.float32),
'dropout': tf.placeholder_with_default(0., shape = ())
}
# Create model
model = None
if model_name == 'gcn_ae':
# Standard Graph Autoencoder
model = GCNModelAE(placeholders, num_features, features_nonzero)
elif model_name == 'gcn_vae':
# Standard Graph Variational Autoencoder
| tensorflow.sparse_placeholder | 12,553 |
import tensorflow as tf
sigma = tf.clip_by_value(sigma, 0.0, 1.0)
norm_dist = tf.distributions.Normal(loc=mu * self.a_bound, scale=sigma)
| tensorflow.distributions.Normal | 12,554 |
import tensorflow as tf
vs[0].graph.colocate_with(vs[0]):
counter = tf.Variable(
0, name="counter", trainable=False, dtype=tf.int32)
with tf.name_scope('AccumGradOptimizer'):
ops = []
for s, gv in zip(slots, grads_and_vars):
g, v = gv
| tensorflow.name_scope | 12,555 |
import tensorflow as tf
target_q_ph = q_func(obs_tp1_float, self.num_actions, 'target_q_func', reuse = tf.AUTO_REUSE)
if double_q:
target_index = tf.math.argmax(q_func(obs_tp1_float, self.num_actions, 'q_func', reuse = tf.AUTO_REUSE), axis = 1, output_type = tf.int32)
target_v_ph = tf.gather_nd(target_q_ph, tf.stack([tf.range(tf.shape(target_q_ph)[0]), target_index], axis=1))
else:
target_v_ph = tf.math.reduce_max(target_q_ph, axis = 1)
backup_ph = self.rew_t_ph + (1 - self.done_mask_ph) * (gamma * target_v_ph)
self.total_error = tf.math.reduce_mean(huber_loss(q_func_ph - backup_ph))
q_func_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='q_func')
target_q_func_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='target_q_func')
# construct optimization op (with gradient clipping)
self.learning_rate = tf.placeholder(tf.float32, (), name="learning_rate")
optimizer = self.optimizer_spec.constructor(learning_rate=self.learning_rate, **self.optimizer_spec.kwargs)
self.train_fn = minimize_and_clip(optimizer, self.total_error,
var_list=q_func_vars, clip_val=grad_norm_clipping)
# update_target_fn will be called periodically to copy Q network to target Q network
update_target_fn = []
for var, var_target in zip(sorted(q_func_vars, key=lambda v: v.name),
sorted(target_q_func_vars, key=lambda v: v.name)):
| tensorflow.get_collection | 12,556 |
import tensorflow as tf
shape=[hidden_size, num_attention_heads * head_size],
initializer=initializer)
w = tf.reshape(w, [hidden_size, num_attention_heads, head_size])
b = tf.get_variable(
name="bias",
shape=[num_attention_heads * head_size],
| tensorflow.get_variable | 12,557 |
import tensorflow as tf
'''
Output is of shape (in_w // 2, in_h // 2, out_ch)
'''
assert in_w % 2 == 0 and in_h % 2 == 0, 'Width & height ({} & {}) must both be even!'.format(in_w, in_h)
with tf.variable_scope('fac_reduc'):
# Split area into 2 halves
half_1 = tf.nn.avg_pool(X, ksize=(1, 1, 1, 1), strides=(1, 2, 2, 1), padding='VALID')
shifted_X = tf.pad(X, ((0, 0), (0, 1), (0, 1), (0, 0)))[:, 1:, 1:, :]
half_2 = tf.nn.avg_pool(shifted_X, ksize=(1, 1, 1, 1), strides=(1, 2, 2, 1), padding='VALID')
# Apply 1 x 1 convolution to each half separately
W_half_1 = self._make_var('W_half_1', (1, 1, in_ch, out_ch >> 1))
X_half_1 = tf.nn.conv2d(half_1, W_half_1, (1, 1, 1, 1), padding='VALID')
| tensorflow.nn.avg_pool | 12,558 |
import tensorflow as tf
def build_anet(self, state_in, name, reuse=False, batch_size=64):
reg = None
with tf.variable_scope(name, reuse=reuse):
layer_a1 = tf.layers.dense(state_in, 512, tf.nn.relu, kernel_regularizer=reg)
layer_a2 = tf.layers.dense(layer_a1, 256, tf.nn.relu, kernel_regularizer=reg)
lstm_a = tf.nn.rnn_cell.LSTMCell(num_units=256)
| tensorflow.layers.dense | 12,559 |
import tensorflow as tf
epsilon=hparams.vq_epsilon,
ema=hparams.ema,
means=means)
inputs = None
batch_size = hparams.batch_size
targets = tf.random_uniform([batch_size,
hparams.img_len,
hparams.img_len,
hparams.hidden_size],
minval=-1., maxval=1.)
target_space_id = None
| tensorflow.random_uniform | 12,560 |
import tensorflow as tf
tf.greater_equal(target_global_step, FLAGS.first_pretrain_steps),
tf.float32)
rl_learning_rate = FLAGS.rl_learning_rate * enable_rl_optimizer
rl_learning_rate = tf.train.piecewise_constant(
target_global_step, [800,],
[rl_learning_rate, rl_learning_rate * 0.1])
optimizer = tf.train.AdamOptimizer(rl_learning_rate)
target_train_op = optimizer.minimize(
rl_empirical_loss,
target_global_step,
var_list=tf.trainable_variables(rl_scope.name))
out_metric = {
'rl_empirical_loss': rl_empirical_loss,
'rl_entropy_loss': rl_entropy_loss,
'rl_reward': rl_reward,
'rl_step_baseline': rl_step_baseline,
'rl_baseline': rl_baseline,
'rl_advantage': rl_advantage,
'log_prob': log_prob,
}
| tensorflow.trainable_variables | 12,561 |
import tensorflow as tf
NUMBER_OF_CLASSES = 2
def get_input_function():
"""A function to get test inputs. Returns an image with one box."""
image = tf.random_uniform([32, 32, 3], dtype=tf.float32)
key = tf.constant('image_000000')
class_label = tf.random_uniform(
[1], minval=0, maxval=NUMBER_OF_CLASSES, dtype=tf.int32)
box_label = tf.random_uniform(
[1, 4], minval=0.4, maxval=0.6, dtype=tf.float32)
multiclass_scores = tf.random_uniform(
[1, NUMBER_OF_CLASSES], minval=0.4, maxval=0.6, dtype=tf.float32)
return {
fields.InputDataFields.image: image,
fields.InputDataFields.key: key,
fields.InputDataFields.groundtruth_classes: class_label,
fields.InputDataFields.groundtruth_boxes: box_label,
fields.InputDataFields.multiclass_scores: multiclass_scores
}
| tensorflow.random_uniform | 12,562 |
import tensorflow as tf
# Load IRK weights
tmp = np.float32(np.loadtxt('../../Utilities/IRK_weights/Butcher_IRK%d.txt' % (q), ndmin = 2))
weights = np.reshape(tmp[0:q**2+q], (q+1,q))
self.IRK_alpha = weights[0:-1,:]
self.IRK_beta = weights[-1:,:]
self.IRK_times = tmp[q**2+q:]
# tf placeholders and graph
self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,
log_device_placement=True))
self.x0_tf = tf.placeholder(tf.float32, shape=(None, self.x0.shape[1]))
self.x1_tf = tf.placeholder(tf.float32, shape=(None, self.x1.shape[1]))
self.u0_tf = tf.placeholder(tf.float32, shape=(None, self.u0.shape[1]))
self.u1_tf = tf.placeholder(tf.float32, shape=(None, self.u1.shape[1]))
self.dummy_x0_tf = tf.placeholder(tf.float32, shape=(None, self.q)) # dummy variable for fwd_gradients
self.dummy_x1_tf = tf.placeholder(tf.float32, shape=(None, self.q)) # dummy variable for fwd_gradients
self.U0_pred = self.net_U0(self.x0_tf) # N0 x q
self.U1_pred = self.net_U1(self.x1_tf) # N1 x q
self.loss = tf.reduce_sum(tf.square(self.u0_tf - self.U0_pred)) + \
| tensorflow.placeholder | 12,563 |
import tensorflow as tf
if save_interval and checkpoint_path and i != 0 and i % save_interval == 0:
self.save(checkpoint_path)
if 'validation' in self.datasets and i % validation_interval == 0:
metrics = self.evaluate('validation', mute=True)
tf.logging.info(
'Iter {:4d}: loss {:.4f}'.format(i, loss) +
''.join([', {} {:.4f}'.format(m, metrics[m]) for m in metrics]))
if output_dir is not None:
train_writer.add_summary(summaries, i)
metrics_summaries = tf.Summary(value=[
tf.Summary.Value(tag=m, simple_value=v)
for m, v in metrics.items()])
train_writer.add_summary(metrics_summaries, i)
tf.logging.info('Training finished')
def predict(self, data, keys='*', batch=False):
assert set(data.keys()) >= set(self.data_shape.keys())
if isinstance(keys, str):
if keys == '*':
op = self.pred_out # just gather all outputs
else:
| tensorflow.Summary.Value | 12,564 |
import tensorflow as tf
for key, value in zip(act_values_dict.keys(), act_values):
act_values_dict[key] += value
summary = tf.Summary()
current_global_step = sess.run(global_step)
| tensorflow.Summary | 12,565 |
import tensorflow as tf
"""
To run:
"python -m saliency.integrated_gradients_test" from the PAIR-code/saliency
directory.
"""
def testIntegratedGradientsGetMask(self):
with tf.Graph().as_default() as graph:
x = tf.placeholder(shape=[None, 3], dtype=tf.float32)
y = 5 * x[:, 0] + x[:, 0] * x[:, 1] + tf.sin(x[:, 2])
with tf.Session() as sess:
# Calculate the value of `y` at the baseline.
x_baseline_val = np.array([[0.5, 0.8, 1.0]], dtype=np.float)
y_baseline_val = sess.run(y, feed_dict={x: x_baseline_val})
# Calculate the value of `y` at the input.
| tensorflow.placeholder | 12,566 |
import tensorflow as tf
all_input_ids, shape=[num_examples, seq_length],
dtype=tf.int32),
"input_mask":
tf.constant(
all_input_mask,
shape=[num_examples, seq_length],
| tensorflow.constant | 12,567 |
import tensorflow as tf
Return:
A tuple of `SparseTensor` (neibors, weights).
neighbors: A `SparseTensor` of `int64`.
weights: A `SparseTensor` of `float`.
types: A `SparseTensor` of `int32`
"""
sp_returns = base._LIB_OP.get_full_neighbor(nodes, edge_types)
return tf.SparseTensor(*sp_returns[:3]), tf.SparseTensor(*sp_returns[3:6]), \
tf.SparseTensor(*sp_returns[6:])
def get_sorted_full_neighbor(nodes, edge_types):
"""
Args:
nodes: A `Tensor` of `int64`.
| tensorflow.SparseTensor | 12,568 |
import tensorflow as tf
handle0_value = sess.run(
handle, feed_dict={sp_input: input0_val})
handle1_value = sess.run(
handle, feed_dict={sp_input: input1_val})
sparse_handles = tf.convert_to_tensor(
[handle0_value, handle1_value], dtype=tf.int64)
sp_roundtrip = take_many_sparse_from_tensors_map(
sparse_map_op=handle.op, sparse_handles=sparse_handles)
| tensorflow.convert_to_tensor | 12,569 |
import tensorflow as tf
weights_regularizer = tf.contrib.layers.l2_regularizer(cfgs.WEIGHT_DECAY)
with tf.variable_scope(tf.get_variable_scope()):
for i in range(num_gpu):
with tf.device('/gpu:%d' % i):
with tf.name_scope('tower_%d' % i):
with slim.arg_scope(
[slim.model_variable, slim.variable],
device='/device:CPU:0'):
with slim.arg_scope([slim.conv2d, slim.conv2d_in_plane,
| tensorflow.name_scope | 12,570 |
import tensorflow as tf
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.abs | 12,571 |
import tensorflow as tf
# Calculate output (+) integration: h2 (8, 9)
h2 = self.output_integration(
h1=h1,
c2=c2,
g2=g2,
h2=h2,
layer=layer)
if self.adapation:
eta = getattr(self, 'eta_%s' % layer)
e = tf.gather(eta, i0, axis=-1)
h2 *= e
return h1, h2
def full(self, i0, x, l1_h2, l2_h2, l3_h2):
"""hGRU body.
Take the recurrent h2 from a low level and imbue it with
information froma high layer. This means to treat the lower
layer h2 as the X and the higher layer h2 as the recurrent state.
This will serve as I/E from the high layer along with feedback
| tensorflow.gather | 12,572 |
import tensorflow as tf
with tf.variable_scope('x_entropy'):
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))
# Define your AdamOptimiser, using FLAGS.learning_rate to minimixe the loss function
decayed_learning_rate = tf.train.exponential_decay(FLAGS.learning_rate, tf.Variable(0, trainable=False), 1000, 0.8)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
optimiser = tf.train.AdamOptimizer(decayed_learning_rate, name="Adam").minimize(cross_entropy)
# calculate the prediction and the accuracy
accuracy, acc_op = tf.metrics.accuracy(labels=tf.argmax(y_, axis=1), predictions=tf.argmax(y_conv, axis=1))
loss_summary = tf.summary.scalar('Loss', cross_entropy)
acc_summary = tf.summary.scalar('Accuracy', accuracy)
# summaries for TensorBoard visualisation
validation_summary = tf.summary.merge([img_summary, acc_summary])
training_summary = tf.summary.merge([img_summary, loss_summary])
test_summary = tf.summary.merge([img_summary, acc_summary])
| tensorflow.argmax | 12,573 |
import tensorflow as tf
from tensorflow_metadata.proto.v0 import schema_pb2
def _make_tensors_with_override():
x = tf.compat.v1.placeholder(tf.int64, (None,))
schema_inference.set_tensor_schema_override(x, tf.constant(5), tf.constant(6))
return {'x': x}
class SchemaInferenceTest(test_case.TransformTestCase):
| tensorflow.constant | 12,574 |
import tensorflow as tf
grads, _ = tf.clip_by_global_norm(grads, 40.0)
# copy weights from the parameter server to the local model
self.sync = tf.group(*[v1.assign(v2) for v1, v2 in zip(pi.var_list, self.network.var_list)])
grads_and_vars = list(zip(grads, self.network.var_list))
self.inc_step = self.global_step.assign_add(tf.shape(pi.x)[0])
# each worker has a different set of adam optimizer parameters
opt = tf.train.AdamOptimizer(1e-4)
self.train_op = tf.group(opt.apply_gradients(grads_and_vars), self.inc_step)
self.summary_writer = None
self.local_steps = 0
def start(self, sess, summary_writer):
self.runner.start_runner(sess, summary_writer)
self.summary_writer = summary_writer
| tensorflow.train.AdamOptimizer | 12,575 |
import tensorflow as tf
d_layer_1_all = tf.layers.dense(din_all, 80, activation=tf.nn.sigmoid, name='f1_att' + stag)
d_layer_2_all = tf.layers.dense(d_layer_1_all, 40, activation=tf.nn.sigmoid, name='f2_att' + stag)
d_layer_3_all = tf.layers.dense(d_layer_2_all, 1, activation=None, name='f3_att' + stag)
d_layer_3_all = tf.reshape(d_layer_3_all, [-1, 1, tf.shape(facts)[1]])
scores = d_layer_3_all
if mask is not None:
mask = tf.equal(mask, tf.ones_like(mask))
key_masks = tf.expand_dims(mask, 1) # [B, 1, T]
paddings = tf.ones_like(scores) * (-2 ** 32 + 1)
scores = tf.where(key_masks, scores, paddings) # [B, 1, T]
# Activation
if softmax_stag:
scores = tf.nn.softmax(scores) # [B, 1, T]
# Weighted sum
if mode == 'SUM':
output = tf.matmul(scores, facts) # [B, 1, H]
# output = tf.reshape(output, [-1, tf.shape(facts)[-1]])
else:
scores = tf.reshape(scores, [-1, tf.shape(facts)[1]])
output = facts * tf.expand_dims(scores, -1)
output = tf.reshape(output, tf.shape(facts))
if return_alphas:
return output, scores
| tensorflow.nn.softmax | 12,576 |
import tensorflow as tf
dec, mem = tf.nn.seq2seq.embedding_rnn_seq2seq(
enc_inp, dec_inp, cell, num_encoder_symbols=2,
num_decoder_symbols=5, embedding_size=2)
sess.run([tf.global_variables_initializer()])
res = sess.run(dec)
self.assertEqual(3, len(res))
self.assertEqual((2, 5), res[0].shape)
res = sess.run([mem])
self.assertEqual((2, 2), res[0].c.shape)
self.assertEqual((2, 2), res[0].h.shape)
# Test with state_is_tuple=False.
with tf.variable_scope("no_tuple"):
cell1 = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=False)
dec, mem = tf.nn.seq2seq.embedding_rnn_seq2seq(
enc_inp, dec_inp, cell1, num_encoder_symbols=2,
num_decoder_symbols=5, embedding_size=2)
sess.run([tf.global_variables_initializer()])
res = sess.run(dec)
self.assertEqual(3, len(res))
self.assertEqual((2, 5), res[0].shape)
res = sess.run([mem])
self.assertEqual((2, 4), res[0].shape)
# Test externally provided output projection.
w = tf.get_variable("proj_w", [2, 5])
b = tf.get_variable("proj_b", [5])
with tf.variable_scope("proj_seq2seq"):
| tensorflow.nn.seq2seq.embedding_rnn_seq2seq | 12,577 |
import tensorflow as tf
"""Define the graph inputs"""
batch_size = tf.placeholder(tf.int32, [], name='batch_size')
x = tf.placeholder(tf.float32, [None, num_steps, input_size_x], name='x')
y = tf.placeholder(tf.float32, [None, num_steps, input_size_y], name='y')
input_prob = tf.placeholder(tf.float32, name='input_prob')
state_prob = tf.placeholder(tf.float32,name='state_prob')
| tensorflow.placeholder | 12,578 |
import tensorflow as tf
lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(RNN_SIZE,state_is_tuple=True)
c_init = np.zeros((1, lstm_cell.state_size.c), np.float32)
h_init = np.zeros((1, lstm_cell.state_size.h), np.float32)
state_init = [c_init, h_init]
c_in = tf.placeholder(tf.float32, [1, lstm_cell.state_size.c])
h_in = tf.placeholder(tf.float32, [1, lstm_cell.state_size.h])
state_in = (c_in, h_in)
rnn_in = tf.expand_dims(self.h3, [0])
step_size = tf.shape(inputs)[:1]
state_in = tf.nn.rnn_cell.LSTMStateTuple(c_in, h_in)
lstm_outputs, lstm_state = tf.nn.dynamic_rnn(
lstm_cell, rnn_in, initial_state=state_in, sequence_length=step_size,
time_major=False)
lstm_c, lstm_h = lstm_state
state_out = (lstm_c[:1, :], lstm_h[:1, :])
self.rnn_out = tf.reshape(lstm_outputs, [-1, RNN_SIZE])
'''
CHANGES
- removed blocking layer
- edited out stop_gradient lines (Dont need them)
'''
# Value FC
value = Dense(units=1, kernel_initializer=normalized_columns_initializer(1.0), bias_initializer=None, activation=None)(inputs=self.rnn_out)
# rnn_out_frozen = tf.stop_gradient(self.rnn_out)
next_loc_mean = Dense(units=2, kernel_initializer=normalized_columns_initializer(1.0), bias_initializer=None, activation=tf.math.tanh)(inputs=self.rnn_out) # was rnn_out_frozen
loc_std = Dense(units=1, kernel_initializer=normalized_columns_initializer(1.0), activation=tf.nn.softplus)(inputs = self.rnn_out)
# Policy FC
| tensorflow.reshape | 12,579 |
import tensorflow as tf
self.loss_GABA = self.lambda_l2*squared_loss(self.images_fake_A,self.image_real_A) + binary_cross_entropy_loss(labels=tf.ones_like(self.D_B_fake),logits=self.D_B_fake)
self.loss_GBAB = self.lambda_l2*squared_loss(self.images_fake_B_,self.image_real_B) + binary_cross_entropy_loss(labels=tf.ones_like(self.D_A_fake),logits=self.D_A_fake)
self.generator_loss = self.loss_GABA + self.loss_GBAB
self.D_B_loss_real = binary_cross_entropy_loss(tf.ones_like(self.D_B_real),self.D_B_real)
self.D_B_loss_fake = binary_cross_entropy_loss(tf.zeros_like(self.D_B_fake),self.D_B_fake)
self.D_B_loss = (self.D_B_loss_real + self.D_B_loss_fake) / 2.0
self.D_A_loss_real = binary_cross_entropy_loss(tf.ones_like(self.D_A_real),self.D_A_real)
self.D_A_loss_fake = binary_cross_entropy_loss(tf.zeros_like(self.D_A_fake),self.D_A_fake)
| tensorflow.zeros_like | 12,580 |
import tensorflow as tf
# end=int(end)
label_id = [0]*max_seq_length
label_id[start:end]=[1]*(end-start)
if ex_index < 5:
tf.logging.info("*** Example ***")
tf.logging.info("guid: %s" % (example.guid))
tf.logging.info("tokens: %s" % " ".join(
[tokenization.printable_text(x) for x in tokens]))
tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
tf.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
tf.logging.info("label: {}" .format(label_id))
| tensorflow.logging.info | 12,581 |
import tensorflow as tf
boxlist2: Mx4
Returns:
a tensor with shape [N, M] representing pairwise intersections
"""
x_min1, y_min1, x_max1, y_max1 = tf.split(boxlist1, 4, axis=1)
x_min2, y_min2, x_max2, y_max2 = tf.split(boxlist2, 4, axis=1)
all_pairs_min_ymax = tf.minimum(y_max1, tf.transpose(y_max2))
all_pairs_max_ymin = tf.maximum(y_min1, tf.transpose(y_min2))
intersect_heights = tf.maximum(0.0, all_pairs_min_ymax - all_pairs_max_ymin)
all_pairs_min_xmax = tf.minimum(x_max1, tf.transpose(x_max2))
all_pairs_max_xmin = tf.maximum(x_min1, tf.transpose(x_min2))
intersect_widths = tf.maximum(0.0, all_pairs_min_xmax - all_pairs_max_xmin)
return intersect_heights * intersect_widths
@under_name_scope()
def pairwise_iou(boxlist1, boxlist2):
"""Computes pairwise intersection-over-union between box collections.
Args:
boxlist1: Nx4 floatbox
| tensorflow.transpose | 12,582 |
import tensorflow as tf
print('Num of sample per eps is %d' % (num_sample))
# Construct predictions
image = tf.placeholder(tf.float32, shape=[hps.batch_size, image_size, image_size,
num_channel]) ############MNIST and CIFAR10 are different ar here
adv_image = tf.placeholder(tf.float32, shape=[hps.batch_size, image_size, image_size,
num_channel]) ############MNIST and CIFAR10 are different ar here
predict = tf.placeholder(tf.float32, shape=[hps.batch_size, 10])
predict_nor, tsne_logit_nor = models(hps, image, FLAGS.RCE_train, logits=False, tsne_logits=True)
predict_adv, tsne_logit_adv = models(hps, adv_image, FLAGS.RCE_train, logits=False, tsne_logits=True)
# Calculate entropy
argmax_y_onehot = tf.one_hot(tf.argmax(predict, 1), 10, on_value=0.0, off_value=1.0, axis=-1)
normalized_y_nonmaximal = tf.reduce_sum(predict * argmax_y_onehot, 1)
| tensorflow.placeholder | 12,583 |
import tensorflow as tf
params_size_t = self._cell.params_size()
self._rnn_params = tf.get_variable(
"lstm_params",
initializer=tf.random_uniform(
[params_size_t], -config.init_scale, config.init_scale),
validate_shape=False)
| tensorflow.random_uniform | 12,584 |
import tensorflow as tf
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)
| tensorflow.nn.softmax | 12,585 |
import tensorflow as tf
class TrainR3DetGWD(Train):
def get_gtboxes_and_label(self, gtboxes_and_label_h, gtboxes_and_label_r, num_objects):
return gtboxes_and_label_h[:int(num_objects), :].astype(np.float32), \
gtboxes_and_label_r[:int(num_objects), :].astype(np.float32)
def main(self):
with tf.Graph().as_default() as graph, tf.device('/cpu:0'):
num_gpu = len(cfgs.GPU_GROUP.strip().split(','))
global_step = slim.get_or_create_global_step()
lr = self.warmup_lr(cfgs.LR, global_step, cfgs.WARM_SETP, num_gpu)
tf.summary.scalar('lr', lr)
optimizer = tf.train.MomentumOptimizer(lr, momentum=cfgs.MOMENTUM)
r3det_gwd = build_whole_network.DetectionNetworkR3DetGWD(cfgs=self.cfgs,
is_training=True)
with tf.name_scope('get_batch'):
if cfgs.IMAGE_PYRAMID:
shortside_len_list = tf.constant(cfgs.IMG_SHORT_SIDE_LEN)
shortside_len = tf.random_shuffle(shortside_len_list)[0]
else:
shortside_len = cfgs.IMG_SHORT_SIDE_LEN
| tensorflow.summary.scalar | 12,586 |
import tensorflow as tf
dataset.training_X, dataset.training_y, dataset.validation_X, dataset.validation_y
if not os.path.exists(weights_dir):
os.mkdir(weights_dir)
if not os.path.exists(weights_dir + '/best_models'):
os.mkdir(weights_dir + '/best_models')
# Create a saver.
saver = tf.train.Saver(max_to_keep=None)
if self.is_summary:
training_batch_summary_op = tf.merge_all_summaries(key=TRAINING_BATCH_SUMMARIES)
training_epoch_summary_op = tf.merge_all_summaries(key=TRAINING_EPOCH_SUMMARIES)
validation_batch_summary_op = tf.merge_all_summaries(key=VALIDATION_BATCH_SUMMARIES)
validation_epoch_summary_op = tf.merge_all_summaries(key=VALIDATION_EPOCH_SUMMARIES)
# Build an initialization operation to run below.
init = tf.global_variables_initializer()
gpu_options = tf.GPUOptions(
| tensorflow.merge_all_summaries | 12,587 |
import tensorflow as tf
if FLAGS.profile and hvd.rank() == 0:
ProfilerHook = tf.train.ProfilerHook(save_steps=FLAGS.hooking_frequence, output_dir=FLAGS.output_dir, show_dataflow=True, show_memory=True)
hooks.append(ProfilerHook)
# If TPU is not available, this will fall back to normal Estimator on CPU
# or GPU.
estimator = tf.estimator.Estimator(
model_fn=model_fn,
config=run_config)
if FLAGS.do_train:
tf.logging.info("***** Running training *****")
tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
| tensorflow.estimator.Estimator | 12,588 |
import tensorflow as tf
class Augmentator(object):
def __init__(self,type,size=1,mean=0,std=1):
self.size = size
if type=='scramble':
self.augment = self.scramble
elif type=='mix_scramble':
self.augment = self.mix_scramble
elif type=='blur':
self.augment = self.gaussian_blur
self.pointwise_filter = tf.eye(3, batch_shape=[1, 1])
elif type=='high_low_pass':
self.augment = self.high_low_pass
self.kernel = self.gaussian_kernel(size,mean,std)
self.kernel = tf.tile(self.kernel[:, :, tf.newaxis, tf.newaxis], [1, 1, 3, 1])
self.pointwise_filter = tf.eye(3, batch_shape=[1, 1])
self.paddings = [[size,size],[size,size],[0,0]]
elif type=='no_op':
self.augment = self.no_op
| tensorflow.eye | 12,589 |
import tensorflow as tf
tf.app.flags.DEFINE_integer('batch_size', 32, "the number of examples in a batch")
tf.app.flags.DEFINE_integer('ul_batch_size', 128, "the number of unlabeled examples in a batch")
tf.app.flags.DEFINE_integer('eval_batch_size', 100, "the number of eval examples in a batch")
tf.app.flags.DEFINE_integer('eval_freq', 5, "")
tf.app.flags.DEFINE_integer('num_epochs', 120, "the number of epochs for training")
tf.app.flags.DEFINE_integer('epoch_decay_start', 80, "epoch of starting learning rate decay")
tf.app.flags.DEFINE_integer('num_iter_per_epoch', 400, "the number of updates per epoch")
tf.app.flags.DEFINE_float('learning_rate', 0.001, "initial leanring rate")
tf.app.flags.DEFINE_float('mom1', 0.9, "initial momentum rate")
tf.app.flags.DEFINE_float('mom2', 0.5, "momentum rate after epoch_decay_start")
tf.app.flags.DEFINE_string('method', 'vat', "{vat, vatent, baseline}")
if FLAGS.dataset == 'cifar10':
from cifar10 import inputs, unlabeled_inputs
| tensorflow.app.flags.DEFINE_float | 12,590 |
import tensorflow as tf
if not file_pattern:
file_pattern = _FILE_PATTERN
file_pattern = os.path.join(dataset_dir, file_pattern % split_name)
# Allowing None in the signature so that dataset_factory can use the default.
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)),
}
items_to_handlers = {
'image': slim.tfexample_decoder.Image(shape=[32, 32, 3]),
'label': slim.tfexample_decoder.Tensor('image/class/label'),
}
decoder = slim.tfexample_decoder.TFExampleDecoder(
keys_to_features, items_to_handlers)
labels_to_names = None
| tensorflow.zeros | 12,591 |
import tensorflow as tf
str(v.shape).ljust(20))
v_size = np.prod(np.array(v.shape.as_list())).tolist() # mutiple all dimension size
total_size += v_size
tf.logging.info("Total trainable variables size: %d", total_size)
learning_rate = get_learning_rate_decay(params.learning_rate,
global_step, params)
learning_rate = tf.convert_to_tensor(learning_rate, dtype=tf.float32)
tf.summary.scalar("learning_rate", learning_rate)
# Create optimizer
opt = tf.train.AdamOptimizer(learning_rate,
beta1=params.adam_beta1,
beta2=params.adam_beta2,
epsilon=params.adam_epsilon)
if params.update_cycle == 1:
train_op = tf.contrib.layers.optimize_loss(
name="training",
loss=loss,
global_step=global_step,
learning_rate=learning_rate,
| tensorflow.train.AdamOptimizer | 12,592 |
import tensorflow as tf
# Graph mode testing
with tf.Graph().as_default():
energy_fn, _, _ = l2hmc.get_scg_energy_fn()
dynamics = l2hmc.Dynamics(
x_dim=hparams.x_dim,
minus_loglikelihood_fn=energy_fn,
n_steps=hparams.n_steps,
eps=hparams.eps)
x = tf.placeholder(tf.float32, shape=[None, hparams.x_dim])
x_, v_, x_accept_prob, x_out = dynamics.apply_transition(x)
samples = npr.normal(size=[hparams.n_samples, hparams.x_dim])
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
np_x_, np_v_, np_x_accept_prob, np_x_out = sess.run(
[x_, v_, x_accept_prob, x_out], feed_dict={x: samples})
| tensorflow.placeholder | 12,593 |
import tensorflow as tf
instead of an operation that modifies var_matrix.
Args:
var_matrix: 2D tensor (Variable)
maxnorm: the maximum Euclidean norm
Returns:
A new tensor where all rows have been scaled as necessary
'''
axis_norms = tf.sqrt(tf.reduce_sum(tf.square(var_matrix), 1))
scaling = maxnorm / tf.maximum(axis_norms, maxnorm)
return var_matrix * tf.expand_dims(scaling, 1)
class BaseModel(object):
''' Base class for embedding-based relational learning models that use
maxnorm regularization. Subclasses must implement _create_model() and
populate self.train_step, and can optionally populate self.post_step for
post-processing.
| tensorflow.maximum | 12,594 |
import tensorflow as tf
if config.decay is not None:
self.var_ema = tf.train.ExponentialMovingAverage(config.decay)
ema_op = self.var_ema.apply(tf.trainable_variables())
with tf.control_dependencies([ema_op]):
self.loss = tf.identity(self.loss)
self.assign_vars = []
for var in tf.global_variables():
v = self.var_ema.average(var)
if v:
self.assign_vars.append(tf.assign(var,v))
def get_loss(self):
return self.loss
def get_global_step(self):
return self.global_step
| tensorflow.assign | 12,595 |
from tensorflow.python.framework import ops
if not inputs or not isinstance(inputs, (list, tuple)):
raise ValueError("inputs must be a list of at least one Tensor with the "
"same dtype and shape")
inputs = ops.convert_n_to_tensor_or_indexed_slices(inputs)
if not all(isinstance(x, ops.Tensor) for x in inputs):
raise ValueError("inputs must be a list of at least one Tensor with the "
| tensorflow.python.framework.ops.convert_n_to_tensor_or_indexed_slices | 12,596 |
import tensorflow as tf
last_layer = tf.nn.tanh(projected)
elif dnn_nonlin == 'sigmoid':
last_layer = tf.nn.sigmoid(projected)
elif dnn_nonlin == 'relu':
last_layer = tf.nn.relu(projected)
else:
raise NotImplementedError()
if mode == 'train' and dnn_keep_prob < 1.0:
last_layer = tf.nn.dropout(last_layer, dnn_keep_prob)
last_layer_size = layer_size
print('{}: {}'.format(layer_name, last_layer.get_shape()))
export_feat_tensors[layer_name] = last_layer
dnn_output = last_layer
dnn_output_size = last_layer_size
| tensorflow.nn.dropout | 12,597 |
from tensorflow.python.ops import array_ops
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],
self._num_units,
True,
bias_initializer=self._bias_initializer,
kernel_initializer=self._kernel_initializer)
c = self._activation(self._candidate_linear([inputs, r_state]))
new_h = (1. - att_score) * state + att_score * c
| tensorflow.python.ops.array_ops.split | 12,598 |
import tensorflow as tf
from texar.tf.modules.regressors.xlnet_regressor import XLNetRegressor
from texar.tf.utils.test import pretrained_test
# pylint: disable=too-many-locals, no-member
class XLNetRegressorTest(tf.test.TestCase):
"""Tests :class:`~texar.tf.modules.XLNetRegressor` class.
"""
@pretrained_test
def test_model_loading(self):
r"""Tests model loading functionality."""
inputs = tf.placeholder(dtype=tf.int32, shape=[None, None])
for pretrained_model_name in XLNetRegressor.available_checkpoints():
regressor = XLNetRegressor(
pretrained_model_name=pretrained_model_name)
_ = regressor(inputs)
def test_trainable_variables(self):
"""Tests the functionality of automatically collecting trainable
variables.
"""
inputs = tf.placeholder(dtype=tf.int32, shape=[None, None])
# case 1
hparams = {
| tensorflow.placeholder | 12,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.