seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
import tensorflow as tf
(total_loss, per_example_loss, logits, probabilities) = create_model(
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
if init_checkpoint:
(assignment_map, initialized_variable_names
) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint, different_vocabulary=False)
if use_tpu:
def tpu_scaffold():
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
return tf.train.Scaffold()
scaffold_fn = tpu_scaffold
else:
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
tf.logging.info("**** Trainable Variables ****")
for var in tvars:
init_string = ""
if var.name in initialized_variable_names:
init_string = ", *INIT_FROM_CKPT*"
tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
init_string)
output_spec = None
| tensorflow.train.Scaffold | 800 |
import tensorflow as tf
aspect_ratio_range=[0.75, 1.33],
area_range=[0.08, 1.0],
max_attempts=10,
use_image_if_no_bounding_boxes=True)
is_bad = tf.reduce_sum(tf.cast(tf.equal(bbox_size, jpeg_shape), tf.int32)) >= 2
def good():
offset_y, offset_x, _ = tf.unstack(bbox_begin)
target_height, target_width, _ = tf.unstack(bbox_size)
crop_window = tf.stack([offset_y, offset_x, target_height, target_width])
image = tf.image.decode_and_crop_jpeg(
byte, crop_window, channels=3, **JPEG_OPT)
image = uint8_resize_bicubic(image, [224, 224])
return image
def bad():
image = tf.image.decode_jpeg(
tf.reshape(byte, shape=[]), 3, **JPEG_OPT)
| tensorflow.stack | 801 |
import tensorflow as tf
if self.is_summary:
train_writer.close()
validation_writer.close()
def _feature_matching_loss(self, real_data_features, fake_data_features):
real_data_mean = tf.reduce_mean(real_data_features, axis=0)
fake_data_mean = tf.reduce_mean(fake_data_features, axis=0)
feature_loss = tf.reduce_mean(tf.abs(tf.subtract(real_data_mean, fake_data_mean)))
return feature_loss
def _tower_loss_semi_supervised(self, inputs, targets, gpu_idx=0, num_classes=11,
is_fm_loss=False):
with tf.variable_scope("train_specific"):
| tensorflow.subtract | 802 |
import tensorflow as tf
res = sess.run(dec)
self.assertEqual(3, len(res))
self.assertEqual((2, 4), res[0].shape)
res = sess.run([mem])
self.assertEqual((2, 2), res[0].shape)
def testAttentionDecoderStateIsTuple(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()])
| tensorflow.nn.rnn_cell.MultiRNNCell | 803 |
import tensorflow as tf
mask = tf.expand_dims(mask, -1)
| tensorflow.expand_dims | 804 |
import tensorflow as tf
save_dir = self._TestDir("abs_paths")
abs_path = os.path.join(save_dir, "model-0")
ckpt = tf.train.generate_checkpoint_state_proto(save_dir, abs_path)
self.assertEqual(ckpt.model_checkpoint_path, abs_path)
self.assertTrue(os.path.isabs(ckpt.model_checkpoint_path))
self.assertEqual(len(ckpt.all_model_checkpoint_paths), 1)
self.assertEqual(ckpt.all_model_checkpoint_paths[-1], abs_path)
def testRelPath(self):
train_dir = "train"
model = os.path.join(train_dir, "model-0")
# model_checkpoint_path should have no "train" directory part.
new_rel_path = "model-0"
ckpt = tf.train.generate_checkpoint_state_proto(train_dir, model)
self.assertEqual(ckpt.model_checkpoint_path, new_rel_path)
self.assertEqual(len(ckpt.all_model_checkpoint_paths), 1)
self.assertEqual(ckpt.all_model_checkpoint_paths[-1], new_rel_path)
def testAllModelCheckpointPaths(self):
save_dir = self._TestDir("all_models_test")
abs_path = os.path.join(save_dir, "model-0")
for paths in [None, [], ["model-2"]]:
ckpt = tf.train.generate_checkpoint_state_proto(
save_dir,
abs_path,
all_model_checkpoint_paths=paths)
| tensorflow.train.generate_checkpoint_state_proto | 805 |
import tensorflow as tf
with tf.device(self.cpu_device):
if self.task_index == 0 and FLAGS.summary_verbosity > 0:
tf.summary.scalar('learning_rate', learning_rate)
tf.summary.scalar('total_loss', total_loss)
for grad, var in avg_grads:
if grad is not None:
tf.summary.histogram(var.op.name + '/gradients', grad)
for var in tf.trainable_variables():
tf.summary.histogram(var.op.name, var)
fetches = [train_op, total_loss] + enqueue_ops
return (enqueue_ops, fetches)
def add_forward_pass_and_gradients(
self, host_images, host_labels, nclass, phase_train, device_num,
input_data_type, data_type, input_nchan, use_synthetic_gpu_images,
gpu_copy_stage_ops, gpu_compute_stage_ops, gpu_grad_stage_ops):
"""Add ops for forward-pass and gradient computations."""
| tensorflow.summary.histogram | 806 |
import tensorflow as tf
x0 = tf.minimum(tf.maximum(x[:, :, :, 0], -1.), 1.)
x1 = tf.minimum(tf.maximum(
x[:, :, :, 1] + coeffs[:, :, :, 0] * x0, -1.), 1.)
x2 = tf.minimum(tf.maximum(
x[:, :, :, 2] + coeffs[:, :, :, 1] * x0 + coeffs[:, :, :, 2] * x1, -1.), 1.)
return tf.concat([tf.reshape(x0, xs[:-1] + [1]), tf.reshape(x1, xs[:-1] + [1]), tf.reshape(x2, xs[:-1] + [1])], 3)
| tensorflow.reshape | 807 |
import tensorflow as tf
filtered_value_node,
vocab_filename=vocab_filename,
store_frequency=store_frequency,
fingerprint_shuffle=fingerprint_shuffle,
input_dtype=input_dtype,
file_format=file_format,
# LINT.IfChange(input_is_sorted)
input_is_sorted=(top_k is not None and key_fn is None and
not fingerprint_shuffle)
# LINT.ThenChange(beam/analyzer_impls.py:top_k_impl)
)
scope = tf.compat.v1.get_default_graph().get_name_scope()
unfiltered_vocab_size_node = nodes.apply_operation(
analyzer_nodes.VocabularyCount,
merge_output_value_node,
label=f'VocabularyCountUnfiltered[{scope}]')
unfiltered_vocab_size = analyzer_nodes.bind_future_as_tensor(
unfiltered_vocab_size_node,
analyzer_nodes.TensorInfo(tf.int64, [], None),
name=f'{vocab_filename}_unpruned_vocab_size')
filtered_vocab_size_node = nodes.apply_operation(
analyzer_nodes.VocabularyCount,
filtered_value_node,
| tensorflow.compat.v1.get_default_graph | 808 |
import tensorflow as tf
def sparse_categorical_crossentropy(output, target, from_logits=False):
"""Categorical crossentropy between an output tensor
and a target tensor, where the target is an integer tensor.
"""
# Note: tf.nn.softmax_cross_entropy_with_logits
# expects logits, Keras expects probabilities.
if not from_logits:
epsilon = _to_tensor(_EPSILON, output.dtype.base_dtype)
output = tf.clip_by_value(output, epsilon, 1 - epsilon)
output = tf.log(output)
output_shape = output.get_shape()
targets = cast(flatten(target), 'int64')
logits = tf.reshape(output, [-1, int(output_shape[-1])])
try:
res = tf.nn.sparse_softmax_cross_entropy_with_logits(
labels=targets, logits=logits)
except TypeError:
res = tf.nn.sparse_softmax_cross_entropy_with_logits(
| tensorflow.log | 809 |
import tensorflow as tf
# argument prediction
# first encode decoded action template and teh true action template
choice = tf.floor(tf.random_uniform([1], self.use_inputs_prob, 1 + self.use_inputs_prob, tf.float32))
prediction_action_argmax = tf.stop_gradient(tf.argmax(self.predictions_action, 1))
predicted_action_templates_embedding = embedding(
input=prediction_action_argmax,
length=action_templates_vocabulary_length,
size=action_templates_embedding_size,
name='action_templates_embedding'
)
true_action_template_embedding = tf.gather(predicted_action_templates_embedding.embedding_table, actions_template)
predicted_action_templates_embedding = tf.stop_gradient(predicted_action_templates_embedding)
action_templates_embedding = choice * true_action_template_embedding + (1.0 - choice) * predicted_action_templates_embedding
dialogue_state_action_template = tf.concat(
1,
[
dialogue_state,
action_templates_embedding
],
name='dialogue_state_action_template'
)
dialogue_state_action_template_size = (
dialogue_state_size +
| tensorflow.stop_gradient | 810 |
import tensorflow as tf
with tf.device(self.devices[device_num]):
# Rescale to [0, 1)
images *= 1. / 256
# Rescale to [-1,1] instead of [0, 1)
images = tf.subtract(images, 0.5)
images = tf.multiply(images, 2.0)
if self.data_format == 'NCHW':
images = tf.transpose(images, [0, 3, 1, 2])
if input_data_type != data_type:
| tensorflow.multiply | 811 |
import tensorflow as tf
ch_emb = tf.reduce_max(ch_emb, axis = 1)
qh_emb = tf.reduce_max(qh_emb, axis = 1)
ch_emb = tf.reshape(ch_emb, [N, PL, ch_emb.shape[-1]])
qh_emb = tf.reshape(qh_emb, [N, QL, ch_emb.shape[-1]])
| tensorflow.reshape | 812 |
from tensorflow.python.framework import tensor_util
name: `String`. The name to give this op.
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"))
def get_shape(self, x, name="get_shape"):
"""Returns `Tensor`'s shape partitioned into `sample`, `batch`, `event`.
| tensorflow.python.framework.tensor_util.constant_value | 813 |
import tensorflow as tf
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.
| tensorflow.variable_scope | 814 |
import tensorflow as tf
"""Base class for translation problems."""
def is_generate_per_split(self):
return True
def example_reading_spec(self):
data_fields = {"dist_targets": tf.VarLenFeature(tf.int64)}
if self.has_inputs:
data_fields["inputs"] = tf.VarLenFeature(tf.int64)
# hack: ignoring true targets and putting dist_targets in targets
data_items_to_decoders = {
"inputs": tf.contrib.slim.tfexample_decoder.Tensor("inputs"),
"targets": tf.contrib.slim.tfexample_decoder.Tensor("dist_targets"),
}
return (data_fields, data_items_to_decoders)
| tensorflow.VarLenFeature | 815 |
import tensorflow as tf
with tf.variable_scope('output', reuse=forward_only):
with tf.variable_scope('softmax'):
W = tf.get_variable('W', [self.num_hidden, self.num_classes],
# initializer=tf.random_uniform_initializer(-0.003, 0.003))
initializer=tf.contrib.layers.xavier_initializer())
# initializer=tf.truncated_normal_initializer(stddev=0.1))
b = tf.get_variable('b', [self.num_classes], initializer=tf.constant_initializer(0.1))
logits = tf.matmul(last_outputs, W) + b
self.embed_inputs = embed_inputs
return logits
def loss(self, logits, forward_only=None):
cost = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=tf.cast(self.y, tf.float32))
mean_cost = tf.reduce_mean(cost)
y_pred = tf.argmax(logits, 1)
correct_pred = tf.equal(y_pred, tf.argmax(self.y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
if forward_only:
str_summary_type = 'eval'
loss_summ = tf.summary.scalar("{0}_loss".format(str_summary_type), mean_cost)
acc_summ = tf.summary.scalar("{0}_accuracy".format(str_summary_type), accuracy)
merged = tf.summary.merge([loss_summ, acc_summ])
return mean_cost, accuracy, y_pred, merged
else:
return mean_cost, accuracy, y_pred
| tensorflow.reduce_mean | 816 |
import tensorflow as tf
# add histograms
if not reuse:
tf.histogram_summary(weights1.name, weights1)
tf.histogram_summary(weights2.name, weights2)
| tensorflow.histogram_summary | 817 |
import tensorflow as tf
pred_annotation, logits = inference(image, keep_probability)
tf.summary.image("input_image", image, max_outputs=2)
tf.summary.image("ground_truth", tf.cast(annotation, tf.uint8), max_outputs=2)
tf.summary.image("pred_annotation", tf.cast(pred_annotation, tf.uint8), max_outputs=2)
| tensorflow.cast | 818 |
import tensorflow as tf
# otherwise not_eos will crash)
tf.not_equal(length, 0),
fn_not_eos,
lambda: True,
)
return tf.cond(
tf.equal(batch_size, 1),
# If batch_size == 1, we check EOS for early stoping
lambda: tf.logical_and(not_overflow, not_eos),
# Else, just wait for max length
lambda: not_overflow)
return not_overflow
result, logits, loss = tf.while_loop(
while_exit_cond,
infer_step, [result, logits, loss],
shape_invariants=[
| tensorflow.logical_and | 819 |
import tensorflow as tf
def testModelWithBucketsScopeAndLoss(self):
"""Test that variable scope reuse is not reset after model_with_buckets."""
classes = 10
buckets = [(4, 4), (8, 8)]
with self.test_session():
# Here comes a sample Seq2Seq model using GRU cells.
def SampleGRUSeq2Seq(enc_inp, dec_inp, weights, per_example_loss):
"""Example sequence-to-sequence model that uses GRU cells."""
def GRUSeq2Seq(enc_inp, dec_inp):
cell = tf.nn.rnn_cell.MultiRNNCell([tf.nn.rnn_cell.GRUCell(24)] * 2,
state_is_tuple=True)
return tf.nn.seq2seq.embedding_attention_seq2seq(
enc_inp, dec_inp, cell, num_encoder_symbols=classes,
num_decoder_symbols=classes, embedding_size=24)
targets = [dec_inp[i+1] for i in range(len(dec_inp) - 1)] + [0]
return tf.nn.seq2seq.model_with_buckets(
enc_inp, dec_inp, targets, weights, buckets, GRUSeq2Seq,
per_example_loss=per_example_loss)
# Now we construct the copy model.
inp = [tf.placeholder(tf.int32, shape=[None]) for _ in range(8)]
out = [tf.placeholder(tf.int32, shape=[None]) for _ in range(8)]
weights = [tf.ones_like(inp[0], dtype=tf.float32) for _ in range(8)]
with tf.variable_scope("root"):
| tensorflow.nn.seq2seq.embedding_attention_seq2seq | 820 |
import tensorflow as tf
Returns
-------
A tensor with the variance of elements of `x`.
"""
axis = _normalize_axis(axis, get_ndim(x))
if x.dtype.base_dtype == tf.bool:
x = tf.cast(x, tf.float32)
m = tf.reduce_mean(x, axis=axis, keep_dims=True)
devs_squared = tf.square(x - m)
return tf.reduce_mean(devs_squared, axis=axis, keep_dims=keepdims)
| tensorflow.cast | 821 |
from tensorflow.python.framework import ops
return self.read_value()
# Register a conversion function which reads the value of the variable,
# allowing instances of the class to be used as tensors.
def _tensor_conversion(var, dtype=None, name=None, as_ref=False):
return var._dense_var_to_tensor(dtype=dtype, name=name, as_ref=as_ref) # pylint: disable=protected-access
ops.register_tensor_conversion_function(ReplicatedVariable, _tensor_conversion)
if not TF_23:
ops.register_dense_tensor_like_type(ReplicatedVariable)
| tensorflow.python.framework.ops.register_dense_tensor_like_type | 822 |
import tensorflow as tf
def gather_indexes(sequence_tensor, positions):
"""Gathers the vectors at the specific positions over a minibatch."""
sequence_shape = 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
# add sequence mask for:
# 1. random shuffle lm modeling---xlnet with random shuffled input
# 2. left2right and right2left language modeling
# 3. conditional generation
def generate_seq2seq_mask(attention_mask, mask_sequence, seq_type, **kargs):
if seq_type == 'seq2seq':
| tensorflow.reshape | 823 |
import tensorflow as tf
train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file)
tf.logging.info("***** Running training *****")
tf.logging.info(" Num examples = %d", len(train_examples))
tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
tf.logging.info(" Num steps = %d", num_train_steps)
train_input_fn = file_based_input_fn_builder(
| tensorflow.logging.info | 824 |
import tensorflow as tf
context_vectors = []
weights = []
attn_heads = encoder.attn_heads or 1
scope = scope or 'attention_{}'.format(encoder.name)
for i in range(attn_heads):
scope_ = scope if i == 0 else scope + '_{}'.format(i + 1)
context_vector, weights_ = attention_function(encoder=encoder, scope=scope_, **kwargs)
context_vectors.append(context_vector)
weights.append(weights_)
context_vector = tf.concat(context_vectors, axis=-1)
weights = sum(weights) / len(weights)
if encoder.attn_mapping:
with tf.variable_scope(scope):
context_vector = dense(context_vector, encoder.attn_mapping, use_bias=False, name='output')
return context_vector, weights
def multi_attention(state, hidden_states, encoders, encoder_input_length, pos=None, aggregation_method='sum',
prev_weights=None, **kwargs):
| tensorflow.concat | 825 |
import tensorflow as tf
Returns:
Minibatch standard deviation feature map image added to
channels of shape
[cur_batch_size, image_size, image_size, 1].
"""
with tf.variable_scope(
"{}/grouped_minibatch_stddev".format(self.name)):
# The group size should be less than or equal to the batch size.
# shape = ()
group_size = tf.minimum(
x=group_size, y=cur_batch_size, name="group_size"
)
print_obj("grouped_minibatch_stddev", "group_size", group_size)
# Split minibatch into M groups of size group_size, rank 5 tensor.
# shape = (
# group_size,
# cur_batch_size / group_size,
# image_size,
| tensorflow.minimum | 826 |
import tensorflow as tf
)
with tf.variable_scope("loss"):
if is_training:
output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
output_layer = tf.reshape(output_layer, [-1, hidden_size])
logits = tf.matmul(output_layer, output_weight, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
logits = tf.reshape(logits, [-1, FLAGS.max_seq_length, 11])
| tensorflow.reshape | 827 |
from tensorflow.python.framework import ops
If the default graph is being used to define a function, the
returned list of tensors are those accessed inside the function body
but defined outside the function body so far. Otherwise, returns an
empty list.
"""
g = ops.get_default_graph()
if isinstance(g, _FuncGraph):
return g.extra_inputs
else:
return []
| tensorflow.python.framework.ops.get_default_graph | 828 |
import tensorflow as tf
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([], tf.int64),
}
| tensorflow.FixedLenFeature | 829 |
import tensorflow as tf
def neural_net(self, X, weights, biases):
num_layers = len(weights) + 1
H = 2.0*(X - self.lb)/(self.ub - self.lb) - 1.0
for l in range(0,num_layers-2):
W = weights[l]
b = biases[l]
H = tf.tanh(tf.add(tf.matmul(H, W), b))
W = weights[-1]
b = biases[-1]
Y = tf.add(tf.matmul(H, W), b)
return Y
def fwd_gradients_0(self, U, x):
g = tf.gradients(U, x, grad_ys=self.dummy_x0_tf)[0]
| tensorflow.matmul | 830 |
import tensorflow as tf
shape = out.get_shape()
print('pool{}'.format(l + 1))
print('\t{} --> {}'.format(bottom.name, out.name))
print('\t{} --> {}'.format(bottom.get_shape(), out.get_shape()))
with tf.variable_scope('scale'):
bottom = out
if FLAGS.pm[l + 1] == FLAGS.pm[l]:
kernel_size = 1 # useless 1x1 pooling
elif int(FLAGS.pm[l + 1]) < int(FLAGS.pm[l]):
num_scales_prev = int(FLAGS.pm[l])
num_scales_current = int(FLAGS.pm[l + 1])
kernel_size = (num_scales_prev - num_scales_current) + 1
else:
raise ValueError('Number of scales must stay constant or decrease, got {}'.format(FLAGS.pm))
out = tf.nn.max_pool3d(bottom, ksize=[1,kernel_size,1,1,1], strides=[1,1,1,1,1], padding='VALID')
shape = out.get_shape()
print('scale{}'.format(l + 1))
print('\t{} --> {}'.format(bottom.name, out.name))
print('\t{} --> {}'.format(bottom.get_shape(), out.get_shape()))
with tf.variable_scope('fully_connected'):
bottom = out
bottom_shape = bottom.get_shape().as_list()
reshape = tf.reshape(
bottom,
[-1, bottom_shape[1] * bottom_shape[2] * bottom_shape[3] * bottom_shape[4]])
W_fc1 = weight_variable([bottom_shape[1] * bottom_shape[2] * bottom_shape[3] * bottom_shape[4], NUM_CLASSES()])
| tensorflow.nn.max_pool3d | 831 |
import tensorflow as tf
return res
class ptr_net:
def __init__(self, batch, hidden, keep_prob=1.0, is_train=None, scope="ptr_net"):
self.gru = tf.contrib.rnn.GRUCell(hidden)
self.batch = batch
self.scope = scope
self.keep_prob = keep_prob
self.is_train = is_train
self.dropout_mask = dropout(tf.ones(
[batch, hidden], dtype=tf.float32), keep_prob=keep_prob, is_train=is_train)
def __call__(self, init, match, d, mask):
with tf.variable_scope(self.scope):
d_match = dropout(match, keep_prob=self.keep_prob,
is_train=self.is_train)
inp, logits1 = pointer(d_match, init * self.dropout_mask, d, mask)
d_inp = dropout(inp, keep_prob=self.keep_prob,
is_train=self.is_train)
| tensorflow.ones | 832 |
import tensorflow as tf
# TRAINING PROGRESS EVENTS
def _on_training_start(self, sess):
# Writers and savers
self.summary_writer = tf.summary.FileWriter(FLAGS.logdir, sess.graph)
self.saver = tf.train.Saver()
self._build_embedding_saver(sess)
self._restore_model(sess)
# Loss summaries
self._build_summaries()
self.epoch_stats = get_stats_template()
self.stats = Bunch(
| tensorflow.train.Saver | 833 |
import tensorflow as tf
'model_scope', None,
'Model scope name used to replace the name_scope in checkpoint.')
tf.app.flags.DEFINE_string(
'checkpoint_exclude_scopes', None,
'Comma-separated list of scopes of variables to exclude when restoring from a checkpoint.')
tf.app.flags.DEFINE_boolean(
'ignore_missing_vars', True,
'When restoring a checkpoint would ignore missing variables.')
tf.app.flags.DEFINE_boolean(
'run_on_cloud', False,
'Wether we will train on cloud.')
tf.app.flags.DEFINE_boolean(
'seq_train', False,
'Wether we will train a sequence model.')
tf.app.flags.DEFINE_string(#
'model_to_train', 'blouse, dress, outwear, skirt, trousers', #'all, blouse, dress, outwear, skirt, trousers', 'skirt, dress, outwear, trousers',
'The sub-model to train (comma-separated list).')
FLAGS = tf.app.flags.FLAGS
#--model_scope=blouse --checkpoint_path=./logs/all --data_format=channels_last --batch_size=1
def input_pipeline(is_training=True, model_scope=FLAGS.model_scope, num_epochs=FLAGS.epochs_per_eval):
if 'all' in model_scope:
lnorm_table = tf.contrib.lookup.HashTable(tf.contrib.lookup.KeyValueTensorInitializer(tf.constant(config.global_norm_key, dtype=tf.int64),
tf.constant(config.global_norm_lvalues, dtype=tf.int64)), 0)
rnorm_table = tf.contrib.lookup.HashTable(tf.contrib.lookup.KeyValueTensorInitializer(tf.constant(config.global_norm_key, dtype=tf.int64),
tf.constant(config.global_norm_rvalues, dtype=tf.int64)), 1)
else:
lnorm_table = tf.contrib.lookup.HashTable(tf.contrib.lookup.KeyValueTensorInitializer(tf.constant(config.local_norm_key, dtype=tf.int64),
| tensorflow.app.flags.DEFINE_string | 834 |
import tensorflow as tf
import tensorflow as tf
import numpy as np
class Model(object):
def __init__(self, vars):
self.saver = tf.train.Saver(vars)
def session(self, sess):
if sess is not None:
self.sess = sess
else:
| tensorflow.train.Saver | 835 |
import tensorflow as tf
A tensor with the same format as the input with the data either intact
(if kernel_size == 1) or padded (if kernel_size > 1).
"""
pad_total = kernel_size - 1
pad_beg = pad_total // 2
pad_end = pad_total - pad_beg
if data_format == 'channels_first':
padded_inputs = tf.pad(inputs, [[0, 0], [0, 0],
[pad_beg, pad_end], [pad_beg, pad_end]])
else:
padded_inputs = tf.pad(inputs, [[0, 0], [pad_beg, pad_end],
[pad_beg, pad_end], [0, 0]])
return padded_inputs
def conv2d_fixed_padding(inputs, filters, kernel_size, strides, data_format):
"""Strided 2-D convolution with explicit padding."""
# The padding is consistent and is based only on `kernel_size`, not on the
# dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone).
if strides > 1:
inputs = fixed_padding(inputs, kernel_size, data_format)
| tensorflow.pad | 836 |
import tensorflow as tf
act_values_dict = {}
feed_dict = {ul_u_eval_train: random_sphere_numpy(ul_u_eval_train.shape)}
for key, _ in losses_eval_train.iteritems():
act_values_dict[key] = 0
n_iter_per_epoch = NUM_EVAL_EXAMPLES / FLAGS.eval_batch_size
for i in range(n_iter_per_epoch):
values = losses_eval_train.values()
act_values = sess.run(values, feed_dict=feed_dict)
for key, value in zip(act_values_dict.keys(), act_values):
act_values_dict[key] += value
summary = tf.Summary()
current_global_step = sess.run(global_step)
for key, value in act_values_dict.iteritems():
print("train-" + key, value / n_iter_per_epoch)
summary.value.add(tag=key, simple_value=value / n_iter_per_epoch)
if writer_train is not None:
writer_train.add_summary(summary, current_global_step)
# Eval on test data
act_values_dict = {}
| tensorflow.Summary | 837 |
import tensorflow as tf
kernel_initializer=initializer,
name="dense_1",
use_bias=False)
cls_logits = tf.squeeze(cls_logits, -1)
return_dict["cls_logits"] = cls_logits
| tensorflow.squeeze | 838 |
import tensorflow as tf
b_soft_no_learn = np.array(
[0.25, 0.25] + [-0.25] * (self.num_branches - 2), dtype=np.float32)
b_soft_no_learn = np.reshape(b_soft_no_learn, [1, self.num_branches])
self.b_soft_no_learn = tf.constant(b_soft_no_learn, dtype=tf.float32)
with tf.variable_scope("attention"):
self.w_attn_1 = tf.get_variable("w_1", [self.lstm_size, self.lstm_size])
| tensorflow.constant | 839 |
import tensorflow as tf
method=0)
gtboxes_in_img_r = self.drawer.draw_boxes_with_categories(img_batch=img,
boxes=gtboxes_and_label_r[
:, :-1],
labels=gtboxes_and_label_r[
:, -1],
method=1,
is_csl=True)
tf.summary.image('Compare/gtboxes_h_gpu:%d' % i, gtboxes_in_img_h)
tf.summary.image('Compare/gtboxes_r_gpu:%d' % i, gtboxes_in_img_r)
if cfgs.ADD_BOX_IN_TENSORBOARD:
detections_in_img = self.drawer.draw_boxes_with_categories_and_scores(
img_batch=img,
boxes=outputs[0],
scores=outputs[1],
| tensorflow.summary.image | 840 |
import tensorflow as tf
tf.app.flags.DEFINE_string('eval_dir', '',
'Directory to keep eval outputs.')
tf.app.flags.DEFINE_integer('eval_batch_count', 10,
'Number of batches to eval.')
tf.app.flags.DEFINE_bool('eval_once', False,
'Whether evaluate the model only once.')
tf.app.flags.DEFINE_string('log_root', '',
'Directory to keep the checkpoints. Should be a '
'parent directory of FLAGS.train_dir/eval_dir.')
tf.app.flags.DEFINE_integer('num_gpus', 0,
'Number of gpus used for training. (0 or 1)')
tf.app.flags.DEFINE_integer('num_residual_units', 5,
| tensorflow.app.flags.DEFINE_string | 841 |
import tensorflow as tf
self.loss = tf.reduce_mean(tf.square(tf.subtract(self.value_estimate, self.target)))
self.optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
self.train_op = self.optimizer.minimize(
self.loss, global_step=tf.contrib.framework.get_global_step())
def predict(self, state, sess=None):
sess = sess or tf.get_default_session()
return sess.run(self.value_estimate, { self.state: [state] })[0][0]
def update(self, state, target, sess=None):
sess = sess or tf.get_default_session()
feed_dict = { self.state: state, self.target: target }
| tensorflow.get_default_session | 842 |
import tensorflow as tf
l2=tf.nn.relu(l2)
l3=tf.matmul(l2, self.w3)+self.b3
l3=tf.nn.relu(l3)
out=tf.matmul(l3, self.w4)+self.b4
return out
def test_inference(self,images):
images=tf.cast(images,tf.float32)/255.0
l1 = tf.matmul(images, self.w1)+self.b1
l1=tf.nn.relu(l1)
l2 = tf.matmul(l1, self.w2)+self.b2
l2=tf.nn.relu(l2)
l3=tf.matmul(l2, self.w3)+self.b3
l3=tf.nn.relu(l3)
out=tf.matmul(l3, self.w4)+self.b4
return out
def valid_inference(self,images):
images=tf.cast(images,tf.float32)/255.0
l1 = tf.matmul(images, self.w1)+self.b1
l1=tf.nn.relu(l1)
l2 = tf.matmul(l1, self.w2)+self.b2
l2=tf.nn.relu(l2)
l3=tf.matmul(l2, self.w3)+self.b3
| tensorflow.matmul | 843 |
from tensorflow.contrib.rnn import BasicLSTMCell, RNNCell, DropoutWrapper, MultiRNNCell
state_keep_prob=decoder.rnn_state_keep_prob)
else:
cell = GRUCell(decoder.cell_size, reuse=reuse, layer_norm=decoder.layer_norm)
if decoder.use_dropout and decoder.cell_type.lower() != 'dropoutgru':
cell = DropoutWrapper(cell, input_keep_prob=decoder.rnn_input_keep_prob,
output_keep_prob=decoder.rnn_output_keep_prob,
state_keep_prob=decoder.rnn_state_keep_prob,
variational_recurrent=decoder.pervasive_dropout,
dtype=tf.float32, input_size=input_size_)
cells.append(cell)
if len(cells) == 1:
return cells[0]
else:
return CellWrapper(MultiRNNCell(cells))
def look(time, state, input_, prev_weights=None, pos=None, context=None):
prev_weights_ = [prev_weights if i == align_encoder_id else None for i in range(len(encoders))]
pos_ = None
if decoder.pred_edits:
pos_ = [pos if i == align_encoder_id else None for i in range(len(encoders))]
if decoder.attn_prev_word:
state = tf.concat([state, input_], axis=1)
if decoder.attn_prev_attn and context is not None:
state = tf.concat([state, context], axis=1)
if decoder.hidden_state_scaling:
attention_states_ = [states * decoder.hidden_state_scaling for states in attention_states]
| tensorflow.contrib.rnn.MultiRNNCell | 844 |
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.train.import_meta_graph | 845 |
import tensorflow as tf
mag = tf.norm(self.s_diff, axis=1) * tf.norm(gcut, axis=1) + .0001
dcos = dot / mag
manager_loss = -tf.reduce_sum((self.r - cutoff_vf_manager) * dcos)
| tensorflow.reduce_sum | 846 |
import tensorflow as tf
else:
is_real_example = tf.ones(tf.shape(label_ids), dtype=tf.float32)
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
(total_loss, per_example_loss, logits, probabilities) = create_model(
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
if init_checkpoint:
(assignment_map, initialized_variable_names
) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)
if use_tpu:
def tpu_scaffold():
| tensorflow.trainable_variables | 847 |
import tensorflow as tf
# sigma = tf.layers.dense(layer_a2, self.a_dim, tf.nn.softplus, kernel_regularizer=reg)
sigma = tf.get_variable(name='pi_sigma', shape=self.a_dim, initializer=tf.constant_initializer(0.5))
sigma = tf.clip_by_value(sigma, 0.0, 1.0)
norm_dist = tf.distributions.Normal(loc=mu * self.a_bound, scale=sigma)
params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=name)
return norm_dist, params
def build_cnet(self, state_in, name, reuse=False):
reg = tf.contrib.layers.l2_regularizer(1e-3)
with tf.variable_scope(name, reuse=reuse):
layer_c1 = tf.layers.dense(state_in, 512, tf.nn.relu, kernel_regularizer=reg)
layer_c2 = tf.layers.dense(layer_c1, 256, tf.nn.relu, kernel_regularizer=reg)
vf = tf.layers.dense(layer_c2, 1, kernel_regularizer=reg)
params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=name)
return vf, params
# Update the network
def train(self, s, a, r, adv):
| tensorflow.variable_scope | 848 |
import tensorflow as tf
loss = tf.map_fn(fn=lambda inp: sample_compute(inp), elems=tf.range(resample), dtype=tf.float32,
parallel_iterations=32)
final_loss = tf.reduce_mean(loss)
return final_loss
def contra_traj_lossV6(pred, tgt, horizon=12):
horizon_pred, horizon_tgt = horizon_sumV1(pred, horizon), horizon_sumV1(tgt, horizon)
# horizon_pred, horizon_tgt = horizon_sumV2(pred, tgt, horizon)
pred_flat1, pred_flat2 = tf.reshape(horizon_pred, [-1, 1]), tf.reshape(horizon_pred, [1, -1])
tgt_flat1, tgt_flat2 = tf.reshape(horizon_tgt, [-1, 1]), tf.reshape(horizon_tgt, [1, -1])
tgt_dif = tgt_flat1 - tgt_flat2
pred_dif = pred_flat1 - pred_flat2
geq = tf.cast(tgt_dif > 0, tf.bool)
tgt_posi_dif = tf.where(geq, tgt_dif, -tgt_dif)
pred_posi_dif = tf.where(geq, pred_dif, -pred_dif)
loss = tf.maximum(0., tgt_posi_dif - pred_posi_dif)
cstr_pct = tf.math.count_nonzero(loss, dtype=tf.float32) / tf.cast(tf.reduce_prod(tf.shape(loss)), tf.float32)
final_loss = tf.reduce_mean(loss)
| tensorflow.reshape | 849 |
import tensorflow as tf
loss = tf.metrics.mean(
| tensorflow.metrics.mean | 850 |
from tensorflow.python.training import device_setter
self._model_dir = model_dir
if self._model_dir is None:
self._model_dir = tempfile.mkdtemp()
logging.info('Using temporary folder as model directory: %s',
self._model_dir)
# Create a run configuration
self._config = BaseEstimator._Config()
# Set device function depending if there are replicas or not.
if self._config.num_ps_replicas > 0:
ps_ops = ['Variable', 'AutoReloadVariable']
self._device_fn = device_setter.replica_device_setter(
ps_tasks=self._config.num_ps_replicas,
merge_devices=False, ps_ops=ps_ops)
else:
self._device_fn = None
# Features and targets TensorSingature objects.
self._features_info = None
self._targets_info = None
@abc.abstractproperty
def _get_train_ops(self, features, targets):
| tensorflow.python.training.device_setter.replica_device_setter | 851 |
import tensorflow as tf
with tf.variable_scope(name):
w = tf.get_variable(
name="kernel",
shape=[hidden_size, num_attention_heads * head_size],
initializer=initializer)
w = tf.reshape(w, [hidden_size, num_attention_heads, head_size])
b = tf.get_variable(
name="bias",
shape=[num_attention_heads * head_size],
initializer=tf.zeros_initializer)
b = tf.reshape(b, [num_attention_heads, head_size])
ret = tf.einsum("BFH,HND->BFND", input_tensor, w)
ret += b
if activation is not None:
return activation(ret)
else:
return ret
def dense_layer_3d_proj(input_tensor,
hidden_size,
| tensorflow.reshape | 852 |
import tensorflow as tf
self.assertAllEqual(x - y, op_value)
if tf.test.is_built_with_cuda() and dtype in [np.float32, np.float64]:
| tensorflow.test.is_built_with_cuda | 853 |
from tensorflow.python.framework import tensor_util
segment_ids_shape = op.inputs[1].get_shape()
mid = segment_ids_shape.ndims
if mid is None:
return [tensor_shape.unknown_shape()]
else:
num_segments = tensor_util.ConstantValue(op.inputs[2])
return [tensor_shape.TensorShape([num_segments]).concatenate(
data_shape[mid:])]
@ops.RegisterShape("LinSpace")
def _LinspaceShape(op):
num = tensor_util.ConstantValue(op.inputs[2])
return [tensor_shape.vector(num)]
| tensorflow.python.framework.tensor_util.ConstantValue | 854 |
import tensorflow as tf
blk_shape[0], q_shape[1] * strides[1], q_shape[2] * strides[2], 3
], strides)
blk_indices_crop = blk_indices_crop // tf.stack([1, strides[1], strides[2]])
return blk_indices_crop
def _strides_one():
# Calculate otuput indices when strides = 1.
return blk_indices[:, :q_shape[1], :q_shape[2], :]
strides_gt_one = tf.logical_or(tf.greater(strides[1], 1), tf.greater(strides[2], 1))
blk_indices_crop = tf.cond(strides_gt_one, _strides_gt_one, _strides_one)
y = tf.scatter_nd(blk_indices_crop, q, out_shape)
return y
return tf.cond(
tf.equal(tf.size(blk_indices_), 0), lambda: tf.zeros(out_shape, dtype=x.dtype),
_conv_nonzero)
# returns an int64 start timer handle that should be passed to cuda_timer_end_op
def cuda_timer_start_op():
return sbnet_module.cuda_timer_start()
| tensorflow.scatter_nd | 855 |
import tensorflow as tf
def weight_variable(self,name, shape):
with tf.variable_scope(name) as scope:
weights = tf.get_variable('weights',
shape=shape,
dtype=tf.float32,
initializer=tf.truncated_normal_initializer(stddev=0.1, dtype=tf.float32))
return weights
def bias_variable(self,name, shape):
| tensorflow.truncated_normal_initializer | 856 |
import tensorflow as tf
if FLAGS.do_train:
train_file = os.path.join(FLAGS.output_dir, "train.tf_record")
file_based_convert_examples_to_features(
train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file)
tf.logging.info("***** Running training *****")
tf.logging.info(" Num examples = %d", len(train_examples))
tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
tf.logging.info(" Num steps = %d", num_train_steps)
train_input_fn = file_based_input_fn_builder(
input_file=train_file,
seq_length=FLAGS.max_seq_length,
is_training=True,
drop_remainder=True)
estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
| tensorflow.logging.info | 857 |
import tensorflow as tf
def train(self):
self.fetch_datasets()
if FLAGS.model == AUTOENCODER:
self.build_ae_model()
elif FLAGS.model == PREDICTIVE:
self.build_predictive_model()
else:
self.build_denoising_model()
self._init_optimizer()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
self._on_training_start(sess)
try:
for current_epoch in range(FLAGS.max_epochs):
start = time.time()
full_set_blur = len(self.train_set) < 50000
ds = self._get_blurred_dataset() if full_set_blur else self.train_set
if FLAGS.model == AUTOENCODER:
# Autoencoder Training
| tensorflow.Session | 858 |
import tensorflow as tf
def dynamic_batching(paths):
spectrograms, max_x = [], 0
for path in paths:
spectrograms.append(np.load("spectrogram/" + path + ".npy"))
if spectrograms[-1].shape[0] > max_x:
max_x = spectrograms[-1].shape[0]
return spectrograms, max_x
# In[4]:
tf.reset_default_graph()
sess = tf.InteractiveSession()
model = Model()
sess.run(tf.global_variables_initializer())
# In[5]:
for e in range(30):
pbar = tqdm(range(0, len(text_files), batch_size), desc="minibatch loop")
total_cost, total_acc = 0, 0
for k in pbar:
| tensorflow.reset_default_graph | 859 |
import tensorflow as tf
"""
# Infer predictions using argmax
decoded = tf.cast(tf.argmax(inputs, axis=-1), tf.int32)
# Adjust event vals according to representation
| tensorflow.argmax | 860 |
import tensorflow as tf
import tensorflow as tf
import cifar10
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('train_dir', '/tmp/cifar10_train',
"""Directory where to write event logs """
"""and checkpoint.""")
tf.app.flags.DEFINE_integer('max_steps', 1000000,
"""Number of batches to run.""")
tf.app.flags.DEFINE_integer('num_gpus', 1,
"""How many GPUs to use.""")
tf.app.flags.DEFINE_boolean('log_device_placement', False,
"""Whether to log device placement.""")
def tower_loss(scope):
"""Calculate the total loss on a single tower running the CIFAR model.
Args:
scope: unique prefix string identifying the CIFAR tower, e.g. 'tower_0'
Returns:
Tensor of shape [] containing the total loss for a batch of data
| tensorflow.app.flags.DEFINE_boolean | 861 |
import tensorflow as tf
optimizer = tf.train.AdamOptimizer(learning_rate=hparams.learning_rate)
train_op, loss, _ = graph_step(dynamics, optimizer, x)
# Single thread; fairer comparison against eager
session_conf = tf.ConfigProto(inter_op_parallelism_threads=1)
with tf.Session(config=session_conf) as sess:
sess.run(tf.global_variables_initializer())
# Warmup to reduce initialization effect when timing
for _ in range(hparams.n_warmup_iters):
_, _ = sess.run([train_op, loss])
# Training
| tensorflow.global_variables_initializer | 862 |
import tensorflow as tf
# forward pass
if cfg.TEST.HAS_RPN:
feed_dict={net.data: blobs['data'], net.im_info: blobs['im_info'], net.keep_prob: 1.0}
else:
feed_dict={net.data: blobs['data'], net.rois: blobs['rois'], net.keep_prob: 1.0}
run_options = None
run_metadata = None
if cfg.TEST.DEBUG_TIMELINE:
run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
run_metadata = tf.RunMetadata()
#theta_tensor = tf.get_default_graph().get_tensor_by_name('spt_trans_theta')
cls_score, cls_prob, bbox_pred, rois = sess.run([net.get_output('cls_score'),
net.get_output('cls_prob'), net.get_output('bbox_pred'), net.get_output('rois')],
feed_dict=feed_dict,
options=run_options,
run_metadata=run_metadata)
| tensorflow.RunOptions | 863 |
import tensorflow as tf
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:
| tensorflow.global_variables_initializer | 864 |
import tensorflow as tf
[cur_batch_size, image_size, image_size, num_channels].
params: dict, user passed parameters.
group_size: int, size of image groups.
Returns:
Image with minibatch standard deviation feature map added to
channels of shape
[cur_batch_size, image_size, image_size, num_channels + 1].
"""
with tf.variable_scope("{}/minibatch_stddev".format(self.name)):
# Get dynamic shape of image.
# shape = (4,)
dynamic_image_shape = tf.shape(
input=X, name="dynamic_image_shape"
)
print_obj(
"\nminibatch_stddev",
"dynamic_image_shape",
dynamic_image_shape
)
# Extract current batch size (in case this is a partial batch).
cur_batch_size = dynamic_image_shape[0]
| tensorflow.shape | 865 |
import tensorflow as tf
updated_ema_count, axis=-1)
with tf.control_dependencies([e_loss]):
update_means = tf.assign(self.means, updated_ema_means)
with tf.control_dependencies([update_means]):
loss += self.hparams.beta * e_loss
| tensorflow.assign | 866 |
import tensorflow as tf
K = 1/(2*D-3)
A1 = euclidean_norm_squared(tf.subtract(tf.expand_dims(X, 0), tf.expand_dims(X, 1)), axis=2)
A = (1/(N**2)) * tf.reduce_sum((1/tf.sqrt(y + K*A1)))
B1 = euclidean_norm_squared(X, axis=1)
| tensorflow.sqrt | 867 |
import tensorflow as tf
def get_dropout(self, dropout_rate, is_training):
return 1 - (tf.to_float(is_training) * dropout_rate)
| tensorflow.to_float | 868 |
from tensorflow.contrib.framework import tensor_util
update_op: An operation that increments the `total` and `count` variables
appropriately.
Raises:
ValueError: If `predictions` and `labels` have mismatched shapes, 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.
"""
predictions, labels = tensor_util.remove_squeezable_dimensions(
predictions, labels)
predictions.get_shape().assert_is_compatible_with(labels.get_shape())
radial_diffs = math_ops.mul(predictions, labels)
radial_diffs = math_ops.reduce_sum(radial_diffs,
reduction_indices=[dim,],
keep_dims=True)
mean_distance, update_op = streaming_mean(radial_diffs, weights,
None,
| tensorflow.contrib.framework.tensor_util.remove_squeezable_dimensions | 869 |
import tensorflow as tf
else:
block = layer + inp
block = tf.nn.relu(block, name='relu')
| tensorflow.nn.relu | 870 |
import tensorflow as tf
else:
os.environ['CUDA_VISIBLE_DEVICES'] = f'{args.gpu}'
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
| tensorflow.ConfigProto | 871 |
import tensorflow as tf
return server_test_data, decode_params
def _non_adaptive_many_to_one_encode_decode():
"""Implementation of the method for `EncodingStageInterface`."""
server_graph = tf.Graph()
with server_graph.as_default():
shape = input_values[0].shape
encode_params, decode_params = stage.get_params()
with self.session(server_graph) as sess:
encode_params, decode_params = self.evaluate_tf_py_list(
[encode_params, decode_params], sess)
client_test_data = []
for x in input_values:
client_graph = tf.Graph()
with client_graph.as_default():
encoded_x = stage.encode(x, encode_params)
with self.session(client_graph):
encoded_x = self.evaluate(encoded_x)
client_test_data.append(TestData(x, encoded_x))
server_test_data = []
with server_graph.as_default():
with self.session(server_graph) as sess:
for test_data in client_test_data:
decoded_x = stage.decode(
test_data.encoded_x, decode_params, shape=shape)
server_test_data.append(
test_data._replace(decoded_x=sess.run(decoded_x)))
| tensorflow.Graph | 872 |
import tensorflow as tf
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)
| tensorflow.constant | 873 |
from tensorflow.contrib.eager.python.examples.l2hmc import l2hmc
def benchmark_eager_defun(self):
self._benchmark_eager(defun=True)
def _benchmark_eager(self, defun=False):
"""Benchmark Eager performance."""
hparams = get_default_hparams()
for sample_size in [10, 25, 50, 100, 200]:
hparams.n_samples = sample_size
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)
optimizer = tf.train.AdamOptimizer(learning_rate=hparams.learning_rate)
step_fn = tfe.defun(step) if defun else step
# Warmup to reduce initialization effect when timing
| tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.get_scg_energy_fn | 874 |
import tensorflow as tf
from official.mnist import mnist_eager
from official.utils.misc import keras_utils
def device():
return "/device:GPU:0" if tfe.num_gpus() else "/device:CPU:0"
def data_format():
return "channels_first" if tfe.num_gpus() else "channels_last"
def random_dataset():
batch_size = 64
images = tf.random_normal([batch_size, 784])
labels = tf.random_uniform([batch_size], minval=0, maxval=10, dtype=tf.int32)
return tf.data.Dataset.from_tensors((images, labels))
def train(defun=False):
model = mnist.create_model(data_format())
if defun:
model.call = tfe.defun(model.call)
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
dataset = random_dataset()
with tf.device(device()):
mnist_eager.train(model, optimizer, dataset,
step_counter=tf.train.get_or_create_global_step())
| tensorflow.random_uniform | 875 |
import tensorflow as tf
def _get_lstm_cell(self, config, is_training):
if config.rnn_mode == BASIC:
return tf.contrib.rnn.BasicLSTMCell(
config.hidden_size, forget_bias=0.0, state_is_tuple=True,
reuse=not is_training)
| tensorflow.contrib.rnn.BasicLSTMCell | 876 |
from tensorflow.python.framework import ops
ops.RegisterShape("Relu")(common_shapes.unchanged_shape)
ops.RegisterShape("Relu6")(common_shapes.unchanged_shape)
| tensorflow.python.framework.ops.RegisterShape | 877 |
import tensorflow as tf
tf.app.flags.DEFINE_integer(
'num_cpu_threads', 0,
'The number of cpu cores used to train.')
tf.app.flags.DEFINE_float(
'gpu_memory_fraction', 1., 'GPU memory fraction to use.')
# scaffold related configuration
tf.app.flags.DEFINE_string(
'data_dir', '../PASCAL/VOC_TF/VOC0712TF/',
'The directory where the dataset input data is stored.')
tf.app.flags.DEFINE_string(
'dataset_name', 'pascalvoc_0712', 'The name of the dataset to load.')
tf.app.flags.DEFINE_integer(
| tensorflow.app.flags.DEFINE_string | 878 |
import tensorflow as tf
q_func_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='q_func')
target_q_func_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='target_q_func')
| tensorflow.get_collection | 879 |
import tensorflow as tf
create_initializer(initializer_range), query_act, "query")
# `key_layer` = [B, T, N, H]
k = dense_layer_3d(to_tensor, num_attention_heads, size_per_head,
create_initializer(initializer_range), key_act, "key")
# `value_layer` = [B, T, N, H]
v = dense_layer_3d(to_tensor, num_attention_heads, size_per_head,
create_initializer(initializer_range), value_act, "value")
q = tf.transpose(q, [0, 2, 1, 3])
k = tf.transpose(k, [0, 2, 1, 3])
v = tf.transpose(v, [0, 2, 1, 3])
if attention_mask is not None:
attention_mask = tf.reshape(
attention_mask, [batch_size, 1, to_seq_length, 1])
# 'new_embeddings = [B, N, F, H]'
new_embeddings = dot_product_attention(q, k, v, attention_mask,
attention_probs_dropout_prob)
| tensorflow.transpose | 880 |
import tensorflow as tf
scaling = maxnorm / tf.maximum(row_norms, maxnorm)
scaled = var_matrix * tf.expand_dims(scaling, 1)
| tensorflow.expand_dims | 881 |
import tensorflow as tf
scores = tf.nn.softmax(scores) # [B, 1, T]
# Weighted sum
if mode == 'SUM':
output = tf.matmul(scores, facts) # [B, 1, H]
# output = tf.reshape(output, [-1, tf.shape(facts)[-1]])
else:
scores = tf.reshape(scores, [-1, tf.shape(facts)[1]])
output = facts * tf.expand_dims(scores, -1)
output = tf.reshape(output, tf.shape(facts))
return output
def din_fcn_attention(query, facts, attention_size, mask, stag='null', mode='SUM', softmax_stag=1, time_major=False, return_alphas=False, forCnn=False):
if isinstance(facts, tuple):
# In case of Bi-RNN, concatenate the forward and the backward RNN outputs.
facts = tf.concat(facts, 2)
| tensorflow.expand_dims | 882 |
import tensorflow as tf
saver = tf.train.Saver()
adv_images = adv_craft_func(hps, images, FLAGS.attack_method, eps=FLAGS.eps, RCE_train=FLAGS.RCE_train)
model_nor = model_name.ResNet(hps, images, FLAGS.mode, Reuse=True)
model_nor.build_graph()
model_adv = model_name.ResNet(hps, adv_images, FLAGS.mode, Reuse=True)
model_adv.build_graph()
# Open session and restore checkpoint
sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
tf.train.start_queue_runners(sess)
sess.run(tf.global_variables_initializer())
ckpt_state = tf.train.get_checkpoint_state(FLAGS.log_root) # Choose dir according to rt
tf.logging.info('Loading checkpoint %s', ckpt_state.model_checkpoint_path)
saver.restore(sess, ckpt_state.model_checkpoint_path)
logits_nor = model_nor.t_SNE_logits
logits_adv = model_adv.t_SNE_logits
dim_logits = logits_nor.shape[1]
if hps.batch_size!=logits_nor.shape[0]:
print('Error!!!!!')
return
logits_all = np.reshape(np.array([]),(0,dim_logits))
labels_all = np.array([])
is_adv_all = np.array([])
| tensorflow.logging.info | 883 |
from tensorflow.python.framework import ops
Raises:
ValueError: if the arguments are invalid.
"""
if len(inputs) != len(sig.input_arg):
raise ValueError("Expected number of arguments: %d, received: %d" %
(len(sig.input_arg), len(inputs)))
name = kwargs.pop("name", None)
attrs = _parse_kwargs_as_attrs(**kwargs)
g = ops.get_default_graph()
func_name = sig.name
output_types = [dtypes.DType(x.type) for x in sig.output_arg]
with ops.name_scope(name, func_name, inputs) as name:
op = g.create_op(
func_name,
list(inputs),
output_types,
| tensorflow.python.framework.ops.get_default_graph | 884 |
import tensorflow as tf
@property
def perm(self):
return self._perm
@property
def rightmost_transposed_ndims(self):
return self._rightmost_transposed_ndims
def _forward(self, x):
return self._transpose(x, self.perm)
def _inverse(self, y):
return self._transpose(y, tf.argsort(self.perm))
def _inverse_log_det_jacobian(self, y):
return tf.constant(0, dtype=y.dtype)
def _forward_log_det_jacobian(self, x):
return tf.constant(0, dtype=x.dtype)
def _transpose(self, x, perm):
sample_batch_ndims = tf.rank(x) - self.rightmost_transposed_ndims
perm = tf.concat([
tf.range(sample_batch_ndims),
| tensorflow.argsort | 885 |
import tensorflow as tf
def parse(line):
"""Parse a line from the colors dataset."""
# Each line of the dataset is comma-separated and formatted as
# color_name, r, g, b
# so `items` is a list [color_name, r, g, b].
items = tf.string_split([line], ",").values
rgb = tf.string_to_number(items[1:], out_type=tf.float32) / 255.
# Represent the color name as a one-hot encoded character sequence.
color_name = items[0]
chars = tf.one_hot(tf.decode_raw(color_name, tf.uint8), depth=256)
# The sequence length is needed by our RNN.
length = tf.cast(tf.shape(chars)[0], dtype=tf.int64)
return rgb, chars, length
def maybe_download(filename, work_directory, source_url):
"""Download the data from source url, unless it's already here.
Args:
filename: string, name of the file in the directory.
| tensorflow.decode_raw | 886 |
import tensorflow as tf
with self.assertRaises(ValueError):
schema_inference.infer_feature_schema(tensors, graph)
def test_bucketization_annotation(self):
# TODO(b/132098015): Schema annotations aren't yet supported in OSS builds.
# pylint: disable=g-import-not-at-top
try:
from tensorflow_transform import annotations_pb2
except ImportError:
return
# pylint: enable=g-import-not-at-top
with tf.compat.v1.Graph().as_default() as graph:
inputs = {
'foo': tf.convert_to_tensor([0, 1, 2, 3]),
'bar': tf.convert_to_tensor([0, 2, 0, 2]),
}
boundaries_foo = tf.expand_dims(tf.convert_to_tensor([.5, 1.5]), axis=0)
boundaries_bar = tf.expand_dims(tf.convert_to_tensor([.1, .2]), axis=0)
outputs = {}
# tft.apply_buckets will annotate the feature in the output schema to
# indicate the bucket boundaries that were applied.
outputs['Bucketized_foo'] = mappers.apply_buckets(inputs['foo'],
boundaries_foo)
outputs['Bucketized_bar'] = mappers.apply_buckets(inputs['bar'],
boundaries_bar)
| tensorflow.convert_to_tensor | 887 |
import tensorflow as tf
add=True,
transpose=transpose)
else:
y = sbnet_module.sparse_scatter(
q,
indices.bin_counts,
indices.active_block_indices,
x,
dynamic_bsize=tf.constant(block_params.bsize_out, dtype=tf.int32),
dynamic_bstride=tf.constant(block_params.bsize_out, dtype=tf.int32),
dynamic_boffset=tf.constant([0, 0], dtype=tf.int32),
add=True,
transpose=transpose)
return y
| tensorflow.constant | 888 |
from tensorflow.python import debug as tf_debug
hooks = []
if FLAGS.use_hvd:
hooks.append(hvd.BroadcastGlobalVariablesHook(0))
if hvd.rank() == -1: #if debug, set 0
CLIDebugHook = tf_debug.LocalCLIDebugHook(ui_type='readline')
CLIDebugHook.add_tensor_filter("has_inf_or_nan", tf_debug.has_inf_or_nan)
hooks.append(CLIDebugHook)
if FLAGS.profile and hvd.rank() == 0:
ProfilerHook = tf.train.ProfilerHook(save_steps=FLAGS.hooking_frequence, output_dir=FLAGS.output_dir, show_dataflow=True, show_memory=True)
| tensorflow.python.debug.LocalCLIDebugHook | 889 |
from tensorflow.python.ops import control_flow_ops
with tf.control_dependencies(update_ops):
barrier = tf.no_op(name='update_barrier')
self.d_losses[-1] = control_flow_ops.with_dependencies([barrier], self.d_losses[-1])
self.g_losses[-1] = control_flow_ops.with_dependencies([barrier], self.g_losses[-1])
self.d_loss_real = control_flow_ops.with_dependencies([barrier], self.d_loss_real)
self.d_loss_fake = control_flow_ops.with_dependencies([barrier], self.d_loss_fake)
self.d_loss_class = control_flow_ops.with_dependencies([barrier], self.d_loss_class)
t_vars = self._get_vars_semi_supervised()
| tensorflow.python.ops.control_flow_ops.with_dependencies | 890 |
import tensorflow as tf
"""
with tf.name_scope(name):
| tensorflow.name_scope | 891 |
from tensorflow.python.platform import gfile
self.assertTrue(gfile.Exists(s1))
self.assertTrue(gfile.Exists(save._MetaGraphFilename(s1)))
# Exercise the second helper.
# Adding s2 again (old s2 is removed first, then new s2 appended)
s2 = save2.save(sess, os.path.join(save_dir, "s2"))
self.assertEqual([s3, s2], save2.last_checkpoints)
# Created by the first helper.
self.assertTrue(gfile.Exists(s1))
self.assertTrue(gfile.Exists(save._MetaGraphFilename(s1)))
# Deleted by the first helper.
self.assertFalse(gfile.Exists(s3))
self.assertFalse(gfile.Exists(save._MetaGraphFilename(s3)))
self.assertTrue(gfile.Exists(s2))
self.assertTrue(gfile.Exists(save._MetaGraphFilename(s2)))
# Adding s1 (s3 should now be deleted as oldest in list)
| tensorflow.python.platform.gfile.Exists | 892 |
import tensorflow as tf
tf.summary.image('Compare/final_detection_gpu:%d' % i, detections_in_img)
loss_dict = outputs[-1]
total_loss_dict, total_losses = self.loss_dict(loss_dict, num_gpu)
if i == num_gpu - 1:
regularization_losses = tf.get_collection(
tf.GraphKeys.REGULARIZATION_LOSSES)
# weight_decay_loss = tf.add_n(slim.losses.get_regularization_losses())
total_losses = total_losses + tf.add_n(regularization_losses)
tf.get_variable_scope().reuse_variables()
grads = optimizer.compute_gradients(total_losses)
if cfgs.GRADIENT_CLIPPING_BY_NORM is not None:
grads = slim.learning.clip_gradient_norms(grads, cfgs.GRADIENT_CLIPPING_BY_NORM)
tower_grads.append(grads)
self.log_printer(fcos, optimizer, global_step, tower_grads, total_loss_dict, num_gpu*cfgs.BATCH_SIZE, graph)
| tensorflow.add_n | 893 |
import tensorflow as tf
features['image'] = _cifar_augment_image(features['image'])
return features, targets
def flatten_image(features, targets):
"""Flatten the image."""
img = features['image']
flat = tf.cast(tf.reshape(img, [-1]), tf.int64)
tgt = tf.expand_dims(targets, axis=0)
flat_with_target = tf.concat([flat, tgt], axis=0)
new_features = {}
new_features['image'] = flat_with_target
predict_image_weight = predict_image_train_weight if training else 0.0
mask_begin = tf.ones_like(flat)
mask_begin = tf.cast(mask_begin, tf.float32) * predict_image_weight
mask_end = tf.cast(tf.ones_like(tgt), tf.float32)
new_features['mask'] = tf.concat([mask_begin, mask_end], axis=0)
return new_features, flat_with_target
if training:
dataset = dataset.map(augment)
dataset = dataset.map(flatten_image)
return dataset
@gin.configurable(module='trax.data', denylist=['dataset', 'training'])
def downsampled_imagenet_flatten_bare_preprocess(dataset, training):
"""Preprocessing for downsampled_imagenet.
| tensorflow.ones_like | 894 |
import tensorflow as tf
'softmax_w', [hidden_size, vocab_size], dtype=tf.float32)
softmax_b = tf.get_variable('softmax_b', [vocab_size], dtype=tf.float32)
logits = tf.nn.xw_plus_b(output, softmax_w, softmax_b)
logits = tf.reshape(logits, [self.batch_size, self.num_steps, vocab_size])
loss = tf.contrib.seq2seq.sequence_loss(
logits,
input_.targets,
tf.ones([self.batch_size, self.num_steps], dtype=tf.float32),
average_across_timesteps=False,
average_across_batch=True)
self._cost = tf.reduce_sum(loss)
self._final_state = state
if not is_training:
return
self._lr = tf.Variable(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(
| tensorflow.reduce_sum | 895 |
import tensorflow as tf
stddev=1e-1,
name='synthetic_images')
labels = tf.random_uniform(
[batch_size],
| tensorflow.random_uniform | 896 |
import tensorflow as tf
init = tf.initialize_all_variables()
config=tf.ConfigProto()
config.gpu_options.allow_growth=True
#init=tf.initialize_all_variables()
def train(train_num=64,test_num=32,lr=1e-4,loop_count=10000,report_step=100,save_step=1000,restore=False):
with tf.Session(config=config) as sess:
sess.run(init)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
if restore:
tf.train.Saver().restore(sess,path)
| tensorflow.Session | 897 |
import tensorflow as tf
decode_normalize=False,
validation="",
references=[""],
save_checkpoint_secs=0,
save_checkpoint_steps=1000,
)
return params
def import_params(model_dir, model_name, params):
model_dir = os.path.abspath(model_dir)
p_name = os.path.join(model_dir, "params.json")
m_name = os.path.join(model_dir, model_name + ".json")
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
| tensorflow.gfile.Exists | 898 |
import tensorflow as tf
exp(Z) = (X / exp(mu))^(1/sigma)
"""
params = self.parameterizer(x1)
mus, log_sigmas = params[:,:,:,0::2], params[:,:,:,1::2]
# compute softplus activation
z2, ldj = log_gaussianize(x2, mus, log_sigmas)
z2 = tf.where(x2 > self.epsilon, z2, x2)
ldj = tf.where(x2 > self.epsilon, ldj, tf.zeros_like(ldj))
return z2, tf.math.reduce_sum(ldj, axis=[1,2,3])
def _inverse(self, x1, z2, **kwargs):
params = self.parameterizer(x1)
mus, log_sigmas = params[:,:,:,0::2], params[:,:,:,1::2]
x2, ldj = log_gaussianize(z2, mus, log_sigmas, inverse=tf.constant(True))
x2 = tf.where(z2 > self.epsilon, x2, z2)
ldj = tf.where(z2 > self.epsilon, ldj, tf.zeros_like(ldj))
return x2, tf.math.reduce_sum(ldj, axis=[1,2,3])
def half_gaussianize(x, log_sigmas, inverse=tf.constant(False)):
if inverse:
z = tf.math.exp(log_sigmas)*x
ldj = tf.math.reduce_sum(log_sigmas, axis=[1,2,3])
else:
z = x*tf.math.exp(-log_sigmas)
ldj = -tf.math.reduce_sum(log_sigmas, axis=[1,2,3])
return z, ldj
class HalfGaussianize(Parameterize):
| tensorflow.where | 899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.