seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
import tensorflow as tf
def input_fn(params):
"""The actual input function."""
batch_size = params["batch_size"]
num_examples = len(features)
# This is for demo purposes and does NOT scale to large data sets. We do
# not use Dataset.from_generator() because that uses tf.py_func which is
# not TPU compatible. The right way to load data is with TFRecordReader.
d = tf.data.Dataset.from_tensor_slices({
"input_ids":
tf.constant(
all_input_ids, shape=[num_examples, seq_length],
dtype=tf.int32),
"input_mask":
tf.constant(
all_input_mask,
shape=[num_examples, seq_length],
dtype=tf.int32),
"segment_ids":
tf.constant(
all_segment_ids,
shape=[num_examples, seq_length],
| tensorflow.constant | 6,000 |
import tensorflow as tf
return safe_get(name, list(shape), initializer=tf.constant_initializer(weights), dtype=tf.float32)
def batched_matrix_vector_multiply(vector, matrix):
""" computes x^T A in mini-batches. """
vector_batch_as_matricies = tf.expand_dims(vector, [1])
mult_result = tf.matmul(vector_batch_as_matricies, matrix)
squeezed_result = tf.squeeze(mult_result, [1])
return squeezed_result
def euclidean_loss_layer(a, b, multiplier=100.0, use_l1=False, eps=0.01):
| tensorflow.matmul | 6,001 |
import tensorflow as tf
self.padding = padding
self.epsilon = epsilon
def __call__(self,input_var,name=None,**kwargs) :
def _init():
v_norm = tf.nn.l2_normalize(self.v,axis=[0,1,2])
t = tf.nn.conv2d(input_var,v_norm,self.strides,self.padding,data_format='NHWC')
mu,var = tf.nn.moments(t,axes=[0,1,2])
std = tf.sqrt(var+self.epsilon)
return [tf.assign(self.g,1/std),tf.assign(self.b,-1.*mu/std)]
require_init = tf.reduce_any(tf.is_nan(self.g))
init_ops = tf.cond(require_init,_init,lambda : [self.g,self.b])
with tf.control_dependencies(init_ops):
w = tf.reshape(self.g,[1,1,1,tf.shape(self.v)[-1]]) * tf.nn.l2_normalize(self.v,axis=[0,1,2])
return tf.nn.bias_add(
| tensorflow.sqrt | 6,002 |
import tensorflow as tf
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
| tensorflow.shape | 6,003 |
import tensorflow as tf
output_bias = tf.get_variable(
"output_bias",
shape=[bert_config.vocab_size],
initializer=tf.zeros_initializer(),
)
logits = tf.matmul(input_tensor, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
log_probs = tf.nn.log_softmax(logits, axis=-1)
label_ids = tf.reshape(label_ids, [-1])
label_weights = tf.reshape(label_weights, [-1])
one_hot_labels = tf.one_hot(
label_ids, depth=bert_config.vocab_size, dtype=tf.float32
)
# The `positions` tensor might be zero-padded (if the sequence is too
# short to have the maximum number of predictions). The `label_weights`
# tensor has a value of 1.0 for every real prediction and 0.0 for the
# padding predictions.
| tensorflow.reshape | 6,004 |
import tensorflow as tf
def random_apply(fn, image, prob=1.):
b, *_ = image.get_shape().as_list()
chance = tf.less(tf.random_uniform([b], 0, 1.0), prob)
return tf.where(chance, fn(image), tf.identity(image))
def color_distortion(image, s=1.0):
lower, upper, x = (1 - 0.8 * s), (1 + 0.8 * s), image
x = tf.image.random_brightness(x, max_delta=0.8*s)
x = tf.image.random_contrast(x, lower=lower, upper=upper)
x = tf.image.random_saturation(x, lower=lower, upper=upper)
x = tf.image.random_hue(x, max_delta=0.2*s)
x = tf.clip_by_value(x, 0, 1)
return x
def color_drop(image):
| tensorflow.image.random_brightness | 6,005 |
import tensorflow as tf
if FLAGS.mode == 'train':
train_dataset_reader = dataset.BatchDatset(train_records, image_options)
validation_dataset_reader = dataset.BatchDatset(valid_records, image_options)
sess = tf.Session()
print("Setting up Saver...")
saver = tf.train.Saver()
# create two summary writers to show training loss and validation loss in the same graph
# need to create two folders 'train' and 'validation' inside FLAGS.logs_dir
train_writer = tf.summary.FileWriter(FLAGS.logs_dir + '/train', sess.graph)
validation_writer = tf.summary.FileWriter(FLAGS.logs_dir + '/validation')
sess.run(tf.global_variables_initializer())
ckpt = tf.train.get_checkpoint_state(FLAGS.logs_dir)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess, ckpt.model_checkpoint_path)
print("Model restored...")
if FLAGS.mode == "train":
for itr in xrange(MAX_ITERATION):
train_images, train_annotations = train_dataset_reader.next_batch(FLAGS.batch_size)
z_ = np.random.uniform(low=-1.0, high=1.0, size=(FLAGS.batch_size,4,4,128))
# print(train_images)
feed_dict = {image: train_images, annotation: train_annotations, keep_probability: 0.85, z: z_}
#train_images[:,50:100,50:100,:] =0
v = 0
| tensorflow.train.get_checkpoint_state | 6,006 |
import tensorflow as tf
done_mask_ph = tf.placeholder(tf.float32, [None], name="done")
importance_weights_ph = tf.placeholder(tf.float32, [None], name="weight")
# q network evaluation
q_t = q_func(obs_t_input.get(), num_actions, scope="q_func", reuse=True) # reuse parameters from act
q_func_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=tf.get_variable_scope().name + "/q_func")
# target q network evalution
q_tp1 = q_func(obs_tp1_input.get(), num_actions, scope="target_q_func")
target_q_func_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=tf.get_variable_scope().name + "/target_q_func")
| tensorflow.get_variable_scope | 6,007 |
import tensorflow as tf
preserving the original aspect ratio.
Args:
height: an int32 scalar tensor indicating the current height.
width: an int32 scalar tensor indicating the current width.
smallest_side: A python integer or scalar `Tensor` indicating the size of
the smallest side after resize.
Returns:
new_height: an int32 scalar tensor indicating the new height.
new_width: and int32 scalar tensor indicating the new width.
"""
smallest_side = tf.convert_to_tensor(smallest_side, dtype=tf.int32)
height = tf.to_float(height)
width = tf.to_float(width)
smallest_side = tf.to_float(smallest_side)
scale = tf.cond(tf.greater(height, width),
lambda: smallest_side / width,
lambda: smallest_side / height)
new_height = tf.to_int32(height * scale)
new_width = tf.to_int32(width * scale)
return new_height, new_width
def _aspect_preserving_resize(image, smallest_side):
"""Resize images preserving the original aspect ratio.
Args:
| tensorflow.to_float | 6,008 |
import tensorflow as tf
self.assertEqual(set(tf.matching_files(pattern % '*').eval()),
self._subset(files, [0, 1, 2, 3, 4, 5]))
self.assertEqual(set(tf.matching_files(pattern % '[cxz]').eval()),
self._subset(files, [0, 1]))
self.assertEqual(set(tf.matching_files(pattern % '[0-9]').eval()),
self._subset(files, [3, 4]))
if __name__ == '__main__':
tf.test.main()
| tensorflow.test.main | 6,009 |
import tensorflow as tf
self.assertEqual(3, len(res))
self.assertEqual((2, 4), res[0].shape)
res = sess.run([mem])
self.assertEqual(1, len(res))
self.assertEqual((2, 2), res[0].shape)
def testEmbeddingRNNDecoder(self):
with self.test_session() as sess:
with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)):
inp = [tf.constant(0.5, shape=[2, 2])] * 2
cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True)
_, enc_state = tf.nn.rnn(cell, inp, dtype=tf.float32)
dec_inp = [tf.constant(i, tf.int32, shape=[2]) for i in range(3)]
dec, mem = tf.nn.seq2seq.embedding_rnn_decoder(
dec_inp, enc_state, cell, num_symbols=4, embedding_size=2)
sess.run([tf.global_variables_initializer()])
res = sess.run(dec)
self.assertEqual(3, len(res))
self.assertEqual((2, 2), res[0].shape)
res = sess.run([mem])
self.assertEqual(1, len(res))
self.assertEqual((2, 2), res[0].c.shape)
| tensorflow.nn.rnn | 6,010 |
import tensorflow as tf
# Note: this warning is misleading in the context where tokens are ranked
# based on mutual information rather than frequency.
tf.compat.v1.logging.warn(
'frequency_threshold %d <= 1 is a no-op, use None instead.',
| tensorflow.compat.v1.logging.warn | 6,011 |
import tensorflow as tf
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"):
dec, _ = tf.nn.seq2seq.embedding_rnn_seq2seq(
enc_inp, dec_inp, cell, num_encoder_symbols=2,
num_decoder_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)
| tensorflow.get_variable | 6,012 |
from tensorflow.python.framework import ops
the return type is `quint8`.
"""
with ops.op_scope([x], name, "Tanh") as name:
x = ops.convert_to_tensor(x, name="x")
| tensorflow.python.framework.ops.op_scope | 6,013 |
import tensorflow as tf
self.saver = tf.train.Saver()
def train_network(self):
self.learning_rate = tf.placeholder(tf.float32)
self.d_optimizer = tf.train.AdamOptimizer(self.learning_rate,beta1=self.beta1,beta2=self.beta2).minimize(self.discriminator_loss,var_list=self.d_variables)
self.g_optimizer = tf.train.AdamOptimizer(self.learning_rate,beta1=self.beta1,beta2=self.beta2).minimize(self.generator_loss,var_list=self.g_variables)
self.init_op = tf.global_variables_initializer()
| tensorflow.placeholder | 6,014 |
import tensorflow as tf
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
def _selector(self, context, h, reuse=False):
with tf.variable_scope('selector', reuse=reuse):
w = tf.get_variable('w', [self.H, 1], initializer=self.weight_initializer)
b = tf.get_variable('b', [1], initializer=self.const_initializer)
beta = tf.nn.sigmoid(tf.matmul(h, w) + b, 'beta') # (N, 1)
context = tf.multiply(beta, context, name='selected_context')
return context, beta
def _decode_lstm(self, x, h, context, dropout=False, reuse=False):
with tf.variable_scope('logits', reuse=reuse):
w_h = tf.get_variable('w_h', [self.H, self.M], initializer=self.weight_initializer)
b_h = tf.get_variable('b_h', [self.M], initializer=self.const_initializer)
| tensorflow.variable_scope | 6,015 |
import tensorflow as tf
if self.mc.LOAD_PRETRAINED_MODEL:
assert tf.gfile.Exists(self.mc.PRETRAINED_MODEL_PATH), \
'Cannot find pretrained model at the given path:' \
| tensorflow.gfile.Exists | 6,016 |
from tensorflow.python.estimator.canned import head as head_lib
class CoreGradientBoostedDecisionTreeEstimator(test_util.TensorFlowTestCase):
def testTrainEvaluateInferDoesNotThrowError(self):
head_fn = head_lib._binary_logistic_head_with_sigmoid_cross_entropy_loss(
loss_reduction=losses.Reduction.SUM_OVER_NONZERO_WEIGHTS)
learner_config = learner_pb2.LearnerConfig()
learner_config.num_classes = 2
| tensorflow.python.estimator.canned.head._binary_logistic_head_with_sigmoid_cross_entropy_loss | 6,017 |
import tensorflow as tf
self.d_loss_fake = tf.nn.sigmoid_cross_entropy_with_logits(
logits=self.end_points_D['D_on_G_logits'],
labels=tf.zeros_like(self.end_points_D['D_on_G_logits']))
self.d_loss_class = tf.reduce_mean(self.d_loss_class)
self.d_loss_real = tf.reduce_mean(self.d_loss_real)
self.d_loss_fake = tf.reduce_mean(self.d_loss_fake)
if is_fm_loss:
global_pool_head = self.end_points_D['global_pool']
real_data_features = tf.slice(global_pool_head, [0, 0], [batch_size_train, num_classes])
fake_data_features = tf.slice(global_pool_head, [batch_size_train, 0],
[batch_size_train, num_classes])
self.g_loss = self._feature_matching_loss(real_data_features, fake_data_features)
else:
generator_target_prob = self.cnf['generator_target_prob'] # 0.75 / 2.0
self.g_loss = self._sigmoid_kl_with_logits(self.end_points_D['D_on_G_logits'],
generator_target_prob)
self.g_loss = tf.reduce_mean(self.g_loss)
if gpu_idx == 0:
| tensorflow.slice | 6,018 |
import tensorflow as tf
samples, logits, losses = self.sample(features)
# Concatenate the already-generated recent_output with last timestep
# of the newly-generated samples.
if target_modality.top_is_pointwise:
cur_sample = samples[:, -1, :, :]
else:
cur_sample = samples[:,
common_layers.shape_list(recent_output)[1], :, :]
cur_sample = tf.to_int64(tf.expand_dims(cur_sample, axis=1))
samples = tf.concat([recent_output, cur_sample], axis=1)
if not context.in_eager_mode():
samples.set_shape([None, None, None, 1])
# Assuming we have one shard for logits.
logits = tf.concat([recent_logits, logits[:, -1:]], 1)
loss = sum([l for l in losses.values() if l is not None])
return samples, logits, loss
# Create an initial output tensor. This will be passed
# to the infer_step, which adds one timestep at every iteration.
if "partial_targets" in features:
initial_output = tf.to_int64(features["partial_targets"])
while len(initial_output.get_shape().as_list()) < 4:
initial_output = tf.expand_dims(initial_output, 2)
batch_size = common_layers.shape_list(initial_output)[0]
else:
batch_size = common_layers.shape_list(features["inputs"])[0]
initial_output = tf.zeros((batch_size, 0, 1, 1), dtype=tf.int64)
| tensorflow.concat | 6,019 |
import tensorflow as tf
# Upsampling
up1 = common_deconv2d(dwn5,self.gf*8,stride=1,padding='valid',name='up1') # 16x16 -> 16x16
#print(np.shape(up1))
up2 = common_deconv2d(up1,self.gf*4,name='up2') # 16x16 -> 32x32
up3 = common_deconv2d(up2,self.gf*2,name='up3') # 32x32 -> 64x64
up4 = common_deconv2d(up3,self.gf,name='up4') # 64x64 -> 128x128
out_img = tf.contrib.layers.conv2d_transpose(up4,self.channels,kernel_size=4,stride=2,padding='SAME',activation_fn=tf.nn.tanh) # 128x128 -> 256x256
#print('out_img',(np.shape(out_img)))
return out_img
def build_discriminator(self,image,reuse=False,name='discriminator'):
| tensorflow.contrib.layers.conv2d_transpose | 6,020 |
import tensorflow as tf
Pooling 3D op
'''
if is_max_pool:
x = tf.nn.max_pool3d(x, ksize=kernel_size, strides=strides, padding='VALID', name=layer_name)
else:
x = tf.nn.avg_pool3d(x, ksize=kernel_size, strides=strides, padding='VALID', name=layer_name)
return x
def batch_norm(x):
'''
| tensorflow.nn.avg_pool3d | 6,021 |
import tensorflow as tf
y_centers = y_centers * stride[0]
# x_centers = x_centers + offset[1]
# y_centers = y_centers + offset[0]
x_centers, y_centers = tf.meshgrid(x_centers, y_centers)
widths, x_centers = tf.meshgrid(widths, x_centers)
heights, y_centers = tf.meshgrid(heights, y_centers)
anchor_centers = tf.stack([x_centers, y_centers], axis=2)
anchor_centers = tf.reshape(anchor_centers, [-1, 2])
anchor_sizes = tf.stack([widths, heights], axis=2)
anchor_sizes = tf.reshape(anchor_sizes, [-1, 2])
anchors = tf.concat([anchor_centers - .5 * anchor_sizes,
anchor_centers + .5 * anchor_sizes], 1)
# anchors = box_utils.convert_yxyx_to_xyxy_format(anchors)
return anchors
if __name__ == '__main__':
| tensorflow.stack | 6,022 |
import tensorflow as tf
name: str = "spherical_harmonics_generate_l_m_permutations") -> Tuple[TensorLike, TensorLike]:
with tf.name_scope(name):
| tensorflow.name_scope | 6,023 |
import tensorflow as tf
min_depth=min_depth,
depth_multiplier=depth_multiplier,
data_format=data_format,
scope=scope)
with tf.variable_scope('Logits'):
if data_format.startswith('NC'):
net = tf.transpose(net, [0, 2, 3, 4, 1])
kernel_size = i3d_utils.reduced_kernel_size_3d(net, [2, 7, 7])
net = layers.avg_pool3d(
net,
kernel_size,
stride=1,
| tensorflow.transpose | 6,024 |
import tensorflow as tf
labels: (tf.Tensor) A tensor of the same shape as `output`. A value >= 1 means a
relevant example.
propensity_weights: (tf.Tensor) A tensor of the same shape as `output` containing the weight of each element.
name: A string used as the name for this variable scope.
Returns:
(tf.Tensor) A single value tensor containing the loss.
"""
loss = None
with tf.name_scope(name, "click_weighted_log_loss",[output]):
click_prob = tf.sigmoid(output)
loss = tf.losses.log_loss(labels, click_prob, propensity_weights)
return loss
| tensorflow.losses.log_loss | 6,025 |
import tensorflow as tf
if mode == compat.ModeKeys.INFER:
input_dict["trg_input"] = target_bos
else:
input_dict["trg"] = batch_of_data["label"]
input_dict["trg_length"] = deduce_text_length(batch_of_data["label"],
self._multilingual_dp.meta["pad_id"],
self._multilingual_dp.meta["padding_mode"])
input_dict["trg_input"] = tf.concat([tf.expand_dims(target_bos, axis=1),
batch_of_data["label"][:, :-1]], axis=1)
return input_dict
def get_data_postprocess_fn(self, data_status, **kwargs) -> callable:
if data_status == compat.DataStatus.PROJECTED:
return self._multilingual_dp.decode
| tensorflow.expand_dims | 6,026 |
import tensorflow as tf
init_scale = .01
m_init, v_init = tf.nn.moments(x, [0, 1, 2])
scale_init = init_scale / tf.sqrt(v_init + 1e-10)
| tensorflow.nn.moments | 6,027 |
import tensorflow as tf
average_across_timesteps=False,
average_across_batch=True)
# Update the cost
self._cost = tf.reduce_sum(loss)
self._final_state = state
if not is_training:
return
self._lr = tf.Variable(0.0, trainable=False)
tvars = tf.trainable_variables()
grads, _ = tf.clip_by_global_norm(tf.gradients(self._cost, tvars),
config.max_grad_norm)
optimizer = tf.train.GradientDescentOptimizer(self._lr)
self._train_op = optimizer.apply_gradients(
zip(grads, tvars),
global_step=tf.contrib.framework.get_or_create_global_step())
self._new_lr = tf.placeholder(
tf.float32, shape=[], name="new_learning_rate")
self._lr_update = tf.assign(self._lr, self._new_lr)
| tensorflow.trainable_variables | 6,028 |
import tensorflow as tf
def contra_step_lossV1(pred, tgt, temp=10.0):
# Step-wise contrastive loss
pred1, pred2 = tf.split(pred, 2, axis=0)
tgt1, tgt2 = tf.split(tgt, 2, axis=0)
soft_sign = tf.tanh((tgt1 - tgt2) * temp)
loss = tf.maximum(0.0, soft_sign * ((tgt1 - tgt2) - (pred1 - pred2)))
loss = tf.reduce_mean(loss)
return loss
| tensorflow.tanh | 6,029 |
import tensorflow as tf
embedding_size = len([x for x in vocab_processor.transform(texts)])
# Split up data set into train/test
train_indices = np.random.choice(len(texts), round(len(texts)*0.8), replace=False)
test_indices = np.array(list(set(range(len(texts))) - set(train_indices)))
texts_train = [x for ix, x in enumerate(texts) if ix in train_indices]
texts_test = [x for ix, x in enumerate(texts) if ix in test_indices]
target_train = [x for ix, x in enumerate(target) if ix in train_indices]
target_test = [x for ix, x in enumerate(target) if ix in test_indices]
# Setup Index Matrix for one-hot-encoding
identity_mat = tf.diag(tf.ones(shape=[embedding_size]))
# Create variables for logistic regression
A = tf.Variable(tf.random_normal(shape=[embedding_size,1]))
b = tf.Variable(tf.random_normal(shape=[1,1]))
# Initialize placeholders
x_data = tf.placeholder(shape=[sentence_size], dtype=tf.int32)
y_target = tf.placeholder(shape=[1, 1], dtype=tf.float32)
# Text-Vocab Embedding
x_embed = tf.nn.embedding_lookup(identity_mat, x_data)
x_col_sums = tf.reduce_sum(x_embed, 0)
# Declare model operations
x_col_sums_2D = tf.expand_dims(x_col_sums, 0)
model_output = tf.add(tf.matmul(x_col_sums_2D, A), b)
| tensorflow.random_normal | 6,030 |
import tensorflow as tf
alpha_mean = tf.get_variable('alpha_mean_layer'+str(h),
shape=[1, 1, n_basis, n_out],
initializer=tf.random_normal_initializer())
alpha_logstd = tf.get_variable('alpha_logstd_layer'+str(h),
shape=[1, 1, n_basis, n_out],
initializer=tf.random_normal_initializer())
alpha_std = tf.exp(alpha_logstd)
# Compute epsilon from {n_samples} standard Gaussian
# epsilon = tf.random_normal([n_samples, 1, n_out*2, n_out])
epsilon = tf.random_uniform([n_samples, 1, n_basis, n_out])
hyp_params = tf.get_variable('hyp_params_layer'+str(h),
shape=[2],
initializer=tf.random_normal_initializer())
l1, l2 = tf.nn.sigmoid(hyp_params[0]), tf.exp(hyp_params[1])
epsilon = tf.sinh(epsilon*l2)/tf.cosh(epsilon*l2)**l1/l2
# Compute A_{h+1}
A = tf.tile(alpha_mean+epsilon*alpha_std, [1, tf.shape(X)[0], 1, 1])
# Compute z_{h}A_{h+1}
Z1 = tf.matmul(Z, A[:,:,:n_basis//2,:])/tf.sqrt(n_basis*.5)
Z2 = tf.matmul(Z, A[:,:,n_basis//2:,:])/tf.sqrt(n_basis*.5)
# Compute u_{h+1} and v_{h+1}
U, V = tf.cos(Z1)+tf.cos(Z2), tf.sin(Z1)+tf.sin(Z2)
Z = tf.concat([U, V], 3)/tf.sqrt(n_out*1.)
KL += tf.reduce_mean(alpha_std**2+alpha_mean**2-2*alpha_logstd-1)/2.
# Output layer
else:
F = tf.squeeze(tf.layers.dense(Z, n_out), [2])
return F, KL | tensorflow.cosh | 6,031 |
import tensorflow as tf
the smallest side after resize.
Returns:
new_height: an int32 scalar tensor indicating the new height.
new_width: and int32 scalar tensor indicating the new width.
"""
smallest_side = tf.convert_to_tensor(smallest_side, dtype=tf.int32)
height = tf.to_float(height)
width = tf.to_float(width)
smallest_side = tf.to_float(smallest_side)
scale = tf.cond(tf.greater(height, width),
lambda: smallest_side / width,
lambda: smallest_side / height)
new_height = tf.to_int32(height * scale)
new_width = tf.to_int32(width * scale)
return new_height, new_width
| tensorflow.to_float | 6,032 |
import tensorflow as tf
# Use a variable name map to set the saved tensor names
val = save.save(sess, save_path)
self.assertTrue(isinstance(val, six.string_types))
self.assertEqual(save_path, val)
# Verify that the original names are not in the Saved file
save = tf.train.Saver({"v0": v0, "v1": v1})
with self.assertRaisesOpError("not found in checkpoint"):
save.restore(sess, save_path)
# Verify that the mapped names are present in the Saved file and can be
# Restored using remapped names.
with self.test_session() as sess:
v0 = tf.Variable(-1.0, name="v0")
v1 = tf.Variable(-1.0, name="v1")
with self.assertRaisesOpError("uninitialized value v0"):
sess.run(v0)
with self.assertRaisesOpError("uninitialized value v1"):
sess.run(v1)
save = tf.train.Saver({"save_prefix/v0": v0, "save_prefix/v1": v1})
save.restore(sess, save_path)
# Check that the parameter nodes have been restored.
self.assertEqual(10.0, v0.eval())
| tensorflow.Variable | 6,033 |
import tensorflow as tf
print("***************")
print("Training done!!")
save_path = saver.save(sess, ckpt_name)
print("Model saved in file: %s" % save_path)
print ("creating protobuf...")
g_1 = tf.get_default_graph()
with tf.Session(graph = g_1) as sess:
saver = tf.train.import_meta_graph('save/model.ckpt.meta', clear_devices=True)
saver.restore(sess, ckpt_name)
graph_def = tf.graph_util.convert_variables_to_constants(sess, sess.graph_def, dst_nodes)
tf.train.write_graph(tf.graph_util.extract_sub_graph(graph_def, dst_nodes), path, fname, as_text=False)
| tensorflow.graph_util.extract_sub_graph | 6,034 |
import tensorflow as tf
h1 = tf.matmul(tf.transpose(c_hot_flat, perm=[1, 0, 2]), self.means)
h1 = tf.transpose(h1, perm=[1, 0, 2])
h1 = tf.reshape(h1, shape=h1_shape)
h1_shape[0] = self.hparams.batch_size
h2 = tf.layers.dense(tf.nn.relu(h1), self.hparams.filter_size, name="vch2")
res = tf.layers.dense(
tf.nn.relu(h2), self.hparams.hidden_size, name="vcfin")
return res
def discrete_bottleneck(self, x):
"""Discretization bottleneck for latent variables.
| tensorflow.nn.relu | 6,035 |
import tensorflow as tf
nin = x.get_shape()[1].value
w = tf.get_variable("w", [nin, nh], initializer=ortho_init(init_scale))
print("w is "+str(w))
b = tf.get_variable("b", [nh], initializer=tf.constant_initializer(init_bias))
return tf.matmul(x, w)+b
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])
return [tf.squeeze(v, [1]) for v in tf.split(axis=1, num_or_size_splits=nsteps, value=h)]
def seq_to_batch(h, flat = False):
shape = h[0].get_shape().as_list()
if not flat:
assert(len(shape) > 1)
nh = h[0].get_shape()[-1].value
return tf.reshape(tf.concat(axis=1, values=h), [-1, nh])
else:
return tf.reshape(tf.stack(values=h, axis=1), [-1])
| tensorflow.split | 6,036 |
import tensorflow as tf
# filters=y_size[-1],
# kernel_size=kernels,
# trainable=self.train,
# use_bias=use_bias,
# activation=self.ff_nl)
resized = tf.nn.conv3d_transpose(
value=x,
filter=kernel,
output_shape=y_size,
strides=[1] + strides + [1],
padding=self.padding,
name='resize_x_to_y')
resized = tf.nn.bias_add(
resized,
bias)
resized = self.ff_nl(resized)
return resized
elif mode == 'replicate_n_transpose':
resized = tf.image.resize_images(
x,
y_size[:-1],
kernel,
align_corners=False)
resized = tf.nn.conv3d_transpose(
| tensorflow.nn.bias_add | 6,037 |
import tensorflow as tf
p = self._testParams()
mdl = p.Instantiate()
mdl.FPropDefaultTheta()
all_vars = tf.trainable_variables()
py_utils.SumSquared(all_vars)
| tensorflow.trainable_variables | 6,038 |
import tensorflow as tf
batch_size = params["batch_size"]
num_examples = len(features)
# This is for demo purposes and does NOT scale to large data sets. We do
# not use Dataset.from_generator() because that uses tf.py_func which is
# not TPU compatible. The right way to load data is with TFRecordReader.
d = tf.data.Dataset.from_tensor_slices({
"input_ids":
tf.constant(
all_input_ids, shape=[num_examples, seq_length],
dtype=tf.int32),
"input_mask":
tf.constant(
all_input_mask,
shape=[num_examples, seq_length],
dtype=tf.int32),
"segment_ids":
| tensorflow.constant | 6,039 |
import tensorflow as tf
# case: train mode (uses stats of the current batch)
mean = tf.reduce_mean(_x, axis=reduction_axes)
brodcast_mean = tf.reshape(mean, broadcast_shape)
std = tf.reduce_mean(tf.square(_x - brodcast_mean) + epsilon, axis=reduction_axes)
std = tf.sqrt(std)
brodcast_std = tf.reshape(std, broadcast_shape)
x_normed = (_x - brodcast_mean) / (brodcast_std + epsilon)
# x_normed = tf.layers.batch_normalization(_x, center=False, scale=False)
x_p = tf.sigmoid(x_normed)
return alphas * (1.0 - x_p) * _x + x_p * _x
class QAAttGRUCell(RNNCell):
"""Gated Recurrent Unit cell (cf. http://arxiv.org/abs/1406.1078).
Args:
num_units: int, The number of units in the GRU cell.
| tensorflow.sigmoid | 6,040 |
import tensorflow as tf
if result[key_name] > best_perf:
best_perf = result[key_name]
best_perf_global_step = global_step
elif len(_find_valid_cands(global_step)) > 1:
_remove_checkpoint(checkpoint_path)
writer.write("=" * 50 + "\n")
writer.flush()
with tf.gfile.GFile(best_trial_info_file, "w") as best_info:
best_info.write("{}:{}:{}".format(
global_step, best_perf_global_step, best_perf))
writer.close()
for ext in ["meta", "data-00000-of-00001", "index"]:
src_ckpt = "model.ckpt-{}.{}".format(best_perf_global_step, ext)
| tensorflow.gfile.GFile | 6,041 |
import tensorflow as tf
with tf.control_dependencies(self.update_ops):
self.train_op = optimizer.apply_gradients(grads_pruned, global_step=self.global_step)
self.summary_op = tf.summary.merge_all()
self.log_op = [lrn_rate, loss, pr_trainable, pr_maskable] + list(metrics.values())
self.log_op_names = ['lr', 'loss', 'pr_trn', 'pr_msk'] + list(metrics.keys())
self.init_op = tf.variables_initializer(self.vars)
self.init_opt_op = tf.variables_initializer(optimizer_base.variables())
if FLAGS.enbl_multi_gpu:
self.bcast_op = mgw.broadcast_global_variables(0)
self.saver_train = tf.train.Saver(self.vars)
def __build_eval(self):
"""Build the evaluation graph."""
with tf.Graph().as_default():
# create a TF session for the current graph
config = tf.ConfigProto()
if FLAGS.enbl_multi_gpu:
| tensorflow.train.Saver | 6,042 |
import tensorflow as tf
with graph.as_default():
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)
return loss, embedding_vector
dataset = utils.tf_dataset(*random_samples, batchsize=args.global_batch_size,
to_sparse_tensor=True, repeat=1)
train_iterator = dataset.make_initializable_iterator()
iterator_init = train_iterator.initializer
inputs, labels = train_iterator.get_next()
| tensorflow.gradients | 6,043 |
import tensorflow as tf
False, wd, keep_prob, is_train)
# ensure the seletion is right
dep_selection = tf.logical_and(rep_mask, dep_selection)
head_selection = tf.logical_and(rep_mask, head_selection)
rep_dep_tensor, rep_dep_mask, dep_org_idx = reduce_data_rep_max_len(rep_map, dep_selection)
rep_head_tensor,rep_head_mask, head_org_idx = reduce_data_rep_max_len(rep_map, head_selection)
sl_dep, sl_head = tf.shape(rep_dep_tensor)[1], tf.shape(rep_head_tensor)[1]
if keep_unselected:
unhead_selection = tf.logical_and(rep_mask, tf.logical_not(head_selection))
rep_unhead_tensor, rep_unhead_mask, unhead_org_idx = reduce_data_rep_max_len(rep_map, unhead_selection)
sl_unhead = tf.shape(rep_unhead_tensor)[1]
attn_result = tf.cond(
tf.equal(sl_head, 0),
lambda: tf.zeros([bs, 0, hn], tf.float32),
lambda: self_attention_for_selected_head(
head_selection, head_org_idx, sl_head, rep_head_mask,
dep_selection, dep_org_idx, sl_dep, rep_dep_mask,
rep_map, rep_dep_tensor, keep_prob, is_train, direction, ivec
)
)
if keep_unselected:
input_idx = tf.tile(tf.expand_dims(tf.range(sl), 0), [bs, 1])
pooling_result = tf.cond(
tf.equal(sl_unhead, 0),
lambda: tf.zeros([bs, 0, hn], tf.float32),
lambda: mean_pooling_for_unselected_head(
unhead_org_idx, sl_unhead, rep_unhead_mask,
| tensorflow.zeros | 6,044 |
import tensorflow as tf
#accuracy1 = tf.reduce_sum(
# tf.nn.in_top_k(tf.cast(tf.Variable(predictions2), tf.float32),
# tf.cast((tf.constant(np_labels), 1), tf.float32)))
accuracy1 = tf.reduce_sum(
input_tensor=tf.cast(tf.nn.in_top_k(predictions=tf.constant(predictions1),
targets=tf.constant(np_labels), k=1), tf.float32))
accuracy5 = tf.reduce_sum(
input_tensor=tf.cast(tf.nn.in_top_k(predictions=tf.constant(predictions1),
targets=tf.constant(np_labels), k=5), tf.float32))
np_accuracy1, np_accuracy5 = sess.run([accuracy1, accuracy5])
##print(labels)
total_accuracy1 += np_accuracy1
total_accuracy5 += np_accuracy5
print("Processed %d images. (Top1 accuracy, Top5 accuracy) = (%0.4f, %0.4f)" \
% (num_processed_images, total_accuracy1/num_processed_images,
total_accuracy5/num_processed_images))
| tensorflow.constant | 6,045 |
import tensorflow as tf
return tf.less(i, tf.shape(batch)[1])
def body(batch, output, i):
self_attention_tmp = din_fcn_attention(batch[:, i, :], batch,
ATTENTION_SIZE, mask, softmax_stag=1, stag=stag,
mode='LIST')
self_attention_tmp = tf.reduce_sum(self_attention_tmp, 1)
output = output.write(i, self_attention_tmp)
return batch, output, i + 1
output_ta = tf.TensorArray(dtype=tf.float32,
size=0,
dynamic_size=True,
element_shape=(facts[:, 0, :].get_shape()))
_, output_op, _ = tf.while_loop(cond, body, [facts, output_ta, 0])
self_attention = output_op.stack()
self_attention = tf.transpose(self_attention, perm = [1, 0, 2])
return self_attention
def din_fcn_shine(query, facts, attention_size, mask, stag='null', mode='SUM', softmax_stag=1, time_major=False, return_alphas=False):
if isinstance(facts, tuple):
# In case of Bi-RNN, concatenate the forward and the backward RNN outputs.
facts = tf.concat(facts, 2)
if time_major:
# (T,B,D) => (B,T,D)
facts = tf.array_ops.transpose(facts, [1, 0, 2])
# Trainable parameters
| tensorflow.while_loop | 6,046 |
import tensorflow as tf
# Make a prediction on every word.
def GetWordPred(o_):
logits = tf.nn.xw_plus_b(o_, pred_mat, pred_bias)
return tf.nn.softmax(logits)
self.preds_by_word = tf.pack([GetWordPred(o_) for o_ in mats])
| tensorflow.nn.softmax | 6,047 |
import tensorflow as tf
with tf.variable_scope(name):
self.noise = tf.placeholder(tf.float32, shape=[self.batch_size, self.noise_dim], name='noise') # Noise vector.
self.real_pc = tf.placeholder(tf.float32, shape=[self.batch_size] + self.n_output, name='real_pc') # Ground-truth.
with tf.variable_scope('rotation'):
| tensorflow.placeholder | 6,048 |
import tensorflow as tf
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.matmul | 6,049 |
from tensorflow.python.ops import control_flow_ops
cell = rnn_cell.LSTMCell(
num_units=num_units, initializer=initializer, state_is_tuple=True)
multi_cell = rnn_cell.MultiRNNCell(
[cell() for _ in range(num_layers)])
outputs, final_state = core_rnn.static_rnn(
multi_cell, inputs, dtype=dtypes.float32)
trainable_variables = ops.get_collection(
ops.GraphKeys.TRAINABLE_VARIABLES)
gradients = gradients_impl.gradients([outputs, final_state],
trainable_variables)
training_op = control_flow_ops.group(*gradients)
self._BenchmarkOp(training_op, "tf_rnn_lstm %s %s" %
(config_name, self._GetConfigDesc(config)))
def benchmarkTfRNNLSTMBlockCellTraining(self):
test_configs = self._GetTestConfig()
for config_name, config in test_configs.items():
num_layers = config["num_layers"]
num_units = config["num_units"]
batch_size = config["batch_size"]
seq_length = config["seq_length"]
| tensorflow.python.ops.control_flow_ops.group | 6,050 |
from tensorflow.core.util.event_pb2 import SessionLog
if step == self._last_saved_step:
return
logging.info("Saving checkpoints for %d into %s.", step, self._save_path)
self._last_saved_time = time.time()
self._last_saved_step = step
if self._saver is None:
self._scaffold.saver.save(session, self._save_path, global_step=step)
else:
self._saver.save(session, self._save_path, global_step=step)
self._summary_writer.add_session_log(
SessionLog(
status=SessionLog.CHECKPOINT, checkpoint_path=self._save_path),
step)
class StepCounter(EveryN):
"""Steps per second monitor."""
def __init__(self, every_n_steps=100, output_dir=None,
summary_writer=None):
| tensorflow.core.util.event_pb2.SessionLog | 6,051 |
import tensorflow as tf
if hparams.full_latent_tower:
for i in range(hparams.num_compress_steps):
with tf.variable_scope("latent_downstride%d" % i):
x = common_layers.make_even_size(x)
if i < hparams.filter_double_steps:
filters *= 2
x = common_attention.add_timing_signal_nd(x)
x = tf.layers.conv2d(x, filters, kernel,
activation=common_layers.belu,
strides=(2, 2), padding="SAME")
x = common_layers.layer_norm(x)
else:
x = common_layers.double_discriminator(x)
x = tf.expand_dims(tf.expand_dims(x, axis=1), axis=1)
x = tf.tanh(tf.layers.dense(x, hparams.bottleneck_bits, name="bottleneck"))
d = x + tf.stop_gradient(2.0 * tf.to_float(tf.less(0.0, x)) - 1.0 - x)
if hparams.mode == tf.estimator.ModeKeys.TRAIN:
noise = tf.random_uniform(common_layers.shape_list(x))
noise = 2.0 * tf.to_float(tf.less(hparams.bottleneck_noise, noise)) - 1.0
d *= noise
z = tf.layers.dense(d, final_filters, name="unbottleneck")
return layer + z, 0.0
@registry.register_hparams
def next_frame_basic_stochastic():
"""Basic 2-frame conv model with stochastic tower."""
| tensorflow.layers.dense | 6,052 |
import tensorflow as tf
eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file)
tf.logging.info("***** Running evaluation *****")
tf.logging.info(" Num examples = %d (%d actual, %d padding)",
| tensorflow.logging.info | 6,053 |
import tensorflow as tf
n_repeats,
])), 1), [1, 0])
rep = tf.to_int32(rep)
x = tf.matmul(tf.reshape(x, (-1, 1)), rep)
| tensorflow.to_int32 | 6,054 |
import tensorflow as tf
| tensorflow.scalar_summary | 6,055 |
import tensorflow as tf
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':
train_batch = self.config['batch_size']*self.n_gpus
d = d.repeat().batch(train_batch).prefetch(train_batch)
self.dataset_iterators[n] = d.make_one_shot_iterator()
else:
| tensorflow.device | 6,056 |
import tensorflow as tf
log_scales = tf.maximum(predictions[:, :, :, :, nr_mix:2 * nr_mix], -7.)
coeffs = tf.nn.tanh(predictions[:, :, :, :, 2 * nr_mix:3 * nr_mix])
| tensorflow.nn.tanh | 6,057 |
import tensorflow as tf
td = 0
with tf.device("/gpu:0"):
conv = nn_ops.conv3d(d1, d2, strides, padding)
with tf.Session(config=config) as sess:
t22 = time.time()
expected = sess.run(conv)
| tensorflow.Session | 6,058 |
import tensorflow as tf
hparams = get_default_hparams()
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)
samples = tf.random_normal(shape=[hparams.n_samples, hparams.x_dim])
x_, v_, x_accept_prob, x_out = dynamics.apply_transition(samples)
self.assertEqual(x_.shape, v_.shape)
self.assertEqual(x_out.shape, samples.shape)
self.assertEqual(x_.shape, x_out.shape)
self.assertEqual(x_accept_prob.shape, (hparams.n_samples,))
| tensorflow.random_normal | 6,059 |
import tensorflow as tf
# Loss functions and training
epsilon_decay = tf.train.polynomial_decay(self.EPSILON, self.global_step, self.EPS_LEN, 0.1, power=1)
ratio = tf.maximum(pi.prob(batch['actions']), 1e-6) / tf.maximum(pi_old.prob(batch['actions']), 1e-6)
ratio = tf.clip_by_value(ratio, 0, 10)
surr1 = batch['advantage'] * ratio
surr2 = batch['advantage'] * tf.clip_by_value(ratio, 1 - epsilon_decay, 1 + epsilon_decay)
| tensorflow.clip_by_value | 6,060 |
import tensorflow as tf
return (loss, per_example_loss, log_probs)
def gather_indexes(sequence_tensor, positions):
"""Gathers the vectors at the specific positions over a minibatch."""
sequence_shape = modeling.get_shape_list(sequence_tensor, expected_rank=3)
batch_size = sequence_shape[0]
seq_length = sequence_shape[1]
width = sequence_shape[2]
flat_offsets = tf.reshape(
tf.range(0, batch_size, dtype=tf.int32) * seq_length, [-1, 1]
)
flat_positions = tf.reshape(positions + flat_offsets, [-1])
flat_sequence_tensor = tf.reshape(sequence_tensor, [batch_size * seq_length, width])
output_tensor = tf.gather(flat_sequence_tensor, flat_positions)
return output_tensor
def input_fn_builder(
input_files, max_seq_length, max_predictions_per_seq, is_training, num_cpu_threads=4
):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
def input_fn(params):
"""The actual input function."""
| tensorflow.reshape | 6,061 |
from tensorflow.python.ops import math_ops
# For SparseTensor, calculate separate count for each row.
if isinstance(labels, (ops.SparseTensor, ops.SparseTensorValue)):
labels_sizes = set_ops.set_size(labels)
return math_ops.minimum(labels_sizes, k, name=scope)
# For dense Tensor, calculate scalar count based on last dimension, and
# tile across labels shape.
labels_shape = array_ops.shape(labels)
labels_size = labels_shape[-1]
num_relevant_scalar = math_ops.minimum(labels_size, k)
return array_ops.fill(labels_shape[0:-1], num_relevant_scalar, name=scope)
def expand_and_tile(tensor, multiple, dim=0, name=None):
"""Slice `tensor` shape in 2, then tile along the sliced dimension.
A new dimension is inserted in shape of `tensor` before `dim`, then values are
tiled `multiple` times along the new dimension.
| tensorflow.python.ops.math_ops.minimum | 6,062 |
import tensorflow as tf
# Functionality to update the threshold for parameter space noise.
update_param_noise_threshold_expr = param_noise_threshold.assign(tf.cond(update_param_noise_threshold_ph >= 0,
lambda: update_param_noise_threshold_ph, lambda: param_noise_threshold))
# Put everything together.
deterministic_actions = tf.argmax(q_values_perturbed, axis=1)
batch_size = tf.shape(observations_ph.get())[0]
random_actions = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=num_actions, dtype=tf.int64)
chose_random = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=1, dtype=tf.float32) < eps
stochastic_actions = tf.where(chose_random, random_actions, deterministic_actions)
| tensorflow.argmax | 6,063 |
from tensorflow.contrib.framework import deprecated_arg_values
batch_size=batch_size,
steps=steps,
metrics=metrics,
name=name,
checkpoint_path=checkpoint_path,
hooks=hooks)
@deprecated_arg_values(
estimator.AS_ITERABLE_DATE,
estimator.AS_ITERABLE_INSTRUCTIONS,
as_iterable=False)
def predict(self, x=None, input_fn=None, batch_size=None, as_iterable=True):
"""Returns predicted classes for given features.
| tensorflow.contrib.framework.deprecated_arg_values | 6,064 |
import tensorflow as tf
else:
# initializer = tf.truncated_normal_initializer(stddev=stddev)
with tf.device('/cpu:0'):
var = tf.truncated_normal(shape, stddev=np.sqrt(2 / shape[-1]))
var = tf.round(var * tf.constant(1000, dtype=tf.float32)) / tf.constant(1000, dtype=tf.float32)
var = tf.Variable(var, name='weights')
if wd is not None:
weight_decay = tf.multiply(tf.nn.l2_loss(var), wd, name='weight_loss')
tf.add_to_collection('losses', weight_decay)
return var
def conv1d(inputs,
num_output_channels,
| tensorflow.nn.l2_loss | 6,065 |
import tensorflow as tf
mvn = dists.MultivariateNormalDiag([[mu]], [[sigma]],
validate_args=True)
self.assertFalse(tensor_util.constant_value(mvn.is_scalar_event))
self.assertFalse(tensor_util.constant_value(mvn.is_scalar_batch))
# We now test every codepath within the underlying is_scalar_helper
# function.
# Test case 1, 2.
x = tf.placeholder(dtype=tf.int32, shape=[])
# None would fire an exception were it actually executed.
self.assertTrue(normal._is_scalar_helper(x.get_shape, lambda: None))
self.assertTrue(normal._is_scalar_helper(lambda: tf.TensorShape(None),
lambda: tf.shape(x)))
x = tf.placeholder(dtype=tf.int32, shape=[1])
# None would fire an exception were it actually executed.
self.assertFalse(normal._is_scalar_helper(x.get_shape, lambda: None))
self.assertFalse(normal._is_scalar_helper(lambda: tf.TensorShape(None),
lambda: tf.shape(x)))
# Test case 3.
x = tf.placeholder(dtype=tf.int32)
is_scalar = normal._is_scalar_helper(x.get_shape, lambda: tf.shape(x))
self.assertTrue(is_scalar.eval(feed_dict={x: 1}))
| tensorflow.TensorShape | 6,066 |
import tensorflow as tf
try:
config = load_config(logdir)
except RuntimeError:
print('Failed to load existing config.')
except IOError:
config = save_config(config, logdir)
trainer = trainer_.Trainer(logdir, config=config)
cleanups = []
try:
with tf.variable_scope('graph', use_resource=True):
data = get_batch(datasets, trainer.phase, trainer.reset)
score, summary, cleanups = model_fn(data, trainer, config, logdir)
message = 'Graph contains {} trainable variables.'
tf.logging.info(message.format(tools.count_weights()))
if config.test_steps:
trainer.add_phase(
'test', config.test_steps, score, summary,
batch_size=config.batch_shape[0],
| tensorflow.variable_scope | 6,067 |
import tensorflow as tf
beta_list = []
lstm_cell = tf.contrib.rnn.BasicLSTMCell(num_units=self.H, reuse=tf.get_variable_scope().reuse)
| tensorflow.get_variable_scope | 6,068 |
import tensorflow as tf
kernel,
bias,
strides,
mode='transpose',
use_bias=True):
"""Resize activity x to the size of y using interpolation."""
y_size = y.get_shape().as_list()
if mode == 'resize':
return tf.image.resize_images(
x,
y_size[:-1],
kernel,
align_corners=True)
elif mode == 'transpose':
# strides = np.asarray(self.pool_strides)
# strides[1:] *= len(self.ff_conv_k)
| tensorflow.image.resize_images | 6,069 |
import tensorflow as tf
observations_ph = U.ensure_tf_input(make_obs_ph("observation"))
stochastic_ph = tf.placeholder(tf.bool, (), name="stochastic")
update_eps_ph = tf.placeholder(tf.float32, (), name="update_eps")
eps = tf.get_variable("eps", (), initializer=tf.constant_initializer(0))
q_values = q_func(observations_ph.get(), num_actions, scope="q_func")
deterministic_actions = tf.argmax(q_values, axis=1)
batch_size = tf.shape(observations_ph.get())[0]
random_actions = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=num_actions, dtype=tf.int64)
chose_random = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=1, dtype=tf.float32) < eps
stochastic_actions = tf.where(chose_random, random_actions, deterministic_actions)
| tensorflow.argmax | 6,070 |
from tensorflow.python.framework import tensor_util
yield scope
def _is_all_constant_helper(self, *args):
"""Helper which returns True if all inputs are constant_value."""
return all(tensor_util.constant_value(x) is not None for x in args)
def _assert_non_negative_int32_scalar(self, x):
"""Helper which ensures that input is a non-negative, int32, scalar."""
| tensorflow.python.framework.tensor_util.constant_value | 6,071 |
import tensorflow as tf
supervised_encoder_loss = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(labels=y_input, logits=encoder_output_label_))
all_variables = tf.trainable_variables()
dc_g_var = [var for var in all_variables if 'dc_g_' in var.name]
dc_c_var = [var for var in all_variables if 'dc_c_' in var.name]
en_var = [var for var in all_variables if 'e_' in var.name]
# Optimizers
autoencoder_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate,
beta1=beta1).minimize(autoencoder_loss)
discriminator_g_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate,
beta1=beta1).minimize(dc_g_loss, var_list=dc_g_var)
discriminator_c_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate,
beta1=beta1).minimize(dc_c_loss, var_list=dc_c_var)
generator_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate,
beta1=beta1).minimize(generator_loss, var_list=en_var)
supervised_encoder_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate,
beta1=beta1).minimize(supervised_encoder_loss,
var_list=en_var)
init = tf.global_variables_initializer()
| tensorflow.train.AdamOptimizer | 6,072 |
import tensorflow as tf
self.assertAllClose(masks.numpy(), expected_masks.numpy())
def test_inputs_Distances_to_centers(self):
inputs = tf.random.uniform(
[100, 8], minval=-10, maxval=10.0, dtype=tf.float32)
centers = tf.random.uniform(
| tensorflow.random.uniform | 6,073 |
import tensorflow as tf
coord.join(threads)
def predict_time(loop=100):
feed_dict={
testnum:1
}
with tf.Session(config=config) as sess:
sess.run(init)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
tf.train.Saver().restore(sess,path)
total=0.0
for i in range(loop):
a = datetime.now()
accuracy_np = sess.run([accuracy],feed_dict=feed_dict)
b = datetime.now()
c = (b - a).microseconds
total+=c
print('predict_time(ms): ',total/(loop*1000))
coord.request_stop()
| tensorflow.train.Saver | 6,074 |
import tensorflow as tf
init_b = tf.constant_initializer(0.01)
net = tf.layers.dense(s, 500, activation=tf.nn.relu,
kernel_initializer=init_w, bias_initializer=init_b, name='l1', trainable=trainable)
net = tf.layers.dense(net, 200, activation=tf.nn.relu,
kernel_initializer=init_w, bias_initializer=init_b, name='l2', trainable=trainable)
| tensorflow.layers.dense | 6,075 |
import tensorflow as tf
x = tf.split(x, out_channels, 4)
x = tf.concat([phase_shift_3d(v, r) for v in x], 4)
return x
def pixel_shuffler_3d(x, r, k, out_channels, name):
in_channels = x.get_shape.as_list()[4]
with tf.variable_scope(name):
u = conv3d(x, [k, k, k, in_channels, out_channels*pow(r, 3)], 'conv', bias=True, stride=1)
h = subpixel_conv3d(u, r, out_channels)
return h
def minibatch_discrimination(x, n_kernels, dim_per_kernel, name):
| tensorflow.variable_scope | 6,076 |
import tensorflow as tf
bert_config, is_training, input_ids, input_mask, segment_ids, label_ids,
num_labels, use_one_hot_embeddings)
tvars = tf.trainable_variables()
initialized_variable_names = {}
scaffold_fn = None
| tensorflow.trainable_variables | 6,077 |
import tensorflow as tf
inputs = tf.reshape(inputs, [-1, self.final_size])
inputs = tf.layers.dense(inputs=inputs, units=self.num_classes)
inputs = tf.identity(inputs, 'final_dense')
return inputs
| tensorflow.identity | 6,078 |
import tensorflow as tf
clone_loss = tf.add_n(clone_losses, name='clone_loss')
if num_clones > 1:
clone_loss = tf.div(clone_loss, 1.0 * num_clones,
name='scaled_clone_loss')
| tensorflow.div | 6,079 |
import tensorflow as tf
after applying all the transformations.
"""
# Reshape flattened multiclass scores tensor into a 2D tensor of shape
# [num_boxes, num_classes].
if fields.InputDataFields.multiclass_scores in tensor_dict:
tensor_dict[fields.InputDataFields.multiclass_scores] = tf.reshape(
tensor_dict[fields.InputDataFields.multiclass_scores], [
tf.shape(tensor_dict[fields.InputDataFields.groundtruth_boxes])[0],
num_classes
])
if fields.InputDataFields.groundtruth_boxes in tensor_dict:
tensor_dict = util_ops.filter_groundtruth_with_nan_box_coordinates(
tensor_dict)
tensor_dict = util_ops.filter_unrecognized_classes(tensor_dict)
| tensorflow.shape | 6,080 |
import tensorflow as tf
noise_tensor = tf.random_normal((data_size, INPUT_DIM))
real_data_tensor = tf.random_uniform((data_size, OUTPUT_DIM))
| tensorflow.random_uniform | 6,081 |
import tensorflow as tf
''' Creates final model output and loss for logistic objective
Args:
output: Model output
target: Training target placeholder
add_bias: If True, a bias Variable will be added to the output
Returns:
tuple (final output, loss)
'''
y = output
if add_bias:
bias = tf.Variable([0.0])
y = output + bias
sig_y = tf.clip_by_value(tf.sigmoid(y), 0.001, 0.999) # avoid NaNs
loss = -tf.reduce_sum(target*tf.log(sig_y) + (1-target)*tf.log(1-sig_y))
return sig_y, loss
def ranking_margin_objective(output, margin=1.0):
''' Create final model output and loss for pairwise ranking margin objective
Loss for single pair (f(p), f(n)) = [margin - f(p) + f(n)]+
This only works when given model output on alternating positive/negative
| tensorflow.Variable | 6,082 |
import tensorflow as tf
# compute estimate of best possible value starting from state at t + 1
if double_q:
q_tp1_using_online_net = q_func(obs_tp1_input.get(), num_actions, scope="q_func", reuse=True)
q_tp1_best_using_online_net = tf.arg_max(q_tp1_using_online_net, 1)
q_tp1_best = tf.reduce_sum(q_tp1 * tf.one_hot(q_tp1_best_using_online_net, num_actions), 1)
else:
q_tp1_best = tf.reduce_max(q_tp1, 1)
q_tp1_best_masked = (1.0 - done_mask_ph) * q_tp1_best
# compute RHS of bellman equation
q_t_selected_target = rew_t_ph + gamma * q_tp1_best_masked
# compute the error (potentially clipped)
| tensorflow.reduce_max | 6,083 |
from tensorflow.python.framework import ops
ops.RegisterShape("Sqrt")(common_shapes.unchanged_shape)
ops.RegisterShape("Square")(common_shapes.unchanged_shape)
ops.RegisterShape("Sigmoid")(common_shapes.unchanged_shape)
ops.RegisterShape("Tanh")(common_shapes.unchanged_shape)
ops.RegisterShape("Cast")(common_shapes.unchanged_shape)
ops.RegisterShape("ComplexAbs")(common_shapes.unchanged_shape)
@ops.RegisterShape("Add")
@ops.RegisterShape("Complex")
@ops.RegisterShape("Div")
@ops.RegisterShape("Equal")
@ops.RegisterShape("Greater")
@ops.RegisterShape("GreaterEqual")
@ops.RegisterShape("Less")
@ops.RegisterShape("LessEqual")
@ops.RegisterShape("LogicalAnd")
@ops.RegisterShape("LogicalOr")
@ops.RegisterShape("Maximum")
@ops.RegisterShape("Minimum")
| tensorflow.python.framework.ops.RegisterShape | 6,084 |
import tensorflow as tf
initializer=tf.truncated_normal_initializer(stddev=0.02))
output_bias = tf.get_variable(
"output_bias", [num_labels], initializer=tf.zeros_initializer())
with tf.variable_scope("loss"):
if is_training:
# I.e., 0.1 dropout
output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
logits = tf.matmul(output_layer, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
probabilities = tf.nn.softmax(logits, axis=-1)
log_probs = tf.nn.log_softmax(logits, axis=-1)
one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)
per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
loss = tf.reduce_mean(per_example_loss)
return (loss, per_example_loss, logits, probabilities)
def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps, use_tpu,
use_one_hot_embeddings):
| tensorflow.nn.log_softmax | 6,085 |
import tensorflow as tf
# reconstruction loss
recon_loss_A = tf.reduce_mean(tf.abs(A - ABA), name='recon_loss')
# gan loss
G_loss_A, D_loss_A = LSGAN_losses(A_dis_real, A_dis_fake)
with tf.name_scope('LossB'):
recon_loss_B = tf.reduce_mean(tf.abs(B - BAB), name='recon_loss')
G_loss_B, D_loss_B = LSGAN_losses(B_dis_real, B_dis_fake)
LAMBDA = 10.0
self.g_loss = tf.add((G_loss_A + G_loss_B),
(recon_loss_A + recon_loss_B) * LAMBDA, name='G_loss_total')
| tensorflow.abs | 6,086 |
from tensorflow.python.ops import variable_scope
`false_positives` variables appropriately and whose value matches
`precision`.
Raises:
ValueError: If `predictions` and `labels` have mismatched shapes, or 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.
"""
with variable_scope.variable_scope(
name, 'precision', [predictions, labels]):
predictions, labels = tensor_util.remove_squeezable_dimensions(
predictions, labels)
predictions.get_shape().assert_is_compatible_with(labels.get_shape())
weights = _mask_weights(ignore_mask, weights)
true_positives, true_positives_update_op = _streaming_true_positives(
predictions, labels, weights, metrics_collections=None,
| tensorflow.python.ops.variable_scope.variable_scope | 6,087 |
from tensorflow.python.ops import random_ops
# Benchmarking code
def parameterized_vs_naive(shape, num_iters, use_gpu=False):
np.random.seed(1618) # Make it reproducible.
# No CSE/CF.
optimizer_options = tf.OptimizerOptions(opt_level=tf.OptimizerOptions.L0)
config = tf.ConfigProto(
graph_options=tf.GraphOptions(optimizer_options=optimizer_options))
with tf.Session(config=config) as sess:
with tf.device("/cpu:0" if not use_gpu else None):
param_op = tf.group(random_ops.parameterized_truncated_normal(shape))
naive_op = tf.group(random_ops.truncated_normal(shape))
# Burn-in to avoid session setup costs in the timing.
sess.run(param_op)
sess.run(param_op)
param_dt = timeit.timeit(lambda: sess.run(param_op), number=num_iters)
sess.run(naive_op)
sess.run(naive_op)
naive_dt = timeit.timeit(lambda: sess.run(naive_op), number=num_iters)
return param_dt, naive_dt
| tensorflow.python.ops.random_ops.parameterized_truncated_normal | 6,088 |
import tensorflow as tf
"""
center = [(ss - 1) // 2 for ss in shape]
axes = [tf.range(-cc, ss - cc, dtype=tf.int32) for cc, ss in zip(center, shape)]
# Broadcast and match dimension.
if len(shape) > 1:
for jj in range(len(shape)):
for ii in range(len(shape) + 1):
if ii != jj:
axes[jj] = tf.expand_dims(axes[jj], ii)
for jj in range(len(shape)):
shape_ = [ss for ss in shape] + [1]
shape_[jj] = 1
axes[jj] = tf.tile(axes[jj], shape_)
offset = tf.concat(axes, len(shape))
return offset
def _get_offset_array(shape):
"""
Computes the offset array used to upsample indices with NumPy (static).
:param shape: [list] Window shape.
"""
center = [int(ss - 1) // 2 for ss in shape]
| tensorflow.tile | 6,089 |
from tensorflow.contrib.learn.python.learn.estimators import run_config
learner_config.num_classes = 2
learner_config.constraints.max_tree_depth = 1
model_dir = tempfile.mkdtemp()
config = run_config.RunConfig()
# Use core head
| tensorflow.contrib.learn.python.learn.estimators.run_config.RunConfig | 6,090 |
import tensorflow as tf
if not tf.gfile.Exists(p_name) or not tf.gfile.Exists(m_name):
return params
with tf.gfile.Open(p_name) as fd:
tf.logging.info("Restoring hyper parameters from %s" % p_name)
json_str = fd.readline()
params.parse_json(json_str)
with tf.gfile.Open(m_name) as fd:
tf.logging.info("Restoring model parameters from %s" % m_name)
json_str = fd.readline()
params.parse_json(json_str)
return params
def export_params(output_dir, name, params):
if not tf.gfile.Exists(output_dir):
| tensorflow.logging.info | 6,091 |
import tensorflow as tf
if mode == 'train' and rnn_keep_prob < 1.0:
cell = tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob=rnn_keep_prob)
if rnn_nlayers > 1:
cell = tf.nn.rnn_cell.MultiRNNCell([cell] * rnn_nlayers)
initial_state = cell.zero_state(batch_size, dtype)
# RNN
# TODO: weight init
with tf.variable_scope('rnn_unroll'):
state = initial_state
outputs = []
for i in xrange(rnn_nunroll):
if i > 0:
tf.get_variable_scope().reuse_variables()
(cell_output, state) = cell(rnn_inputs[i], state)
outputs.append(cell_output)
final_state = state
rnn_output = tf.reshape(tf.concat(outputs, axis=1), [batch_size * rnn_nunroll, rnn_size])
| tensorflow.variable_scope | 6,092 |
import tensorflow as tf
train = tf.placeholder(tf.bool, [])
# Build the graph for the deep net
y_conv, img_summary = deepnn(x, train)
# Define your loss function - softmax_cross_entropy
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
| tensorflow.get_collection | 6,093 |
import tensorflow as tf
def train(self, iterations, validation_interval=100, output_dir=None,
save_interval=None, checkpoint_path=None, keep_checkpoints=1):
assert 'training' in self.datasets, 'Training dataset is required.'
if output_dir is not None:
train_writer = tf.summary.FileWriter(output_dir)
if not hasattr(self, 'saver'):
with tf.device('/cpu:0'):
self.saver = tf.train.Saver(save_relative_paths=True,
max_to_keep=keep_checkpoints)
if not self.graph.finalized:
self.graph.finalize()
| tensorflow.device | 6,094 |
import tensorflow as tf
# Trainable parameters
w1 = tf.Variable(tf.random_normal([hidden_size, attention_size], stddev=0.1))
w2 = tf.Variable(tf.random_normal([input_size, attention_size], stddev=0.1))
b = tf.Variable(tf.random_normal([attention_size], stddev=0.1))
v = tf.Variable(tf.random_normal([attention_size], stddev=0.1))
| tensorflow.random_normal | 6,095 |
import tensorflow as tf
import random
import numpy as np
import tensorflow as tf
import tensorflow.contrib.layers as layers
from atari_wrappers import *
from dqn_utils import *
from gym import wrappers
from tensorflow.contrib.layers.python.layers import initializers
def atari_model(img_in, num_actions, scope, reuse=False):
# as described in https://storage.googleapis.com/deepmind-data/assets/papers/DeepMindNature14236Paper.pdf
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)
with tf.variable_scope("action_value"):
out = layers.fully_connected(out, num_outputs=512, activation_fn=tf.nn.relu)
out = layers.fully_connected(out, num_outputs=num_actions, activation_fn=None)
return out
| tensorflow.variable_scope | 6,096 |
from tensorflow.python.framework import constant_op
np.linalg.norm(expected_unclipped),
var0_out[1])
# var1 is not in the var list, so it should not be clipped
self.assertAllCloseAccordingToType([4.0 - 3.0 * 0.01, 5.0 - 3.0 * 0.01],
var1.eval())
def _setupSparse(self, is_distributed, dtype):
with self._maybeWithDevice("/job:ps" if is_distributed else None):
var0 = variables.Variable(
[[0.0, 1.0], [2.0, 3.0], [4.0, 5.0]], dtype=dtype)
var1 = variables.Variable(
[[0.0, 1.0], [0.0, 3.0], [0.0, 5.0]], dtype=dtype)
with self._maybeWithDevice("/job:worker" if is_distributed else None):
grads = ops.IndexedSlices(
constant_op.constant(
[[0.1, 0.1], [0.1, 0.1]], dtype=dtype), [0, 2], [3, 2])
sgd = gradient_descent.GradientDescentOptimizer(3.0)
clip_opt = variable_clipping_optimizer.VariableClippingOptimizer(
sgd, {var0: [1],
var1: [0]}, 2.0)
update_op = clip_opt.apply_gradients(
list(zip([grads, grads], [var0, var1])))
variables.global_variables_initializer().run()
return var0, var1, update_op
def _assertSparseCorrect(self, var0, var1, update_op):
# Fetch params to validate initial values
self.assertAllCloseAccordingToType([[0.0, 1.0], [2.0, 3.0], [4.0, 5.0]],
| tensorflow.python.framework.constant_op.constant | 6,097 |
import tensorflow as tf
# Reset Graph
tf.reset_default_graph()
def testClassifierGraph(self):
FLAGS.rnn_num_layers = 2
model = graphs.VatxtModel()
train_op, _, _ = model.classifier_training()
# Pretrained vars: embedding + LSTM layers
self.assertEqual(
len(model.pretrained_variables), 1 + 2 * FLAGS.rnn_num_layers)
with self.test_session() as sess:
sess.run(tf.global_variables_initializer())
tf.train.start_queue_runners(sess)
sess.run(train_op)
def testLanguageModelGraph(self):
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)
def testMulticlass(self):
FLAGS.num_classes = 10
graphs.VatxtModel().classifier_graph()
| tensorflow.train.start_queue_runners | 6,098 |
from tensorflow.python.ops import nn
"""Inverse Gamma with softplus applied to `alpha` and `beta`."""
def __init__(self,
alpha,
beta,
validate_args=False,
allow_nan_stats=True,
name="InverseGammaWithSoftplusAlphaBeta"):
parameters = locals()
parameters.pop("self")
with ops.name_scope(name, values=[alpha, beta]) as ns:
super(InverseGammaWithSoftplusAlphaBeta, self).__init__(
alpha=nn.softplus(alpha, name="softplus_alpha"),
beta=nn.softplus(beta, name="softplus_gamma"),
validate_args=validate_args,
allow_nan_stats=allow_nan_stats,
name=ns)
self._parameters = parameters
| tensorflow.python.ops.nn.softplus | 6,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.