seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
import tensorflow as tf
'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(
'num_classes', 21, 'Number of classes to use in the dataset.')
tf.app.flags.DEFINE_string(
'dataset_split_name', 'train', 'The name of the train/test split.')
tf.app.flags.DEFINE_string(
'model_dir', './logs_v3/',
'The directory where the model will be stored.')
tf.app.flags.DEFINE_integer(
'log_every_n_steps', 10,
'The frequency with which logs are print.')
tf.app.flags.DEFINE_integer(
'save_summary_steps', 500,
'The frequency with which summaries are saved, in seconds.')
tf.app.flags.DEFINE_integer(
'save_checkpoints_secs', 7200,
'The frequency with which the model is saved, in seconds.')
# model related configuration
tf.app.flags.DEFINE_integer(
'train_image_size', 352,
'The size of the input image for the model to use.')
tf.app.flags.DEFINE_integer(
'resnet_size', 50,
'The size of the ResNet model to use.')
tf.app.flags.DEFINE_integer(
|
tensorflow.app.flags.DEFINE_integer
| 8,300 |
import tensorflow as tf
bias_var_shape = [nf] if one_dim_bias else [1, nf, 1, 1]
nin = x.get_shape()[channel_ax].value
wshape = [rf, rf, nin, nf]
with tf.variable_scope(scope):
w = tf.get_variable("w", wshape, initializer=ortho_init(init_scale))
b = tf.get_variable("b", bias_var_shape, initializer=tf.constant_initializer(0.0))
|
tensorflow.variable_scope
| 8,301 |
import tensorflow as tf
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.
per_example_loss = -tf.reduce_sum(log_probs * one_hot_labels, axis=[-1])
numerator = tf.reduce_sum(label_weights * per_example_loss)
denominator = tf.reduce_sum(label_weights) + 1e-5
loss = numerator / denominator
return (loss, per_example_loss, log_probs)
def get_next_sentence_output(bert_config, input_tensor, labels, clip):
|
tensorflow.reduce_sum
| 8,302 |
import tensorflow as tf
self.assertEqual((2, 2), res[0].shape)
def testDynamicAttentionDecoder1(self):
with self.test_session() as sess:
with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)):
cell = tf.nn.rnn_cell.GRUCell(2)
inp = tf.constant(0.5, shape=[2, 2, 2])
enc_outputs, enc_state = tf.nn.dynamic_rnn(cell, inp, dtype=tf.float32)
attn_states = enc_outputs
dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3
dec, mem = tf.nn.seq2seq.attention_decoder(
dec_inp, enc_state,
attn_states, cell, output_size=4)
sess.run([tf.global_variables_initializer()])
res = sess.run(dec)
self.assertEqual(3, len(res))
self.assertEqual((2, 4), res[0].shape)
res = sess.run([mem])
self.assertEqual((2, 2), res[0].shape)
def testDynamicAttentionDecoder2(self):
with self.test_session() as sess:
with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)):
cell = tf.nn.rnn_cell.GRUCell(2)
inp = tf.constant(0.5, shape=[2, 2, 2])
|
tensorflow.global_variables_initializer
| 8,303 |
import tensorflow as tf
def bad():
image = tf.image.decode_jpeg(
tf.reshape(byte, shape=[]), 3, **JPEG_OPT)
image = resize_shortest_edge(image, jpeg_shape, 224)
image = center_crop(image, 224)
return image
image = tf.cond(is_bad, bad, good)
# TODO other imgproc
image = lighting(image, 0.1,
eigval=np.array([0.2175, 0.0188, 0.0045], dtype='float32') * 255.0,
eigvec=np.array([[-0.5675, 0.7192, 0.4009],
[-0.5808, -0.0045, -0.8140],
[-0.5836, -0.6948, 0.4203]], dtype='float32'))
image = tf.image.random_flip_left_right(image)
image = tf.reverse(image, axis=[2]) # to BGR
return image
return training_mapper if isTrain else validation_mapper
"""
====== Model & Evaluation =======
"""
def eval_on_ILSVRC12(model, sessinit, dataflow):
pred_config = PredictConfig(
model=model,
session_init=sessinit,
|
tensorflow.reverse
| 8,304 |
import tensorflow as tf
else:
init = tf.truncated_normal_initializer(stddev=init_stddev)
X = tf.layers.conv2d(X, out_channels, kernel_size=filtersize, strides=(stride, stride), padding="valid",
kernel_initializer=init)
if norm == 'I':
X = tf.contrib.layers.instance_norm(X, scope=scope, reuse=reuse, epsilon=0.001)
elif norm == 'B':
X = tf.layers.batch_normalization(X, reuse=reuse, training=True)
elif norm == 'G':
X = tf.contrib.layers.group_norm(X, groups=16, scope=scope, reuse=reuse)
if nonlin:
X = tf.nn.leaky_relu(X, 0.2)
return X
with tf.variable_scope('discriminator') as scope:
if reuse:
scope.reuse_variables()
print('D in:', X.get_shape().as_list())
X = self.conv('DZ1', X, 512, 1, 1)
X = tf.nn.leaky_relu(X, 0.2)
|
tensorflow.nn.leaky_relu
| 8,305 |
import tensorflow as tf
one = tf.Variable(1.0)
twos = tf.Variable([2.0, 2.0, 2.0])
init = tf.initialize_all_variables()
save = tf.train.Saver(tf.all_variables())
init.run()
save.save(sess, save_path)
with tf.Session("", graph=tf.Graph()) as sess:
one = tf.Variable(0.0)
twos = tf.Variable([0.0, 0.0, 0.0])
# Saver with no arg, defaults to 'all variables'.
save = tf.train.Saver()
save.restore(sess, save_path)
self.assertAllClose(1.0, one.eval())
|
tensorflow.Graph
| 8,306 |
import tensorflow as tf
wvs = tf.pack(self._inputs)
wvs_weighted = tf.mul(tf.reshape(tf.transpose(self.cs), [-1, 1]),
|
tensorflow.transpose
| 8,307 |
import tensorflow as tf
actions[name] = tf.gather(params=self.actions_memory[name], indices=indices)
terminal = tf.gather(params=self.terminal_memory, indices=indices)
reward = tf.gather(params=self.reward_memory, indices=indices)
if self.include_next_states:
|
tensorflow.gather
| 8,308 |
import tensorflow as tf
raw_output = -tf.reduce_sum(tf.abs(diff_vec), 1)
elif self.dist == 'euclidean':
# +eps because gradients can misbehave for small values in sqrt
raw_output = -tf.sqrt(tf.reduce_sum(tf.square(diff_vec), 1) + self.EPS)
elif self.dist == 'sqeuclidean':
raw_output = -tf.reduce_sum(tf.square(diff_vec), 1)
else:
raise Exception('Unknown distance type')
# Model output
self.output, self.loss = ranking_margin_objective(raw_output, self.margin)
|
tensorflow.square
| 8,309 |
import tensorflow as tf
nodes_list = [nodes]
adj_list = []
for hop_edge_types in edge_types:
neighbor, weight, _ = get_full_neighbor(nodes, hop_edge_types)
next_nodes, next_idx = tf.unique(neighbor.values, out_idx=tf.int64)
next_indices = tf.stack([neighbor.indices[:, 0], next_idx], 1)
next_values = weight.values
next_shape = tf.stack([tf.size(nodes), tf.size(next_nodes)])
next_shape = tf.cast(next_shape, tf.int64)
next_adj = tf.SparseTensor(next_indices, next_values, next_shape)
next_adj = tf.sparse_reorder(next_adj)
nodes_list.append(next_nodes)
adj_list.append(next_adj)
nodes = next_nodes
|
tensorflow.size
| 8,310 |
import tensorflow as tf
# Set shape to remove ambiguity for dense layer.
height, width = params["generator_projection_dims"][0:2]
valid_kernel_size = (
params["discriminator_base_conv_blocks"][0][-1][0]
)
block_conv.set_shape(
[
block_conv.get_shape()[0],
height - valid_kernel_size + 1,
width - valid_kernel_size + 1,
block_conv.get_shape()[-1]]
)
print_obj("use_discriminator_logits_layer", "block_conv", block_conv)
with tf.variable_scope(name_or_scope=self.name, reuse=tf.AUTO_REUSE):
# Flatten final block conv tensor.
block_conv_flat = self.flatten_layer(inputs=block_conv)
print_obj(
"use_discriminator_logits_layer",
"block_conv_flat",
block_conv_flat
)
# Final linear layer for logits.
logits = self.logits_layer(inputs=block_conv_flat)
print_obj("use_discriminator_logits_layer", "logits", logits)
return logits
|
tensorflow.variable_scope
| 8,311 |
import tensorflow as tf
elif norm == 'B':
X = tf.layers.batch_normalization(X, reuse=reuse, training=is_train, name=name)
elif norm == 'G':
X = tf.contrib.layers.group_norm(X, groups=16, scope=scope, reuse=reuse)
if dropout > 0.0:
X = tf.layers.dropout(X, dropout, training=is_train)
if slope < 1.0:
X = tf.nn.leaky_relu(X, slope) if slope > 0.0 else tf.nn.relu(X)
return X
|
tensorflow.layers.dropout
| 8,312 |
import tensorflow as tf
h1 = lrelu(deconv2d(tf.concat([h0, skip_h3], 3),
[self.batch_size, s_h2, s_w2, nf2], name='d_h1', d_h=ns3, d_w=ns3))
h2 = lrelu(deconv2d(tf.concat([h1, skip_h2], 3),
[self.batch_size, s_h1, s_w1, nf1], name='d_h2', d_h=ns2, d_w=ns2))
h3 = lrelu(deconv2d(tf.concat([h2, skip_h1], 3),
[self.batch_size, s_h0, s_w0, nf0], name='d_h3', d_h=ns1, d_w=ns1))
print(h3.get_shape())
h4 = deconv2d(tf.concat([h3, skip_h0], 3),
[self.batch_size, s_h, s_w, self.c_dim], name='d_h4', d_h=ns0, d_w=ns0)
return h4
with tf.variable_scope("deconv") as scope:
output_h4 = decode(trans_z, tgtctx_h3, tgtctx_h2, tgtctx_h1, tgtctx_h0)
scope.reuse_variables()
truthoutput_h4 = decode(tgtimg_z, tgtctx_h3, tgtctx_h2, tgtctx_h1, tgtctx_h0)
self.simloss = tf.reduce_mean((trans_z - tgtimg_z) ** 2) * 1e3
print(tgtimg_z.get_shape())
self.out = output_h4
self.out2 = truthoutput_h4
print(self.out.get_shape())
self.recon1 = tf.nn.l2_loss(tgtimg - self.out)
self.recon2 = tf.nn.l2_loss(tgtimg - self.out2)
if ablation_type == "None":
self.loss = self.recon1 + self.recon2 + self.simloss
elif ablation_type == "L2":
self.loss = self.recon1 + self.recon2
elif ablation_type == "L2L3":
self.loss = self.recon1
elif ablation_type == "L1":
self.loss = self.recon2 + self.simloss
|
tensorflow.reduce_mean
| 8,313 |
import tensorflow as tf
print('feats_other: {}'.format(feats_other_nunroll.get_shape()))
if mode != 'gen':
targets_nunroll = tf.placeholder(dtype, shape=[batch_size, rnn_nunroll])
# TODO: tf.ones acts as an overridable placeholder but this is still awkward
target_weights_nunroll = tf.ones([batch_size, rnn_nunroll], dtype)
# Reshape input tensors to remove nunroll dim; will briefly restore later during RNN if necessary
if cnn_rnn_zack:
feats_audio = tf.reshape(feats_audio_nunroll, shape=[batch_size, rnn_nunroll + zack_hack, audio_nbands, audio_nchannels])
else:
feats_audio = tf.reshape(feats_audio_nunroll, shape=[batch_size * rnn_nunroll, audio_context_len, audio_nbands, audio_nchannels])
feats_other = tf.reshape(feats_other_nunroll, shape=[batch_size * rnn_nunroll, nfeats])
if mode != 'gen':
targets = tf.reshape(targets_nunroll, shape=[batch_size * rnn_nunroll])
target_weights = tf.reshape(target_weights_nunroll, shape=[batch_size * rnn_nunroll])
# CNN
cnn_output = feats_audio
if do_cnn:
layer_last = feats_audio
nfilt_last = audio_nchannels
|
tensorflow.reshape
| 8,314 |
import tensorflow as tf
#im_loss2 = tf.square(self.actions_ph - self.deterministic_actions_ph)*Q_filter_2*self.is_demo_ph
#actor_loss_di1 = tf.reduce_mean(im_loss1)
#actor_loss_di2 = tf.reduce_mean(im_loss2)
self.actor_loss_di = tf.reduce_mean(im_loss1)
imitation_for_priority = tf.reduce_mean(im_loss1,axis=1)
regularizerpi = tf.contrib.layers.l1_l2_regularizer(scale_l1=0.0, scale_l2=1e-5, scope="model/pi")
|
tensorflow.reduce_mean
| 8,315 |
from tensorflow.python.ops import gen_math_ops
def tanh(x, name=None):
"""Computes hyperbolic tangent of `x` element-wise.
Args:
x: A Tensor with type `float`, `double`, `int32`, `complex64`, `int64`,
or `qint32`.
name: A name for the operation (optional).
Returns:
A Tensor with the same type as `x` if `x.dtype != qint32` otherwise
the return type is `quint8`.
"""
with ops.op_scope([x], name, "Tanh") as name:
x = ops.convert_to_tensor(x, name="x")
return gen_math_ops._tanh(x, name=name)
ops.RegisterShape("Abs")(common_shapes.unchanged_shape)
ops.RegisterShape("Ceil")(common_shapes.unchanged_shape)
ops.RegisterShape("Conj")(common_shapes.unchanged_shape)
ops.RegisterShape("Cos")(common_shapes.unchanged_shape)
ops.RegisterShape("Exp")(common_shapes.unchanged_shape)
ops.RegisterShape("Floor")(common_shapes.unchanged_shape)
ops.RegisterShape("Imag")(common_shapes.unchanged_shape)
ops.RegisterShape("Inv")(common_shapes.unchanged_shape)
ops.RegisterShape("IsFinite")(common_shapes.unchanged_shape)
ops.RegisterShape("IsInf")(common_shapes.unchanged_shape)
ops.RegisterShape("IsNan")(common_shapes.unchanged_shape)
|
tensorflow.python.ops.gen_math_ops._tanh
| 8,316 |
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.
(tf.Tensor) A tensor containing the propensity weights.
"""
loss = None
with tf.name_scope(name, "click_weighted_pairwise_loss",[output]):
sliced_output = tf.unstack(output, axis=1)
sliced_label = tf.unstack(labels, axis=1)
sliced_propensity = tf.unstack(propensity_weights, axis=1)
for i in range(len(sliced_output)):
for j in range(i+1, len(sliced_output)):
cur_label_weight = tf.math.sign(sliced_label[i] - sliced_label[j])
cur_propensity = sliced_propensity[i] * sliced_label[i] + sliced_propensity[j] * sliced_label[j]
cur_pair_loss = -tf.exp(sliced_output[i]) / (tf.exp(sliced_output[i]) + tf.exp(sliced_output[j]))
if loss == None:
loss = cur_label_weight * cur_pair_loss * cur_propensity
loss += cur_label_weight * cur_pair_loss * cur_propensity
|
tensorflow.unstack
| 8,317 |
from tensorflow.python.framework import ops
ids, math_ops.equal(ids.values, selected_id))
# TODO(ptucker): Make this more efficient, maybe add a sparse version of
# tf.equal and tf.reduce_any?
# Shape of filled IDs is the same as `ids` with the last dim collapsed to 1.
ids_shape = array_ops.shape(ids, out_type=dtypes.int64)
ids_last_dim = array_ops.size(ids_shape) - 1
filled_selected_id_shape = math_ops.reduced_shape(
ids_shape, array_ops.reshape(ids_last_dim, [1]))
# Intersect `ids` with the selected ID.
filled_selected_id = array_ops.fill(
filled_selected_id_shape, math_ops.to_int64(selected_id))
result = set_ops.set_intersection(filled_selected_id, ids)
return ops.SparseTensor(
indices=result.indices, values=result.values, shape=ids_shape)
def _maybe_select_class_id(labels, predictions_idx, selected_id=None):
"""If class ID is specified, filter all other classes.
Args:
labels: `int64` `Tensor` or `SparseTensor` with shape
[D1, ... DN, num_labels], where N >= 1 and num_labels is the number of
target classes for the associated prediction. Commonly, N=1 and `labels`
has shape [batch_size, num_labels]. [D1, ... DN] must match
`predictions_idx`.
predictions_idx: `int64` `Tensor` of class IDs, with shape [D1, ... DN, k]
where N >= 1. Commonly, N=1 and `predictions_idx` has shape
|
tensorflow.python.framework.ops.SparseTensor
| 8,318 |
import tensorflow as tf
tf.flags.DEFINE_string(
'variable_update', 'parameter_server',
('The method for managing variables: '
'parameter_server, replicated, distributed_replicated, independent'))
tf.flags.DEFINE_boolean(
'use_nccl', True,
'Whether to use nccl all-reduce primitives where possible')
# Distributed training flags.
tf.flags.DEFINE_string('job_name', '',
'One of "ps", "worker", "". Empty for local training')
tf.flags.DEFINE_string('ps_hosts', '', 'Comma-separated list of target hosts')
tf.flags.DEFINE_string('worker_hosts', '',
'Comma-separated list of target hosts')
tf.flags.DEFINE_integer('task_index', 0, 'Index of task within the job')
tf.flags.DEFINE_string('server_protocol', 'grpc', 'protocol for servers')
tf.flags.DEFINE_boolean('cross_replica_sync', True, '')
|
tensorflow.flags.DEFINE_string
| 8,319 |
import tensorflow as tf
if FLAGS.use_tpu:
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
|
tensorflow.contrib.tpu.TPUEstimatorSpec
| 8,320 |
from tensorflow.python.framework import ops
def logical_xor(x, y, name="LogicalXor"):
"""x ^ y = (x | y) & ~(x & y)."""
# TODO(alemi) Make this a cwise op if people end up relying on it.
return logical_and(logical_or(x, y), logical_not(logical_and(x, y)),
name=name)
_OverrideBinaryOperatorHelper(logical_and, "and")
_OverrideBinaryOperatorHelper(logical_or, "or")
_OverrideBinaryOperatorHelper(logical_xor, "xor")
ops.Tensor._override_operator("__lt__", less)
ops.Tensor._override_operator("__le__", less_equal)
ops.Tensor._override_operator("__gt__", greater)
ops.Tensor._override_operator("__ge__", greater_equal)
def range(start, limit, delta=1, name="range"):
"""Creates a sequence of integers.
This operation creates a sequence of integers that begins at `start` and
extends by increments of `delta` up to but not including `limit`.
For example:
```
# 'start' is 3
|
tensorflow.python.framework.ops.Tensor._override_operator
| 8,321 |
import tensorflow as tf
ratios: (height, width)
features_height:
features_width:
offset: (height, width)
Returns:
"""
with tf.variable_scope('anchor_generator'):
if offset is None:
offset = [stride[0]/2, stride[1]/2]
features_width = tf.cast(features_width, tf.int32)
features_height = tf.cast(features_height, tf.int32)
scales = tf.convert_to_tensor(scales, dtype=tf.float32)
ratios = tf.convert_to_tensor(ratios, dtype=tf.float32)
offset = tf.convert_to_tensor(offset, dtype=tf.float32)
scales_grid, ratios_grid = tf.meshgrid(scales,
ratios)
scales_grid = tf.reshape(scales_grid, [-1, 1])
ratios_grid = tf.reshape(ratios_grid, [-1, 1])
ratio_sqrts = tf.sqrt(ratios_grid)
heights = scales_grid / ratio_sqrts * base_size[1]
|
tensorflow.cast
| 8,322 |
import tensorflow as tf
def benchmark_batching_large(self):
with tf.Session() as session:
@dynamic_batching.batch_fn
def f(a, b):
return a + b
outputs = []
for _ in xrange(1000):
outputs.append(f(tf.ones([1, 100000]), tf.ones([1, 100000])))
op_to_benchmark = tf.group(*outputs)
tf.train.start_queue_runners()
self.run_op_benchmark(
name='batching_many_large',
sess=session,
op_or_tensor=op_to_benchmark,
burn_iters=10,
min_iters=50)
|
tensorflow.group
| 8,323 |
import tensorflow as tf
anchor_match_negative_indicator_matrix,
use_semi_hard=use_semi_hard,
anchor_positive_mining_distances=anchor_positive_mining_distances,
anchor_match_mining_distance_matrix=(
anchor_match_mining_distance_matrix)))
def compute_triplet_loss(positive_distances, negative_distances):
losses = tf.nn.relu(positive_distances + margin - negative_distances)
losses = tf.where(
tf.stop_gradient(losses < losses.dtype.max), losses,
tf.zeros_like(losses))
num_nonzero_losses = tf.math.count_nonzero(losses)
loss = tf.math.reduce_mean(losses)
return loss, num_nonzero_losses
loss, num_active_triplets = compute_triplet_loss(anchor_positive_distances,
anchor_negative_distances)
mining_loss, num_active_mining_triplets = compute_triplet_loss(
anchor_positive_mining_distances, anchor_negative_mining_distances)
return (loss, num_active_triplets, anchor_negative_distances, mining_loss,
num_active_mining_triplets, anchor_negative_mining_distances)
|
tensorflow.math.reduce_mean
| 8,324 |
import tensorflow as tf
h_fc1 = tf.nn.relu(tf.add(tf.matmul(h_conv3_flat, W_fc1), b_fc1, 'h_fc1'))
readout = tf.add(tf.matmul(h_fc1, W_fc2), b_fc2, 'h_fc2')
return s, readout, h_fc1
def creat_optimizer(self,readout):
action = tf.placeholder(tf.float32,[None,self.ACTIONS])
y = tf.placeholder(tf.float32,[None])
readout_action = tf.reduce_sum(tf.multiply(readout,action),reduction_indices=1)
cost =tf.reduce_mean(tf.square(y-readout_action))
train_step = tf.train.AdamOptimizer(1e-6).minimize(cost)
return train_step,y,action
#输入一个初始状态s_t,时间为t,之后进行游戏
|
tensorflow.placeholder
| 8,325 |
from tensorflow.python.framework import ops
@ops.RegisterShape("NotEqual")
@ops.RegisterShape("Pow")
@ops.RegisterShape("Sub")
def _BroadcastShape(op):
|
tensorflow.python.framework.ops.RegisterShape
| 8,326 |
from tensorflow.python.ops import math_ops
metric_ops.streaming_recall_at_thresholds, threshold)
return metrics
def _float_weights_or_none(weights):
if weights is None:
return None
return math_ops.to_float(weights)
def _labels_streaming_mean(unused_predictions, labels, weights=None):
return metric_ops.streaming_mean(labels, weights=weights)
def _predictions_streaming_mean(predictions, unused_labels, weights=None):
|
tensorflow.python.ops.math_ops.to_float
| 8,327 |
import tensorflow as tf
initial_state = dense(initial_state, cell_state_size, use_bias=True, name='initial_state_projection',
activation=activation_fn)
if decoder.cell_type.lower() == 'lstm' and decoder.use_lstm_full_state:
initial_output = initial_state
else:
# Last layer's state is the right-most part. Output is the left-most part of an LSTM's state.
initial_output = initial_state[:, -cell_output_size:]
time = tf.constant(0, dtype=tf.int32, name='time')
outputs = tf.TensorArray(dtype=tf.float32, size=time_steps)
samples = tf.TensorArray(dtype=tf.int64, size=time_steps)
inputs = tf.TensorArray(dtype=tf.int64, size=time_steps).unstack(tf.to_int64(tf.transpose(decoder_inputs)))
states = tf.TensorArray(dtype=tf.float32, size=time_steps)
weights = tf.TensorArray(dtype=tf.float32, size=time_steps)
attns = tf.TensorArray(dtype=tf.float32, size=time_steps)
initial_symbol = inputs.read(0) # first symbol is BOS
initial_input = embed(initial_symbol)
|
tensorflow.TensorArray
| 8,328 |
import tensorflow as tf
tf.set_random_seed(0)
|
tensorflow.set_random_seed
| 8,329 |
import tensorflow as tf
pi_loaded.append(load_pi_ckpt(pi_ckpt_path, agent))
return pi_loaded
def create_default_writer_and_save_dir(root_dir):
"""Creates default directories."""
base_dir = osp.expanduser(root_dir)
if not tf.io.gfile.exists(base_dir):
tf.io.gfile.makedirs(base_dir)
tag = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
tb_logdir = osp.join(base_dir, tag, 'tb')
save_dir = osp.join(base_dir, tag, 'train')
tf.io.gfile.makedirs(tb_logdir)
tf.io.gfile.makedirs(save_dir)
writer = tf.contrib.summary.create_file_writer(tb_logdir)
writer.set_as_default()
|
tensorflow.io.gfile.makedirs
| 8,330 |
import tensorflow as tf
def nin(x, num_units, **kwargs):
s = tf.shape(x)
sh = x.get_shape().as_list()
x = tf.reshape(x, [tf.reduce_prod(s[:-1]), sh[-1]])
x = dense(x, num_units, **kwargs)
return tf.reshape(x, [-1] + sh[1:-1] + [num_units])
def dense(x, num_units, scope="dense", training=True, ema=None, init=False, bias_initializer=tf.constant_initializer(0.)):
with tf.variable_scope(scope):
|
tensorflow.reshape
| 8,331 |
import tensorflow as tf
"""Build dynamic graph"""
rnn_outputs, final_state = tf.nn.dynamic_rnn(cell=cell, inputs=rnn_inputs,initial_state=init_state)
|
tensorflow.nn.dynamic_rnn
| 8,332 |
import tensorflow as tf
# 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],
dtype=tf.int32),
|
tensorflow.constant
| 8,333 |
import tensorflow as tf
return roc_sc, auprc_score,accuracy,precision,recall,f ,apk_sc
def construct_placeholders(edge_types):
placeholders = {
'batch': tf.placeholder(tf.int32, name='batch'),
'batch_neg': tf.placeholder(tf.int32, name='batch_neg'),
'batch_node':tf.placeholder(tf.int32,name = 'batch_node'),
'adj_min_batch': tf.placeholder(tf.float32,name='adj_min_batch'),
'sim_min_batch': tf.placeholder(tf.float32,name='sim_min_batch'),
'batch_edge_type_idx': tf.placeholder(tf.int32, shape=(), name='batch_edge_type_idx'),
'batch_row_edge_type': tf.placeholder(tf.int32, shape=(), name='batch_row_edge_type'),
'batch_col_edge_type': tf.placeholder(tf.int32, shape=(), name='batch_col_edge_type'),
'degrees': tf.placeholder(tf.int32),
'dropout': tf.placeholder_with_default(0., shape=()),
}
placeholders.update({
'adj_mats_%d,%d,%d' % (i, j, k): tf.sparse_placeholder(tf.float32)
for i, j in edge_types for k in range(edge_types[i,j])})
placeholders.update({
'feat_%d' % i: tf.sparse_placeholder(tf.float32)
for i, _ in edge_types})
return placeholders
|
tensorflow.placeholder
| 8,334 |
import tensorflow as tf
outputs[-1] * mask_bw, seq_lengths=seq_len, seq_dim=1, batch_dim=0)
out_bw, _ = tf.nn.dynamic_rnn(
gru_bw, inputs_bw, seq_len, initial_state=init_bw, dtype=tf.float32)
out_bw = tf.reverse_sequence(
out_bw, seq_lengths=seq_len, seq_dim=1, batch_dim=0)
outputs.append(tf.concat([out_fw, out_bw], axis=2))
if concat_layers:
res = tf.concat(outputs[1:], axis=2)
else:
res = outputs[-1]
return res
class ptr_net:
|
tensorflow.concat
| 8,335 |
import tensorflow as tf
enc_inp, dec_inp_dict, cell, 2, dec_symbols_dict,
embedding_size=2, feed_previous=True)
outputs_dict2, _ = tf.nn.seq2seq.one2many_rnn_seq2seq(
enc_inp, dec_inp_dict2, cell, 2, dec_symbols_dict,
embedding_size=2, feed_previous=True)
res1 = sess.run(outputs_dict1["0"])
res2 = sess.run(outputs_dict2["0"])
res3 = sess.run(outputs_dict3["0"])
self.assertAllClose(res1, res2)
self.assertAllClose(res1, res3)
def testSequenceLoss(self):
with self.test_session() as sess:
logits = [tf.constant(i + 0.5, shape=[2, 5]) for i in range(3)]
targets = [tf.constant(i, tf.int32, shape=[2]) for i in range(3)]
weights = [tf.constant(1.0, shape=[2]) for i in range(3)]
average_loss_per_example = tf.nn.seq2seq.sequence_loss(
logits, targets, weights,
average_across_timesteps=True,
average_across_batch=True)
res = sess.run(average_loss_per_example)
self.assertAllClose(1.60944, res)
average_loss_per_sequence = tf.nn.seq2seq.sequence_loss(
logits, targets, weights,
average_across_timesteps=False,
average_across_batch=True)
res = sess.run(average_loss_per_sequence)
self.assertAllClose(4.828314, res)
|
tensorflow.constant
| 8,336 |
import tensorflow as tf
rnnout, _, _ = tf.nn.bidirectional_rnn(cell_fw, cell_bw, self._inputs,
dtype=tf.float32,
sequence_length=self.seq_lens)
if proj_size:
out_size = 2 * proj_size
else:
out_size = 2 * hidden_size
self._DoPredictions(out_size, rnnout, self.weights)
self.cost = tf.reduce_mean(self.example_weights * self._xent)
def _DoPredictions(self, in_size, mats, class_weights=None):
"""Takes in an array of states and calculates predictions.
Get the cross-entropy for each example in the vector self._xent.
Args:
in_size: size of the hidden state vectors
mats: list of hidden state vectors
|
tensorflow.reduce_mean
| 8,337 |
import tensorflow as tf
batch_size=FLAGS.eval_batch_size,
use_hvd=FLAGS.use_hvd)
if FLAGS.auto_recover:
hooks.append(tf.data.experimental.CheckpointInputPipelineHook(estimator))
train_spec = tf.estimator.TrainSpec(input_fn=train_input_fn, max_steps=FLAGS.num_train_steps, hooks=hooks)
eval_spec = tf.estimator.EvalSpec(input_fn=eval_input_fn, steps=FLAGS.max_eval_steps)
tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)
if __name__ == "__main__":
# flags.mark_flag_as_required("input_file")
flags.mark_flag_as_required("bert_config_file")
flags.mark_flag_as_required("output_dir")
tf.app.run()
|
tensorflow.app.run
| 8,338 |
from tensorflow.python.ops import array_ops
predictions, labels)
predictions.get_shape().assert_is_compatible_with(labels.get_shape())
count = _create_local('count', [])
mean_prediction = _create_local('mean_prediction', [])
mean_label = _create_local('mean_label', [])
comoment = _create_local('comoment', []) # C_A in update equation
if weights is None:
batch_count = math_ops.to_float(array_ops.size(labels)) # n_B in eqn
weighted_predictions = predictions
weighted_labels = labels
else:
batch_count = math_ops.reduce_sum(
_broadcast_weights(weights, labels)) # n_B in eqn
weighted_predictions = predictions * weights
weighted_labels = labels * weights
|
tensorflow.python.ops.array_ops.size
| 8,339 |
import tensorflow as tf
ent_coef_op = entropy_optimizer.minimize(ent_coef_loss, var_list=self.log_ent_coef)
self.infos_names += ['ent_coef_loss', 'ent_coef']
self.step_ops += [ent_coef_op, ent_coef_loss, self.ent_coef]
# Monitor losses and entropy in tensorboard
tf.summary.scalar('policy_loss', policy_loss)
tf.summary.scalar('qf1_loss', qf1_loss)
tf.summary.scalar('qf2_loss', qf2_loss)
tf.summary.scalar('value_loss', value_loss)
tf.summary.scalar("Imitation_loss",self.actor_loss_di)
tf.summary.scalar('entropy', self.entropy)
tf.summary.scalar('importance weight',tf.reduce_mean(self.weight_ph))
if ent_coef_loss is not None:
tf.summary.scalar('ent_coef_loss', ent_coef_loss)
tf.summary.scalar('ent_coef', self.ent_coef)
tf.summary.scalar('learning_rate', tf.reduce_mean(self.learning_rate_ph))
# Retrieve parameters that must be saved
self.params = tf_util.get_trainable_vars("model")
|
tensorflow.summary.scalar
| 8,340 |
import tensorflow as tf
b_out_initializer = tf.constant_initializer(0.0)
else:
print("Loading Weights")
weights = np.load(self.load_weights_path)
init_state_initializer = tf.constant_initializer(weights['init_state'])
W_in_initializer = tf.constant_initializer(weights['W_in'])
W_rec_initializer = tf.constant_initializer(weights['W_rec'])
W_out_initializer = tf.constant_initializer(weights['W_out'])
b_rec_initializer = tf.constant_initializer(weights['b_rec'])
b_out_initializer = tf.constant_initializer(weights['b_out'])
self.input_connectivity_mask = weights['input_Connectivity']
self.recurrent_connectivity_mask = weights['rec_Connectivity']
self.output_connectivity_mask = weights['output_Connectivity']
self.init_state = tf.get_variable('init_state', [N_batch, N_rec],
|
tensorflow.constant_initializer
| 8,341 |
import tensorflow as tf
return a + b, tf.tile([batch_size], [batch_size])
outputs = [
f(tf.constant([1]), tf.constant([2])),
f(tf.constant([1]), tf.constant([2])),
f(tf.constant([1]), tf.constant([2])),
f(tf.constant([1]), tf.constant([2])),
f(tf.constant([1]), tf.constant([2])),
]
tf.train.start_queue_runners()
results = session.run(outputs)
|
tensorflow.constant
| 8,342 |
import tensorflow as tf
cls_preds: Unscaled log probabilities
alpha: The hyperparameter for adjusting biased samples, default is 0.25
gamma: The hyperparameter for penalizing the easy labeled samples
name: A name for the operation (optional)
Returns:
A 1-D tensor of length batch_size of same type as logits with softmax focal loss
"""
with tf.name_scope(scope, 'focal_loss', [cls_preds, onehot_labels]) as sc:
logits = tf.convert_to_tensor(cls_preds)
onehot_labels = tf.convert_to_tensor(onehot_labels)
precise_logits = tf.cast(logits, tf.float32) if (
logits.dtype == tf.float16) else logits
onehot_labels = tf.cast(onehot_labels, precise_logits.dtype)
predictions = tf.nn.sigmoid(logits)
predictions_pt = tf.where(tf.equal(onehot_labels, 1), predictions, 1.-predictions)
|
tensorflow.convert_to_tensor
| 8,343 |
import tensorflow as tf
(=False) examples.
- *positive_fraction*: desired fraction of positive examples (scalar in [0,1])
in the batch.
Returns:
A boolean tensor of shape [M, N], True for entries which are sampled.
"""
def _minibatch_subsample_fn(inputs):
indicators, targets = inputs
return sample_balanced_positive_negative(tf.cast(indicators, tf.bool),
sample_size,
tf.cast(targets, tf.bool),
positive_fraction=positive_fraction)
return tf.cast(tf.map_fn(_minibatch_subsample_fn, [indicators, labels],
dtype=tf.bool,
parallel_iterations=16,
back_prop=True),
dtype=dtype)
|
tensorflow.cast
| 8,344 |
import tensorflow as tf
if not reduce_instance_dims:
raise NotImplementedError('Per-key elementwise reduction not supported')
with tf.compat.v1.name_scope('mean_and_var_per_key'):
x = tf.cast(x, output_dtype)
key_vocab, key_counts, key_means, key_variances = (
tf_utils.reduce_batch_count_mean_and_var_per_key(
|
tensorflow.cast
| 8,345 |
import tensorflow as tf
def _SparseTensorPlaceholder(self, dtype=None):
if dtype is None: dtype = tf.int32
return tf.SparseTensor(
tf.placeholder(tf.int64),
tf.placeholder(dtype),
tf.placeholder(tf.int64))
|
tensorflow.placeholder
| 8,346 |
import tensorflow as tf
input_image = tf.image.resize(datapoint['image'], (512, 512))
input_mask = tf.image.resize(datapoint['segmentation_mask'], (128, 128))
|
tensorflow.image.resize
| 8,347 |
import tensorflow as tf
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:
image: A 3-D image `Tensor`.
smallest_side: A python integer or scalar `Tensor` indicating the size of
|
tensorflow.greater
| 8,348 |
import tensorflow as tf
for name in sorted(actions):
assignments.append(tf.scatter_update(
ref=self.actions_memory[name],
indices=indices,
updates=actions[name]
))
assignments.append(tf.scatter_update(ref=self.terminal_memory, indices=indices, updates=terminal))
assignments.append(tf.scatter_update(ref=self.reward_memory, indices=indices, updates=reward))
# Add episode indices.
with tf.control_dependencies(control_inputs=assignments):
num_episodes = tf.count_nonzero(input_tensor=terminal, axis=0, dtype=util.tf_dtype('int'))
assignment = tf.assign(
ref=self.episode_indices[self.episode_count: self.episode_count + num_episodes],
value=tf.boolean_mask(tensor=indices, mask=terminal)
)
# Increment episode count.
with tf.control_dependencies(control_inputs=(assignment,)):
assignment = tf.assign_add(ref=self.episode_count, value=num_episodes)
# Increment memory index.
with tf.control_dependencies(control_inputs=(assignment,)):
assignment = tf.assign(
ref=self.episode_indices[-1],
value=tf.where(self.memory_index + num_instances > self.capacity,
self.episode_indices[self.episode_count - 1], self.capacity - 1)
)
|
tensorflow.boolean_mask
| 8,349 |
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
# Mask
# key_masks = tf.sequence_mask(facts_length, tf.shape(facts)[1]) # [B, T]
key_masks = tf.expand_dims(mask, 1) # [B, 1, T]
paddings = tf.ones_like(scores) * (-2 ** 32 + 1)
if not forCnn:
scores = tf.where(key_masks, scores, paddings) # [B, 1, T]
# Scale
# scores = scores / (facts.get_shape().as_list()[-1] ** 0.5)
# Activation
if softmax_stag:
scores = tf.nn.softmax(scores) # [B, 1, T]
|
tensorflow.where
| 8,350 |
from tensorflow.python.framework import ops
@ops.RegisterShape("BatchNormWithGlobalNormalization")
def _BatchNormShape(op):
"""Shape function for BatchNormWithGlobalNormalization op."""
input_shape = op.inputs[0].get_shape().with_rank(4)
mean_shape = op.inputs[1].get_shape().with_rank(1)
var_shape = op.inputs[2].get_shape().with_rank(1)
beta_shape = op.inputs[3].get_shape().with_rank(1)
gamma_shape = op.inputs[4].get_shape().with_rank(1)
mean_shape[0].merge_with(input_shape[3])
var_shape[0].merge_with(input_shape[3])
beta_shape[0].merge_with(input_shape[3])
gamma_shape[0].merge_with(input_shape[3])
return [input_shape]
@ops.RegisterShape("BatchNormWithGlobalNormalizationGrad")
def _BatchNormGradShape(op):
"""Shape function for BatchNormWithGlobalNormalizationGrad op."""
input_shape = op.inputs[0].get_shape().with_rank(4)
mean_shape = op.inputs[1].get_shape().with_rank(1)
var_shape = op.inputs[2].get_shape().with_rank(1)
beta_shape = op.inputs[3].get_shape().with_rank(1)
out_backprop_shape = op.inputs[4].get_shape().with_rank(4)
input_shape = input_shape.merge_with(out_backprop_shape)
vector_dim = input_shape[3]
vector_dim = vector_dim.merge_with(mean_shape[0])
vector_dim = vector_dim.merge_with(var_shape[0])
vector_dim = vector_dim.merge_with(beta_shape[0])
return [input_shape] + ([tensor_shape.vector(vector_dim)] * 4)
|
tensorflow.python.framework.ops.RegisterShape
| 8,351 |
import tensorflow as tf
_, (c, h) = lstm_cell(inputs=tf.concat(axis=1, values=[x[:,t,:], context]), state=[c, h])
logits = self._decode_lstm(x[:,t,:], h, context, dropout=self.dropout, reuse=(t!=0))
loss += tf.reduce_sum(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=captions_out[:, t]) * mask[:, t])
if self.alpha_c > 0:
alphas = tf.transpose(tf.stack(alpha_list), (1, 0, 2)) # (N, T, L)
alphas_all = tf.reduce_sum(alphas, 1) # (N, L)
alpha_reg = self.alpha_c * tf.reduce_sum((16./196 - alphas_all) ** 2)
loss += alpha_reg
return loss / tf.to_float(batch_size)
def build_sampler(self, max_len=20):
|
tensorflow.reduce_sum
| 8,352 |
import tensorflow as tf
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)
|
tensorflow.train.get_checkpoint_state
| 8,353 |
import tensorflow as tf
last_layer_size = layer_size
print('{}: {}'.format(layer_name, last_layer.get_shape()))
export_feat_tensors[layer_name] = last_layer
dnn_output = last_layer
dnn_output_size = last_layer_size
# Logistic regression
with tf.variable_scope('logit') as scope:
logit_w = tf.get_variable('W', shape=[dnn_output_size, 1], initializer=tf.truncated_normal_initializer(stddev=1.0 / dnn_output_size, dtype=dtype), dtype=dtype)
logit_b = tf.get_variable('b', shape=[1], initializer=tf.constant_initializer(0.0), dtype=dtype)
logits = tf.squeeze(tf.nn.bias_add(tf.matmul(dnn_output, logit_w), logit_b), squeeze_dims=[1])
prediction = tf.nn.sigmoid(logits)
prediction_inspect = tf.reshape(prediction, [batch_size, rnn_nunroll])
prediction_final = tf.squeeze(tf.slice(prediction_inspect, [0, rnn_nunroll - 1], [-1, 1]), squeeze_dims=[1])
print('logit: {}'.format(logits.get_shape()))
# Compute loss
if mode != 'gen':
neg_log_lhoods = tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=targets)
if target_weight_strategy == 'rect':
avg_neg_log_lhood = tf.reduce_mean(neg_log_lhoods)
else:
|
tensorflow.matmul
| 8,354 |
from tensorflow.python.ops import state_ops
predictions_idx=predictions_idx, labels=labels, class_id=class_id,
weights=weights)
batch_total_tp = math_ops.to_double(math_ops.reduce_sum(tp))
var = contrib_variables.local_variable(
array_ops.zeros([], dtype=dtypes.float64), name=scope)
return var, state_ops.assign_add(var, batch_total_tp, name='update')
def _sparse_false_positive_at_k(predictions_idx,
labels,
class_id=None,
|
tensorflow.python.ops.state_ops.assign_add
| 8,355 |
import tensorflow as tf
combine_inputs = _WeightedMeanAndVarAccumulator(
count=x_count,
mean=x_mean,
variance=x_variance,
weight=tf.zeros([], tf.float32))
output_shape = ()
if not reduce_instance_dims:
# We need to use tf.expand_dims to artificially add a batch dimension.
output_shape = _get_output_shape_from_input(
tf.expand_dims(x_count, axis=0))
x_mean, x_var = _apply_cacheable_combiner(
WeightedMeanAndVarCombiner(output_dtype.as_numpy_dtype, output_shape),
*combine_inputs)
return x_mean, x_var
@common.log_api_use(common.ANALYZER_COLLECTION)
def tukey_location(x: common_types.TensorType,
|
tensorflow.expand_dims
| 8,356 |
import tensorflow as tf
c = tf.nn.tanh(tf.matmul(features_mean, w_c) + b_c)
return c, h
def _word_embedding(self, inputs, reuse=False):
with tf.variable_scope('word_embedding', reuse=reuse):
w = tf.get_variable('w', [self.V, self.M], initializer=self.emb_initializer)
x = tf.nn.embedding_lookup(w, inputs, name='word_vector') # (N, T, M) or (N, M)
return x
def _project_features(self, features):
with tf.variable_scope('project_features'):
w = tf.get_variable('w', [self.D, self.D], initializer=self.weight_initializer)
features_flat = tf.reshape(features, [-1, self.D])
features_proj = tf.matmul(features_flat, w)
features_proj = tf.reshape(features_proj, [-1, self.L, self.D])
return features_proj
def _attention_layer(self, features, features_proj, h, reuse=False):
with tf.variable_scope('attention_layer', reuse=reuse):
w = tf.get_variable('w', [self.H, self.D], initializer=self.weight_initializer)
b = tf.get_variable('b', [self.D], initializer=self.const_initializer)
w_att = tf.get_variable('w_att', [self.D, 1], initializer=self.weight_initializer)
h_att = tf.nn.relu(features_proj + tf.expand_dims(tf.matmul(h, w), 1) + b) # (N, L, D)
out_att = tf.reshape(tf.matmul(tf.reshape(h_att, [-1, self.D]), w_att), [-1, self.L]) # (N, L)
alpha = tf.nn.softmax(out_att)
context = tf.reduce_sum(features * tf.expand_dims(alpha, 2), 1, name='context') #(N, D)
return context, alpha
|
tensorflow.reshape
| 8,357 |
import tensorflow as tf
|
tensorflow.reshape
| 8,358 |
from tensorflow.python.ops import math_ops
true_positives = _create_local('true_positives', shape=[num_thresholds])
false_negatives = _create_local('false_negatives', shape=[num_thresholds])
true_negatives = _create_local('true_negatives', shape=[num_thresholds])
false_positives = _create_local('false_positives', shape=[num_thresholds])
is_true_positive = math_ops.to_float(
math_ops.logical_and(label_is_pos, pred_is_pos))
is_false_negative = math_ops.to_float(
math_ops.logical_and(label_is_pos, pred_is_neg))
is_false_positive = math_ops.to_float(
math_ops.logical_and(label_is_neg, pred_is_pos))
is_true_negative = math_ops.to_float(
math_ops.logical_and(label_is_neg, pred_is_neg))
if weights is not None:
weights = math_ops.to_float(weights)
|
tensorflow.python.ops.math_ops.logical_and
| 8,359 |
import tensorflow as tf
def metric_fn(masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids,
masked_lm_weights, next_sentence_example_loss,
next_sentence_log_probs, next_sentence_labels):
"""Computes the loss and accuracy of the model."""
masked_lm_log_probs = tf.reshape(masked_lm_log_probs,
[-1, masked_lm_log_probs.shape[-1]])
masked_lm_predictions = tf.argmax(
masked_lm_log_probs, axis=-1, output_type=tf.int32)
masked_lm_example_loss = tf.reshape(masked_lm_example_loss, [-1])
masked_lm_ids = tf.reshape(masked_lm_ids, [-1])
masked_lm_weights = tf.reshape(masked_lm_weights, [-1])
masked_lm_accuracy = tf.metrics.accuracy(
labels=masked_lm_ids,
predictions=masked_lm_predictions,
weights=masked_lm_weights)
masked_lm_mean_loss = tf.metrics.mean(
values=masked_lm_example_loss, weights=masked_lm_weights)
next_sentence_log_probs = tf.reshape(
next_sentence_log_probs, [-1, next_sentence_log_probs.shape[-1]])
next_sentence_predictions = tf.argmax(
next_sentence_log_probs, axis=-1, output_type=tf.int32)
next_sentence_labels = tf.reshape(next_sentence_labels, [-1])
next_sentence_accuracy = tf.metrics.accuracy(
labels=next_sentence_labels, predictions=next_sentence_predictions)
next_sentence_mean_loss = tf.metrics.mean(
values=next_sentence_example_loss)
return {
"masked_lm_accuracy": masked_lm_accuracy,
|
tensorflow.metrics.mean
| 8,360 |
import tensorflow as tf
if time_major:
# (T,B,D) => (B,T,D)
facts = tf.array_ops.transpose(facts, [1, 0, 2])
mask = tf.equal(mask, tf.ones_like(mask))
facts_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer
querry_size = query.get_shape().as_list()[-1]
queries = tf.tile(query, [1, tf.shape(facts)[1]])
queries = tf.reshape(queries, tf.shape(facts))
din_all = tf.concat([queries, facts, queries-facts, queries*facts], axis=-1)
d_layer_1_all = tf.layers.dense(din_all, 80, activation=tf.nn.sigmoid, name='f1_att' + stag)
d_layer_2_all = tf.layers.dense(d_layer_1_all, 40, activation=tf.nn.sigmoid, name='f2_att' + stag)
d_layer_3_all = tf.layers.dense(d_layer_2_all, 1, activation=None, name='f3_att' + stag)
d_layer_3_all = tf.reshape(d_layer_3_all, [-1, 1, tf.shape(facts)[1]])
scores = d_layer_3_all
# Mask
# key_masks = tf.sequence_mask(facts_length, tf.shape(facts)[1]) # [B, T]
key_masks = tf.expand_dims(mask, 1) # [B, 1, T]
paddings = tf.ones_like(scores) * (-2 ** 32 + 1)
scores = tf.where(key_masks, scores, paddings) # [B, 1, T]
# Scale
# scores = scores / (facts.get_shape().as_list()[-1] ** 0.5)
# Activation
if softmax_stag:
|
tensorflow.shape
| 8,361 |
import tensorflow as tf
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)
w_out = tf.get_variable('w_out', [self.M, self.V], initializer=self.weight_initializer)
b_out = tf.get_variable('b_out', [self.V], initializer=self.const_initializer)
|
tensorflow.matmul
| 8,362 |
from tensorflow.python.framework import ops
Args:
ignore_ops: `list` of `string`. Names of ops to ignore.
If None, `GraphDump.IGNORE_OPS` is used.
"""
super(GraphDump, self).__init__()
self._ignore_ops = ignore_ops or GraphDump.IGNORE_OPS
self._data = {}
def begin(self, max_steps=None):
super(GraphDump, self).begin(max_steps=max_steps)
self._tensors = []
graph = ops.get_default_graph()
graph_def = graph.as_graph_def()
for node in graph_def.node:
if node.op in self._ignore_ops:
continue
logging.info("op=%s name=%s.", node.op, node.name)
try:
self._tensors.append(graph.get_tensor_by_name(node.name + ":0"))
except KeyError:
pass
def step_begin(self, step):
|
tensorflow.python.framework.ops.get_default_graph
| 8,363 |
import tensorflow as tf
scales = tf.maximum(scales, lower_bound)
print("Hyper Decoder")
z_strings, z_min_v, z_max_v = entropy_bottleneck.compress(zs)
z_shape = tf.shape(zs)[:]
print("Entropy Encode (Hyper)")
y_strings, y_min_v, y_max_v = conditional_entropy_model.compress(ys, locs, scales)
|
tensorflow.shape
| 8,364 |
import tensorflow as tf
indices = tf.stack((batch_nums, step_nums, passage_word_idx), axis=2) # shape (batch_size, passage_length, 3)
indices = tf.reshape(indices, [-1, 3]) #[batch_size * passage_length, 3]
indices = tf.cast(indices, tf.int64)
shape = [batch_size, passage_length, extended_vsize]
shape = tf.cast(shape, tf.int64)
attn_dist = tf.reshape(attn_dist, shape=[-1]) # [batch_size*passage_length]
one_hot_spare_rep = tf.SparseTensor(indices=indices, values=attn_dist, dense_shape=shape) # [batch_size, passage_length, extended_vsize]
|
tensorflow.cast
| 8,365 |
import tensorflow as tf
assert (len(filter_dims) == 3) # height, width and num_channels out
assert (len(stride_dims) == 2) # stride height and width
input_dims = [b_size, input_dims[1], input_dims[2], input_dims[3]]
num_channels_in = input_dims[-1]
filter_h, filter_w, num_channels_out = filter_dims
stride_h, stride_w = stride_dims
output_dims = get_deconv2d_output_dims(input_dims,
filter_dims,
stride_dims,
padding)
with tf.variable_scope(scope):
deconv_weight = tf.Variable(
tf.random_normal([filter_h, filter_w, num_channels_out, num_channels_in], stddev=0.1, dtype=tf.float32))
deconv_bias = tf.Variable(tf.zeros([num_channels_out], dtype=tf.float32))
map = tf.nn.conv2d_transpose(input_data, deconv_weight, output_dims, strides=[1, stride_h, stride_w, 1],
padding=padding)
map = tf.nn.bias_add(map, deconv_bias)
activation = non_linear_fn(map)
# print(scope, 'out', activation.get_shape().as_list())
return activation
|
tensorflow.random_normal
| 8,366 |
import tensorflow as tf
import numpy as np
import tvm
from tvm import relay
from tvm.contrib import graph_runtime
from tvm.relay.testing.config import ctx_list
import keras
import tensorflow as tf
from tensorflow import keras as tf_keras
# prevent Keras from using up all gpu memory
if tf.executing_eagerly():
gpus = tf.config.list_physical_devices('GPU')
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
else:
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.5
set_session(tf.Session(config=config))
def pytest_generate_tests(metafunc):
|
tensorflow.config.list_physical_devices
| 8,367 |
import tensorflow as tf
fields.InputDataFields.image:
tf.placeholder(tf.float32, [None, None, 3]),
|
tensorflow.placeholder
| 8,368 |
import tensorflow as tf
stride=[2, 2, 2],
padding='VALID'):
""" 3D avg pooling.
Args:
inputs: 5-D tensor BxDxHxWxC
kernel_size: a list of 3 ints
stride: a list of 3 ints
Returns:
Variable tensor
"""
with tf.variable_scope(scope) as sc:
kernel_d, kernel_h, kernel_w = kernel_size
stride_d, stride_h, stride_w = stride
outputs = tf.nn.avg_pool3d(inputs,
ksize=[1, kernel_d, kernel_h, kernel_w, 1],
strides=[1, stride_d, stride_h, stride_w, 1],
padding=padding,
name=sc.name)
return outputs
def batch_norm_template(inputs, is_training, scope, moments_dims, bn_decay):
|
tensorflow.variable_scope
| 8,369 |
import tensorflow as tf
rpn_loss_box = self._smooth_l1_loss(rpn_bbox_pred, rpn_bbox_targets, rpn_bbox_inside_weights,
rpn_bbox_outside_weights, sigma=sigma_rpn, dim=[1, 2, 3])
# RCNN, class loss
cls_score = self._predictions["cls_score"]
label = tf.reshape(self._proposal_targets["labels"], [-1])
cross_entropy = tf.reduce_mean(
tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=tf.reshape(cls_score, [-1, self._num_classes]), labels=label)) # logits仍然是向量,label只含正确答案
|
tensorflow.reshape
| 8,370 |
import tensorflow as tf
# 定義變數
# self.tfs = tf.placeholder(tf.float32, [None, image_features], 'state')
self.tfdc_r = tf.placeholder(tf.float32, [None, 1], 'discounted_r')
# 建立網路層
l1 = tf.layers.dense(
inputs=pre_s,
units=100, # number of hidden units
activation=tf.nn.relu,
name='l1'
)
self.v = tf.layers.dense(
inputs=l1,
units=1, # output units
activation=None,
name='V'
)
# 計算損益
self.advantage = self.tfdc_r - self.v
self.closs = tf.reduce_mean(tf.square(self.advantage))
self.ctrain_op = tf.train.AdamOptimizer(C_LR).minimize(self.closs)
|
tensorflow.layers.dense
| 8,371 |
import tensorflow as tf
'The sigma of Gaussian which generate the target heatmap.')
tf.app.flags.DEFINE_float(
'bbox_border', 25.,
'The nearest distance of the crop border to al keypoints.')
tf.app.flags.DEFINE_integer(
'train_epochs', 50,
'The number of epochs to use for training.')
tf.app.flags.DEFINE_integer(
'epochs_per_eval', 20,
'The number of training epochs to run between evaluations.')
tf.app.flags.DEFINE_integer(
'batch_size', 10,
'Batch size for training and evaluation.')
tf.app.flags.DEFINE_integer(
|
tensorflow.app.flags.DEFINE_integer
| 8,372 |
import tensorflow as tf
for idx, (x, m) in enumerate(zip(xs, ms)):
c = c*(1-m)
h = h*(1-m)
z = _ln(tf.matmul(x, wx), gx, bx) + _ln(tf.matmul(h, wh), gh, bh) + b
i, f, o, u = tf.split(axis=1, num_or_size_splits=4, value=z)
i = tf.nn.sigmoid(i)
f = tf.nn.sigmoid(f)
o = tf.nn.sigmoid(o)
u = tf.tanh(u)
c = f*c + i*u
h = o*tf.tanh(_ln(c, gc, bc))
xs[idx] = h
s = tf.concat(axis=1, values=[c, h])
return xs, s
|
tensorflow.nn.sigmoid
| 8,373 |
import tensorflow as tf
'epochs_per_eval', 20,
'The number of training epochs to run between evaluations.')
tf.app.flags.DEFINE_integer(
'batch_size', 10,
'Batch size for training and evaluation.')
tf.app.flags.DEFINE_integer(
'xt_batch_size', 10,
'Batch size for training and evaluation.')
tf.app.flags.DEFINE_boolean(
'use_ohkm', True,
|
tensorflow.app.flags.DEFINE_integer
| 8,374 |
import tensorflow as tf
initializer=tf.constant_initializer(0),
trainable=False)
with tf.colocate_with(self.means):
self.ema_means = tf.get_variable(
|
tensorflow.colocate_with
| 8,375 |
import tensorflow as tf
self.baseline = tf.Variable(0.0, dtype=tf.float32, trainable=False)
baseline_update = tf.assign_sub(
self.baseline, (1 - self.bl_dec) * (self.baseline - self.reward))
with tf.control_dependencies([baseline_update]):
self.reward = tf.identity(self.reward)
self.loss = self.sample_log_prob * (self.reward - self.baseline)
self.train_step = tf.Variable(0, dtype=tf.int32, trainable=False, name="train_step")
|
tensorflow.identity
| 8,376 |
import tensorflow as tf
def gaussian_kernel(self,size,mean,std):
"""Makes 2D gaussian Kernel for convolution."""
d = tfp.distributions.Normal(mean, std)
vals = d.prob(tf.range(start = -size, limit = size + 1, dtype = tf.float32))
gauss_kernel = tf.einsum('i,j->ij',vals,vals)
return gauss_kernel / tf.reduce_sum(gauss_kernel)
def get_random_patch_size(self):
return np.random.choice([1,2,4,8])
def scramble(self,x):
# assume square patch
n_row,n_col,n_channel = x.shape
n_patch = n_row*n_col // (self.size**2)
patches = tf.image.extract_patches(tf.expand_dims(x,0),sizes=[1,self.size,self.size,1],strides=[1,self.size,self.size,1],rates=[1, 1, 1, 1],padding='VALID')
patches = tf.reshape(patches,[n_patch,self.size,self.size,n_channel])
patches = tf.random.shuffle(patches)
# rand_idx = tf.reshape(tf.random.shuffle(tf.range(0,n_patch)),[n_patch])
# patches = tf.gather(patches, rand_idx, axis=0)
rows = tf.split(patches,n_col//self.size,axis=0)
rows = [tf.concat(tf.unstack(x),axis=1) for x in rows]
x_aug = tf.concat(rows,axis=0)
x_aug = tf.convert_to_tensor(x_aug)
return tf.concat([x, x_aug],axis=2)
def mix_scramble(self,x):
# assume square patch
# sizes = tf.convert_to_tensor([1,2,4,8])
|
tensorflow.expand_dims
| 8,377 |
import tensorflow as tf
_, top_antecedents = tf.nn.top_k(fast_antecedent_scores, c, sorted=False) # [k, c]
top_antecedents_mask = util.batch_gather(antecedents_mask, top_antecedents) # [k, c]
top_fast_antecedent_scores = util.batch_gather(fast_antecedent_scores, top_antecedents) # [k, c]
top_antecedent_offsets = util.batch_gather(antecedent_offsets, top_antecedents) # [k, c]
return top_antecedents, top_antecedents_mask, top_fast_antecedent_scores, top_antecedent_offsets
def distance_pruning(self, top_span_emb, top_span_mention_scores, c):
k = util.shape(top_span_emb, 0)
top_antecedent_offsets = tf.tile(tf.expand_dims(tf.range(c) + 1, 0), [k, 1]) # [k, c]
raw_top_antecedents = tf.expand_dims(tf.range(k), 1) - top_antecedent_offsets # [k, c]
top_antecedents_mask = raw_top_antecedents >= 0 # [k, c]
top_antecedents = tf.maximum(raw_top_antecedents, 0) # [k, c]
top_fast_antecedent_scores = tf.expand_dims(top_span_mention_scores, 1) + tf.gather(top_span_mention_scores, top_antecedents) # [k, c]
top_fast_antecedent_scores += tf.log(tf.to_float(top_antecedents_mask)) # [k, c]
return top_antecedents, top_antecedents_mask, top_fast_antecedent_scores, top_antecedent_offsets
def get_predictions_and_loss(self, tokens, context_word_emb, head_word_emb, lm_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids):
self.dropout = self.get_dropout(self.config["dropout_rate"], is_training)
self.lexical_dropout = self.get_dropout(self.config["lexical_dropout_rate"], is_training)
self.lstm_dropout = self.get_dropout(self.config["lstm_dropout_rate"], is_training)
num_sentences = tf.shape(context_word_emb)[0]
|
tensorflow.maximum
| 8,378 |
import tensorflow as tf
FLAGS.cl_num_layers) + 2
self.assertEqual(len(tf.trainable_variables()), expected_num_vars)
def testEvalGraph(self):
_, _ = graphs.VatxtModel().eval_graph()
def testBidirEvalGraph(self):
_, _ = graphs.VatxtBidirModel().eval_graph()
if __name__ == '__main__':
tf.test.main()
|
tensorflow.test.main
| 8,379 |
import tensorflow as tf
features = sp.identity(features.shape[0]) # featureless
# Some preprocessing
adj_norm = preprocess_graph(adj)
# Define placeholders
placeholders = {
'features': tf.sparse_placeholder(tf.float32),
'adj': tf.sparse_placeholder(tf.float32),
'adj_orig': tf.sparse_placeholder(tf.float32),
'dropout': tf.placeholder_with_default(0., shape=())
}
num_nodes = adj.shape[0]
features = sparse_to_tuple(features.tocoo())
|
tensorflow.sparse_placeholder
| 8,380 |
import tensorflow as tf
tf.add_to_collection(self._initial_state_name, state_tuple.c)
tf.add_to_collection(self._initial_state_name, state_tuple.h)
for state_tuple in self._final_state:
tf.add_to_collection(self._final_state_name, state_tuple.c)
tf.add_to_collection(self._final_state_name, state_tuple.h)
def import_state_tuples(self, state_tuples, name, num_replicas):
restored = []
for i in range(len(state_tuples) * num_replicas):
c = tf.get_collection_ref(name)[2 * i + 0]
h = tf.get_collection_ref(name)[2 * i + 1]
restored.append(tf.contrib.rnn.LSTMStateTuple(c, h))
return tuple(restored)
def import_ops(self):
if self._is_training:
self._train_op = tf.get_collection_ref('train_op')[0]
self._lr = tf.get_collection_ref('lr')[0]
self._new_lr = tf.get_collection_ref('new_lr')[0]
self._lr_update = tf.get_collection_ref('lr_update')[0]
rnn_params = tf.get_collection_ref('rnn_params')
if self._cell and rnn_params:
|
tensorflow.contrib.rnn.LSTMStateTuple
| 8,381 |
import tensorflow as tf
cell_fw = util.CustomLSTMCell(self.config["contextualization_size"], num_sentences, self.lstm_dropout)
with tf.variable_scope("bw_cell"):
cell_bw = util.CustomLSTMCell(self.config["contextualization_size"], num_sentences, self.lstm_dropout)
state_fw = tf.contrib.rnn.LSTMStateTuple(tf.tile(cell_fw.initial_state.c, [num_sentences, 1]), tf.tile(cell_fw.initial_state.h, [num_sentences, 1]))
state_bw = tf.contrib.rnn.LSTMStateTuple(tf.tile(cell_bw.initial_state.c, [num_sentences, 1]), tf.tile(cell_bw.initial_state.h, [num_sentences, 1]))
(fw_outputs, bw_outputs), _ = tf.nn.bidirectional_dynamic_rnn(
cell_fw=cell_fw,
|
tensorflow.tile
| 8,382 |
import tensorflow as tf
of this model under a given target distribution.
Parameters:
y_true: tensor, observations.
y_pred: tensor, output of network.
Returns:
loss value, means negative log-likelihood.
"""
logL = 0
# pre-calculate cumsum
cumsum_y_pred = tf.cumsum(y_pred)
hazard_ratio = tf.exp(y_pred)
cumsum_hazard_ratio = tf.cumsum(hazard_ratio)
if self.train_data['ties'] == 'noties':
log_risk = tf.log(cumsum_hazard_ratio)
likelihood = y_pred - log_risk
# dimension for E: np.array -> [None, 1]
uncensored_likelihood = likelihood * y_true
logL = -tf.reduce_sum(uncensored_likelihood)
else:
# Loop for death times
for t in self.train_data['failures']:
tfail = self.train_data['failures'][t]
trisk = self.train_data['atrisk'][t]
d = len(tfail)
|
tensorflow.cumsum
| 8,383 |
import tensorflow as tf
:param before_padding: [batch_size] tensor of before_padding values.
:param window_size: scalar window size.
:return: [batch_size, window_size] boolean tensor mask.
"""
return tf.logical_not(tf.sequence_mask(before_padding, maxlen=window_size))
def _right_mask(after_padding, window_size):
|
tensorflow.sequence_mask
| 8,384 |
import tensorflow as tf
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)
if task_name != "sts-b":
probabilities = tf.nn.softmax(logits, axis=-1)
predictions = tf.argmax(probabilities, axis=-1, output_type=tf.int32)
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)
else:
probabilities = logits
logits = tf.squeeze(logits, [-1])
predictions = logits
per_example_loss = tf.square(logits - labels)
loss = tf.reduce_mean(per_example_loss)
return (loss, per_example_loss, probabilities, logits, predictions)
|
tensorflow.nn.log_softmax
| 8,385 |
import tensorflow as tf
output_shape=shapes,
strides=self.strides,
padding='SAME',
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):
|
tensorflow.assign
| 8,386 |
import tensorflow as tf
Shape [batch_size, embeddings_dim]
Return: pull away term loss
"""
with tf.name_scope(name):
norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))
normalized_embeddings = embeddings / norm
similarity = tf.matmul(normalized_embeddings, normalized_embeddings, transpose_b=True)
batch_size = tf.cast(tf.shape(embeddings)[0], tf.float32)
pt_loss = (tf.reduce_sum(similarity) - batch_size) / \
(batch_size * (batch_size - 1))
return pt_loss
def log_sum_exp(x):
"""numerically stable log_sum_exp implementation that prevents overflow."""
axis = len(x.get_shape()) - 1
m = tf.reduce_max(x, axis)
|
tensorflow.reduce_sum
| 8,387 |
import tensorflow as tf
def next_num(num):
# This creates a cycle of length 136.
return tf.mod((num * 13), 137)
num = tf.reshape(tf.mod(seed, 136) + 1, (1,))
result = num
for _ in range(num_elements - 1):
num = next_num(num)
result = tf.concat([result, num], 0)
return tf.to_float(result)
@encoding_stage.tf_style_encoding_stage
class PlusRandomNumEncodingStage(encoding_stage.EncodingStageInterface):
"""[Example] encoding stage, adding random values given a random seed.
|
tensorflow.concat
| 8,388 |
from tensorflow.python.ops import array_ops
# Flatten the input if its rank > 1.
predictions_rank = predictions.get_shape().ndims
if predictions_rank > 1:
predictions = array_ops.reshape(predictions, [-1])
labels_rank = labels.get_shape().ndims
if labels_rank > 1:
labels = array_ops.reshape(labels, [-1])
weights = _mask_weights(ignore_mask, weights)
if weights is not None:
weights_rank = weights.get_shape().ndims
if weights_rank > 1:
weights = array_ops.reshape(weights, [-1])
# Accumulate the prediction to current confusion matrix.
current_cm = confusion_matrix_ops.confusion_matrix(
predictions, labels, num_classes, weights=weights, dtype=cm_dtype)
update_op = state_ops.assign_add(total_cm, current_cm)
def compute_mean_iou(name):
"""Compute the mean intersection-over-union via the confusion matrix."""
sum_over_row = math_ops.to_float(math_ops.reduce_sum(total_cm, 0))
sum_over_col = math_ops.to_float(math_ops.reduce_sum(total_cm, 1))
cm_diag = math_ops.to_float(array_ops.diag_part(total_cm))
denominator = sum_over_row + sum_over_col - cm_diag
|
tensorflow.python.ops.array_ops.reshape
| 8,389 |
import tensorflow as tf
# Compute the gradients for the clones.
total_loss, clones_gradients = optimize_clones(clones, optimizer)
if clones_gradients:
if summarize_gradients:
# Add summaries to the gradients.
summaries |= set(_add_gradients_summaries(clones_gradients))
# Create gradient updates.
grad_updates = optimizer.apply_gradients(clones_gradients,
global_step=global_step)
update_ops.append(grad_updates)
update_op = tf.group(*update_ops)
train_op = control_flow_ops.with_dependencies([update_op], total_loss,
name='train_op')
else:
clones_losses = []
regularization_losses = tf.get_collection(
tf.GraphKeys.REGULARIZATION_LOSSES)
for clone in clones:
with tf.name_scope(clone.scope):
clone_loss = _gather_clone_loss(clone, len(clones),
regularization_losses)
if clone_loss is not None:
clones_losses.append(clone_loss)
# Only use regularization_losses for the first clone
|
tensorflow.group
| 8,390 |
import tensorflow as tf
dialogue_state_size +
action_templates_embedding_size
)
# condition on the dialogue state and the decoded template
projection = linear(
input=dialogue_state_action_template,
input_size=dialogue_state_action_template_size,
output_size=dialogue_state_action_template_size,
name='linear_projection_1_predictions_arguments'
)
projection = batch_norm_lin(projection, dialogue_state_action_template_size, self.phase_train,
name='linear_projection_1_predictions_arguments_bn')
activation = tf.nn.relu(projection)
activation = dropout(activation, self.dropout_keep_prob)
projection = linear(
input=activation,
input_size=dialogue_state_action_template_size,
output_size=dialogue_state_action_template_size,
name='linear_projection_2_predictions_arguments'
)
projection = batch_norm_lin(projection, dialogue_state_action_template_size, self.phase_train,
name='linear_projection_2_predictions_arguments_bn')
activation = tf.nn.relu(projection)
activation = dropout(activation, self.dropout_keep_prob)
|
tensorflow.nn.relu
| 8,391 |
import tensorflow as tf
d = d.batch(self.config['eval_batch_size']*self.n_gpus)
self.dataset_iterators[n] = d.make_initializable_iterator()
output_types = d.output_types
output_shapes = d.output_shapes
self.datasets[n] = d
# Perform compatibility checks with the inputs of the child model
for i, spec in self.input_spec.items():
assert i in output_shapes
tf.TensorShape(output_shapes[i]).assert_is_compatible_with(
tf.TensorShape(spec['shape']))
# Used for input shapes of the prediction network
if self.data_shape is None:
self.data_shape = output_shapes
# Handle for the feedable iterator
self.handle = tf.placeholder(tf.string, shape=[])
|
tensorflow.TensorShape
| 8,392 |
import tensorflow as tf
reward = tf.zeros_like(indices, tf.float32)
done = tf.zeros_like(indices, tf.bool)
with tf.control_dependencies([
tf.scatter_update(self._observ, indices, observ),
tf.scatter_update(self._reward, indices, reward),
tf.scatter_update(self._done, indices, done)]):
|
tensorflow.scatter_update
| 8,393 |
import tensorflow as tf
'image/channels': tf.FixedLenFeature([1], tf.int64),
'image/shape': tf.FixedLenFeature([3], tf.int64),
'image/object/bbox/xmin': tf.VarLenFeature(dtype=tf.float32),
'image/object/bbox/ymin': tf.VarLenFeature(dtype=tf.float32),
'image/object/bbox/xmax': tf.VarLenFeature(dtype=tf.float32),
'image/object/bbox/ymax': tf.VarLenFeature(dtype=tf.float32),
'image/object/bbox/label': tf.VarLenFeature(dtype=tf.int64),
'image/object/bbox/difficult': tf.VarLenFeature(dtype=tf.int64),
'image/object/bbox/truncated': tf.VarLenFeature(dtype=tf.int64),
}
items_to_handlers = {
'image': slim.tfexample_decoder.Image('image/encoded', 'image/format'),
'shape': slim.tfexample_decoder.Tensor('image/shape'),
'object/bbox': slim.tfexample_decoder.BoundingBox(
['xmin', 'ymin', 'xmax', 'ymax'], 'image/object/bbox/'),
'object/label': slim.tfexample_decoder.Tensor('image/object/bbox/label'),
|
tensorflow.VarLenFeature
| 8,394 |
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,
|
tensorflow.constant
| 8,395 |
import tensorflow as tf
# Number of steps to train model.
TRAIN_STEPS = 1
CONFIG = tf.ConfigProto(device_count={"GPU": 0})
|
tensorflow.ConfigProto
| 8,396 |
import tensorflow as tf
# if src_enc is not None:
# assert self.is_decoder
# assert src_enc.size(0) == bs
# generate masks
mask, attn_mask = get_masks(slen, lengths, self.causal, padding_mask=attention_mask)
# if self.is_decoder and src_enc is not None:
# src_mask = torch.arange(src_len.max(), dtype=torch.long, device=lengths.device) < src_len[:, None]
# position_ids
if position_ids is None:
position_ids = tf.expand_dims(tf.range(slen), axis=0)
else:
# assert shape_list(position_ids) == [bs, slen] # (slen, bs)
tf.debugging.assert_equal(
shape_list(position_ids), [bs, slen]
), f"Position id shape {shape_list(position_ids)} and input shape {[bs, slen]} mismatched"
# position_ids = position_ids.transpose(0, 1)
# langs
if langs is not None:
# assert shape_list(langs) == [bs, slen] # (slen, bs)
|
tensorflow.range
| 8,397 |
from tensorflow.python.ops import state_ops
for v in var_list:
self._zeros_slot(v, "vstar", self._name)
self._zeros_slot(v, "gold", self._name)
def _apply_dense(self, grad, var):
lr_t = math_ops.cast(self._lr_t, var.dtype.base_dtype)
mu_t = math_ops.cast(self._mu_t, var.dtype.base_dtype)
vstar = self.get_slot(var, "vstar")
gold = self.get_slot(var, "gold")
var_update = state_ops.assign_sub(var, lr_t*(grad + gold + mu_t*(var-vstar))) #Update 'ref' by subtracting 'value
#Create an op that groups multiple operations.
#When this op finishes, all ops in input have finished
return control_flow_ops.group(*[var_update,])
def _apply_sparse_shared(self, grad, var, indices, scatter_add):
lr_t = math_ops.cast(self._lr_t, var.dtype.base_dtype)
mu_t = math_ops.cast(self._mu_t, var.dtype.base_dtype)
vstar = self.get_slot(var, "vstar")
gold = self.get_slot(var, "gold") # glod is not sparse
|
tensorflow.python.ops.state_ops.assign_sub
| 8,398 |
import tensorflow as tf
def _generate_synthetic_snli_data_batch(sequence_length,
batch_size,
vocab_size):
"""Generate a fake batch of SNLI data for testing."""
with tf.device("cpu:0"):
labels = tf.random_uniform([batch_size], minval=1, maxval=4, dtype=tf.int64)
prem = tf.random_uniform(
(sequence_length, batch_size), maxval=vocab_size, dtype=tf.int64)
|
tensorflow.device
| 8,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.