seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
import tensorflow as tf
conv_outputs_ = encoder_inputs_
if encoder.conv_lstm_size:
cell = BasicConvLSTMCell([feature_size, channels], encoder.conv_lstm_size, 1)
encoder_inputs_, _ = tf.nn.bidirectional_dynamic_rnn(
cell, cell, encoder_inputs_,
dtype=tf.float32
)
encoder_inputs_ = tf.concat(encoder_inputs_, axis=2)
if encoder.convolutions:
if encoder.binary:
raise NotImplementedError
pad = tf.nn.embedding_lookup(embeddings, utils.BOS_ID)
pad = tf.expand_dims(tf.expand_dims(pad, axis=0), axis=1)
| tensorflow.concat | 6,500 |
from tensorflow.python.ops import math_ops
false_negatives, math_ops.reduce_sum(is_false_negative, 1))
true_negatives_update_op = state_ops.assign_add(
true_negatives, math_ops.reduce_sum(is_true_negative, 1))
false_positives_update_op = state_ops.assign_add(
| tensorflow.python.ops.math_ops.reduce_sum | 6,501 |
import tensorflow as tf
embedding_size=2)
sess.run([tf.global_variables_initializer()])
res = sess.run(dec)
self.assertEqual(3, len(res))
self.assertEqual((2, 3), 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"):
dec, _ = tf.nn.seq2seq.embedding_tied_rnn_seq2seq(
enc_inp, dec_inp, cell, num_symbols=5, embedding_size=2,
output_projection=(w, b))
sess.run([tf.global_variables_initializer()])
res = sess.run(dec)
self.assertEqual(3, len(res))
self.assertEqual((2, 2), res[0].shape)
# Test that previous-feeding model ignores inputs after the first.
dec_inp2 = [tf.constant(0, tf.int32, shape=[2])] * 3
with tf.variable_scope("other"):
d3, _ = tf.nn.seq2seq.embedding_tied_rnn_seq2seq(
enc_inp, dec_inp2, cell, num_symbols=5, embedding_size=2,
feed_previous=tf.constant(True))
sess.run([tf.global_variables_initializer()])
tf.get_variable_scope().reuse_variables()
| tensorflow.global_variables_initializer | 6,502 |
import tensorflow as tf
# now to upscale to actual image size
deconv_shape1 = image_net["pool4"].get_shape()
W_t1 = utils.weight_variable([4, 4, deconv_shape1[3].value, NUM_OF_CLASSESS], name="W_t1")
b_t1 = utils.bias_variable([deconv_shape1[3].value], name="b_t1")
conv_t1 = utils.conv2d_transpose_strided(conv8, W_t1, b_t1, output_shape=tf.shape(image_net["pool4"]))
fuse_1 = tf.add(conv_t1, image_net["pool4"], name="fuse_1")
deconv_shape2 = image_net["pool3"].get_shape()
W_t2 = utils.weight_variable([4, 4, deconv_shape2[3].value, deconv_shape1[3].value], name="W_t2")
b_t2 = utils.bias_variable([deconv_shape2[3].value], name="b_t2")
conv_t2 = utils.conv2d_transpose_strided(fuse_1, W_t2, b_t2, output_shape=tf.shape(image_net["pool3"]))
fuse_2 = tf.add(conv_t2, image_net["pool3"], name="fuse_2")
shape = tf.shape(image)
deconv_shape3 = tf.stack([shape[0], shape[1], shape[2], NUM_OF_CLASSESS])
W_t3 = utils.weight_variable([16, 16, NUM_OF_CLASSESS, deconv_shape2[3].value], name="W_t3")
b_t3 = utils.bias_variable([NUM_OF_CLASSESS], name="b_t3")
conv_t3 = utils.conv2d_transpose_strided(fuse_2, W_t3, b_t3, output_shape=deconv_shape3, stride=8)
annotation_pred = tf.argmax(conv_t3, dimension=3, name="prediction")
return tf.expand_dims(annotation_pred, dim=3), conv_t3
def train(loss_val, var_list):
optimizer = tf.train.AdamOptimizer(FLAGS.learning_rate)
grads = optimizer.compute_gradients(loss_val, var_list=var_list)
if FLAGS.debug:
# print(len(var_list))
| tensorflow.stack | 6,503 |
import tensorflow as tf
max_timescale: a float
Returns:
a Tensor of timing signals [batch, seq_len, channels]
"""
num_timescales = channels // 2
log_timescale_increment = (
math.log(float(max_timescale) / float(min_timescale)) /
(tf.to_float(num_timescales) - 1))
inv_timescales = min_timescale * tf.exp(
tf.to_float(tf.range(num_timescales)) * -log_timescale_increment)
scaled_time = (
tf.expand_dims(tf.to_float(position), 2) * tf.expand_dims(
tf.expand_dims(inv_timescales, 0), 0))
signal = tf.concat([tf.sin(scaled_time), tf.cos(scaled_time)], axis=2)
signal = tf.pad(signal, [[0, 0], [0, 0], [0, tf.mod(channels, 2)]])
return signal
def embedding_lookup(input_ids,
vocab_size,
embedding_size=128,
initializer_range=0.02,
word_embedding_name="word_embeddings",
use_one_hot_embeddings=False):
"""Looks up words embeddings for id tensor.
| tensorflow.expand_dims | 6,504 |
import tensorflow as tf
elif len(shape) == 4: # assumes NHWC
flat_shape = (np.prod(shape[:-1]), shape[-1])
else:
raise NotImplementedError
a = np.random.normal(0.0, 1.0, flat_shape)
u, _, v = np.linalg.svd(a, full_matrices=False)
q = u if u.shape == flat_shape else v # pick the one with the correct shape
q = q.reshape(shape)
return (scale * q[:shape[0], :shape[1]]).astype(np.float32)
return _ortho_init
def get_session():
return tf.get_default_session()
def var_shape(x):
out = x.get_shape().as_list()
return out
def intprod(x):
return int(np.prod(x))
def numel(x):
| tensorflow.get_default_session | 6,505 |
import tensorflow as tf
method=1,
is_csl=True)
tf.summary.image('Compare/final_detection_gpu:%d' % i, detections_in_img)
| tensorflow.summary.image | 6,506 |
import tensorflow as tf
num_classes = 1000
inputs = tf.random_uniform((batch_size, height, width, 3))
_, end_points = mobilenet_v1.mobilenet_v1(inputs, num_classes)
| tensorflow.random_uniform | 6,507 |
import tensorflow as tf
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)):
# state and target
self.state = tf.placeholder(tf.float32, [None,num_state], "state")
self.target = tf.placeholder(tf.float32, [None,1], name="target")
# layers
| tensorflow.placeholder | 6,508 |
from tensorflow.python.ops import variable_scope
decoder_state: Tuple of [batch_size, gen_hidden_size]
encoder_states: [batch_size, passage_len, encoder_dim]
encoder_features: [batch_size,passage_len,attention_vec_size]
passage_mask: [batch_size, passage_len]
v: [1,1, attention_vec_size]
w_c: [1,1, attention_vec_size]
coverage: [batch_size, passage_len]
'''
with variable_scope.variable_scope("Attention"):
# Equation (11) in the paper
state_features = linear(decoder_state, attention_vec_size, True) # [batch_size, attention_vec_size]
state_features = tf.expand_dims(state_features, 1) # [batch_size, 1, attention_vec_size]
all_features = encoder_features + state_features # [batch_size,passage_len,attention_vec_size]
if use_coverage and coverage is not None:
coverage_features = tf.expand_dims(coverage, axis=-1) * w_c # [batch_size, passage_len, attention_vec_size]
all_features += coverage_features
| tensorflow.python.ops.variable_scope.variable_scope | 6,509 |
import tensorflow as tf
log_prob_tf = tf.nn.log_softmax(pi.logits)
prob_tf = tf.nn.softmax(pi.logits)
# the "policy gradients" loss: its derivative is precisely the policy gradient
# notice that self.ac is a placeholder that is provided externally.
# adv will contain the advantages, as calculated in process_rollout
pi_loss = - tf.reduce_sum(tf.reduce_sum(log_prob_tf * self.ac, [1]) * self.adv)
# loss of value function
vf_loss = 0.5 * tf.reduce_sum(tf.square(pi.vf - self.r))
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
| tensorflow.reduce_sum | 6,510 |
import tensorflow as tf
### Metrics
global_step = tf.compat.v1.train.get_or_create_global_step()
orig_indices = tf.range(
self._sample_batch_size, dtype=relabel_indices.dtype)
with tf.name_scope("relabelling"):
# How often are the originally commanded goals most optimal?
opt_indices = tf.argmax(logits_vec, axis=1)
orig_is_opt = opt_indices == orig_indices
orig_opt_frac = tf.reduce_mean(tf.cast(orig_is_opt, tf.float32))
tf.compat.v2.summary.scalar(
name="orig_task_optimal", data=orig_opt_frac, step=global_step)
# How often is the relabelled goal optimal?
# The relabel_indices are [B, 1], so we need to remove the extra dim.
relabel_is_opt = tf.squeeze(relabel_indices) == orig_indices
relabel_opt_frac = tf.reduce_mean(tf.cast(relabel_is_opt, tf.float32))
tf.compat.v2.summary.scalar(
name="relabel_task_optimal", data=relabel_opt_frac, step=global_step)
| tensorflow.compat.v2.summary.scalar | 6,511 |
import tensorflow as tf
eps = tf.random_normal(tf.shape(mean), dtype=settings.float_type) # N x P
if cov_structure == "diag":
sample = mean + tf.sqrt(cov) * eps # N x P
elif cov_structure == "full":
cov = cov + (tf.eye(tf.shape(mean)[1], dtype=settings.float_type) * settings.numerics.jitter_level)[None, ...] # N x P x P
chol = tf.cholesky(cov) # N x P x P
return mean + (tf.matmul(chol, eps[..., None])[..., 0]) # N x P
else:
raise NotImplementedError # pragma: no cover
return sample # N x P
| tensorflow.matmul | 6,512 |
import tensorflow as tf
self._weight_contrastive_loss_d = weight_contrastive_loss_d
self._aug_color_jitter_prob = aug_color_jitter_prob
self._aug_color_drop_prob = aug_color_drop_prob
# To safe memory ModularGAN supports feeding real and fake samples
# separately through the discriminator. CLGAN does not support this to
# avoid additional additional complexity in create_loss().
assert not self._deprecated_split_disc_calls, \
"Splitting discriminator calls is not supported in CLGAN."
def _latent_projections(self, latents):
bs, dim = latents.get_shape().as_list()
with tf.variable_scope("discriminator_z_projection", reuse=tf.AUTO_REUSE) as scope:
k1 = tf.get_variable("kernel1", [dim, dim * 4])
k2 = tf.get_variable("kernel2", [dim * 4, dim])
z_proj = tf.matmul(tf.nn.leaky_relu(tf.matmul(latents, k1), name=scope.name), k2)
z_proj = z_proj / tf.reshape(tf.norm(z_proj, ord=2, axis=-1), [bs, 1])
return z_proj
def create_loss(self, features, labels, params, is_training=True):
"""Build the loss tensors for discriminator and generator.
This method will set self.d_loss and self.g_loss.
Args:
features: Optional dictionary with inputs to the model ("images" should
contain the real images and "z" the noise for the generator).
labels: Tensor will labels. These are class indices. Use
self._get_one_hot_labels(labels) to get a one hot encoded tensor.
| tensorflow.get_variable | 6,513 |
from tensorflow.examples.tutorials.mnist import input_data
tf.reset_default_graph()
# Import MNIST dataset
self.mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
| tensorflow.examples.tutorials.mnist.input_data.read_data_sets | 6,514 |
import tensorflow as tf
src_loss = get_loss(src_logits, inst_weights, src_one_hot_labels)
dst_loss = get_loss(dst_logits, 1., finetune_one_hot_labels)
l2_loss = []
for v in tf.trainable_variables():
if 'batch_normalization' not in v.name and 'rl_controller' not in v.name:
l2_loss.append(tf.nn.l2_loss(v))
l2_loss = FLAGS.dst_weight_decay * tf.add_n(l2_loss)
enable_pretrain = tf.cast(
tf.greater_equal(global_step, FLAGS.first_pretrain_steps), tf.float32)
loss = src_loss * tf.stop_gradient(loss_weights) * enable_pretrain
loss += dst_loss + l2_loss
return tf.identity(loss), src_loss, dst_loss
def train_model_fn(features, labels, mode, params): # pylint: disable=unused-argument
"""Defines the model function."""
| tensorflow.greater_equal | 6,515 |
import tensorflow as tf
next_sentence_log_probs, next_sentence_labels
])
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
| tensorflow.contrib.tpu.TPUEstimatorSpec | 6,516 |
import tensorflow as tf
ema_op = self.var_ema.apply(tf.trainable_variables())
with tf.control_dependencies([ema_op]):
self.loss = tf.identity(self.loss)
self.shadow_vars = []
self.global_vars = []
for var in tf.global_variables():
v = self.var_ema.average(var)
if v:
self.shadow_vars.append(v)
self.global_vars.append(var)
self.assign_vars = []
for g, v in zip(self.global_vars, self.shadow_vars):
self.assign_vars.append(tf.assign(g, v))
def _create_train_op(self):
# self.lr = tf.minimum(self.learning_rate, self.learning_rate / tf.log(999.) * tf.log(tf.cast(self.global_step, tf.float32) + 1))
self.lr = self.learning_rate
if self.optim_type == 'adagrad':
self.optimizer = tf.train.AdagradOptimizer(self.lr)
elif self.optim_type == 'adam':
self.optimizer = tf.train.AdamOptimizer(learning_rate=self.lr)
elif self.optim_type == 'rprop':
self.optimizer = tf.train.RMSPropOptimizer(self.lr)
elif self.optim_type == 'sgd':
| tensorflow.assign | 6,517 |
import tensorflow as tf
out_height = out_size[1]
out_width = out_size[2]
zero = tf.zeros([], dtype='int32')
# 0 <= z < depth, 0 <= y < height & 0 <= x < width.
| tensorflow.zeros | 6,518 |
import tensorflow as tf
drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_length], tf.int64),
"segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
"label_ids": tf.FixedLenFeature([seq_length], tf.int64),
"is_real_example": tf.FixedLenFeature([1], tf.int64),
}
def _decode_record(record, name_to_features):
| tensorflow.FixedLenFeature | 6,519 |
import tensorflow as tf
from neorl.rl.baselines.shared import ActorCriticRLModel, tf_util, SetVerbosity, TensorboardWriter
from neorl.rl.baselines.shared.runners import AbstractEnvRunner
from neorl.rl.baselines.shared.policies import ActorCriticPolicy, RecurrentActorCriticPolicy
# Filter tensorflow version warnings
import os
# https://stackoverflow.com/questions/40426502/is-there-a-way-to-suppress-the-messages-tensorflow-prints/40426709
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2'}
import warnings
# https://stackoverflow.com/questions/15777951/how-to-suppress-pandas-future-warning
warnings.simplefilter(action='ignore', category=FutureWarning)
warnings.simplefilter(action='ignore', category=Warning)
import tensorflow as tf
tf.get_logger().setLevel('INFO')
tf.autograph.set_verbosity(0)
import logging
tf.get_logger().setLevel(logging.ERROR)
# For ACER
def get_by_index(input_tensor, idx):
"""
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
| tensorflow.get_logger | 6,520 |
import tensorflow as tf
# ul_u = random_sphere(ul_images.shape)
# ul_u_eval_train = random_sphere(ul_images_eval_train.shape)
# ul_u_eval_test = random_sphere(images_eval_test.shape)
ul_u = placeholder_like(ul_images, "ul_u")
ul_u_eval_train = placeholder_like(ul_images_eval_train, "ul_u_eval_train")
ul_u_eval_test = placeholder_like(images_eval_test, "ul_u_eval_test")
with tf.device(FLAGS.device):
lr = tf.placeholder(tf.float32, shape=[], name="learning_rate")
mom = tf.placeholder(tf.float32, shape=[], name="momentum")
with tf.variable_scope("CNN") as scope:
# Build training graph
loss, train_op, global_step, ul_u_updated = build_training_graph(
images, labels, ul_images, ul_u, lr, mom)
scope.reuse_variables()
# Build eval graph
losses_eval_train = build_eval_graph(images_eval_train, labels_eval_train, ul_images_eval_train, ul_u_eval_train)
losses_eval_test = build_eval_graph(images_eval_test, labels_eval_test, images_eval_test, ul_u_eval_test)
| tensorflow.placeholder | 6,521 |
from tensorflow.python.ops import math_ops
Returns:
tf.Tensor with dtype=int32 giving the next array size.
"""
exponent = math_ops.ceil(
math_ops.log(math_ops.cast(required_size, dtypes.float32))
/ math_ops.log(math_ops.cast(growth_factor, dtypes.float32)))
return math_ops.cast(math_ops.ceil(growth_factor ** exponent), dtypes.int32)
| tensorflow.python.ops.math_ops.cast | 6,522 |
import tensorflow as tf
# Compute the policy loss
# Alternative: policy_kl_loss = tf.reduce_mean(logp_pi - min_qf_pi)
policy_kl_loss = tf.reduce_mean((self.ent_coef * logp_pi - min_qf_pi)*self.weight_ph)
actor_for_priority = tf.reduce_mean(self.ent_coef * logp_pi - min_qf_pi,1)
| tensorflow.reduce_mean | 6,523 |
from tensorflow.python.framework import ops
return func(x, y, name=name)
ops.Tensor._override_operator("__%s__" % op_name, binary_op_wrapper)
del binary_op_wrapper
def r_binary_op_wrapper(y, x):
with ops.op_scope([x, y], None, op_name) as name:
assert isinstance(y, ops.Tensor)
x = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name="x")
return func(x, y, name=name)
ops.Tensor._override_operator("__r%s__" % op_name, r_binary_op_wrapper)
del r_binary_op_wrapper
# Conversion table for __truediv__. None entries mean no conversion required.
_TRUEDIV_TABLE = {
types.uint8: types.float32,
types.int8: types.float32,
types.int16: types.float32,
types.int32: types.float64,
types.int64: types.float64,
| tensorflow.python.framework.ops.Tensor._override_operator | 6,524 |
import tensorflow as tf
stochastic_ph = tf.placeholder(tf.bool, (), name="stochastic")
update_eps_ph = tf.placeholder(tf.float32, (), name="update_eps")
update_param_noise_threshold_ph = tf.placeholder(tf.float32, (), name="update_param_noise_threshold")
update_param_noise_scale_ph = tf.placeholder(tf.bool, (), name="update_param_noise_scale")
| tensorflow.placeholder | 6,525 |
import tensorflow as tf
class ModelOwner:
LEARNING_RATE = 0.1
ITERATIONS = 60000 // 30
def __init__(self, player_name):
self.player_name = player_name
with tf.device(tfe.get_config().get_player(player_name).device_name):
self._initialize_weights()
def _initialize_weights(self):
with tf.name_scope('parameters'):
self.w0 = tf.Variable(tf.random_normal([28 * 28, 512]))
self.b0 = tf.Variable(tf.zeros([512]))
self.w1 = tf.Variable(tf.random_normal([512, 10]))
self.b1 = tf.Variable(tf.zeros([10]))
def _build_model(self, x, y):
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)
| tensorflow.random_normal | 6,526 |
from tensorflow.python.ops import array_ops
or `updates_collections` are not a list or tuple.
"""
if sensitivity < 0 or sensitivity > 1:
raise ValueError('`sensitivity` must be in the range [0, 1].')
with variable_scope.variable_scope(name, 'specificity_at_sensitivity',
[predictions, labels]):
kepsilon = 1e-7 # to account for floating point imprecisions
thresholds = [(i + 1) * 1.0 / (num_thresholds - 1)
for i in range(num_thresholds-2)]
thresholds = [0.0 - kepsilon] + thresholds + [1.0 - kepsilon]
(tp, fn, tn, fp, tp_update_op, fn_update_op, tn_update_op,
fp_update_op) = _tp_fn_tn_fp(predictions, labels, thresholds, weights)
assert array_ops.squeeze(fp).get_shape().as_list()[0] == num_thresholds
def compute_specificity_at_sensitivity(name):
"""Computes the specificity at the given sensitivity.
Args:
name: The name of the operation.
Returns:
The specificity using the aggregated values.
"""
sensitivities = math_ops.div(tp, tp + fn + kepsilon)
# We'll need to use this trick until tf.argmax allows us to specify
# whether we should use the first or last index in case of ties.
| tensorflow.python.ops.array_ops.squeeze | 6,527 |
import tensorflow as tf
with tf.control_dependencies(update_ops):
self.trainer = opt.apply_gradients(
gradvars, global_step=self.global_step)
def _eval_graph(self, data):
tower_metrics = self._gpu_tower(data, Mode.EVAL)
with tf.device('/cpu:0'):
self.metrics = {m: tf.reduce_mean(tf.stack([t[m] for t in tower_metrics]))
for m in tower_metrics[0]}
def _pred_graph(self, data):
with tf.name_scope('pred'):
with tf.device('/gpu:0'):
pred_out = self._model(data, Mode.PRED, **self.config)
self.pred_out = {n: tf.identity(p, name=n) for n, p in pred_out.items()}
def _build_graph(self):
# Training and evaluation network, if tf datasets provided
if self.datasets:
# Generate iterators for the given tf datasets
self.dataset_iterators = {}
with tf.device('/cpu:0'):
for n, d in self.datasets.items():
if n == 'training':
| tensorflow.device | 6,528 |
import tensorflow as tf
tf.flags.DEFINE_string(
"tpu_zone", None,
"[Optional] GCE zone where the Cloud TPU is located in. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
tf.flags.DEFINE_string(
"gcp_project", None,
"[Optional] Project name for the Cloud TPU-enabled project. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
flags.DEFINE_integer(
"num_tpu_cores", 8,
"Only used if `use_tpu` is True. Total number of TPU cores to use.")
class InputExample(object):
"""A single training/test example for simple sequence classification."""
def __init__(self, guid, text_a, text_b=None, label=None):
"""Constructs a InputExample.
| tensorflow.flags.DEFINE_string | 6,529 |
import tensorflow as tf
tf_sparse_demo = TFDemo(vocabulary_size=args.max_vocabulary_size_per_gpu * args.gpu_num,
embedding_vec_size=args.embedding_vec_size,
combiner=args.combiner,
slot_num=args.slot_num,
max_nnz=args.max_nnz,
use_hashtable=args.use_hashtable,
num_of_dense_layers=0)
optimizer = utils.get_dense_optimizer(args.optimizer)(learning_rate=0.1)
loss_fn = tf.keras.losses.BinaryCrossentropy(from_logits=True)
def _train_step(inputs, labels, training):
logit, embedding_vector = tf_sparse_demo(inputs, training=training)
loss = loss_fn(labels, logit)
grads = tf.gradients(loss, tf_sparse_demo.trainable_variables,
colocate_gradients_with_ops=True,
unconnected_gradients=tf.UnconnectedGradients.NONE)
train_op = optimizer.apply_gradients(zip(grads, tf_sparse_demo.trainable_variables))
with tf.control_dependencies([train_op]):
loss = tf.identity(loss)
| tensorflow.keras.losses.BinaryCrossentropy | 6,530 |
from tensorflow.python.ops import math_ops
Loss tensor.
"""
target = target[self.name] if isinstance(target, dict) else target
loss_unweighted = self._loss_fn(logits, target)
weight_tensor = self.get_weight_tensor(features)
if weight_tensor is None:
return math_ops.reduce_mean(loss_unweighted, name="loss")
loss_weighted = self._weighted_loss(loss_unweighted, weight_tensor)
return math_ops.div(math_ops.reduce_sum(loss_weighted),
math_ops.to_float(math_ops.reduce_sum(weight_tensor)),
name="loss")
| tensorflow.python.ops.math_ops.reduce_mean | 6,531 |
import tensorflow as tf
updates.append(mean.submit(value))
with tf.control_dependencies(updates):
| tensorflow.control_dependencies | 6,532 |
import tensorflow as tf
if self.batch_norm:
with tf.variable_scope(
| tensorflow.variable_scope | 6,533 |
import tensorflow as tf
if isinstance(scale, numbers.Integral):
raise ValueError('scale cannot be an integer: %s' % (scale,))
if isinstance(scale, numbers.Real):
if scale < 0.:
raise ValueError('Setting a scale less than 0 on a regularizer: %g.' % scale)
if scale == 0.:
return lambda _: None
def l2(weights, name='l2_regularizer'):
"""Applies l2 regularization to weights."""
with tf.name_scope(name):
my_scale = tf.convert_to_tensor(scale, dtype=weights.dtype.base_dtype, name='scale')
return tf.multiply(my_scale, nn.l2_loss(weights), name=name)
return l2
def discretized_mix_logistic_loss(inputs,
predictions,
sum_all=True,
| tensorflow.name_scope | 6,534 |
from tensorflow.python.framework import ops
if updates_collections:
ops.add_to_collections(updates_collections, update_op)
| tensorflow.python.framework.ops.add_to_collections | 6,535 |
from tensorflow.python.training import summary_io
`merge_all_summaries`.
save_steps: `int`, save summaries every N steps. See `EveryN`.
output_dir: `string`, the directory to save the summaries to. Only used
if no `summary_writer` is supplied.
summary_writer: `SummaryWriter`. If `None` and an `output_dir` was passed,
one will be created accordingly.
scaffold: `Scaffold` to get summary_op if it's not provided.
"""
# TODO(ipolosukhin): Implement every N seconds.
super(SummarySaver, self).__init__(every_n_steps=save_steps)
self._summary_op = summary_op
self._summary_writer = summary_writer
if summary_writer is None and output_dir:
self._summary_writer = summary_io.SummaryWriter(output_dir)
self._scaffold = scaffold
# TODO(mdan): Throw an error if output_dir and summary_writer are None.
def set_estimator(self, estimator):
super(SummarySaver, self).set_estimator(estimator)
# TODO(mdan): This line looks redundant.
if self._summary_writer is None:
self._summary_writer = summary_io.SummaryWriter(estimator.model_dir)
def every_n_step_begin(self, step):
super(SummarySaver, self).every_n_step_begin(step)
if self._summary_op is None and self._scaffold is not None:
| tensorflow.python.training.summary_io.SummaryWriter | 6,536 |
import tensorflow as tf
def batch_to_seq(h, nbatch, nsteps, flat=False):
if flat:
h = tf.reshape(h, [nbatch, nsteps])
else:
h = tf.reshape(h, [nbatch, nsteps, -1])
| tensorflow.reshape | 6,537 |
import tensorflow as tf
if len(shape) == 5: # FC 3D
size = shape[1].value*shape[2].value*shape[3].value*shape[4].value
elif len(shape) == 4:
size = shape[1].value*shape[2].value*shape[3].value
else:
size = shape[-1].value
with tf.variable_scope(layer_name):
w = tf.get_variable(name='weight',
shape=[size, out_nodes],
initializer=tf.constant_initializer(0.0))
b = tf.get_variable(name='bias',
shape=[out_nodes],
initializer=tf.constant_initializer(0.0))
# batch?
flat_x = tf.reshape(x, [-1,size])
x = tf.nn.bias_add(tf.matmul(flat_x,w), b)
x = tf.nn.relu(x)
return x
def lstm():
'''
Build LSTM cell
'''
| tensorflow.constant_initializer | 6,538 |
import tensorflow as tf
ValueError
If input tensor is not 2D.
"""
if weight_init is None:
num_features = tensor.get_shape()[-1].value
weight_init = tf.truncated_normal([num_features, size], stddev=0.01)
if bias_init is None:
bias_init = tf.zeros([size])
with tf.name_scope(name, 'fully_connected', [tensor]):
w = tf.Variable(weight_init, name='w', dtype=tf.float32)
b = tf.Variable(bias_init, name='b', dtype=tf.float32)
return tf.nn.xw_plus_b(tensor, w, b)
def weight_decay(penalty_type, penalty):
"""Add weight decay.
Args:
model: TensorflowGraph.
Returns:
A scalar tensor containing the weight decay cost.
| tensorflow.nn.xw_plus_b | 6,539 |
import tensorflow as tf
Returns:
A transformed tensor (tf.float32).
"""
with tf.variable_scope('_interpolate'):
num_batch = im.get_shape().as_list()[0]
depth = im.get_shape().as_list()[1]
height = im.get_shape().as_list()[2]
width = im.get_shape().as_list()[3]
channels = im.get_shape().as_list()[4]
x = tf.to_float(x)
y = tf.to_float(y)
z = tf.to_float(z)
depth_f = tf.to_float(depth)
height_f = tf.to_float(height)
width_f = tf.to_float(width)
# Number of disparity interpolated.
out_depth = out_size[0]
out_height = out_size[1]
out_width = out_size[2]
zero = tf.zeros([], dtype='int32')
# 0 <= z < depth, 0 <= y < height & 0 <= x < width.
max_z = tf.to_int32(tf.shape(im)[1] - 1)
max_y = tf.to_int32(tf.shape(im)[2] - 1)
max_x = tf.to_int32(tf.shape(im)[3] - 1)
| tensorflow.to_float | 6,540 |
import tensorflow as tf
token_type_table = tf.get_variable(
name=token_type_embedding_name,
shape=[token_type_vocab_size, width],
initializer=create_initializer(initializer_range))
# This vocab will be small so we always do one-hot here, since it is always
# faster for a small vocabulary.
flat_token_type_ids = tf.reshape(token_type_ids, [-1])
one_hot_ids = tf.one_hot(flat_token_type_ids, depth=token_type_vocab_size)
token_type_embeddings = tf.matmul(one_hot_ids, token_type_table)
token_type_embeddings = tf.reshape(token_type_embeddings,
[batch_size, seq_length, width])
output += token_type_embeddings
if use_position_embeddings:
assert_op = tf.assert_less_equal(seq_length, max_position_embeddings)
with tf.control_dependencies([assert_op]):
full_position_embeddings = tf.get_variable(
name=position_embedding_name,
shape=[max_position_embeddings, width],
initializer=create_initializer(initializer_range))
# Since the position embedding table is a learned variable, we create it
# using a (long) sequence length `max_position_embeddings`. The actual
# sequence length might be shorter than this, for faster training of
# tasks that do not have long sequences.
#
# So `full_position_embeddings` is effectively an embedding table
# for position [0, 1, 2, ..., max_position_embeddings-1], and the current
# sequence has positions [0, 1, 2, ... seq_length-1], so we can just
| tensorflow.assert_less_equal | 6,541 |
import tensorflow as tf
if reader is None:
reader = tf.TFRecordReader
# Features in Pascal VOC TFRecords.
keys_to_features = {
'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''),
'image/format': tf.FixedLenFeature((), tf.string, default_value='jpeg'),
'image/height': tf.FixedLenFeature([1], tf.int64),
'image/width': tf.FixedLenFeature([1], tf.int64),
'image/channels': tf.FixedLenFeature([1], tf.int64),
'image/shape': tf.FixedLenFeature([3], tf.int64),
'image/object/bbox/xmin': tf.VarLenFeature(dtype=tf.float32),
'image/object/bbox/ymin': tf.VarLenFeature(dtype=tf.float32),
'image/object/bbox/xmax': tf.VarLenFeature(dtype=tf.float32),
'image/object/bbox/ymax': tf.VarLenFeature(dtype=tf.float32),
'image/object/bbox/label': tf.VarLenFeature(dtype=tf.int64),
'image/object/bbox/difficult': tf.VarLenFeature(dtype=tf.int64),
'image/object/bbox/truncated': tf.VarLenFeature(dtype=tf.int64),
}
items_to_handlers = {
'image': slim.tfexample_decoder.Image('image/encoded', 'image/format'),
'shape': slim.tfexample_decoder.Tensor('image/shape'),
'object/bbox': slim.tfexample_decoder.BoundingBox(
['xmin', 'ymin', 'xmax', 'ymax'], 'image/object/bbox/'),
'object/label': slim.tfexample_decoder.Tensor('image/object/bbox/label'),
'object/difficult': slim.tfexample_decoder.Tensor('image/object/bbox/difficult'),
'object/truncated': slim.tfexample_decoder.Tensor('image/object/bbox/truncated'),
| tensorflow.VarLenFeature | 6,542 |
from tensorflow.python.framework import ops
with ops.device(device):
return array_ops.unstack(values)
else:
with ops.device(tensors[0].device):
sizes = array_ops.stack(
[array_ops.shape(tensor)[0] for tensor in tensors])
values = array_ops.concat(tensors, axis=0)
with ops.device(device):
sizes = array_ops.unstack(sizes)
return list(array_ops.split(values, sizes, axis=0))
def _scheduled_stamp_resource_op_runner(batch, stamp):
"""Runs a batch operation on a stamped resource."""
| tensorflow.python.framework.ops.device | 6,543 |
from tensorflow.python.ops import random_ops
def _get_batch_shape(self):
return array_ops.broadcast_static_shape(
self.alpha.get_shape(), self.beta.get_shape())
def _event_shape(self):
return constant_op.constant([], dtype=dtypes.int32)
def _get_event_shape(self):
return tensor_shape.scalar()
def _sample_n(self, n, seed=None):
"""See the documentation for tf.random_gamma for more details."""
return 1. / random_ops.random_gamma([n], self.alpha, beta=self.beta,
dtype=self.dtype, seed=seed)
def _log_prob(self, x):
x = control_flow_ops.with_dependencies([check_ops.assert_positive(x)] if
self.validate_args else [], x)
return (self.alpha * math_ops.log(self.beta) -
math_ops.lgamma(self.alpha) -
(self.alpha + 1.) * math_ops.log(x) - self.beta / x)
def _prob(self, x):
return math_ops.exp(self._log_prob(x))
| tensorflow.python.ops.random_ops.random_gamma | 6,544 |
import tensorflow as tf
logits += self.b_soft_no_learn
op_id = tf.multinomial(logits, 1)
| tensorflow.multinomial | 6,545 |
import tensorflow as tf
"""See base class."""
del num_summands # Unused.
del decode_params # Unused.
return tf.tile(encoded_tensors[self.ENCODED_VALUES_KEY], shape)
| tensorflow.tile | 6,546 |
from tensorflow import keras
dataset = dataset.repeat(num_epochs).batch(batch_size)
iterator = dataset.make_one_shot_iterator()
batch_features, batch_labels = iterator.get_next()
return batch_features, batch_labels
return _input_fn
# Create inference model using Keras
# The model here is a dnn regressor
def make_keras_estimator(output_dir):
from tensorflow import keras
model = keras.models.Sequential()
model.add(keras.layers.Dense(32, input_shape=(N_INPUTS,), name=TIMESERIES_INPUT_LAYER))
model.add(keras.layers.Activation('relu'))
model.add(keras.layers.Dense(1))
model.compile(loss = 'mean_squared_error',
optimizer = 'adam',
metrics = ['mae', 'mape']) # mean absolute [percentage] error
return keras.estimator.model_to_estimator(model, model_dir=output_dir)
# Create the inference model
def simple_rnn(features, labels, mode):
# 0. Reformat input shape to become a sequence
x = tf.split(features[TIMESERIES_COL], N_INPUTS, 1)
| tensorflow.keras.layers.Dense | 6,547 |
import tensorflow as tf
# If channel counts finally don't match, convert channel counts with 1x1 conv
if ch != ch_out:
with tf.variable_scope('convert_conv'):
X = self._do_conv(X, w, h, ch, ch_out, filter_size=1, is_train=is_train)
X = tf.reshape(X, (-1, w_out, h_out, ch_out)) # Sanity shape check
return X
def _add_fully_connected(self, X, in_shape, out_ch, no_reg=False):
ch = np.prod(in_shape)
X = tf.reshape(X, (-1, ch))
W = self._make_var('W', (ch, out_ch), no_reg=no_reg)
X = tf.matmul(X, W)
X = tf.reshape(X, (-1, out_ch)) # Sanity shape check
return X
def _add_factorized_reduction(self, X, in_w, in_h, in_ch, out_ch, is_train=False):
'''
Output is of shape (in_w // 2, in_h // 2, out_ch)
'''
| tensorflow.reshape | 6,548 |
import tensorflow as tf
antecedents_mask = antecedent_offsets >= 1 # [k, k]
fast_antecedent_scores = tf.expand_dims(top_span_mention_scores, 1) + tf.expand_dims(top_span_mention_scores, 0) # [k, k]
| tensorflow.expand_dims | 6,549 |
import tensorflow as tf
output, state = update(state, input_)
elif decoder.update_first:
output, state = update(state, input_, None, input_symbol)
context, new_weights = look(time, output, input_, pos=pos, prev_weights=prev_weights, context=context)
if decoder.conditional_rnn:
with tf.variable_scope('conditional_2'):
output, state = update(state, context)
elif not decoder.generate_first:
output, state = update(state, input_, context, input_symbol)
output_ = generate(output, input_, context)
| tensorflow.variable_scope | 6,550 |
import tensorflow as tf
return res
# build a one hot representation corresponding to the integer tensor
# the one-hot dimension is appended to the integer tensor shape
def as_one_hot(input_, n_indices):
"""Convert indices to one-hot."""
shape = input_.get_shape().as_list()
n_elem = numpy.prod(shape)
indices = tf.range(n_elem)
indices = tf.cast(indices, tf.int64)
indices_input = tf.concat(axis=0, values=[indices, tf.reshape(input_, [-1])])
indices_input = tf.reshape(indices_input, [2, -1])
indices_input = tf.transpose(indices_input)
res = tf.sparse_to_dense(
indices_input, [n_elem, n_indices], 1., 0., name="flat_one_hot")
res = tf.reshape(res, [elem for elem in shape] + [n_indices])
return res
def squeeze_2x2(input_):
"""Squeezing operation: reshape to convert space to channels."""
| tensorflow.reshape | 6,551 |
import tensorflow as tf
scope: optional name scope for summary tags.
Returns:
a scalar tensor representing the correlation loss value.
"""
with tf.name_scope(name):
source_samples -= tf.reduce_mean(source_samples, 0)
target_samples -= tf.reduce_mean(target_samples, 0)
source_samples = tf.nn.l2_normalize(source_samples, 1)
target_samples = tf.nn.l2_normalize(target_samples, 1)
| tensorflow.name_scope | 6,552 |
import tensorflow as tf
def build_cnet(self, state_in, name, reuse=False):
reg = tf.contrib.layers.l2_regularizer(1e-3)
with tf.variable_scope(name, reuse=reuse):
| tensorflow.contrib.layers.l2_regularizer | 6,553 |
import tensorflow as tf
Fetches experiences for given indices.
Args:
indices: Index tensor
Returns: Batch of experiences
"""
states = dict()
for name in sorted(self.states_memory):
states[name] = tf.gather(params=self.states_memory[name], indices=indices)
internals = dict()
for name in sorted(self.internals_memory):
internals[name] = tf.gather(params=self.internals_memory[name], indices=indices)
actions = dict()
for name in sorted(self.actions_memory):
actions[name] = tf.gather(params=self.actions_memory[name], indices=indices)
terminal = tf.gather(params=self.terminal_memory, indices=indices)
reward = tf.gather(params=self.reward_memory, indices=indices)
if self.include_next_states:
assert util.rank(indices) == 1
next_indices = (indices + 1) % self.capacity
| tensorflow.gather | 6,554 |
import tensorflow as tf
import tensorflow as tf
import random
from tensorflow.contrib import slim
from npu_bridge.estimator import npu_ops
from tensorflow.core.protobuf.rewriter_config_pb2 import RewriterConfig
tf.app.flags.DEFINE_integer('input_size', 512, '')
tf.app.flags.DEFINE_integer('batch_size_per_gpu', 14, '')
tf.app.flags.DEFINE_integer('num_readers', 16, '')
tf.app.flags.DEFINE_float('learning_rate', 0.0001, '')
tf.app.flags.DEFINE_integer('max_steps', 100000, '')
tf.app.flags.DEFINE_integer('loss_scale', 1024, '')
tf.app.flags.DEFINE_float('moving_average_decay', 0.997, '')
tf.app.flags.DEFINE_string('gpu_list', '1', '')
tf.app.flags.DEFINE_string('checkpoint_path', '/tmp/east_resnet_v1_50_rbox/', '')
tf.app.flags.DEFINE_boolean('restore', False, 'whether to resotre from checkpoint')
tf.app.flags.DEFINE_integer('save_checkpoint_steps', 1000, '')
tf.app.flags.DEFINE_integer('save_summary_steps', 100, '')
tf.app.flags.DEFINE_string('pretrained_model_path', None, '')
tf.app.flags.DEFINE_boolean('allow_mix_precision', False, 'whether to allow mix precision')
tf.app.flags.DEFINE_boolean('auto_tune', False, 'whether to autotune')
| tensorflow.app.flags.DEFINE_integer | 6,555 |
from tensorflow.python.ops import state_ops
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_sub | 6,556 |
import tensorflow as tf
train_op, _, _ = graphs.VatxtModel().language_model_training()
with self.test_session() as sess:
sess.run(tf.global_variables_initializer())
tf.train.start_queue_runners(sess)
sess.run(train_op)
| tensorflow.train.start_queue_runners | 6,557 |
import tensorflow as tf
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
| tensorflow.sqrt | 6,558 |
from tensorflow.python.framework import constant_op
class OpsTest(test.TestCase):
"""Ops tests."""
def test_softmax_classifier(self):
with self.cached_session() as session:
features = array_ops.placeholder(dtypes.float32, [None, 3])
labels = array_ops.placeholder(dtypes.float32, [None, 2])
weights = constant_op.constant([[0.1, 0.1], [0.1, 0.1], [0.1, 0.1]])
biases = constant_op.constant([0.2, 0.3])
class_weight = constant_op.constant([0.1, 0.9])
prediction, loss = ops.softmax_classifier(features, labels, weights,
biases, class_weight)
self.assertEqual(prediction.get_shape()[1], 2)
self.assertEqual(loss.get_shape(), [])
value = session.run(loss, {features: [[0.2, 0.3, 0.2]], labels: [[0, 1]]})
self.assertAllClose(value, 0.55180627)
def test_embedding_lookup(self):
| tensorflow.python.framework.constant_op.constant | 6,559 |
import tensorflow as tf
cls_index = tf.one_hot(cls_index, seq_len, axis=-1, dtype=tf.float32)
cls_feature = tf.einsum("lbh,bl->bh", output, cls_index)
# get the representation of START
start_p = tf.nn.softmax(start_logits_masked, axis=-1,
name="softmax_start")
start_feature = tf.einsum("lbh,bl->bh", output, start_p)
# note(zhiliny): no dependency on end_feature so that we can obtain
# one single `cls_logits` for each sample
ans_feature = tf.concat([start_feature, cls_feature], -1)
ans_feature = tf.layers.dense(
| tensorflow.einsum | 6,560 |
import tensorflow as tf
start_positions = tf.reshape(features["start_positions"], [-1])
start_index = tf.one_hot(start_positions, depth=seq_len, axis=-1,
dtype=tf.float32)
start_features = tf.einsum("lbh,bl->bh", output, start_index)
start_features = tf.tile(start_features[None], [seq_len, 1, 1])
end_logits = tf.layers.dense(
tf.concat([output, start_features], axis=-1), xlnet_config.d_model,
kernel_initializer=initializer, activation=tf.tanh, name="dense_0")
end_logits = tf.contrib.layers.layer_norm(
end_logits, begin_norm_axis=-1)
end_logits = tf.layers.dense(
end_logits, 1,
kernel_initializer=initializer,
name="dense_1")
end_logits = tf.transpose(tf.squeeze(end_logits, -1), [1, 0])
end_logits_masked = end_logits * (1 - p_mask) - 1e30 * p_mask
end_log_probs = tf.nn.log_softmax(end_logits_masked, -1)
else:
# during inference, compute the end logits based on beam search
start_top_log_probs, start_top_index = tf.nn.top_k(
start_log_probs, k=FLAGS.start_n_top)
start_index = tf.one_hot(start_top_index,
depth=seq_len, axis=-1, dtype=tf.float32)
start_features = tf.einsum("lbh,bkl->bkh", output, start_index)
end_input = tf.tile(output[:, :, None],
[1, 1, FLAGS.start_n_top, 1])
start_features = tf.tile(start_features[None],
[seq_len, 1, 1, 1])
| tensorflow.squeeze | 6,561 |
import tensorflow as tf
num_dec_timesteps = 3
def TestModel(seq2seq):
with self.test_session(graph=tf.Graph()) as sess:
tf.set_random_seed(111)
random.seed(111)
| tensorflow.Graph | 6,562 |
import tensorflow as tf
if "is_real_example" in features:
is_real_example = tf.cast(features["is_real_example"], dtype=tf.float32)
| tensorflow.cast | 6,563 |
import tensorflow as tf
'keep_checkpoint_max': 100,
}
config = tf.contrib.tpu.RunConfig(**run_config_args)
if FLAGS.warm_start_ckpt_path:
var_names = []
checkpoint_path = FLAGS.warm_start_ckpt_path
reader = tf.train.NewCheckpointReader(checkpoint_path)
for key in reader.get_variable_to_shape_map():
keep_str = 'Momentum|global_step|finetune_global_step'
if not re.findall('({})'.format(keep_str,), key):
var_names.append(key)
tf.logging.info('Warm-starting tensors: %s', sorted(var_names))
| tensorflow.train.NewCheckpointReader | 6,564 |
from tensorflow.contrib.learn.python.learn import ops
ids = np.random.randint(0, n_embed, ids_shape)
with self.cached_session():
embed_np = embeds[ids]
embed_tf = ops.embedding_lookup(embeds, ids).eval()
self.assertEqual(embed_np.shape, embed_tf.shape)
self.assertAllClose(embed_np, embed_tf)
| tensorflow.contrib.learn.python.learn.ops.embedding_lookup | 6,565 |
import tensorflow as tf
features = {'member/name': tf.io.FixedLenFeature([], tf.string),
'member/encoded': tf.io.FixedLenFeature([], tf.string),
'member/age': tf.io.FixedLenFeature([], tf.int64),
'member/height': tf.io.VarLenFeature(tf.float32),
| tensorflow.io.FixedLenFeature | 6,566 |
import tensorflow as tf
def N0(mean, variance):
return 1.0/(tf.sqrt(2.0 * m.pi * variance)) * tf.exp((-(mean**2))/(2*variance))
N = tf.cast(tf.shape(X)[0], tf.float32)
if y is None:
y = silverman_rule_of_thumb(N)
A = tf.subtract(tf.expand_dims(X, 0), tf.expand_dims(X, 1))
return (1.0/(N*N)) * tf.reduce_sum(N0(A, 2*y)) + N0(0.0, 2.0 + 2*y) - (2/N) * tf.reduce_sum(N0(X, 1.0 + 2*y))
def cw_2d(X, y=None):
def __phi(x):
def __phi_f(s):
t = s/7.5
| tensorflow.expand_dims | 6,567 |
import tensorflow as tf
# pylint: disable=unused-variable,invalid-name
def testDynamicAttentionDecoderStateIsTuple(self):
with self.test_session() as sess:
with tf.variable_scope(
"root", initializer=tf.constant_initializer(0.5)):
cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True)
cell = tf.nn.rnn_cell.MultiRNNCell(cells=[cell] * 2,
state_is_tuple=True)
inp = tf.constant(0.5, shape=[2, 2, 2])
enc_outputs, enc_state = tf.nn.rnn(cell, inp, dtype=tf.float32)
attn_states = tf.concat(1, [tf.reshape(e, [-1, 1, cell.output_size])
for e in enc_outputs])
dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3
dec, mem = tf.nn.seq2seq.attention_decoder(
dec_inp, enc_state,
attn_states, cell, output_size=4)
sess.run([tf.global_variables_initializer()])
res = sess.run(dec)
self.assertEqual(3, len(res))
self.assertEqual((2, 4), res[0].shape)
res = sess.run([mem])
self.assertEqual(2, len(res[0]))
self.assertEqual((2, 2), res[0][0].c.shape)
self.assertEqual((2, 2), res[0][0].h.shape)
self.assertEqual((2, 2), res[0][1].c.shape)
self.assertEqual((2, 2), res[0][1].h.shape)
| tensorflow.nn.seq2seq.attention_decoder | 6,568 |
import tensorflow as tf
self.assertAllClose(res1, res2)
self.assertAllClose(res1, res3)
def testEmbeddingTiedRNNSeq2Seq(self):
with self.test_session() as sess:
with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)):
enc_inp = [tf.constant(1, tf.int32, shape=[2]) for i in range(2)]
dec_inp = [tf.constant(i, tf.int32, shape=[2]) for i in range(3)]
cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True)
dec, mem = tf.nn.seq2seq.embedding_tied_rnn_seq2seq(
enc_inp, dec_inp, cell, num_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)
| tensorflow.nn.seq2seq.embedding_tied_rnn_seq2seq | 6,569 |
import tensorflow as tf
lr=FLAGS.learning_rate))
def weight_variable(shape):
"""weight_variable generates a weight variable of a given shape."""
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial, name='weights')
def bias_variable(shape):
| tensorflow.truncated_normal | 6,570 |
import tensorflow as tf
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,
}
| tensorflow.reshape | 6,571 |
from tensorflow.python.framework import ops
false_negatives_compute_op]):
update_op = compute_recall('update_op')
if metrics_collections:
ops.add_to_collections(metrics_collections, recall)
if updates_collections:
ops.add_to_collections(updates_collections, update_op)
return recall, update_op
def _at_k_name(name, k=None, class_id=None):
if k is not None:
| tensorflow.python.framework.ops.add_to_collections | 6,572 |
from tensorflow.python.ops import variable_scope
# Run the decoder RNN cell. cell_output = decoder state
cell_output, state_t = self.cell(x, state_t_1)
context_t, attn_dist, coverage_t = self.attention(state_t, options.attention_vec_size, encoder_states,
encoder_features, passage_mask, v, w_c=w_c,
use_coverage=options.use_coverage, coverage=coverage_t_1)
# Calculate p_gen, Equation (8)
if options.pointer_gen:
with tf.variable_scope('calculate_pgen'):
p_gen = linear([context_t, state_t.c, state_t.h, x], 1, True) # [batch_size, 1]
p_gen = tf.sigmoid(p_gen)
# Concatenate the cell_output (= decoder state) and the context vector, and pass them through a linear layer
# This is V[s_t, h*_t] + b in the paper
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)
| tensorflow.python.ops.variable_scope.variable_scope | 6,573 |
from tensorflow.python.client import timeline
if not FLAGS.forward_only:
lossval = results[1]
else:
lossval = 0.
train_time = time.time() - start_time
step_train_times.append(train_time)
if step >= 0 and (step == 0 or (step + 1) % FLAGS.display_every == 0):
log_fn('%i\t%s\t%.3f' % (
step + 1, get_perf_timing_str(batch_size, step_train_times),
lossval))
if trace_filename is not None and step == -1:
log_fn('Dumping trace to', trace_filename)
trace = timeline.Timeline(step_stats=run_metadata.step_stats)
with open(trace_filename, 'w') as trace_file:
trace_file.write(trace.generate_chrome_trace_format(show_memory=True))
return summary_str
def get_perf_timing_str(batch_size, step_train_times, scale=1):
times = np.array(step_train_times)
speeds = batch_size / times
speed_mean = scale * batch_size / np.mean(times)
if scale == 1:
speed_uncertainty = np.std(speeds) / np.sqrt(float(len(speeds)))
speed_madstd = 1.4826 * np.median(np.abs(speeds - np.median(speeds)))
speed_jitter = speed_madstd
| tensorflow.python.client.timeline.Timeline | 6,574 |
from tensorflow.python.framework import ops
return [tensor_shape.unknown_shape(ndims=4)]
@ops.RegisterShape("Conv2DBackpropInput")
def _Conv2DBackpropInputShape(op):
"""Shape function for the Conv2DBackpropInput op."""
| tensorflow.python.framework.ops.RegisterShape | 6,575 |
import tensorflow as tf
gt_boxes: BS x MaxNumGTs x 4
orig_gt_counts: BS
Returns:
list of length BS, each element is output of pairwise_iou: N x M
(where N is number of boxes for image and M is number of GTs for image)
"""
prefix = "pairwise_iou_batch"
# For each image index, extract a ?x4 boxlist and gt_boxlist
per_images_iou = []
for batch_idx in range(batch_size):
box_mask_for_image = tf.equal(proposal_boxes[:, 0], batch_idx)
single_image_boxes = tf.boolean_mask(proposal_boxes, box_mask_for_image)
single_image_boxes = single_image_boxes[:, 1:]
single_image_gt_boxes = gt_boxes[batch_idx, 0:orig_gt_counts[batch_idx], :]
single_image_iou = pairwise_iou(single_image_boxes, single_image_gt_boxes)
per_images_iou.append(single_image_iou)
return per_images_iou
| tensorflow.equal | 6,576 |
import tensorflow as tf
click_feature[i] = tf.expand_dims(tf.ones_like(self.labels[i]) , -1)
# click_feature[list_size:]=[tf.expand_dims(tf.zeros_like(self.labels[i]) , -1) for _ in range(3*list_size)]
click_feature[list_size:list_size+i] =[tf.expand_dims(self.labels[k] , -1) for k in range(i-1,-1,-1)]
click_feature[2*list_size:2*list_size+i+1]=[tf.expand_dims(self.types[k] , -1) for k in range(i,-1,-1)]
click_feature[3*list_size:3*list_size+list_size-i-1]=[tf.expand_dims(self.types[k] , -1) for k in range(i+1,list_size)]
# Predict propensity with a simple network
output_propensity_list.append(propensity_network(tf.concat(click_feature, 1), i))
self.click_show=[click_feature[h][0] for h in range(4*list_size)]
return tf.concat(output_propensity_list,1)
def step(self, session, input_feed, forward_only):
"""Run a step of the model feeding the given inputs.
Args:
session: (tf.Session) tensorflow session to use.
input_feed: (dictionary) A dictionary containing all the input feed data.
| tensorflow.concat | 6,577 |
import tensorflow as tf
var_shape = var.get_shape().as_list()
if var_shape == saved_shapes[name]:
restored.append(var)
else:
shape_conflicts.add(name)
found_names -= shape_conflicts
return (restored, sorted(found_names),
sorted(missing_names), sorted(shape_conflicts))
def load(self, checkpoint_path, flexible_restore=True):
if tf.gfile.IsDirectory(checkpoint_path):
checkpoint_path = tf.train.latest_checkpoint(checkpoint_path)
if checkpoint_path is None:
raise ValueError('Checkpoint directory is empty.')
if flexible_restore:
var_list, found, missing, conflicts = self._checkpoint_var_search(
checkpoint_path)
tf.logging.info('Restoring variables: \n\t{}'.format(
'\n\t'.join(found)))
if len(missing) > 0:
| tensorflow.gfile.IsDirectory | 6,578 |
from tensorflow.python.ops import math_ops
weights_tiled = array_ops.tile(array_ops.reshape(
_broadcast_weights(weights, predictions), [1, -1]), [num_thresholds, 1])
thresh_tiled.get_shape().assert_is_compatible_with(
weights_tiled.get_shape())
is_true_positive *= weights_tiled
is_false_negative *= weights_tiled
is_false_positive *= weights_tiled
is_true_negative *= weights_tiled
true_positives_update_op = state_ops.assign_add(
true_positives, math_ops.reduce_sum(is_true_positive, 1))
false_negatives_update_op = state_ops.assign_add(
false_negatives, math_ops.reduce_sum(is_false_negative, 1))
true_negatives_update_op = state_ops.assign_add(
true_negatives, math_ops.reduce_sum(is_true_negative, 1))
false_positives_update_op = state_ops.assign_add(
false_positives, math_ops.reduce_sum(is_false_positive, 1))
return (true_positives, false_negatives, true_negatives, false_positives,
true_positives_update_op, false_negatives_update_op,
| tensorflow.python.ops.math_ops.reduce_sum | 6,579 |
import tensorflow as tf
self.dropout_mask = []
for layer in range(num_layers):
input_size_ = input_size if layer == 0 else 2 * num_units
gru_fw = tf.contrib.cudnn_rnn.CudnnGRU(1, num_units)
gru_bw = tf.contrib.cudnn_rnn.CudnnGRU(1, num_units)
init_fw = tf.tile(tf.Variable(
tf.zeros([1, 1, num_units])), [1, batch_size, 1])
init_bw = tf.tile(tf.Variable(
| tensorflow.contrib.cudnn_rnn.CudnnGRU | 6,580 |
import tensorflow as tf
gru_fw, gru_bw = self.grus[layer]
init_fw, init_bw = self.inits[layer]
mask_fw, mask_bw = self.dropout_mask[layer]
with tf.variable_scope("fw_{}".format(layer)):
out_fw, _ = tf.nn.dynamic_rnn(
gru_fw, outputs[-1] * mask_fw, seq_len, initial_state=init_fw, dtype=tf.float32)
with tf.variable_scope("bw_{}".format(layer)):
inputs_bw = tf.reverse_sequence(
outputs[-1] * mask_bw, seq_lengths=seq_len, seq_dim=1, batch_dim=0)
out_bw, _ = tf.nn.dynamic_rnn(
gru_bw, inputs_bw, seq_len, initial_state=init_bw, dtype=tf.float32)
out_bw = tf.reverse_sequence(
out_bw, seq_lengths=seq_len, seq_dim=1, batch_dim=0)
outputs.append(tf.concat([out_fw, out_bw], axis=2))
if concat_layers:
res = tf.concat(outputs[1:], axis=2)
else:
res = outputs[-1]
return res
class ptr_net:
| tensorflow.reverse_sequence | 6,581 |
import tensorflow as tf
# Trainable parameters
mask = tf.equal(mask, tf.ones_like(mask))
facts_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer
querry_size = query.get_shape().as_list()[-1]
query = tf.layers.dense(query, facts_size, activation=None, name='f1' + stag)
query = prelu(query)
queries = tf.tile(query, [1, tf.shape(facts)[1]])
queries = tf.reshape(queries, tf.shape(facts))
din_all = tf.concat([queries, facts, queries-facts, queries*facts], axis=-1)
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
# Mask
# key_masks = tf.sequence_mask(facts_length, tf.shape(facts)[1]) # [B, T]
key_masks = tf.expand_dims(mask, 1) # [B, 1, T]
paddings = tf.ones_like(scores) * (-2 ** 32 + 1)
if not forCnn:
scores = tf.where(key_masks, scores, paddings) # [B, 1, T]
# Scale
# scores = scores / (facts.get_shape().as_list()[-1] ** 0.5)
| tensorflow.shape | 6,582 |
import tensorflow as tf
name='example_weights')
embeddings = c2v.GetEmbeddings(self.x)
self._inputs = [tf.squeeze(input_, [1]) for input_ in
tf.split(1, max_sequence_len, embeddings)]
# Need to prepare a mask to zero out the padding symbols.
| tensorflow.split | 6,583 |
from tensorflow.contrib.distributions.python.ops import distribution_util
def _batch_shape_tensor(self):
return array_ops.shape(self.rate)
def _batch_shape(self):
return self.rate.get_shape()
def _event_shape_tensor(self):
return constant_op.constant([], dtype=dtypes.int32)
def _event_shape(self):
return tensor_shape.scalar()
@distribution_util.AppendDocstring(_poisson_sample_note)
def _log_prob(self, x):
return self._log_unnormalized_prob(x) - self._log_normalization()
@distribution_util.AppendDocstring(_poisson_sample_note)
def _prob(self, x):
return math_ops.exp(self._log_prob(x))
@distribution_util.AppendDocstring(_poisson_sample_note)
def _log_cdf(self, x):
return math_ops.log(self.cdf(x))
| tensorflow.contrib.distributions.python.ops.distribution_util.AppendDocstring | 6,584 |
import tensorflow as tf
a = tf.constant_initializer([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
# Runs the op.
| tensorflow.matmul | 6,585 |
import tensorflow as tf
current_image_id_ph = tf.placeholder(tf.int32, [])
progress = networks.compute_progress(
current_image_id_ph,
stable_stage_num_images,
transition_stage_num_images,
num_blocks=3)
x = tf.random_normal([2, 16, 16, 3])
logits, _ = networks.discriminator(
x, progress, _num_filters_stub,
networks.ResolutionSchedule(
start_resolutions=(4, 4), scale_base=2, num_resolutions=3))
fake_loss = tf.reduce_sum(tf.square(logits))
| tensorflow.random_normal | 6,586 |
import tensorflow as tf
with tf.variable_scope("stats") as scope:
for i in range(hparams.tacotron_num_gpus):
tf.summary.histogram("mel_outputs %d" % i, model.tower_mel_outputs[i])
tf.summary.histogram("mel_targets %d" % i, model.tower_mel_targets[i])
tf.summary.scalar("before_loss", model.before_loss)
tf.summary.scalar("after_loss", model.after_loss)
if hparams.predict_linear:
tf.summary.scalar("linear_loss", model.linear_loss)
for i in range(hparams.tacotron_num_gpus):
tf.summary.histogram("mel_outputs %d" % i, model.tower_linear_outputs[i])
tf.summary.histogram("mel_targets %d" % i, model.tower_linear_targets[i])
tf.summary.scalar("regularization_loss", model.regularization_loss)
tf.summary.scalar("stop_token_loss", model.stop_token_loss)
tf.summary.scalar("loss", model.loss)
tf.summary.scalar("learning_rate", model.learning_rate) # Control learning rate decay speed
if hparams.tacotron_teacher_forcing_mode == "scheduled":
tf.summary.scalar("teacher_forcing_ratio", model.ratio) # Control teacher forcing
# ratio decay when mode = "scheduled"
gradient_norms = [tf.norm(grad) for grad in model.gradients]
tf.summary.histogram("gradient_norm", gradient_norms)
tf.summary.scalar("max_gradient_norm", tf.reduce_max(gradient_norms)) # visualize
# gradients (in case of explosion)
return tf.summary.merge_all()
| tensorflow.summary.scalar | 6,587 |
import tensorflow as tf
filter_h, filter_w, num_channels_out = filter_dims
stride_h, stride_w = stride_dims
with tf.variable_scope(scope):
conv_weight = tf.Variable(
tf.truncated_normal([filter_h, filter_w, num_channels_in, num_channels_out], stddev=0.1, dtype=tf.float32))
conv_bias = tf.Variable(tf.zeros([num_channels_out], dtype=tf.float32))
map = tf.nn.conv2d(input, conv_weight, strides=[1, stride_h, stride_w, 1], padding=padding, dilations=dilation)
if bias is True:
| tensorflow.truncated_normal | 6,588 |
import tensorflow as tf
eval_drop_remainder = True if FLAGS.use_tpu else False
eval_input_fn = file_based_input_fn_builder(
input_file=eval_file,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=eval_drop_remainder)
result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps)
output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt")
with tf.gfile.GFile(output_eval_file, "w") as writer:
tf.logging.info("***** Eval results *****")
for key in sorted(result.keys()):
tf.logging.info(" %s = %s", key, str(result[key]))
writer.write("%s = %s\n" % (key, str(result[key])))
if FLAGS.do_predict:
predict_examples = processor.get_test_examples(FLAGS.data_dir)
num_actual_predict_examples = len(predict_examples)
if FLAGS.use_tpu:
# TPU requires a fixed batch size for all batches, therefore the number
# of examples must be a multiple of the batch size, or else examples
# will get dropped. So we pad with fake examples which are ignored
| tensorflow.logging.info | 6,589 |
import tensorflow as tf
def post_cbhg(inputs, input_dim, is_training, depth):
return cbhg(
inputs,
None,
is_training,
scope='post_cbhg',
K=8,
projections=[256, input_dim],
depth=depth)
def cbhg(inputs, input_lengths, is_training, scope, K, projections, depth):
with tf.variable_scope(scope):
with tf.variable_scope('conv_bank'):
# Convolution bank: concatenate on the last axis to stack channels from all convolutions
conv_outputs = tf.concat(
[conv1d(inputs, k, 128, tf.nn.relu, is_training, 'conv1d_%d' % k) for k in range(1, K + 1)],
axis=-1
)
# Maxpooling:
maxpool_output = tf.layers.max_pooling1d(
conv_outputs,
pool_size=2,
| tensorflow.variable_scope | 6,590 |
import tensorflow as tf
for state in states:
dJr = tf.matmul(tf.nn.relu(state),
tf.matmul(tf.abs(self.W_rec) * self.rec_Connectivity, self.Dale_rec))
reg += tf.reduce_sum(tf.square(dJr))
return reg / (self.N_steps * self.N_batch)
# train the model using Adam
def train(self, sess, generator,
learning_rate=.001, training_iters=50000,
batch_size=64, display_step=10,weight_save_step=100, save_weights_path= None,
generator_function= None, training_weights_path = None):
# train with gradient clipping
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
grads = optimizer.compute_gradients(self.loss)
clipped_grads = [(tf.clip_by_norm(grad, 1.0), var)
if grad is not None else (grad, var)
for grad, var in grads]
# add vanishing gradient regularizer
#out, test = self.dOmega_dWrec()
#clipped_grads[0] = (tf.add(out[0], clipped_grads[0][0]), clipped_grads[0][1])
#clipped_grads[0] = (tf.Print(clipped_grads[0][0], [clipped_grads[0][0]], "gw_rec"), clipped_grads[0][1])
optimize = optimizer.apply_gradients(clipped_grads)
# run session
sess.run(tf.global_variables_initializer())
| tensorflow.train.AdamOptimizer | 6,591 |
import tensorflow as tf
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]
| tensorflow.ones_like | 6,592 |
import tensorflow as tf
"""Dataset for iterating over text."""
import collections
import numpy as np
import tensorflow as tf
def _split_string(string):
"""Splits a byte string into an array of character bytes."""
text = tf.compat.as_text(string)
ret = np.empty(len(text), dtype=np.object)
for i, char in enumerate(text):
ret[i] = tf.compat.as_bytes(char)
return ret
def vocabulary(filename, max_size=None, num_oov_buckets=1):
"""Builds vocabulary and ID lookup tables from the given file."""
| tensorflow.compat.as_text | 6,593 |
import tensorflow as tf
# overall pruning ratios of trainable & maskable variables
pr_trainable = calc_prune_ratio(self.trainable_vars)
pr_maskable = calc_prune_ratio(self.maskable_vars)
tf.summary.scalar('pr_trainable', pr_trainable)
tf.summary.scalar('pr_maskable', pr_maskable)
# build masks and corresponding operations for weight sparsification
self.masks, self.prune_op = self.__build_masks()
# optimizer & gradients
optimizer_base = tf.train.MomentumOptimizer(lrn_rate, FLAGS.momentum)
if not FLAGS.enbl_multi_gpu:
optimizer = optimizer_base
else:
optimizer = mgw.DistributedOptimizer(optimizer_base)
grads_origin = optimizer.compute_gradients(loss, self.trainable_vars)
grads_pruned = self.__calc_grads_pruned(grads_origin)
# TF operations & model saver
self.sess_train = sess
| tensorflow.train.MomentumOptimizer | 6,594 |
import tensorflow as tf
tensor_dict = {
fields.InputDataFields.image:
tf.constant(np_image),
fields.InputDataFields.groundtruth_classes:
tf.constant(np.array([3, 1], np.int32))
}
def mul_two_model_preprocessor_fn(image):
return (image * 2, tf.expand_dims(tf.shape(image)[1:], axis=0))
def add_five_to_image_data_augmentation_fn(tensor_dict):
tensor_dict[fields.InputDataFields.image] += 5
return tensor_dict
num_classes = 4
input_transformation_fn = functools.partial(
| tensorflow.shape | 6,595 |
import tensorflow as tf
threads = [self.checkedThread(target=run_assign, args=(assign_op,))
for assign_op in assigns]
for t in threads:
t.start()
for t in threads:
t.join()
vals = p.eval()
# Assert every element is taken from one of the assignments.
self.assertTrue((vals > 0).all())
self.assertTrue((vals <= 20).all())
if __name__ == "__main__":
tf.test.main()
| tensorflow.test.main | 6,596 |
import tensorflow as tf
with self.test_session() as sess:
var = tf.Variable(var_value, name=var_name)
save = tf.train.Saver({var_name: var})
var.initializer.run()
| tensorflow.train.Saver | 6,597 |
import tensorflow as tf
if decoder.cell_type.lower() == 'lstm' and decoder.use_lstm_full_state:
initial_output = initial_state
else:
# Last layer's state is the right-most part. Output is the left-most part of an LSTM's state.
initial_output = initial_state[:, -cell_output_size:]
time = tf.constant(0, dtype=tf.int32, name='time')
outputs = tf.TensorArray(dtype=tf.float32, size=time_steps)
samples = tf.TensorArray(dtype=tf.int64, size=time_steps)
inputs = tf.TensorArray(dtype=tf.int64, size=time_steps).unstack(tf.to_int64(tf.transpose(decoder_inputs)))
states = tf.TensorArray(dtype=tf.float32, size=time_steps)
weights = tf.TensorArray(dtype=tf.float32, size=time_steps)
attns = tf.TensorArray(dtype=tf.float32, size=time_steps)
initial_symbol = inputs.read(0) # first symbol is BOS
initial_input = embed(initial_symbol)
initial_pos = tf.zeros([batch_size], tf.float32)
initial_weights = tf.zeros(tf.shape(attention_states[align_encoder_id])[:2])
zero_context = tf.zeros(shape=tf.shape(attention_states[align_encoder_id][:,0])) # FIXME
with tf.variable_scope('decoder_{}'.format(decoder.name)):
initial_context, _ = look(0, initial_output, initial_input, pos=initial_pos, prev_weights=initial_weights,
context=zero_context)
initial_data = tf.concat([initial_state, initial_context, tf.expand_dims(initial_pos, axis=1), initial_weights],
axis=1)
context_size = initial_context.shape[1].value
| tensorflow.TensorArray | 6,598 |
from tensorflow.python.framework import tensor_util
Returns:
sample_dims: `Tensor` (1D, `int32`).
batch_dims: `Tensor` (1D, `int32`).
event_dims: `Tensor` (1D, `int32`).
"""
with self._name_scope(name, values=[x]):
def make_dims(start_sum, size, name):
"""Closure to make dims range."""
start_sum = start_sum if start_sum else (
array_ops.zeros((), dtype=dtypes.int32, name="zero"),)
if self._is_all_constant_helper(size, *start_sum):
start = sum(tensor_util.constant_value(s) for s in start_sum)
stop = start + tensor_util.constant_value(size)
return ops.convert_to_tensor(
list(range(start, stop)), dtype=dtypes.int32, name=name)
else:
start = sum(start_sum)
return math_ops.range(start, start + size)
sample_ndims = self.get_sample_ndims(x, name=name)
return (make_dims((), sample_ndims, name="sample_dims"),
make_dims((sample_ndims,), self.batch_ndims, name="batch_dims"),
make_dims((sample_ndims, self.batch_ndims),
self.event_ndims, name="event_dims"))
| tensorflow.python.framework.tensor_util.constant_value | 6,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.