seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
import tensorflow as tf
("gpu" if tfe.num_gpus() > 0 else "cpu"),
iters=num_epochs * num_batches,
extras={"examples_per_sec": examples_per_sec},
wall_time=wall_time)
if __name__ == "__main__":
tf.enable_eager_execution()
tf.test.main()
| tensorflow.enable_eager_execution | 4,200 |
import tensorflow as tf
nin = x.get_shape()[1].value
w = tf.get_variable("w", [nin, nh], initializer=ortho_init(init_scale))
b = tf.get_variable("b", [nh], initializer=tf.constant_initializer(init_bias))
return tf.matmul(x, w)+b
def batch_to_seq(h, nbatch, nsteps, flat=False):
if flat:
h = tf.reshape(h, [nbatch, nsteps])
else:
h = tf.reshape(h, [nbatch, nsteps, -1])
return [tf.squeeze(v, [1]) for v in tf.split(axis=1, num_or_size_splits=nsteps, value=h)]
def seq_to_batch(h, flat = False):
shape = h[0].get_shape().as_list()
| tensorflow.reshape | 4,201 |
import tensorflow as tf
v_size = np.prod(np.array(v.shape.as_list())).tolist() # mutiple all dimension size
total_size += v_size
tf.logging.info("Total trainable variables size: %d", total_size)
| tensorflow.logging.info | 4,202 |
import tensorflow as tf
# session.run(update_target_fn)
# you should update every target_update_freq steps, and you may find the
# variable num_param_updates useful for this (it was initialized to 0)
obs_t_batch,act_t_batch,rew_t_batch,obs_tp1_batch,done_mask_batch = replay_buffer.sample(batch_size)
if not model_initialized:
initialize_interdependent_variables(session,tf.global_variables(),
{obs_t_ph: obs_t_batch,obs_tp1_ph: obs_tp1_batch,})
model_initialized = True
session.run([total_error,train_fn],
feed_dict={obs_t_ph: obs_t_batch,act_t_ph: act_t_batch, rew_t_ph: rew_t_batch,
obs_tp1_ph: obs_tp1_batch,done_mask_ph: done_mask_batch,
| tensorflow.global_variables | 4,203 |
import tensorflow as tf
b_t2 = utils.bias_variable([deconv_shape2[3].value], name="b_t2")
conv_t2 = utils.conv2d_transpose_strided(fuse_1, W_t2, b_t2, output_shape=tf.shape(image_net["pool3"]))
fuse_2 = tf.add(conv_t2, image_net["pool3"], name="fuse_2")
shape = tf.shape(image)
deconv_shape3 = tf.stack([shape[0], shape[1], shape[2], 3])
W_t3 = utils.weight_variable([16, 16, 3, deconv_shape2[3].value], name="W_t3")
b_t3 = utils.bias_variable([3], name="b_t3")
conv_t3 = tf.nn.relu(utils.conv2d_transpose_strided(fuse_2, W_t3, b_t3, output_shape=deconv_shape3, stride=8))
annotation_pred = tf.argmax(conv_t3, dimension=3, name="prediction")
return tf.expand_dims(annotation_pred, dim=3), conv_t3
def train(loss_val, var_list):
optimizer = tf.train.AdamOptimizer(FLAGS.learning_rate)
grads = optimizer.compute_gradients(loss_val, var_list=var_list)
if FLAGS.debug:
# print(len(var_list))
| tensorflow.argmax | 4,204 |
import tensorflow as tf
blocked_cols = tf.Dimension(0)
batch_shape = tf.TensorShape(None)
| tensorflow.TensorShape | 4,205 |
import tensorflow as tf
` See the top of the file for details.
"""
with tf.variable_scope(scope, reuse=reuse):
observations_ph = U.ensure_tf_input(make_obs_ph("observation"))
stochastic_ph = tf.placeholder(tf.bool, (), name="stochastic")
update_eps_ph = tf.placeholder(tf.float32, (), name="update_eps")
eps = tf.get_variable("eps", (), initializer=tf.constant_initializer(0))
| tensorflow.placeholder | 4,206 |
import tensorflow as tf
img_w = img_w_batch[i]
inputs_list.append([img, gtboxes_and_label_h, gtboxes_and_label_r, num_objects, img_h, img_w])
tower_grads = []
biases_regularizer = tf.no_regularizer
weights_regularizer = tf.contrib.layers.l2_regularizer(cfgs.WEIGHT_DECAY)
with tf.variable_scope(tf.get_variable_scope()):
for i in range(num_gpu):
with tf.device('/gpu:%d' % i):
with tf.name_scope('tower_%d' % i):
with slim.arg_scope(
[slim.model_variable, slim.variable],
device='/device:CPU:0'):
with slim.arg_scope([slim.conv2d, slim.conv2d_in_plane,
slim.conv2d_transpose, slim.separable_conv2d,
slim.fully_connected],
weights_regularizer=weights_regularizer,
biases_regularizer=biases_regularizer,
| tensorflow.device | 4,207 |
import tensorflow as tf
v = tf.Variable(tf.random_normal([attention_size], stddev=0.1))
with tf.name_scope('v'):
# Applying fully connected layer with non-linear activation to each of the B*T timestamps;
# the shape of `tmp` is (B,T,D)*(D,A)=(B,T,A), where A=attention_size
tmp1 = tf.tensordot(facts, w1, axes=1)
tmp2 = tf.tensordot(query, w2, axes=1)
tmp2 = tf.reshape(tmp2, [-1, 1, tf.shape(tmp2)[-1]])
tmp = tf.tanh((tmp1 + tmp2) + b)
# For each of the timestamps its vector of size A from `tmp` is reduced with `v` vector
v_dot_tmp = tf.tensordot(tmp, v, axes=1, name='v_dot_tmp') # (B,T) shape
key_masks = mask # [B, 1, T]
# key_masks = tf.expand_dims(mask, 1) # [B, 1, T]
paddings = tf.ones_like(v_dot_tmp) * (-2 ** 32 + 1)
v_dot_tmp = tf.where(key_masks, v_dot_tmp, paddings) # [B, 1, T]
alphas = tf.nn.softmax(v_dot_tmp, name='alphas') # (B,T) shape
# Output of (Bi-)RNN is reduced with attention vector; the result has (B,D) shape
#output = tf.reduce_sum(facts * tf.expand_dims(alphas, -1), 1)
output = facts * tf.expand_dims(alphas, -1)
output = tf.reshape(output, tf.shape(facts))
# output = output / (facts.get_shape().as_list()[-1] ** 0.5)
if not return_alphas:
return output
else:
return output, alphas
def din_attention(query, facts, attention_size, mask, stag='null', mode='SUM', softmax_stag=1, time_major=False, return_alphas=False):
if isinstance(facts, tuple):
| tensorflow.where | 4,208 |
import tensorflow as tf
passage_len = input_shape[1]
# map decoder inputs to word embeddings
decoder_inputs = tf.unstack(decoder_inputs, axis=1) # max_enc_steps * [batch_size]
answer_batch_unstack = tf.unstack(answer_batch, axis=1)
# initialize all the variables
state_t_1 = init_state
| tensorflow.unstack | 4,209 |
from tensorflow.python.ops import math_ops
ids: `int64` `Tensor` or `SparseTensor` of IDs.
selected_id: Int id to select.
Returns:
`SparseTensor` of same dimensions as `ids`. This contains only the entries
equal to `selected_id`.
"""
if isinstance(ids, (ops.SparseTensor, ops.SparseTensorValue)):
return sparse_ops.sparse_retain(
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(
| tensorflow.python.ops.math_ops.equal | 4,210 |
import tensorflow as tf
opt_denoise = self.optimizer_func(self.hparams.learning_rate)
opt_ranker = self.optimizer_func(self.ranker_learning_rate)
denoise_updates = opt_denoise.apply_gradients(zip(denoise_gradients, denoise_params),
global_step=self.global_step)
ranker_updates = opt_ranker.apply_gradients(zip(ranking_model_gradients, ranking_model_params))
self.updates = tf.group(denoise_updates, ranker_updates)
def DenoisingNet(self, list_size, forward_only=False, scope=None):
with tf.variable_scope(scope or "denoising_model"):
# If we are in testing, do not compute propensity
if forward_only:
return tf.ones_like(self.output)#, tf.ones_like(self.output)
| tensorflow.group | 4,211 |
import tensorflow as tf
}
self._sess.run(m.vars_assign_op, feed_dict=var_feeddict)
def _make_placeholders(self):
w = self._train_params['image_size']
h = self._train_params['image_size']
in_ch = 3 # Num channels of input images
train_images_ph = tf.placeholder(tf.int32, name='train_images_ph', shape=(None, w, h, in_ch)) # Train images
pred_images_ph = tf.placeholder(tf.int32, name='pred_images_ph', shape=(None, w, h, in_ch)) # Predict images
train_classes_ph = tf.placeholder(tf.int32, name='train_classes_ph', shape=(None,)) # Train classes
pred_classes_ph = tf.placeholder(tf.int32, name='pred_classes_ph', shape=(None,)) # Predict classes
normal_arch_ph = tf.placeholder(tf.int32, name='normal_arch_ph', shape=(CELL_NUM_BLOCKS, 4))
reduction_arch_ph = tf.placeholder(tf.int32, name='reduction_arch_ph', shape=(CELL_NUM_BLOCKS, 4))
return _ModelPlaceholder(train_images_ph, train_classes_ph, pred_images_ph, pred_classes_ph,
normal_arch_ph, reduction_arch_ph)
def _forward(self, X, step, normal_arch, reduction_arch, is_train=False, **knobs):
K = self._train_params['K'] # No. of classes
in_ch = 3 # Num channels of input images
w = self._train_params['image_size'] # Initial input width
h = self._train_params['image_size'] # Initial input height
dropout_keep_prob = knobs['dropout_keep_prob']
use_dynamic_arch = knobs['downscale']
L = knobs['num_layers'] # Total number of layers
initial_block_ch = knobs['initial_block_ch'] # Initial no. of channels for operations in block
| tensorflow.placeholder | 4,212 |
import tensorflow as tf
class TFRecordDataset(TFDataset):
def get_num_partitions(self):
self.train_rdd.getNumPartitions()
def __init__(self, file_path, parse_fn, batch_size,
batch_per_thread, hard_code_batch_size=False, validation_file_path=None):
import tensorflow as tf
g = tf.Graph()
with g.as_default():
serialized_example = tf.placeholder(dtype=tf.string, shape=[])
results = parse_fn(serialized_example)
flattened = nest.flatten(results)
output_names = [tf.cast(t, dtype=tf.float32).name for t in flattened]
serialized_graph = bytearray(g.as_graph_def().SerializeToString())
sc = getOrCreateSparkContext()
train_rdd = callBigDlFunc("float", "createRDDFromTFRecords",
file_path, sc, serialized_graph,
serialized_example.name, output_names)
validation_rdd = None
if validation_file_path is not None:
validation_rdd = callBigDlFunc("float", "createRDDFromTFRecords",
validation_file_path, sc, serialized_graph,
serialized_example.name, output_names)
| tensorflow.cast | 4,213 |
import tensorflow as tf
"output_bias",
shape=[bert_config.vocab_size],
initializer=tf.zeros_initializer(),
)
logits = tf.matmul(input_tensor, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
log_probs = tf.nn.log_softmax(logits, axis=-1)
| tensorflow.matmul | 4,214 |
import tensorflow as tf
locs, scales = tf.map_fn(loop_hyper_deocder, zs, dtype=(tf.float32, tf.float32),
parallel_iterations=1, back_prop=False)
lower_bound = 1e-9# TODO
scales = tf.maximum(scales, lower_bound)
print("Hyper Decoder")
ys = conditional_entropy_model.decompress(y_strings, locs, scales, y_min_v, y_max_v, y_shape)
| tensorflow.maximum | 4,215 |
import tensorflow as tf
s = tf.matmul(g, f, transpose_b=True) # # [bs, N, N]
beta = tf.nn.softmax(s) # attention map
print('attention beta dims: ' + str(s.get_shape().as_list()))
h = tf.reshape(h, shape=[-1, h.shape[1]*h.shape[2], h.shape[-1]])
print('attention h flat dims: ' + str(h.get_shape().as_list()))
o = tf.matmul(beta, h) # [bs, N, C]
print('attention o dims: ' + str(o.get_shape().as_list()))
| tensorflow.reshape | 4,216 |
import tensorflow as tf
landm_valid = tf.reshape(y_true[..., 14], [num_batch * num_prior, 1])
class_true = tf.reshape(y_true[..., 15], [num_batch * num_prior, 1])
# define filter mask: class_true = 1 (pos), 0 (neg), -1 (ignore)
# landm_valid = 1 (w landm), 0 (w/o landm)
mask_pos = tf.equal(class_true, 1)
mask_neg = tf.equal(class_true, 0)
mask_landm = tf.logical_and(tf.equal(landm_valid, 1), mask_pos)
# landm loss (smooth L1)
mask_landm_b = tf.broadcast_to(mask_landm, tf.shape(landm_true))
loss_landm = _smooth_l1_loss(tf.boolean_mask(landm_true, mask_landm_b),
tf.boolean_mask(landm_pred, mask_landm_b))
loss_landm = tf.reduce_mean(loss_landm)
# localization loss (smooth L1)
mask_pos_b = tf.broadcast_to(mask_pos, tf.shape(loc_true))
loss_loc = _smooth_l1_loss(tf.boolean_mask(loc_true, mask_pos_b),
tf.boolean_mask(loc_pred, mask_pos_b))
loss_loc = tf.reduce_mean(loss_loc)
# classification loss (crossentropy)
| tensorflow.boolean_mask | 4,217 |
import tensorflow as tf
num_decoder_symbols, embedding_size=2, feed_previous=feed_previous)
def EmbeddingRNNSeq2SeqNoTupleF(enc_inp, dec_inp, feed_previous):
cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=False)
return tf.nn.seq2seq.embedding_rnn_seq2seq(
enc_inp, dec_inp, cell, num_encoder_symbols,
num_decoder_symbols, embedding_size=2, feed_previous=feed_previous)
def EmbeddingTiedRNNSeq2Seq(enc_inp, dec_inp, feed_previous):
cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True)
return tf.nn.seq2seq.embedding_tied_rnn_seq2seq(
enc_inp, dec_inp, cell, num_decoder_symbols, embedding_size=2,
feed_previous=feed_previous)
def EmbeddingTiedRNNSeq2SeqNoTuple(enc_inp, dec_inp, feed_previous):
cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=False)
return tf.nn.seq2seq.embedding_tied_rnn_seq2seq(
enc_inp, dec_inp, cell, num_decoder_symbols, embedding_size=2,
feed_previous=feed_previous)
def EmbeddingAttentionSeq2Seq(enc_inp, dec_inp, feed_previous):
cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True)
return tf.nn.seq2seq.embedding_attention_seq2seq(
enc_inp, dec_inp, cell, num_encoder_symbols,
num_decoder_symbols, embedding_size=2, feed_previous=feed_previous)
def EmbeddingAttentionSeq2SeqNoTuple(enc_inp, dec_inp, feed_previous):
cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=False)
return tf.nn.seq2seq.embedding_attention_seq2seq(
enc_inp, dec_inp, cell, num_encoder_symbols,
| tensorflow.nn.rnn_cell.BasicLSTMCell | 4,218 |
import tensorflow as tf
def model(X, M, Y, train=False, reuse=False):
with tf.variable_scope('model', reuse=reuse):
we = tf.get_variable("we", [n_vocab+n_special+n_ctx, n_embd], initializer=tf.random_normal_initializer(stddev=0.02))
we = dropout(we, embd_pdrop, train)
| tensorflow.random_normal_initializer | 4,219 |
import tensorflow as tf
self.assertEqual(save_path + ".meta", meta_graph_filename)
# Restore a different "v0" from shard 0 of the saved files.
with tf.Session(
target="",
config=tf.ConfigProto(device_count={"CPU": 2})) as sess:
with sess.graph.device("/cpu:0"):
v0 = tf.Variable(111, name="v0")
save = tf.train.Saver({"v0": v0}, sharded=True)
tf.initialize_all_variables().run()
self.assertEqual(111, v0.eval())
save.restore(sess, save_path + "-00000-of-00002")
self.assertEqual(10, v0.eval())
# Restore a different "v1" from shard 1 of the saved files.
with tf.Session(
| tensorflow.train.Saver | 4,220 |
import tensorflow as tf
**conv_kwargs))
h2 = activ(conv(h, 'c2', nf=64, rf=4, stride=2, init_scale=np.sqrt(2), **conv_kwargs))
h3 = activ(conv(h2, 'c3', nf=64, rf=3, stride=1, init_scale=np.sqrt(2), **conv_kwargs))
h3 = conv_to_fc(h3)
return activ(fc(h3, 'fc1', nh=512, init_scale=np.sqrt(2)))
class CnnPolicy(object):
def __init__(self, sess, ob_space, ac_space, nbatch, nsteps, reuse=False, **conv_kwargs): #pylint: disable=W0613
self.pdtype = make_pdtype(ac_space)
X, processed_x = observation_input(ob_space, nbatch)
# X:0~255 processed_x:0~1.0
with tf.variable_scope("model", reuse=reuse):
h = nature_cnn(processed_x, **conv_kwargs)
vf = fc(h, 'v', 1)[:,0]
self.pd, self.pi = self.pdtype.pdfromlatent(h, init_scale=0.01)
a0 = self.pd.sample()
neglogp0 = self.pd.neglogp(a0)
self.initial_state = None
def step(ob, *_args, **_kwargs):
a, v, neglogp = sess.run([a0, vf, neglogp0], {X:ob})
| tensorflow.variable_scope | 4,221 |
import tensorflow as tf
"""Generate input and target data.
The task of language model is to predict the next word.
Args:
chunk: A Tensor of text data.
Returns:
A namedtuple of input and target data.
"""
input_text = tf.map_fn(lambda x: x[:-1], chunk)
target_text = tf.map_fn(lambda x: x[1:], chunk)
return (input_text, target_text)
def build_to_ids_fn(vocab, max_seq_len):
"""Constructs function mapping examples to sequences of token indices."""
_, _, bos, eos = get_special_tokens(len(vocab))
table_values = np.arange(len(vocab), dtype=np.int64)
table = tf.lookup.StaticVocabularyTable(
tf.lookup.KeyValueTensorInitializer(vocab, table_values),
| tensorflow.map_fn | 4,222 |
import tensorflow as tf
train_model = self.policy(self.sess, self.observation_space, self.action_space, self.n_envs,
self.n_steps + 1, n_batch_train, reuse=True, **self.policy_kwargs)
with tf.variable_scope("moving_average"):
# create averaged model
ema = tf.train.ExponentialMovingAverage(self.alpha)
| tensorflow.variable_scope | 4,223 |
import tensorflow as tf
assert self.cnf['batch_size_train'] % self.cnf.get('num_gpus', 1) == 0, (
'Batch size must be divisible by number of GPUs')
self.inputs = tf.placeholder(
tf.float32,
shape=(None, self.model.image_size[0], self.model.image_size[0], 3),
| tensorflow.placeholder | 4,224 |
import tensorflow as tf
self._lr = tf.Variable(0.0, trainable=False)
tvars = tf.trainable_variables()
grads, _ = tf.clip_by_global_norm(tf.gradients(self._cost, tvars),
config.max_grad_norm)
optimizer = tf.train.GradientDescentOptimizer(self._lr)
self._train_op = optimizer.apply_gradients(
zip(grads, tvars),
global_step=tf.contrib.framework.get_or_create_global_step())
| tensorflow.train.GradientDescentOptimizer | 4,225 |
import tensorflow as tf
# bce_loss_list.append(tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=pred_outputs[pred_ind], labels=targets_list[pred_ind]/255., name='loss_{}'.format(pred_ind)), name='loss_mean_{}'.format(pred_ind)))
# mse_loss = tf.multiply(params['mse_weight'] / params['num_stacks'], tf.add_n(bce_loss_list), name='mse_loss')
# tf.summary.scalar('mse', mse_loss)
# tf.losses.add_loss(mse_loss)
# Add weight decay to the loss. We exclude the batch norm variables because
# doing so leads to a small improvement in accuracy.
loss = mse_loss + params['weight_decay'] * tf.add_n([tf.nn.l2_loss(v) for v in tf.trainable_variables() if 'batch_normalization' not in v.name])
total_loss = tf.identity(loss, name='total_loss')
tf.summary.scalar('loss', total_loss)
if mode == tf.estimator.ModeKeys.EVAL:
return tf.estimator.EstimatorSpec(mode=mode, loss=loss, predictions=predictions, eval_metric_ops=metrics)
if mode == tf.estimator.ModeKeys.TRAIN:
global_step = tf.train.get_or_create_global_step()
| tensorflow.identity | 4,226 |
import tensorflow as tf
strides=strides,
padding=padding,
name=scope.name)
if hasattr(input_, "shape"):
if input_.get_shape().as_list()[1] < filter_size[0]:
res = tf.slice(res, [
0, filter_size[0] - input_.get_shape().as_list()[1],
filter_size[1] - input_.get_shape().as_list()[2], 0
], [-1, -1, -1, -1])
if bias:
biases = variable_on_cpu("biases", [dim_out], tf.constant_initializer(0.))
res = tf.nn.bias_add(res, biases)
if nonlinearity is not None:
res = nonlinearity(res)
return res
def max_pool_2x2(input_):
"""Max pooling."""
return tf.nn.max_pool(
input_, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME")
| tensorflow.nn.bias_add | 4,227 |
import tensorflow as tf
# Intentionally using tf.Session() instead of self.test_session() to have
# control over closing the session. test_session() is a cached session.
with tf.Session():
coord = tf.train.Coordinator()
tf.train.start_queue_runners(coord=coord)
# Sleep to make sure the queue runner has started the first run call.
time.sleep(_SLEEP_TIME)
# Session closed.
| tensorflow.train.start_queue_runners | 4,228 |
from tensorflow.python.ops import state_ops
var_update = state_ops.assign_sub(var, lr_t * (scaled_grad + gold))
return control_flow_ops.group(*[var_update, ])
def _apply_sparse(self, grad, var): # sparse grad (only for the shakespeare model)
return self._apply_sparse_shared(
grad.values, var, grad.indices, lambda x, i, v: state_ops.scatter_add(x, i, v))
def set_params(self, cog, avg_gradient, client):
with client.model.graph.as_default():
all_vars = tf.trainable_variables()
for variable, value in zip(all_vars, cog):
| tensorflow.python.ops.state_ops.scatter_add | 4,229 |
import tensorflow as tf
return estimator_spec
elif mode == tf.estimator.ModeKeys.PREDICT:
print(logits.get_shape(), "===logits shape===")
pred_label = tf.argmax(logits, axis=-1, output_type=tf.int32)
prob = tf.nn.softmax(logits)
max_prob = tf.reduce_max(prob, axis=-1)
estimator_spec = tf.estimator.EstimatorSpec(
mode=mode,
| tensorflow.nn.softmax | 4,230 |
import tensorflow as tf
target: A tensor with the same shape as `output`.
from_logits: Whether `output` is expected to be a logits tensor.
By default, we consider that `output`
encodes a probability distribution.
# Returns
A tensor.
"""
# Note: tf.nn.softmax_cross_entropy_with_logits
# expects logits, Keras expects probabilities.
if not from_logits:
# transform back to logits
epsilon = _to_tensor(_EPSILON, output.dtype.base_dtype)
output = tf.clip_by_value(output, epsilon, 1 - epsilon)
output = tf.log(output / (1 - output))
try:
return tf.nn.sigmoid_cross_entropy_with_logits(labels=target, logits=output)
except TypeError:
return tf.nn.sigmoid_cross_entropy_with_logits(logits=output, labels=target)
def sum(x, axis=None, keepdims=False):
"""Sum of the values in a tensor, alongside the specified axis.
Parameters
----------
x: A tensor or variable.
axis: An integer, the axis to sum over.
| tensorflow.log | 4,231 |
import tensorflow as tf
anchor_scales,
anchor_ratios,
height,
width)
init = tf.global_variables_initializer()
with tf.Session(config=tf.ConfigProto(device_count={'GPU': 0})) as sess:
sess.run(init)
anchors_out = sess.run(anchors)
print(anchors_out[-30:])
print(anchors.shape)
print(anchors_out[158623])
| tensorflow.ConfigProto | 4,232 |
import tensorflow as tf
state_in = (c_in, h_in)
rnn_in = tf.expand_dims(self.h3, [0])
step_size = tf.shape(inputs)[:1]
state_in = tf.nn.rnn_cell.LSTMStateTuple(c_in, h_in)
lstm_outputs, lstm_state = tf.nn.dynamic_rnn(
lstm_cell, rnn_in, initial_state=state_in, sequence_length=step_size,
time_major=False)
lstm_c, lstm_h = lstm_state
| tensorflow.nn.dynamic_rnn | 4,233 |
import tensorflow as tf
v_path = conv3d(rb, 3, channel_nr, 'SYMMETRIC', 'relu')
v_path = conv3d(v_path, 3, 1, 'SYMMETRIC', None)
w_path = conv3d(rb, 3, channel_nr, 'SYMMETRIC', 'relu')
w_path = conv3d(w_path, 3, 1, 'SYMMETRIC', None)
b_out = tf.keras.layers.concatenate([u_path, v_path, w_path])
return b_out
def upsample3d(input_tensor, res_increase):
"""
Resize the image by linearly interpolating the input
using TF '``'resize_bilinear' function.
| tensorflow.keras.layers.concatenate | 4,234 |
import tensorflow as tf
res = sess.run([mem])
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)
| tensorflow.nn.seq2seq.attention_decoder | 4,235 |
from tensorflow.python.ops import math_ops
Args:
required_size: number or tf.Tensor specifying required array capacity.
growth_factor: optional number or tf.Tensor specifying the growth factor
between subsequent allocations.
Returns:
tf.Tensor with dtype=int32 giving the next array size.
"""
exponent = math_ops.ceil(
math_ops.log(math_ops.cast(required_size, dtypes.float32))
/ math_ops.log(math_ops.cast(growth_factor, dtypes.float32)))
return math_ops.cast(math_ops.ceil(growth_factor ** exponent), dtypes.int32)
def streaming_concat(values,
axis=0,
max_size=None,
metrics_collections=None,
updates_collections=None,
name=None):
"""Concatenate values along an axis across batches.
| tensorflow.python.ops.math_ops.cast | 4,236 |
import tensorflow as tf
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
| tensorflow.range | 4,237 |
import tensorflow as tf
output_spec = None
if mode == tf.estimator.ModeKeys.TRAIN:
train_op = optimization.create_optimizer(
total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
train_op=train_op,
scaffold_fn=scaffold_fn)
elif mode == tf.estimator.ModeKeys.EVAL:
def metric_fn(per_example_loss, label_ids, logits, is_real_example):
predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)
accuracy = tf.metrics.accuracy(
labels=label_ids, predictions=predictions, weights=is_real_example)
loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example)
return {
"eval_accuracy": accuracy,
"eval_loss": loss,
}
eval_metrics = (metric_fn,
[per_example_loss, label_ids, logits, is_real_example])
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
eval_metrics=eval_metrics,
| tensorflow.argmax | 4,238 |
import tensorflow as tf
orig_indices = tf.range(
self._sample_batch_size, dtype=relabel_indices.dtype)
with tf.name_scope("relabelling"):
# How often are the originally commanded goals most optimal?
opt_indices = tf.argmax(logits_vec, axis=1)
orig_is_opt = opt_indices == orig_indices
orig_opt_frac = tf.reduce_mean(tf.cast(orig_is_opt, tf.float32))
tf.compat.v2.summary.scalar(
name="orig_task_optimal", data=orig_opt_frac, step=global_step)
# How often is the relabelled goal optimal?
# The relabel_indices are [B, 1], so we need to remove the extra dim.
| tensorflow.cast | 4,239 |
import tensorflow as tf
pred_mask = pred_mask[..., tf.newaxis]
return pred_mask[0]
dataset, info = tfds.load('oxford_iiit_pet:3.*.*', with_info=True)
def normalize(input_image, input_mask):
input_image = tf.cast(input_image, tf.float32) / 255.0
input_mask -= 1
return input_image, input_mask
def load_image_train(datapoint):
"""Load images for training."""
input_image = tf.image.resize(datapoint['image'], (512, 512))
input_mask = tf.image.resize(datapoint['segmentation_mask'], (128, 128))
if tf.random.uniform(()) > 0.5:
input_image = tf.image.flip_left_right(input_image)
input_mask = tf.image.flip_left_right(input_mask)
input_image, input_mask = normalize(input_image, input_mask)
return input_image, input_mask
def load_image_test(datapoint):
input_image = tf.image.resize(datapoint['image'], (512, 512))
input_mask = tf.image.resize(datapoint['segmentation_mask'], (128, 128))
| tensorflow.image.resize | 4,240 |
from tensorflow.python.framework import ops
`precision`.
Raises:
ValueError: If `ignore_mask` is not `None` and its shape doesn't match
`predictions`, or if `weights` is not `None` and its shape doesn't match
`predictions`, or if either `metrics_collections` or `updates_collections`
are not a list or tuple.
ValueError: If `top_k_predictions` has rank < 2.
"""
default_name = _at_k_name('precision', class_id=class_id)
with ops.name_scope(
name, default_name,
(top_k_predictions, labels, ignore_mask, weights)) as scope:
rank = array_ops.rank(top_k_predictions)
check_rank_op = control_flow_ops.Assert(
math_ops.greater_equal(rank, 2),
['top_k_predictions must have rank 2 or higher, e.g. [batch_size, k].'])
with ops.control_dependencies([check_rank_op]):
return _streaming_sparse_precision_at_k(
top_k_idx=top_k_predictions,
| tensorflow.python.framework.ops.name_scope | 4,241 |
import tensorflow as tf
strides = [1] + strides + [1]
filter_ = get_variable('filter_{}'.format(k),
[filter_height, filter_width, in_channels, out_channels])
encoder_inputs_ = tf.nn.conv2d(encoder_inputs_, filter_, strides, padding='SAME')
if encoder.batch_norm:
encoder_inputs_ = tf.layers.batch_normalization(encoder_inputs_, training=training,
| tensorflow.nn.conv2d | 4,242 |
import tensorflow as tf
else:
if reuse:
ret.append(tf.variable_scope(
tf.get_variable_scope(), reuse=True))
else:
# work around https://github.com/tensorflow/tensorflow/issues/14703
ret.append(tf.variable_scope(tf.get_variable_scope()))
# always clear existing ns # TODO check existing ns
if len(self._name) and self._name != self._vs_name:
ret.append(tf.name_scope(self._name + '/'))
return ret
def _keys_to_freeze(self):
if self.is_main_training_tower:
return []
if self.is_training:
return [tf.GraphKeys.SUMMARIES, MOVING_SUMMARY_OPS_KEY]
# freeze UPDATE_OPS during inference because they should never be used
| tensorflow.name_scope | 4,243 |
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)))
| tensorflow.expand_dims | 4,244 |
import tensorflow as tf
mask1 = tf.constant([[1, 1],
[0, 1]], dtype=tf.float32)
mask2 = tf.constant([[1, 0],
[1, 1]], dtype=tf.float32)
mask3 = tf.constant([[1, 1],
[1, 1]], dtype=tf.float32)
mask4 = tf.constant([[0, 0],
[0, 0]], dtype=tf.float32)
| tensorflow.constant | 4,245 |
import tensorflow as tf
return
from tensorflow_transform import annotations_pb2 # pylint: disable=g-import-not-at-top
message_type = annotations_pb2.VocabularyMetadata.DESCRIPTOR.full_name
unfiltered_vocabulary_size = tf.expand_dims(unfiltered_vocabulary_size, 0)
filtered_vocabulary_size = tf.expand_dims(filtered_vocabulary_size, 0)
file_name = tf.convert_to_tensor([vocab_filename])
descriptor_source = descriptor_pb2.FileDescriptorSet()
| tensorflow.expand_dims | 4,246 |
from tensorflow.python.framework import ops
```
# tensor 'real' is [2.25, 3.25]
# tensor `imag` is [4.75, 5.75]
tf.complex(real, imag) ==> [[2.25 + 4.74j], [3.25 + 5.75j]]
```
Args:
real: A `Tensor` of type `float`.
imag: A `Tensor` of type `float`.
name: A name for the operation (optional).
Returns:
A `Tensor` of type `complex64`.
"""
with ops.op_scope([real, imag], name, "Complex") as name:
return gen_math_ops._complex(real, imag, name=name)
def round(x, name=None):
"""Rounds the values of a tensor to the nearest integer, element-wise.
For example:
```python
# 'a' is [0.9, 2.5, 2.3, -4.4]
tf.round(a) ==> [ 1.0, 3.0, 2.0, -4.0 ]
```
Args:
| tensorflow.python.framework.ops.op_scope | 4,247 |
import tensorflow as tf
one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)
per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
loss = tf.reduce_sum(per_example_loss)
return (loss, per_example_loss, logits)
def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps, use_tpu,
use_one_hot_embeddings):
def model_fn(features, labels, mode, params):
tf.logging.info("*** Features ***")
for name in sorted(features.keys()):
tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
input_ids = features["input_ids"]
input_mask = features["input_mask"]
segment_ids = features["segment_ids"]
label_ids = features["label_ids"]
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
| tensorflow.logging.info | 4,248 |
import tensorflow as tf
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)
| tensorflow.get_variable | 4,249 |
from tensorflow.python.ops import math_ops
"""
with variable_scope.variable_scope(name, 'mean_iou', [predictions, labels]):
# Check if shape is compatible.
predictions.get_shape().assert_is_compatible_with(labels.get_shape())
# Local variable to accumulate the predictions in the confusion matrix.
cm_dtype = dtypes.int64 if weights is not None else dtypes.float64
total_cm = _create_local('total_confusion_matrix',
shape=[num_classes, num_classes], dtype=cm_dtype)
# Cast the type to int64 required by confusion_matrix_ops.
predictions = math_ops.to_int64(predictions)
labels = math_ops.to_int64(labels)
num_classes = math_ops.to_int64(num_classes)
# 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:
| tensorflow.python.ops.math_ops.to_int64 | 4,250 |
import tensorflow as tf
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):
"""
Implementation of parameterize for a half-Gaussian prior.
"""
def __init__(self, input_shape=None, name='gaussianize', *args, **kwargs):
super().__init__(*args, num_parameters=1, input_shape=input_shape, name=name, **kwargs)
def _forward(self, x1, x2, **kwargs):
| tensorflow.math.reduce_sum | 4,251 |
import tensorflow as tf
def _create_dummy_vars():
"""Dummy vars for restore to work when not using TPU codepath."""
var_names = set([v.name for v in tf.global_variables()])
if "losses_avg/problem_0/total_loss:0" in var_names:
return
with tf.variable_scope("losses_avg"):
with tf.variable_scope("problem_0"):
for var_name in ["total", "extra", "training"]:
tf.get_variable(
"%s_loss" % var_name, initializer=100.0, trainable=False)
with tf.variable_scope("train_stats"):
tf.get_variable("problem_0_steps", initializer=0, trainable=False)
# These metrics are implemented with py_funcs and therefore do no work with TPU
TPU_METRIC_BLACKLIST = set([
metrics.Metrics.APPROX_BLEU,
| tensorflow.get_variable | 4,252 |
import tensorflow as tf
h = tf.nn.dropout(h, 0.5)
h_logits = tf.matmul(h, w_h) + b_h
if self.ctx2out:
w_ctx2out = tf.get_variable('w_ctx2out', [self.D, self.M], initializer=self.weight_initializer)
h_logits += tf.matmul(context, w_ctx2out)
if self.prev2out:
| tensorflow.get_variable | 4,253 |
import tensorflow as tf
valid_image_batch,valid_label_batch=get_valid_batch(valid_image,valid_label,validnum)
valid_inf=work.valid_inference(valid_image_batch)
valid_labels=tf.one_hot(valid_label_batch,classnum)
#train_step=tf.train.GradientDescentOptimizer(0.001).minimize(cross_entropy)
valid_pre = tf.reshape(valid_inf, [validnum, classnum])
valid_correct_prediction=tf.equal(tf.argmax(valid_inf,1),tf.argmax(valid_labels,1))
valid_accuracy=tf.reduce_mean(tf.cast(valid_correct_prediction,tf.float32))
valid_pre = tf.argmax(valid_pre, 1)
valid_true = tf.argmax(valid_labels, 1)
target_names = ['class sg', 'class bm', 'class wd', 'class wt', 'class wj', 'class wo', 'class ym', 'class shq', 'class shj',
'class no', 'class yh', 'class fb']
init = tf.initialize_all_variables()
config=tf.ConfigProto()
| tensorflow.argmax | 4,254 |
import tensorflow as tf
b = bias_variable([FLAGS.feats_per_layer])
Wx_b = tf.nn.conv3d(bottom, W, strides=[1,1,1,1,1], padding='VALID') + b
out = tf.nn.relu(Wx_b)
| tensorflow.nn.conv3d | 4,255 |
import tensorflow as tf
from utils import get_random_batch, read_config_file, create_dir
RUN_IN_GPU = False
def train_acregnet_model(config):
tf.reset_default_graph()
tf_config = tf.ConfigProto()
if RUN_IN_GPU:
tf_config.gpu_options.allow_growth = True
sess = tf.Session(config=tf_config)
train_ims, _ = DataHandler.load_images(config['train_ims_file'])
train_lbs, _ = DataHandler.load_labels(config['train_lbs_file'])
print('Loading training data...done')
acregnet = ACRegNet(sess, config, 'ACRegNet', is_train=True)
print('Building AC-RegNet model...done')
print('Training...')
for i in range(config['iterations']):
batch_ims_x, batch_ims_y, batch_lbs_x, batch_lbs_y = get_random_batch(
train_ims, config['batch_size'], train_lbs)
| tensorflow.Session | 4,256 |
from tensorflow.python.ops import logging_ops
loss = self._target_column.loss(logits, targets, features)
logging_ops.scalar_summary("loss", loss)
| tensorflow.python.ops.logging_ops.scalar_summary | 4,257 |
import tensorflow as tf
if not os.path.isfile(char_embedding_meta):
with open(char_embedding_meta, "w", encoding="utf-8") as f:
for symbol in symbols:
if symbol == " ":
symbol = "\\s" # For visual purposes, swap space with \s
f.write("{}\n".format(symbol))
char_embedding_meta = char_embedding_meta.replace(log_dir, "..")
# Book keeping
step = 0
time_window = ValueWindow(100)
loss_window = ValueWindow(100)
saver = tf.train.Saver(max_to_keep=5)
log("Tacotron training set to a maximum of {} steps".format(args.tacotron_train_steps))
# Memory allocation on the GPU as needed
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.allow_soft_placement = True
# Train
with tf.Session(config=config) as sess:
try:
summary_writer = tf.summary.FileWriter(tensorboard_dir, sess.graph)
| tensorflow.train.Saver | 4,258 |
import tensorflow as tf
start_top_log_probs, start_top_index = tf.nn.top_k(
start_log_probs, k=FLAGS.start_n_top)
start_index = tf.one_hot(start_top_index,
depth=seq_len, axis=-1, dtype=tf.float32)
start_features = tf.einsum("lbh,bkl->bkh", output, start_index)
end_input = tf.tile(output[:, :, None],
[1, 1, FLAGS.start_n_top, 1])
start_features = tf.tile(start_features[None],
[seq_len, 1, 1, 1])
end_input = tf.concat([end_input, start_features], axis=-1)
| tensorflow.tile | 4,259 |
import tensorflow as tf
with tf.variable_scope('B'):
| tensorflow.variable_scope | 4,260 |
import tensorflow as tf
hidden = beam_search.resize_like(hidden, state)
input_length = beam_search.resize_like(input_length, state)
context_vector, weights_ = attention(state=state, hidden_states=hidden, encoder=encoder,
encoder_input_length=input_length, pos=pos_, context=context_vector,
prev_weights=prev_weights_, **kwargs)
attns.append(context_vector)
weights.append(weights_)
if aggregation_method == 'sum':
context_vector = tf.reduce_sum(tf.stack(attns, axis=2), axis=2)
else:
context_vector = tf.concat(attns, axis=1)
return context_vector, weights
def attention_decoder(decoder_inputs, initial_state, attention_states, encoders, decoder, encoder_input_length,
feed_previous=0.0, align_encoder_id=0, feed_argmax=True, training=True, **kwargs):
"""
| tensorflow.stack | 4,261 |
from tensorflow.contrib.learn.python.learn.estimators import dnn_linear_combined
input_fn = test_data.iris_input_logistic_fn
metrics = classifier.fit(input_fn=input_fn, steps=_ITERS).evaluate(
input_fn=input_fn, steps=100)
self._assertSingleClassMetrics(metrics)
def benchmarkMultiClass(self):
iris = base.load_iris()
cont_feature = feature_column.real_valued_column('feature', dimension=4)
bucketized_feature = feature_column.bucketized_column(
cont_feature, test_data.get_quantile_based_buckets(iris.data, 10))
classifier = dnn_linear_combined.DNNLinearCombinedClassifier(
n_classes=3,
linear_feature_columns=(bucketized_feature,),
dnn_feature_columns=(cont_feature,),
dnn_hidden_units=(3, 3))
input_fn = test_data.iris_input_multiclass_fn
metrics = classifier.fit(input_fn=input_fn, steps=_ITERS).evaluate(
input_fn=input_fn, steps=100)
self._assertCommonMetrics(metrics)
def benchmarkPartitionedVariables(self):
| tensorflow.contrib.learn.python.learn.estimators.dnn_linear_combined.DNNLinearCombinedClassifier | 4,262 |
import tensorflow as tf
input_size = encoder_inputs_.get_shape()[2].value
def get_initial_state(name='initial_state'):
if encoder.train_initial_states:
initial_state = get_variable(name, initializer=tf.zeros(cell_state_size))
return tf.tile(tf.expand_dims(initial_state, axis=0), [batch_size, 1])
else:
return None
if encoder.bidir:
rnn = lambda reuse: stack_bidirectional_dynamic_rnn(
| tensorflow.expand_dims | 4,263 |
import tensorflow as tf
gan_train_ops.generator_train_op,
global_step.assign_add(1))
if params['use_tpu']:
# TPU version of EstimatorSpec
return tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
predictions=predictions,
loss=loss,
train_op=train_op,)
else:
return tf.estimator.EstimatorSpec(
mode=mode,
predictions=predictions,
loss=loss,
train_op=train_op,)
def train_input_fn(params={}):
# make some fake noise
data_size = 100
noise_tensor = tf.random_normal((data_size, INPUT_DIM))
| tensorflow.estimator.EstimatorSpec | 4,264 |
import tensorflow as tf
with sess.graph.device("/cpu:1"):
v1 = tf.Variable(20, name="v1")
save = tf.train.Saver({"v0": v0, "v1": v1}, sharded=True)
tf.initialize_all_variables().run()
val = save.save(sess, save_path)
self.assertEqual(save_path + "-?????-of-00002", val)
meta_graph_filename = save._MetaGraphFilename(val)
self.assertEqual(save_path + ".meta", meta_graph_filename)
# Restore a different "v0" from shard 0 of the saved files.
with tf.Session(
target="",
config=tf.ConfigProto(device_count={"CPU": 2})) as sess:
with sess.graph.device("/cpu:0"):
v0 = tf.Variable(111, name="v0")
save = tf.train.Saver({"v0": v0}, sharded=True)
tf.initialize_all_variables().run()
self.assertEqual(111, v0.eval())
save.restore(sess, save_path + "-00000-of-00002")
self.assertEqual(10, v0.eval())
# Restore a different "v1" from shard 1 of the saved files.
with tf.Session(
target="",
config=tf.ConfigProto(device_count={"CPU": 2})) as sess:
with sess.graph.device("/cpu:0"):
v1 = tf.Variable(222)
save = tf.train.Saver({"v1": v1}, sharded=True)
| tensorflow.Variable | 4,265 |
from tensorflow.python.ops import array_ops
relevant_per_k = _sparse_true_positive_at_k(
predictions_idx_per_k, labels_per_k, name='relevant_per_k')
tp_per_k = math_ops.cumsum(relevant_per_k, axis=-1, name='tp_per_k')
retrieved_per_k = math_ops.cumsum(
array_ops.ones_like(relevant_per_k), axis=-1, name='retrieved_per_k')
precision_per_k = math_ops.div(
math_ops.to_double(tp_per_k), math_ops.to_double(retrieved_per_k),
name='precision_per_k')
| tensorflow.python.ops.array_ops.ones_like | 4,266 |
import tensorflow as tf
return None
def build_generator(self,image,reuse=False,name='generator'):
with tf.variable_scope(name):
if reuse:
tf.get_variable_scope().reuse_variables()
else:
assert tf.get_variable_scope().reuse is False
"""U-Net Generator"""
def lrelu(x, alpha,name='lrelu'):
with tf.variable_scope(name):
return tf.nn.relu(x) - alpha * tf.nn.relu(-x)
def instance_norm(x,name='instance_norm'):
| tensorflow.get_variable_scope | 4,267 |
import tensorflow as tf
k_h=3,k_w=3,stddev=0.02) :
assert k_h%2==1 and k_w%2==1, 'kernel size should be odd numbers to ensure exact size'
with tf.variable_scope(name) :
self.w = tf.get_variable('w', [k_h, k_w, input_dim, output_dim],
initializer=tf.random_normal_initializer(stddev=stddev))
self.b = tf.get_variable('b',[output_dim], initializer=tf.constant_initializer(0.0))
self.padding = [ [0,0],[k_h//2,k_h//2],[k_w//2,k_w//2],[0,0] ]
def __call__(self,input_var,name=None,**kwargs):
_,h,w,c = input_var.shape.as_list()
_t = tf.image.resize_nearest_neighbor(input_var, [h*2, w*2])
_t = tf.pad(_t,self.padding, mode='SYMMETRIC')
return tf.nn.bias_add(
tf.nn.conv2d(_t, self.w,
data_format='NHWC', #we can't use cudnn due to resize method...
strides=[1,1,1,1], padding="VALID"),
self.b,data_format='NHWC',name=name)
def get_variables(self):
return {'w':self.w,'b':self.b}
class WeightNormSymPadConv2d(object): #Resize and Convolution(upsacle by 2)
| tensorflow.image.resize_nearest_neighbor | 4,268 |
import tensorflow as tf
:return: does not return anything
"""
# Reconstruction Phase
with tf.variable_scope(tf.get_variable_scope()):
encoder_output_label, encoder_output_latent = encoder(x_input)
# Concat class label and the encoder output
decoder_input = tf.concat([encoder_output_label, encoder_output_latent], 1)
decoder_output = decoder(decoder_input)
# Regularization Phase
with tf.variable_scope(tf.get_variable_scope()):
d_g_real = discriminator_gauss(real_distribution)
d_g_fake = discriminator_gauss(encoder_output_latent, reuse=True)
with tf.variable_scope(tf.get_variable_scope()):
d_c_real = discriminator_categorical(categorial_distribution)
d_c_fake = discriminator_categorical(encoder_output_label, reuse=True)
# Semi-Supervised Classification Phase
with tf.variable_scope(tf.get_variable_scope()):
encoder_output_label_, _ = encoder(x_input_l, reuse=True, supervised=True)
| tensorflow.get_variable_scope | 4,269 |
import tensorflow as tf
v_norm = tf.nn.l2_normalize(self.v,axis=0)
t = tf.matmul(input_var,v_norm)
mu,var = tf.nn.moments(t,axes=[0])
std = tf.sqrt(var+self.epsilon)
| tensorflow.nn.moments | 4,270 |
import tensorflow as tf
transformed_features = self.bottom(features)
with tf.variable_scope("body"):
log_info("Building model body")
| tensorflow.variable_scope | 4,271 |
import tensorflow as tf
with h5py.File(embedding_weight_file, 'r') as fin:
# +1 for padding
self._n_tokens_vocab = fin['embedding'].shape[0] + 1
else:
self._n_tokens_vocab = None
with tf.variable_scope('bilm', custom_getter=custom_getter):
self._build()
def _build(self):
if self.use_character_inputs:
self._build_word_char_embeddings()
| tensorflow.variable_scope | 4,272 |
import tensorflow as tf
config=tf.ConfigProto(device_count={"CPU": 2})) as sess:
with sess.graph.device("/cpu:0"):
v0 = tf.Variable(111, name="v0")
with sess.graph.device("/cpu:1"):
| tensorflow.Variable | 4,273 |
import tensorflow as tf
reduce_sum(tf.square(grad),
reduction_indices=red_ind,
keepdims=True))
normalized_grad = old_div(grad, tf.sqrt(square))
else:
normalized_grad = tf.sign(grad)
normalized_grad = tf.stop_gradient(normalized_grad)
scaled_grad = eps * normalized_grad
#目标是让loss下降
adv_x = x - scaled_grad
if (clip_min is not None) and (clip_max is not None):
adv_x = tf.clip_by_value(adv_x, clip_min, clip_max)
return adv_x
#DeepFool 仅实现了目标攻击
def deepfool(x,
loss=None,
bounds=(0,1)):
(clip_min, clip_max)=bounds
grad, = tf.gradients(loss, x)
r=old_div(grad*loss,tf.reduce_sum(tf.square(grad)))
| tensorflow.clip_by_value | 4,274 |
import tensorflow as tf
# Single thread; fairer comparison against eager
session_conf = tf.ConfigProto(inter_op_parallelism_threads=1)
| tensorflow.ConfigProto | 4,275 |
import tensorflow as tf
# TPU loop is finished, setting max_queue value to the same as number of
# iterations will make the summary writer only flush the data to storage
# once per loop.
with (tf.contrib.summary.create_file_writer(
params['model_dir'],
max_queue=params['iterations_per_loop']).as_default()):
with tf.contrib.summary.always_record_summaries():
tf.contrib.summary.scalar(
'total_loss', tf.reduce_mean(total_loss), step=global_step)
tf.contrib.summary.scalar(
'total_rpn_loss', tf.reduce_mean(total_rpn_loss),
step=global_step)
| tensorflow.contrib.summary.always_record_summaries | 4,276 |
import tensorflow as tf
flattened_lm_emb = tf.reshape(lm_emb, [num_sentences * max_sentence_length * lm_emb_size, lm_num_layers])
flattened_aggregated_lm_emb = tf.matmul(flattened_lm_emb, tf.expand_dims(self.lm_weights, 1)) # [num_sentences * max_sentence_length * emb, 1]
aggregated_lm_emb = tf.reshape(flattened_aggregated_lm_emb, [num_sentences, max_sentence_length, lm_emb_size])
aggregated_lm_emb *= self.lm_scaling
context_emb_list.append(aggregated_lm_emb)
context_emb = tf.concat(context_emb_list, 2) # [num_sentences, max_sentence_length, emb]
head_emb = tf.concat(head_emb_list, 2) # [num_sentences, max_sentence_length, emb]
context_emb = tf.nn.dropout(context_emb, self.lexical_dropout) # [num_sentences, max_sentence_length, emb]
head_emb = tf.nn.dropout(head_emb, self.lexical_dropout) # [num_sentences, max_sentence_length, emb]
text_len_mask = tf.sequence_mask(text_len, maxlen=max_sentence_length) # [num_sentence, max_sentence_length]
context_outputs = self.lstm_contextualize(context_emb, text_len, text_len_mask) # [num_words, emb]
num_words = util.shape(context_outputs, 0)
genre_emb = tf.gather(tf.get_variable("genre_embeddings", [len(self.genres), self.config["feature_size"]]), genre) # [emb]
sentence_indices = tf.tile(tf.expand_dims(tf.range(num_sentences), 1), [1, max_sentence_length]) # [num_sentences, max_sentence_length]
flattened_sentence_indices = self.flatten_emb_by_sentence(sentence_indices, text_len_mask) # [num_words]
flattened_head_emb = self.flatten_emb_by_sentence(head_emb, text_len_mask) # [num_words]
| tensorflow.sequence_mask | 4,277 |
import tensorflow as tf
m = train_X.shape[0]
n_output_1 = test_y_1.shape[1]
n_output_2 = test_y_2.shape[1]
lr = args.lr
n_epoch = args.n_epoch
n_batch_size = args.n_batch_size
reg_lambda = args.reg_lambda
keep_prob = args.keep_prob
cross_stitch_enabled = args.cross_stitch_enabled
with tf.variable_scope("placeholder"):
X = tf.placeholder(tf.float32, (None, 128), "X")
y_1 = tf.placeholder(tf.float32, (None, n_output_1), "y_1")
y_2 = tf.placeholder(tf.float32, (None, n_output_2), "y_2")
is_training = tf.placeholder(tf.bool, (), "is_training")
with tf.variable_scope("network"):
with contrib.framework.arg_scope(
[contrib.layers.fully_connected],
# he initialization
weights_initializer=contrib.layers.variance_scaling_initializer(),
# l2 regularization
weights_regularizer=contrib.layers.l2_regularizer(reg_lambda),
| tensorflow.placeholder | 4,278 |
import tensorflow as tf
return 49.0 * 21.0 / 1024.0
elif kh == 14 and kw == 14:
return 196.0 * 21.0 / 4096.0
else:
rec = tf.cast(kw * kh, tf.float32)
n_max = 7 + tf.math.ceil(tf.math.log(rec) / tf.math.log(2.))
ns = tf.range(0., n_max)
ns_pow = tf.pow(2., ns)
ks = tf.round(ns_pow / rec)
diffs = tf.math.abs(ks / ns_pow - 1 / rec)
n = tf.argmin(diffs)
k = ks[n]
scale = k / tf.pow(2., tf.cast(n, tf.float32))
scale *= rec
return scale
@register_keras_serializable(
package='Vitis', name='VitisGlobalAveragePooling2D')
class VitisGlobalAveragePooling2D(tf.keras.layers.GlobalAveragePooling2D):
"""Vitis version of GlobalAveragePooling2D layer.
This is an Vitis version of average pooling to simulate DPU behaviour which to
integer approximations for averaging of specific sizes.
| tensorflow.cast | 4,279 |
import tensorflow as tf
'''
# for summary
with tf.name_scope('accuracy') as scope:
correct = tf.equal(tf.arg_max(logits,1), tf.arg_max(labels,1))
correct = tf.cast(correct, tf.float32)
accuracy = tf.reduce_mean(correct)*100.0
tf.summary.scalar(scope+'accuracy',accuracy)
return accuracy
def num_correct_prediction(logits, labels):
'''
Evaluate the quality of the logits at predicting the label
'''
correct = tf.equal(tf.arg_max(logits,1), tf.arg_max(labels,1))
correct = tf.cast(correct, tf.int32)
n_correct = tf.reduce_sum(correct)
return n_correct
def optimize(loss, learning_rate, global_step):
'''
Optimization, use Gradient Descent as default
'''
with tf.name_scope('optimizer'):
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss, global_step=global_step)
| tensorflow.arg_max | 4,280 |
import tensorflow as tf
from tensorflow.contrib.tensorboard.plugins import projector
from Bunch import Bunch
tf.app.flags.DEFINE_string('input_path', '../data/tmp/grid03.14.c.tar.gz', 'input folder')
tf.app.flags.DEFINE_string('input_name', '', 'input folder')
tf.app.flags.DEFINE_string('test_path', '', 'test set folder')
tf.app.flags.DEFINE_string('net', 'f100-f3', 'model configuration')
tf.app.flags.DEFINE_string('model', 'noise', 'Type of the model to use: Autoencoder (ae)'
'WhatWhereAe (ww) U-netAe (u)')
tf.app.flags.DEFINE_string('postfix', '', 'Postfix for the training folder')
| tensorflow.app.flags.DEFINE_string | 4,281 |
import tensorflow as tf
beta = tf.nn.softmax(s, axis=-1) # attention map
| tensorflow.nn.softmax | 4,282 |
from tensorflow.python.ops import math_ops
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
# If the value of the denominator is 0, set it to 1 to avoid
# zero division.
denominator = math_ops.select(
math_ops.greater(denominator, 0),
denominator,
array_ops.ones_like(denominator))
iou = math_ops.div(cm_diag, denominator)
return math_ops.reduce_mean(iou, name=name)
mean_iou = compute_mean_iou('mean_iou')
if metrics_collections:
ops.add_to_collections(metrics_collections, mean_iou)
if updates_collections:
| tensorflow.python.ops.math_ops.greater | 4,283 |
from tensorflow.python.platform import tf_logging as logging
self._model_dir = tempfile.mkdtemp()
logging.info('Using temporary folder as model directory: %s',
| tensorflow.python.platform.tf_logging.info | 4,284 |
import tensorflow as tf
(tf.Tensor) A single value tensor containing the loss.
"""
loss = None
with tf.name_scope(name, "softmax_loss",[output]):
label_dis = labels / tf.reduce_sum(labels, 1, keep_dims=True)
loss = tf.nn.softmax_cross_entropy_with_logits(logits=output, labels=label_dis) * tf.reduce_sum(labels, 1)
return tf.reduce_sum(loss) / tf.reduce_sum(labels)
def get_normalized_weights(self, propensity):
"""Computes listwise softmax loss with propensity weighting.
Args:
propensity: (tf.Tensor) A tensor of the same shape as `output` containing the weight of each element.
| tensorflow.reduce_sum | 4,285 |
import tensorflow as tf
setattr(
self,
'alpha_%s' % layer,
tf.constant(0.))
else:
setattr(
| tensorflow.constant | 4,286 |
from tensorflow.python.ops import math_ops
# `retrieved_per_k` (int32) - Number of predicted values at each k. This is
# the precision denominator.
# `precision_per_k` (float64) - Precision at each k. This is the "P_{i}"
# term from the formula above.
# `relevant_precision_per_k` (float64) - Relevant precisions; i.e.,
# precisions at all k for which relevance indicator is true.
relevant_per_k = _sparse_true_positive_at_k(
predictions_idx_per_k, labels_per_k, name='relevant_per_k')
tp_per_k = math_ops.cumsum(relevant_per_k, axis=-1, name='tp_per_k')
retrieved_per_k = math_ops.cumsum(
array_ops.ones_like(relevant_per_k), axis=-1, name='retrieved_per_k')
precision_per_k = math_ops.div(
math_ops.to_double(tp_per_k), math_ops.to_double(retrieved_per_k),
name='precision_per_k')
relevant_precision_per_k = math_ops.mul(
precision_per_k, math_ops.to_double(relevant_per_k),
name='relevant_precision_per_k')
# Reduce along k dimension to get the sum, yielding a [D1, ... DN] tensor.
precision_sum = math_ops.reduce_sum(
relevant_precision_per_k, reduction_indices=(-1,), name='precision_sum')
# Divide by number of relevant items to get average precision. These are
# the "num_relevant_items" and "AveP" terms from the formula above.
| tensorflow.python.ops.math_ops.to_double | 4,287 |
import tensorflow as tf
mdl = p.Instantiate()
mdl.FPropDefaultTheta()
all_vars = tf.trainable_variables()
py_utils.SumSquared(all_vars)
def testCollectVarHistogram(self):
with self.session(use_gpu=False, graph=tf.Graph()):
p = self._testParams()
mdl = p.Instantiate()
mdl.FPropDefaultTheta()
var_grads = py_utils.ComputeGradients(mdl.loss, mdl.vars)
summary_utils.CollectVarHistogram(var_grads)
| tensorflow.Graph | 4,288 |
import tensorflow as tf
return uint8_resize_bicubic(image, shape)
def center_crop(image, size):
image_height = tf.shape(image)[0]
image_width = tf.shape(image)[1]
offset_height = (image_height - size) // 2
offset_width = (image_width - size) // 2
image = tf.slice(image, [offset_height, offset_width, 0], [size, size, -1])
return image
def lighting(image, std, eigval, eigvec):
v = tf.random_normal(shape=[3], stddev=std) * eigval
inc = tf.matmul(eigvec, tf.reshape(v, [3, 1]))
image = tf.cast(tf.cast(image, tf.float32) + tf.reshape(inc, [3]), image.dtype)
return image
def validation_mapper(byte):
image = tf.image.decode_jpeg(
tf.reshape(byte, shape=[]), 3, **JPEG_OPT)
image = resize_shortest_edge(image, tf.shape(image), 256)
image = center_crop(image, 224)
image = tf.reverse(image, axis=[2]) # to BGR
return image
def training_mapper(byte):
jpeg_shape = tf.image.extract_jpeg_shape(byte) # hwc
| tensorflow.reshape | 4,289 |
import tensorflow as tf
class_pred = tf.reshape(y_pred[2], [num_batch * num_prior, num_class])
loc_true = tf.reshape(y_true[..., :4], [num_batch * num_prior, 4])
landm_true = tf.reshape(y_true[..., 4:14], [num_batch * num_prior, 10])
landm_valid = tf.reshape(y_true[..., 14], [num_batch * num_prior, 1])
class_true = tf.reshape(y_true[..., 15], [num_batch * num_prior, 1])
# define filter mask: class_true = 1 (pos), 0 (neg), -1 (ignore)
# landm_valid = 1 (w landm), 0 (w/o landm)
| tensorflow.reshape | 4,290 |
import tensorflow as tf
td_map[self.train_model.states_ph] = states
td_map[self.train_model.dones_ph] = masks
td_map[self.polyak_model.states_ph] = states
td_map[self.polyak_model.dones_ph] = masks
if writer is not None:
# run loss backprop with summary, but once every 10 runs save the metadata (memory, compute time, ...)
if self.full_tensorboard_log and (1 + (steps / self.n_batch)) % 10 == 0:
run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
run_metadata = tf.RunMetadata()
step_return = self.sess.run([self.summary] + self.run_ops, td_map, options=run_options,
run_metadata=run_metadata)
writer.add_run_metadata(run_metadata, 'step%d' % steps)
else:
step_return = self.sess.run([self.summary] + self.run_ops, td_map)
writer.add_summary(step_return[0], steps)
step_return = step_return[1:]
else:
| tensorflow.RunMetadata | 4,291 |
import tensorflow as tf
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
| tensorflow.stack | 4,292 |
import tensorflow as tf
tf.app.flags.DEFINE_integer('seed', 1, "initial random seed")
tf.app.flags.DEFINE_bool('validation', False, "")
tf.app.flags.DEFINE_integer('batch_size', 32, "the number of examples in a batch")
tf.app.flags.DEFINE_integer('ul_batch_size', 128, "the number of unlabeled examples in a batch")
tf.app.flags.DEFINE_integer('eval_batch_size', 100, "the number of eval examples in a batch")
tf.app.flags.DEFINE_integer('eval_freq', 5, "")
tf.app.flags.DEFINE_integer('num_epochs', 120, "the number of epochs for training")
tf.app.flags.DEFINE_integer('epoch_decay_start', 80, "epoch of starting learning rate decay")
tf.app.flags.DEFINE_integer('num_iter_per_epoch', 400, "the number of updates per epoch")
tf.app.flags.DEFINE_float('learning_rate', 0.001, "initial leanring rate")
tf.app.flags.DEFINE_float('mom1', 0.9, "initial momentum rate")
tf.app.flags.DEFINE_float('mom2', 0.5, "momentum rate after epoch_decay_start")
tf.app.flags.DEFINE_string('method', 'vat', "{vat, vatent, baseline}")
| tensorflow.app.flags.DEFINE_integer | 4,293 |
from tensorflow.python.ops import state_ops
else:
batch_count = math_ops.reduce_sum(
_broadcast_weights(weights, labels)) # n_B in eqn
weighted_predictions = predictions * weights
weighted_labels = labels * weights
update_count = state_ops.assign_add(count, batch_count) # n_AB in eqn
prev_count = update_count - batch_count # n_A in update equation
# We update the means by Delta=Error*BatchCount/(BatchCount+PrevCount)
# batch_mean_prediction is E[x_B] in the update equation
batch_mean_prediction = _safe_div(
| tensorflow.python.ops.state_ops.assign_add | 4,294 |
import tensorflow as tf
# Apply 1 x 1 convolution to each half separately
W_half_1 = self._make_var('W_half_1', (1, 1, in_ch, out_ch >> 1))
X_half_1 = tf.nn.conv2d(half_1, W_half_1, (1, 1, 1, 1), padding='VALID')
W_half_2 = self._make_var('W_half_2', (1, 1, in_ch, out_ch >> 1))
X_half_2 = tf.nn.conv2d(half_2, W_half_2, (1, 1, 1, 1), padding='VALID')
# Concat both halves across channels
X = tf.concat([X_half_1, X_half_2], axis=3)
# Apply batch normalization
X = self._add_batch_norm(X, out_ch, is_train=is_train)
X = tf.reshape(X, (-1, in_w // 2, in_h // 2, out_ch)) # Sanity shape check
| tensorflow.concat | 4,295 |
import tensorflow as tf
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
| tensorflow.get_collection | 4,296 |
import tensorflow as tf
keep_prob=1., is_train=None, wd=0., activation='elu', hn=None):
assert direction is not None
def scaled_tanh(x, scale=5.):
return scale * tf.nn.tanh(1. / scale * x)
bs, sl, vec = tf.shape(rep_tensor)[0], tf.shape(rep_tensor)[1], tf.shape(rep_tensor)[2]
ivec = hn or rep_tensor.get_shape().as_list()[2]
input_dim = rep_tensor.get_shape().as_list()[2]
with tf.variable_scope(scope or 'block_simple'):
# @1. split sequence
with tf.variable_scope('split_seq'):
| tensorflow.shape | 4,297 |
import tensorflow as tf
config.log_device_placement=True
sess = tf.Session(config=config)
| tensorflow.Session | 4,298 |
import tensorflow as tf
alpha_fixed_progress = [
sess.run(
networks._discriminator_alpha(block_id,
tf.constant(1.2, tf.float32)))
for block_id in range(1, 5)
]
self.assertArrayNear(alpha_fixed_block_id, [1, 1, 1, 0.8, 0, 0, 0], 1.0e-6)
self.assertArrayNear(alpha_fixed_progress, [0, 0.8, 1, 1], 1.0e-6)
def test_blend_images_in_stable_stage(self):
x_np = np.random.normal(size=[2, 8, 8, 3])
x = tf.constant(x_np, tf.float32)
x_blend = networks.blend_images(
x,
progress=tf.constant(0.0),
resolution_schedule=networks.ResolutionSchedule(
scale_base=2, num_resolutions=2),
num_blocks=2)
with self.test_session(use_gpu=True) as sess:
x_blend_np = sess.run(x_blend)
x_blend_expected_np = sess.run(layers.upscale(layers.downscale(x, 2), 2))
self.assertNDArrayNear(x_blend_np, x_blend_expected_np, 1.0e-6)
def test_blend_images_in_transition_stage(self):
x_np = np.random.normal(size=[2, 8, 8, 3])
x = tf.constant(x_np, tf.float32)
x_blend = networks.blend_images(
x,
tf.constant(0.2),
| tensorflow.constant | 4,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.