seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
from tensorflow.python.framework import ops
def _apply_dense(self, grad, var):
return training_ops.apply_gradient_descent(
var,
self._learning_rate_tensor,
grad,
use_locking=self._use_locking).op
def _apply_sparse(self, grad, var):
delta = ops.IndexedSlices(grad.values * self._learning_rate_tensor,
grad.indices, grad.dense_shape)
return var.scatter_sub(delta, use_locking=self._use_locking)
def _prepare(self):
self._learning_rate_tensor = ops.convert_to_tensor(self._learning_rate,
name="learning_rate")
| tensorflow.python.framework.ops.convert_to_tensor | 4,000 |
import tensorflow as tf
A training Optimizer.
Raises:
NotImplementedError: If an unsupported optimizer is requested.
"""
# TODO(user): gradient clipping (see Minimize)
if optimizer == 'adagrad':
train_op = tf.train.AdagradOptimizer(learning_rate)
elif optimizer == 'adam':
train_op = tf.train.AdamOptimizer(learning_rate)
elif optimizer == 'momentum':
train_op = tf.train.MomentumOptimizer(learning_rate, momentum)
elif optimizer == 'rmsprop':
train_op = tf.train.RMSPropOptimizer(learning_rate, momentum)
elif optimizer == 'sgd':
train_op = tf.train.GradientDescentOptimizer(learning_rate)
else:
raise NotImplementedError('Unsupported optimizer %s' % optimizer)
return train_op
| tensorflow.train.GradientDescentOptimizer | 4,001 |
import tensorflow as tf
cluster=tpu_cluster_resolver,
master=FLAGS.master,
model_dir=FLAGS.output_dir,
save_checkpoints_steps=FLAGS.save_checkpoints_steps,
tpu_config=tf.contrib.tpu.TPUConfig(
iterations_per_loop=FLAGS.iterations_per_loop,
num_shards=FLAGS.num_tpu_cores,
per_host_input_for_training=is_per_host))
| tensorflow.contrib.tpu.TPUConfig | 4,002 |
from tensorflow.python.ops import math_ops
predictions.get_shape().assert_is_compatible_with(labels.get_shape())
is_false_positive = math_ops.logical_and(math_ops.equal(labels, 0),
math_ops.equal(predictions, 1))
return _count_condition(is_false_positive, weights, metrics_collections,
| tensorflow.python.ops.math_ops.equal | 4,003 |
import tensorflow as tf
inputs (list[tf.Tensor]): List of input placeholders.
extra_inputs (list[tf.Tensor]): List of extra input placeholders.
kwargs (dict): Extra unused keyword arguments. Some optimizers
have extra input, e.g. KL constraint.
"""
del kwargs
with tf.name_scope(self._name):
self._target = target
self._train_op = self._tf_optimizer.minimize(
loss, var_list=target.get_params())
if extra_inputs is None:
| tensorflow.name_scope | 4,004 |
import tensorflow as tf
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)
| tensorflow.matmul | 4,005 |
import tensorflow as tf
for l in range(len(outputs)):
outputs_all[l].append(outputs[l])
# merge outputs on CPU
with tf.device('/cpu:0'):
merged = []
for outputs in outputs_all:
merged.append(merge(outputs, mode='concat', concat_axis=0))
| tensorflow.device | 4,006 |
import tensorflow as tf
'l2_h2_bn',
reuse=self.scope_reuse) as scope:
l2_h2 = tf.contrib.layers.batch_norm(
inputs=l2_h2,
| tensorflow.contrib.layers.batch_norm | 4,007 |
import tensorflow as tf
for grad, var in itertools.chain(*tower_gradvars):
if grad is not None:
all_grads.setdefault(var, []).append(grad)
for var, grads in all_grads.items():
if len(grads) == 1:
avg_grad = grads[0]
else:
avg_grad = tf.multiply(tf.add_n(grads), 1. / len(grads))
gradvars.append((avg_grad, var))
self.loss = tf.reduce_mean(tower_losses)
tf.summary.scalar('loss', self.loss)
# Create optimizer ops
self.global_step = tf.Variable(0, trainable=False, name='global_step')
opt = tf.train.RMSPropOptimizer(self.config['learning_rate'])
with tf.control_dependencies(update_ops):
self.trainer = opt.apply_gradients(
gradvars, global_step=self.global_step)
def _eval_graph(self, data):
tower_metrics = self._gpu_tower(data, Mode.EVAL)
with tf.device('/cpu:0'):
self.metrics = {m: tf.reduce_mean(tf.stack([t[m] for t in tower_metrics]))
for m in tower_metrics[0]}
def _pred_graph(self, data):
with tf.name_scope('pred'):
with tf.device('/gpu:0'):
| tensorflow.train.RMSPropOptimizer | 4,008 |
import tensorflow as tf
self.tail_input = tf.placeholder(tf.int32, shape=[None])
self.target = tf.placeholder(tf.float32, shape=[None])
| tensorflow.placeholder | 4,009 |
import tensorflow as tf
encoded_history = reduce_max(conv3, [1, 2])
with tf.name_scope("Decoder"):
second_to_last_user_utterance = encoded_utterances[:, history_length - 3, 0, :]
last_system_utterance = encoded_utterances[:, history_length - 2, 0, :]
last_user_utterance = encoded_utterances[:, history_length - 1, 0, :]
dialogue_state = tf.concat(
1,
[
encoded_history,
last_user_utterance,
last_system_utterance,
second_to_last_user_utterance,
],
| tensorflow.concat | 4,010 |
import tensorflow as tf
def test_output_must_have_batch_dimension(self):
with self.test_session() as session:
@dynamic_batching.batch_fn
def f(_):
return tf.constant(1)
output = f(tf.constant([1]))
coord = tf.train.Coordinator()
tf.train.start_queue_runners(coord=coord)
with self.assertRaises(tf.errors.CancelledError):
session.run(output)
| tensorflow.constant | 4,011 |
import tensorflow as tf
# Calculate: m(x) m(x)^T + m(x) \mu(x)^T + \mu(x) m(x)^T,
# where m(x) is the mean_function and \mu(x) is fmean
e_mean_mean = expectation(pXnew, mean_function, mean_function) # N x D x D
Lit_q_mu = tf.matrix_triangular_solve(Luu, q_mu, adjoint=True)
e_mean_Kuf = expectation(pXnew, mean_function, (kern, feat)) # N x D x M
# einsum isn't able to infer the rank of e_mean_Kuf, hence we explicitly set the rank of the tensor:
e_mean_Kuf = tf.reshape(e_mean_Kuf, [num_data, num_func, num_ind])
e_fmean_mean = tf.einsum("nqm,mz->nqz", e_mean_Kuf, Lit_q_mu) # N x D x D
e_related_to_mean = e_fmean_mean + tf.matrix_transpose(e_fmean_mean) + e_mean_mean
if full_output_cov:
fvar = (
tf.matrix_diag(tf.tile((eKff - tf.trace(Li_eKuffu_Lit))[:, None], [1, num_func])) +
| tensorflow.reshape | 4,012 |
import tensorflow as tf
eps=hparams.eps)
optimizer = tf.train.AdamOptimizer(learning_rate=hparams.learning_rate)
| tensorflow.train.AdamOptimizer | 4,013 |
import tensorflow as tf
#Place Holders for the input/output data
def create_placeholders(Nfeat, Nlab):
"""
Creates the placeholders for the tensorflow session.
Arguments:
Nfeat -- scalar, size of the feature vector (number of features)
Nlab -- scalar, size of the label vector (number of labels)
Returns:
X -- placeholder for the data input, of shape [n_x, None] and dtype "float"
Y -- placeholder for the input labels, of shape [n_y, None] and dtype "float"
"""
X = tf.placeholder(shape= [Nfeat, None], dtype= "float64" )
Y = tf.placeholder(shape= [Nlab, None], dtype= "float64" )
return X, Y
#parameters initialization
def initialize_parameters(layers, activation, stbeta):
'''
Initialise the parameters of the model:
Arguments:
layers: Topology of the network. Array contaning number of layers and number of units in each layer.
activation: list of activation functions, for each layer in the network.
| tensorflow.placeholder | 4,014 |
import tensorflow as tf
self.terminals_ph = tf.placeholder(tf.float32, shape=(None, 1), name='terminals')
self.rewards_ph = tf.placeholder(tf.float32, shape=(None, 1), name='rewards')
| tensorflow.placeholder | 4,015 |
import tensorflow as tf
dtype = initial_learning_rate.dtype
maximal_learning_rate = tf.cast(self.maximal_learning_rate, dtype)
step_size = tf.cast(self.step_size, dtype)
cycle = tf.floor(1 + step / (2 * step_size))
| tensorflow.cast | 4,016 |
import tensorflow as tf
def get_keypoint(image, targets, predictions, heatmap_size, height, width, category, clip_at_zero=True, data_format='channels_last', name=None):
predictions = tf.reshape(predictions, [1, -1, heatmap_size*heatmap_size])
pred_max = tf.reduce_max(predictions, axis=-1)
pred_indices = tf.argmax(predictions, axis=-1)
pred_x, pred_y = tf.cast(tf.floormod(pred_indices, heatmap_size), tf.float32), tf.cast(tf.floordiv(pred_indices, heatmap_size), tf.float32)
width, height = tf.cast(width, tf.float32), tf.cast(height, tf.float32)
pred_x, pred_y = pred_x * width / tf.cast(heatmap_size, tf.float32), pred_y * height / tf.cast(heatmap_size, tf.float32)
if clip_at_zero:
pred_x, pred_y = pred_x * tf.cast(pred_max>0, tf.float32), pred_y * tf.cast(pred_max>0, tf.float32)
pred_x = pred_x * tf.cast(pred_max>0, tf.float32) + tf.cast(pred_max<=0, tf.float32) * (width / 2.)
pred_y = pred_y * tf.cast(pred_max>0, tf.float32) + tf.cast(pred_max<=0, tf.float32) * (height / 2.)
if config.PRED_DEBUG:
| tensorflow.cast | 4,017 |
import tensorflow as tf
loss_entropy = - 0.01 * tf.reduce_mean(pi.entropy())
loss = loss_pg + loss_vf + loss_entropy
opt = tf.train.AdamOptimizer(self.LR)
self.train_op = opt.minimize(loss, global_step=self.global_step, var_list=pi_params + vf_params)
self.pi_new_params = [oldp.assign(p) for p, oldp in zip(pi_params, pi_old_params)]
self.vf_new_params = [oldp.assign(p) for p, oldp in zip(vf_params, vf_old_params)]
self.sess.run(tf.global_variables_initializer())
# Tensorboard
if summary_dir is not None:
self.writer = tf.summary.FileWriter(summary_dir)
tf.summary.scalar('Loss/Policy', loss_pg)
tf.summary.scalar('Loss/Value', loss_vf)
tf.summary.scalar('Loss/Entropy', loss_entropy)
tf.summary.scalar('Loss/Total', loss)
tf.summary.scalar('Var/Epsilon', epsilon_decay)
tf.summary.scalar('Var/Policy Mode', tf.reduce_mean(pi.mode()))
tf.summary.scalar('Var/Policy Sigma', tf.reduce_mean(pi.stddev()))
tf.summary.scalar('Var/Value', tf.reduce_mean(self.vf))
self.summarise = tf.summary.merge(tf.get_collection(tf.GraphKeys.SUMMARIES))
# AC net
def build_anet(self, state_in, name, reuse=False):
reg = tf.contrib.layers.l2_regularizer(1e-3)
with tf.variable_scope(name, reuse=reuse):
| tensorflow.summary.scalar | 4,018 |
import tensorflow as tf
idx_z1_y0_x1 = base_z1_y0 + x1_clip
idx_z1_y1_x0 = base_z1_y1 + x0_clip
idx_z1_y1_x1 = base_z1_y1 + x1_clip
# Use indices to lookup pixels in the flat image and restore
# channels dim
im_flat = tf.reshape(im, tf.stack([-1, channels]))
im_flat = tf.to_float(im_flat)
i_z0_y0_x0 = tf.gather(im_flat, idx_z0_y0_x0)
i_z0_y0_x1 = tf.gather(im_flat, idx_z0_y0_x1)
i_z0_y1_x0 = tf.gather(im_flat, idx_z0_y1_x0)
i_z0_y1_x1 = tf.gather(im_flat, idx_z0_y1_x1)
i_z1_y0_x0 = tf.gather(im_flat, idx_z1_y0_x0)
i_z1_y0_x1 = tf.gather(im_flat, idx_z1_y0_x1)
i_z1_y1_x0 = tf.gather(im_flat, idx_z1_y1_x0)
i_z1_y1_x1 = tf.gather(im_flat, idx_z1_y1_x1)
# Finally calculate interpolated values.
x0_f = tf.to_float(x0)
x1_f = tf.to_float(x1)
y0_f = tf.to_float(y0)
y1_f = tf.to_float(y1)
z0_f = tf.to_float(z0)
z1_f = tf.to_float(z1)
# Check the out-of-boundary case.
x0_valid = tf.to_float(
tf.less_equal(x0, max_x) & tf.greater_equal(x0, 0))
x1_valid = tf.to_float(
| tensorflow.gather | 4,019 |
from tensorflow.contrib.metrics.python.ops import metric_ops
def _predictions_streaming_mean(predictions, unused_labels, weights=None):
return metric_ops.streaming_mean(predictions, weights=weights)
| tensorflow.contrib.metrics.python.ops.metric_ops.streaming_mean | 4,020 |
import tensorflow as tf
label_ids = features["label_ids"]
is_real_example = None
if "is_real_example" in features:
is_real_example = tf.cast(features["is_real_example"], dtype=tf.float32)
else:
is_real_example = tf.ones(tf.shape(label_ids), dtype=tf.float32)
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
(total_loss, per_example_loss, logits, probabilities) = create_model(
| tensorflow.shape | 4,021 |
import tensorflow as tf
if not shape[1]:
raise ValueError("Linear expects shape[1] of arguments: %s" % str(shapes))
else:
total_arg_size += shape[1]
# Now the computation.
with tf.variable_scope(scope or "Linear"):
matrix = tf.get_variable("Matrix", [total_arg_size, output_size])
if len(args) == 1:
res = tf.matmul(args[0], matrix)
else:
res = tf.matmul(tf.concat(values=args, axis=1), matrix)
if not bias:
return res
bias_term = tf.get_variable("Bias", [output_size], initializer=tf.constant_initializer(bias_start))
return res + bias_term
def _clip_and_normalize(word_probs, epsilon):
'''
word_probs: 1D tensor of [vsize]
'''
word_probs = tf.clip_by_value(word_probs, epsilon, 1.0 - epsilon)
return word_probs / tf.reduce_sum(word_probs, axis=-1, keep_dims=True) # scale preds so that the class probas of each sample sum to 1
def CE_loss(word_probs, answers, loss_weights):
'''
word_probs: [batch_size, max_dec_steps, vocab]
| tensorflow.constant_initializer | 4,022 |
import tensorflow as tf
batch_size = tf.shape(a)[0]
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 | 4,023 |
import tensorflow as tf
def _input_fn_builder(self, input_file, is_training):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
def input_fn(params):
"""The actual input function."""
d = tf.data.TFRecordDataset(input_file)
if is_training:
d = d.repeat()
d = d.shuffle(buffer_size=100)
return d.apply(
| tensorflow.data.TFRecordDataset | 4,024 |
import tensorflow as tf
#
# If the input is a 2D tensor of shape [batch_size, seq_length], we
# reshape to [batch_size, seq_length, 1].
if input_ids.shape.ndims == 2:
input_ids = tf.expand_dims(input_ids, axis=[-1])
embedding_table = tf.get_variable(
name=word_embedding_name,
shape=[vocab_size, embedding_size],
initializer=create_initializer(initializer_range))
if use_one_hot_embeddings:
flat_input_ids = tf.reshape(input_ids, [-1])
one_hot_input_ids = tf.one_hot(flat_input_ids, depth=vocab_size)
output = tf.matmul(one_hot_input_ids, embedding_table)
else:
output = tf.nn.embedding_lookup(embedding_table, input_ids)
input_shape = get_shape_list(input_ids)
output = tf.reshape(output,
input_shape[0:-1] + [input_shape[-1] * embedding_size])
return (output, embedding_table)
def embedding_postprocessor(input_tensor,
| tensorflow.one_hot | 4,025 |
import tensorflow as tf
"""
with tf.variable_scope(name_or_scope=self.name, reuse=tf.AUTO_REUSE):
| tensorflow.variable_scope | 4,026 |
import tensorflow as tf
# Create the output to the network. This is our one hot encoding of 2 possible values (TODO)!
Y = tf.placeholder(name='Y', shape=[None,data_y.shape[1]], dtype=tf.float32)
print ("building network ")
for i, filter_size in enumerate(filter_list):
with tf.variable_scope("conv/stack/{}".format(i), reuse=None):
# initialize filter
W = tf.get_variable(
name='W',
shape=[filter_size, num_feature, 1, num_filter],
initializer=tf.contrib.layers.xavier_initializer_conv2d())
# convolve w and input
conv = tf.nn.conv2d(
name='conv',
input=X,
filter=W,
strides=[1, 1, 1, 1],
padding='VALID')
#add bias of size = out cannels
b = tf.get_variable(
name='b',
shape=[num_filter],
initializer=tf.constant_initializer(0.0))
H = tf.nn.bias_add(
| tensorflow.nn.conv2d | 4,027 |
import tensorflow as tf
gru_bw = tf.contrib.cudnn_rnn.CudnnGRU(1, num_units)
init_fw = tf.tile(tf.Variable(
tf.zeros([1, 1, num_units])), [1, batch_size, 1])
init_bw = tf.tile(tf.Variable(
tf.zeros([1, 1, num_units])), [1, batch_size, 1])
mask_fw = dropout(tf.ones([1, batch_size, input_size_], dtype=tf.float32),
keep_prob=keep_prob, is_train=is_train, mode=None)
mask_bw = dropout(tf.ones([1, batch_size, input_size_], dtype=tf.float32),
| tensorflow.zeros | 4,028 |
import tensorflow as tf
with self.assertRaisesRegexp(tf.errors.InvalidArgumentError,
'Shapes of inputs much be equal'):
coord.join()
def test_output_must_have_batch_dimension(self):
with self.test_session() as session:
@dynamic_batching.batch_fn
def f(_):
return tf.constant(1)
output = f(tf.constant([1]))
coord = tf.train.Coordinator()
tf.train.start_queue_runners(coord=coord)
with self.assertRaises(tf.errors.CancelledError):
session.run(output)
| tensorflow.constant | 4,029 |
import tensorflow as tf
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])
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,
num_heads=2)
sess.run([tf.global_variables_initializer()])
res = sess.run(dec)
self.assertEqual(3, len(res))
self.assertEqual((2, 4), res[0].shape)
| tensorflow.nn.dynamic_rnn | 4,030 |
from tensorflow.python.platform import test
with session.Session(worker.target):
var0, var1, update_op = self._setupSparse(True, dtype)
self._assertSparseCorrect(var0, var1, update_op)
if __name__ == "__main__":
test.main()
| tensorflow.python.platform.test.main | 4,031 |
import tensorflow as tf
tf.nn.softmax_cross_entropy_with_logits(labels=y_input, logits=encoder_output_label_))
all_variables = tf.trainable_variables()
dc_g_var = [var for var in all_variables if 'dc_g_' in var.name]
dc_c_var = [var for var in all_variables if 'dc_c_' in var.name]
en_var = [var for var in all_variables if 'e_' in var.name]
# Optimizers
autoencoder_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate,
beta1=beta1).minimize(autoencoder_loss)
discriminator_g_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate,
beta1=beta1).minimize(dc_g_loss, var_list=dc_g_var)
discriminator_c_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate,
beta1=beta1).minimize(dc_c_loss, var_list=dc_c_var)
generator_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate,
beta1=beta1).minimize(generator_loss, var_list=en_var)
supervised_encoder_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate,
beta1=beta1).minimize(supervised_encoder_loss,
var_list=en_var)
init = tf.global_variables_initializer()
# Reshape immages to display them
input_images = tf.reshape(x_input, [-1, 28, 28, 1])
| tensorflow.train.AdamOptimizer | 4,032 |
import tensorflow as tf
if self.irl_model.score_trajectories:
# TODO: should I add to reward here or after advantage computation?
for i, path in enumerate(paths):
path['rewards'][-1] += self.irl_model_wt * probs[i]
else:
for i, path in enumerate(paths):
path['rewards'] += self.irl_model_wt * probs[i]
return paths
def train(self,weightname):
sess = tf.get_default_session()
sess.run(tf.global_variables_initializer())
if self.init_pol_params is not None:
self.policy.set_param_values(self.init_pol_params)
if self.init_irl_params is not None:
self.irl_model.set_params(self.init_irl_params)
self.start_worker()
start_time = time.time()
returns = []
self.myweights.append(self.irl_model.get_weights())
| tensorflow.get_default_session | 4,033 |
import tensorflow as tf
eval_examples = processor.get_dev_examples(FLAGS.data_dir)
eval_file = os.path.join(FLAGS.output_dir, "eval.tf_record")
file_based_convert_examples_to_features(
eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file)
tf.logging.info("***** Running evaluation *****")
tf.logging.info(" Num examples = %d", len(eval_examples))
tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
# This tells the estimator to run through the entire set.
eval_steps = None
# However, if running eval on the TPU, you will need to specify the
# number of steps.
if FLAGS.use_tpu:
| tensorflow.logging.info | 4,034 |
import tensorflow as tf
@property
def state_size(self):
return sum(self.cell.state_size)
@property
def output_size(self):
return self.cell.output_size
def __call__(self, inputs, state, scope=None):
state = tf.split(value=state, num_or_size_splits=self.num_splits, axis=1)
new_h, new_state = self.cell(inputs, state, scope=scope)
return new_h, tf.concat(new_state, 1)
def multi_encoder(encoder_inputs, encoders, encoder_input_length, other_inputs=None, training=True, **kwargs):
"""
Build multiple encoders according to the configuration in `encoders`, reading from `encoder_inputs`.
The result is a list of the outputs produced by those encoders (for each time-step), and their final state.
:param encoder_inputs: list of tensors of shape (batch_size, input_length), one tensor for each encoder.
:param encoders: list of encoder configurations
:param encoder_input_length: list of tensors of shape (batch_size,) (one tensor for each encoder)
| tensorflow.concat | 4,035 |
import tensorflow as tf
intersections = pairwise_intersection(boxlist1, boxlist2)
areas1 = area(boxlist1)
areas2 = area(boxlist2)
unions = (
tf.expand_dims(areas1, 1) + tf.expand_dims(areas2, 0) - intersections)
return tf.where(
tf.equal(intersections, 0.0),
tf.zeros_like(intersections), tf.truediv(intersections, unions))
| tensorflow.expand_dims | 4,036 |
import tensorflow as tf
h = h
z = tf.matmul(x, wx) + tf.matmul(h, wh) + 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(c)
xs[idx] = h
s = tf.concat(axis=1, values=[c, h])
return xs, s
def ortho_init(scale=1.0):
def _ortho_init(shape, dtype, partition_info=None):
| tensorflow.tanh | 4,037 |
import tensorflow as tf
def lstm_network(input, scope='lstm_network'):
with tf.variable_scope(scope):
# tf.nn.rnn_cell
lstm_cell1 = tf.contrib.rnn.BasicLSTMCell(lstm_hidden_size_layer1, forget_bias=1.0)
lstm_cell2 = tf.contrib.rnn.BasicLSTMCell(lstm_hidden_size_layer2, forget_bias=1.0)
lstm_cells = tf.contrib.rnn.MultiRNNCell(cells=[lstm_cell1, lstm_cell2], state_is_tuple=True)
| tensorflow.contrib.rnn.BasicLSTMCell | 4,038 |
import tensorflow as tf
@pytest.mark.parametrize('white', [True, False])
def test_oned(session_tf, white, mu, sqrt, K_batch):
"""
Check that the KL divergence matches a 1D by-hand calculation.
"""
m = 0
mu1d = mu[m,:][None,:] # 1 x N
s1d = sqrt[:,m,m][:,None,None] # N x 1 x 1
K1d = K_batch[:,m,m][:,None,None] # N x 1 x 1
kl = gauss_kl(mu1d,s1d,K1d if not white else None)
kl_tf = tf_kl_1d(tf.reshape(mu1d,(-1,)), # N
tf.reshape(s1d,(-1,)), # N
None if white else tf.reshape(K1d,(-1,))) # N
np.testing.assert_allclose(kl.eval(), kl_tf.eval())
if __name__ == "__main__":
tf.test.main()
| tensorflow.reshape | 4,039 |
import tensorflow as tf
# augmentation functions
# augment
def random_crop_and_resize(images, ratio=0.8):
b, h, w, c = images.get_shape().as_list()
ch, cw = map(lambda x: int(x * ratio), (h, w))
crop = tf.random_crop(images, size=[b, ch, cw, 3])
crop = tf.image.resize(crop, [h, w])
return crop
def random_apply(fn, image, prob=1.):
b, *_ = image.get_shape().as_list()
chance = tf.less(tf.random_uniform([b], 0, 1.0), prob)
return tf.where(chance, fn(image), tf.identity(image))
def color_distortion(image, s=1.0):
lower, upper, x = (1 - 0.8 * s), (1 + 0.8 * s), image
x = tf.image.random_brightness(x, max_delta=0.8*s)
x = tf.image.random_contrast(x, lower=lower, upper=upper)
x = tf.image.random_saturation(x, lower=lower, upper=upper)
x = tf.image.random_hue(x, max_delta=0.2*s)
x = tf.clip_by_value(x, 0, 1)
return x
def color_drop(image):
| tensorflow.random_uniform | 4,040 |
from tensorflow.python.ops import math_ops
if weight_tensor is None:
return math_ops.reduce_mean(loss_unweighted, name="loss")
loss_weighted = self._weighted_loss(loss_unweighted, weight_tensor)
return math_ops.div(math_ops.reduce_sum(loss_weighted),
math_ops.to_float(math_ops.reduce_sum(weight_tensor)),
name="loss")
| tensorflow.python.ops.math_ops.reduce_sum | 4,041 |
import tensorflow as tf
b = tf.get_variable("b", [nh*4], initializer=tf.constant_initializer(0.0))
gc = tf.get_variable("gc", [nh], initializer=tf.constant_initializer(1.0))
bc = tf.get_variable("bc", [nh], initializer=tf.constant_initializer(0.0))
c, h = tf.split(axis=1, num_or_size_splits=2, value=s)
| tensorflow.constant_initializer | 4,042 |
import tensorflow as tf
else:
return tf.reshape(tf.stack(values=h, axis=1), [-1])
def lstm(xs, ms, s, scope, nh, init_scale=1.0):
nbatch, nin = [v.value for v in xs[0].get_shape()]
with tf.variable_scope(scope):
wx = tf.get_variable("wx", [nin, nh*4], initializer=ortho_init(init_scale))
wh = tf.get_variable("wh", [nh, nh*4], initializer=ortho_init(init_scale))
b = tf.get_variable("b", [nh*4], initializer=tf.constant_initializer(0.0))
c, h = tf.split(axis=1, num_or_size_splits=2, value=s)
for idx, (x, m) in enumerate(zip(xs, ms)):
c = c*(1-m)
h = h*(1-m)
z = tf.matmul(x, wx) + tf.matmul(h, wh) + 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(c)
xs[idx] = h
s = tf.concat(axis=1, values=[c, h])
return xs, s
def _ln(x, g, b, e=1e-5, axes=[1]):
u, s = tf.nn.moments(x, axes=axes, keep_dims=True)
x = (x-u)/tf.sqrt(s+e)
x = x*g+b
| tensorflow.split | 4,043 |
import tensorflow as tf
from deepr.layers import base
@base.layer(n_in=2, n_out=3)
def LSTM(tensors, num_units: int, bidirectional: bool = False, **kwargs):
"""LSTM layer."""
words, nwords = tensors
t = tf.transpose(words, perm=[1, 0, 2])
lstm_cell_fw = tf.contrib.rnn.LSTMBlockFusedCell(num_units=num_units, **kwargs)
outputs_fw, (hidden_fw, output_fw) = lstm_cell_fw(t, dtype=tf.float32, sequence_length=nwords)
if bidirectional:
lstm_cell_bw = tf.contrib.rnn.LSTMBlockFusedCell(num_units=num_units, **kwargs)
lstm_cell_bw = tf.contrib.rnn.TimeReversedFusedRNN(lstm_cell_bw)
| tensorflow.transpose | 4,044 |
import tensorflow as tf
ENV_NAME = 'BipedalWalker-v2'
GLOBAL_STEP = tf.Variable(0, trainable=False)
INCREASE_GS = GLOBAL_STEP.assign(tf.add(GLOBAL_STEP, 1))
| tensorflow.Variable | 4,045 |
import tensorflow as tf
elif activation == 'relu':
gru=tf.nn.rnn_cell.GRUCell(state_size, activation = tf.nn.relu)
cell_drop=tf.contrib.rnn.DropoutWrapper(gru,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob)
else:
| tensorflow.contrib.rnn.DropoutWrapper | 4,046 |
import tensorflow as tf
a = np.array([1, 2, 3], dtype=np.float32)
tf_v = tf.Variable(5, dtype=tf.float32)
| tensorflow.Variable | 4,047 |
import tensorflow as tf
x = tf.placeholder(tf.float32, [None, num_steps, input_size_x], name='x')
y = tf.placeholder(tf.float32, [None, num_steps, input_size_y], name='y')
input_prob = tf.placeholder(tf.float32, name='input_prob')
state_prob = tf.placeholder(tf.float32,name='state_prob')
output_prob = tf.placeholder(tf.float32,name='output_prob')
rnn_inputs = x
| tensorflow.placeholder | 4,048 |
import tensorflow as tf
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)
| tensorflow.nn.softmax | 4,049 |
import tensorflow as tf
For tf padding, refer to: https://www.tensorflow.org/api_docs/python/tf/pad
"""
reg_l2 = tf.keras.regularizers.l2(5e-7)
if padding == 'SYMMETRIC' or padding == 'REFLECT':
p = (kernel_size - 1) // 2
x = tf.pad(x, [[0,0],[p,p],[p,p], [p,p],[0,0]], padding)
x = tf.keras.layers.Conv3D(filters, kernel_size, activation=activation, kernel_initializer=initialization, use_bias=use_bias, kernel_regularizer=reg_l2)(x)
else:
assert padding in ['SAME', 'VALID']
x = tf.keras.layers.Conv3D(filters, kernel_size, activation=activation, kernel_initializer=initialization, use_bias=use_bias, kernel_regularizer=reg_l2)(x)
return x
| tensorflow.pad | 4,050 |
import tensorflow as tf
param_noise_threshold = tf.get_variable("param_noise_threshold", (), initializer=tf.constant_initializer(0.05),
trainable=False)
# Unmodified Q.
policy = q_func(sess, ob_space, ac_space, 1, 1, None)
obs_phs = (policy.obs_ph, policy.processed_obs)
# Perturbable Q used for the actual rollout.
with tf.variable_scope("perturbed_model", reuse=False):
perturbable_policy = q_func(sess, ob_space, ac_space, 1, 1, None, obs_phs=obs_phs)
def perturb_vars(original_scope, perturbed_scope):
"""
We have to wrap this code into a function due to the way tf.cond() works.
See https://stackoverflow.com/questions/37063952/confused-by-the-behavior-of-tf-cond for a more detailed
| tensorflow.variable_scope | 4,051 |
import tensorflow as tf
Input:
vecs: A Tensor of shape (batch_size, vec_dim)
segment_inds: A Tensor containing the segment index of each
vec row, should agree with vecs in shape[0]
Output:
A tensor of shape (vec_dim)
"""
if reduction_mode == 'max':
print('USING MAX POOLING FOR REDUCTION!')
vecs_reduced = tf.segment_max(vecs, segment_inds)
elif reduction_mode == 'mean':
print('USING AVG POOLING FOR REDUCTION!')
vecs_reduced = tf.segment_mean(vecs, segment_inds)
vecs_reduced.set_shape([num_segments, vecs.get_shape()[1]])
return vecs_reduced
| tensorflow.segment_max | 4,052 |
import tensorflow as tf
return n - two, result, two
def _double_factorial_loop_condition(n, result, two):
return tf.cast(tf.math.count_nonzero(tf.greater_equal(n, two)), tf.bool)
def double_factorial(n: TensorLike) -> TensorLike:
n = tf.convert_to_tensor(value=n)
two = tf.ones_like(n) * 2
result = tf.ones_like(n)
_, result, _ = tf.while_loop(
cond=_double_factorial_loop_condition,
body=_double_factorial_loop_body,
loop_vars=[n, result, two])
| tensorflow.convert_to_tensor | 4,053 |
import tensorflow as tf
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
init = tf.initialize_all_variables()
| tensorflow.initialize_all_variables | 4,054 |
from tensorflow.contrib.layers.python.ops import sparse_feature_cross_op
"""Tests the new version of the fingerprint concatenation has no collisions.
"""
# Although the last 10 bits of 359 and 1024+359 are identical.
# As a result, all the crosses shouldn't collide.
t1 = constant_op.constant([[359], [359 + 1024]])
t2 = constant_op.constant([list(range(10)), list(range(10))])
cross = sparse_feature_cross_op.sparse_feature_cross(
[t2, t1],
hashed_output=True,
num_buckets=1024,
hash_key=layers.SPARSE_FEATURE_CROSS_DEFAULT_HASH_KEY)
cross_dense = sparse_ops.sparse_tensor_to_dense(cross)
| tensorflow.contrib.layers.python.ops.sparse_feature_cross_op.sparse_feature_cross | 4,055 |
import tensorflow as tf
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
| tensorflow.tanh | 4,056 |
import tensorflow as tf
next_sentence_labels = tf.reshape(next_sentence_labels, [-1])
next_sentence_accuracy = tf.metrics.accuracy(
| tensorflow.metrics.accuracy | 4,057 |
from tensorflow.python.framework import ops
if set_shape:
ret.set_shape(shape)
return ret
# NOTE(mrry): Shapes are conditionally set in the Python wrapper.
ops.RegisterShape("Variable")(common_shapes.unknown_shape)
@ops.RegisterShape("TemporaryVariable")
def _TemporaryVariableShape(op):
"""Shape function for the TemporaryVariable op."""
shape = tensor_util.TensorShapeProtoToList(op.get_attr("shape"))
return [tensor_shape.TensorShape(shape)]
@ops.RegisterShape("DestroyTemporaryVariable")
def _DestroyTemporaryVariableShape(op):
| tensorflow.python.framework.ops.RegisterShape | 4,058 |
import tensorflow as tf
mask2 = tf.constant([[1, 0],
[1, 1]], dtype=tf.float32)
mask3 = tf.constant([[1, 1],
[1, 1]], dtype=tf.float32)
| tensorflow.constant | 4,059 |
from tensorflow.python.framework import ops
biases: a 1D tensor. Dimensions: out_units
name: A name for the operation (optional). If not specified
"xw_plus_b_v1" is used.
Returns:
A 2-D Tensor computing matmul(x, weights) + biases.
Dimensions typically: batch, out_units.
"""
with ops.op_scope([x, weights, biases], name, "xw_plus_b_v1") as name:
x = ops.convert_to_tensor(x, name="x")
weights = ops.convert_to_tensor(weights, name="weights")
biases = ops.convert_to_tensor(biases, name="biases")
mm = math_ops.matmul(x, weights)
return bias_add_v1(mm, biases, name=name)
| tensorflow.python.framework.ops.op_scope | 4,060 |
from tensorflow.python.framework import ops
ops.RegisterShape("Neg")(common_shapes.unchanged_shape)
ops.RegisterShape("Real")(common_shapes.unchanged_shape)
ops.RegisterShape("Rsqrt")(common_shapes.unchanged_shape)
ops.RegisterShape("Sign")(common_shapes.unchanged_shape)
ops.RegisterShape("Sin")(common_shapes.unchanged_shape)
ops.RegisterShape("Sqrt")(common_shapes.unchanged_shape)
ops.RegisterShape("Square")(common_shapes.unchanged_shape)
ops.RegisterShape("Sigmoid")(common_shapes.unchanged_shape)
ops.RegisterShape("Tanh")(common_shapes.unchanged_shape)
ops.RegisterShape("Cast")(common_shapes.unchanged_shape)
ops.RegisterShape("ComplexAbs")(common_shapes.unchanged_shape)
@ops.RegisterShape("Add")
@ops.RegisterShape("Complex")
@ops.RegisterShape("Div")
@ops.RegisterShape("Equal")
@ops.RegisterShape("Greater")
| tensorflow.python.framework.ops.RegisterShape | 4,061 |
import tensorflow as tf
pair_emb = tf.concat([target_emb, top_antecedent_emb, similarity_emb, feature_emb], 2) # [k, c, emb]
with tf.variable_scope("slow_antecedent_scores"):
slow_antecedent_scores = util.ffnn(pair_emb, self.config["ffnn_depth"], self.config["ffnn_size"], 1, self.dropout) # [k, c, 1]
slow_antecedent_scores = tf.squeeze(slow_antecedent_scores, 2) # [k, c]
return slow_antecedent_scores # [k, c]
def get_fast_antecedent_scores(self, top_span_emb):
with tf.variable_scope("src_projection"):
source_top_span_emb = tf.nn.dropout(util.projection(top_span_emb, util.shape(top_span_emb, -1)), self.dropout) # [k, emb]
target_top_span_emb = tf.nn.dropout(top_span_emb, self.dropout) # [k, emb]
return tf.matmul(source_top_span_emb, target_top_span_emb, transpose_b=True) # [k, k]
def flatten_emb_by_sentence(self, emb, text_len_mask):
num_sentences = tf.shape(emb)[0]
max_sentence_length = tf.shape(emb)[1]
emb_rank = len(emb.get_shape())
if emb_rank == 2:
flattened_emb = tf.reshape(emb, [num_sentences * max_sentence_length])
elif emb_rank == 3:
flattened_emb = tf.reshape(emb, [num_sentences * max_sentence_length, util.shape(emb, 2)])
else:
raise ValueError("Unsupported rank: {}".format(emb_rank))
return tf.boolean_mask(flattened_emb, tf.reshape(text_len_mask, [num_sentences * max_sentence_length]))
def lstm_contextualize(self, text_emb, text_len, text_len_mask):
num_sentences = tf.shape(text_emb)[0]
current_inputs = text_emb # [num_sentences, max_sentence_length, emb]
| tensorflow.shape | 4,062 |
import tensorflow as tf
output_t = linear([cell_output] + [context_t], options.gen_hidden_size, True)
with tf.variable_scope('output_projection'):
w = tf.get_variable('w', [options.gen_hidden_size, vocab.vocab_size+1], dtype=tf.float32)
b = tf.get_variable('b', [vocab.vocab_size +1], dtype=tf.float32)
# vocab_scores is the vocabulary distribution before applying softmax.
| tensorflow.get_variable | 4,063 |
import tensorflow as tf
from six.moves import urllib
import tensorflow as tf
# from tensorflow.models.image.cifar10 import cifar10_input
import convert_to_records as records
import numpy as np
FLAGS = tf.app.flags.FLAGS
# Basic model parameters.
tf.app.flags.DEFINE_float('learning_rate', 0.1, 'Initial learning rate.')
tf.app.flags.DEFINE_string('pm', '66661', 'pooling scheme across scales. Each number specifies the number of scales remaining at each layer. The first number has to be the same as used in --num_scales.')
tf.app.flags.DEFINE_integer('conv_kernel', 5, 'Size of convolutional kernel')
tf.app.flags.DEFINE_integer('pool_kernel', 3, 'Size of spatial pooling kernel')
tf.app.flags.DEFINE_integer('feats_per_layer', 32, 'Number of feature channels at each layer')
tf.app.flags.DEFINE_boolean('total_pool', True, 'If true, pool all feature maps to 1x1 size in final layer')
tf.app.flags.DEFINE_integer('pool_stride', '1', 'If 2, we get progressive pooling - with overlap pooling, AlexNet style')
TRAIN_FILE = 'train_{}.tfrecords'.format(records.tfrecord_name())
VALIDATION_FILE = 'validation_{}.tfrecords'.format(records.tfrecord_name())
TEST_FILE = 'test_{}.tfrecords'.format(records.tfrecord_name())
| tensorflow.app.flags.DEFINE_integer | 4,064 |
import tensorflow as tf
return h
def embed(X, we):
#X [-1,,2]
we = convert_gradient_to_tensor(we)
e = tf.gather(we, X)
h = tf.reduce_sum(e, 2)
return h
def clf(x, ny, w_init=tf.random_normal_initializer(stddev=0.02), b_init=tf.constant_initializer(0), train=False):
with tf.variable_scope('clf'):
nx = shape_list(x)[-1]
w = tf.get_variable("w", [nx, ny], initializer=w_init)
b = tf.get_variable("b", [ny], initializer=b_init)
return tf.matmul(x, w)+b
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)
#X:[n_batch_train, 2, n_ctx, 2] -> [n_batch_train*2,n_ctx,2]
X = tf.reshape(X, [-1, n_ctx, 2])
M = tf.reshape(M, [-1, n_ctx])
| tensorflow.get_variable | 4,065 |
from tensorflow.python.platform import test
if __name__ == "__main__":
test.main()
| tensorflow.python.platform.test.main | 4,066 |
import tensorflow as tf
run_time = time.time() - start_time
print('Run time: ', run_time)
print('Time per video: ',run_time/nrof_batches)
def load_and_align_data(image_paths, image_size, margin, gpu_memory_fraction):
print('Creating networks and loading parameters')
with tf.Graph().as_default():
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
with sess.as_default():
pnet, rnet, onet = align.detect_face.create_mtcnn(sess, None)
nrof_samples = len(image_paths)
img_list = [None] * nrof_samples
for i in xrange(nrof_samples):
print(image_paths[i])
img = misc.imread(os.path.expanduser(image_paths[i]))
aligned = misc.imresize(img, (image_size, image_size), interp='bilinear')
prewhitened = facenet.prewhiten(aligned)
img_list[i] = prewhitened
| tensorflow.ConfigProto | 4,067 |
import tensorflow as tf
# by the softmax layer's out_weight of shape [num_units,n_classes]
# plus out_bias
prediction = tf.matmul(outputs[-1], out_weights) + out_bias
output_class = tf.nn.softmax(prediction, name="OUTPUT_CLASS")
| tensorflow.matmul | 4,068 |
import tensorflow as tf
return_dict["end_top_log_probs"] = end_top_log_probs
return_dict["end_top_index"] = end_top_index
# an additional layer to predict answerability
with tf.variable_scope("answer_class"):
# get the representation of CLS
cls_index = tf.one_hot(cls_index, seq_len, axis=-1, dtype=tf.float32)
cls_feature = tf.einsum("lbh,bl->bh", output, cls_index)
# get the representation of START
start_p = tf.nn.softmax(start_logits_masked, axis=-1,
name="softmax_start")
| tensorflow.one_hot | 4,069 |
import tensorflow as tf
'Batch size for training and evaluation.')
tf.app.flags.DEFINE_boolean(
'use_ohkm', True,
'Wether we will use the ohkm for hard keypoints.')
tf.app.flags.DEFINE_string(
'data_format', 'channels_first', # 'channels_first' or 'channels_last'
'A flag to override the data format used in the model. channels_first '
'provides a performance boost on GPU but is not always compatible '
| tensorflow.app.flags.DEFINE_string | 4,070 |
import tensorflow as tf
eval_metrics=eval_metrics,
scaffold_fn=scaffold_fn,
)
else:
output_spec = tf.estimator.EstimatorSpec(mode=mode, loss=total_loss)
else:
raise ValueError("Only TRAIN and EVAL modes are supported: %s" % (mode))
| tensorflow.estimator.EstimatorSpec | 4,071 |
import tensorflow as tf
dec = tf.layers.max_pooling1d(dec, pool_size=2, strides=1, padding="same")
dec = tf.layers.conv1d(dec, embed_size // 2, 3, name="decoder-conv1-1", padding="SAME")
dec = tf.nn.relu(tf.layers.batch_normalization(dec, training=self.training))
dec = tf.layers.conv1d(dec, embed_size // 2, 3, name="decoder-conv1-2", padding="SAME")
dec = tf.layers.batch_normalization(dec, training=self.training)
dec = tf.layers.dense(dec, embed_size // 2)
for i in range(4):
dec = highwaynet(
dec, num_units=embed_size // 2, scope="decoder-highwaynet-{}".format(i)
)
| tensorflow.layers.dense | 4,072 |
import tensorflow as tf
tgt_flat = tf.reshape(horizon_tgt, [-1])
batch = tf.stack([pred_flat, tgt_flat], 1)
| tensorflow.stack | 4,073 |
import tensorflow as tf
render = False # display the game environment
running_reward = None
tf.reset_default_graph()
## Define Q-network q(a,s) that ouput the rewards of 4 actions by given state, i.e. Action-Value Function.
# 4x4 grid can be represented by one-hot vector with 16 integers.
inputs = tf.placeholder(shape=[1, 16], dtype=tf.float32)
net = InputLayer(inputs, name='observation')
net = DenseLayer(net, n_units=4, act=tf.identity,
W_init=tf.random_uniform_initializer(0, 0.01), b_init=None, name='q_a_s')
y = net.outputs # action-value / rewards of 4 actions
predict = tf.argmax(y, 1) # chose action greedily with reward. in Q-Learning, policy is greedy, so we use "max" to select the next action.
## Below we obtain the loss by taking the sum of squares difference between the target and prediction Q values.
nextQ = tf.placeholder(shape=[1, 4], dtype=tf.float32)
loss = tl.cost.mean_squared_error(nextQ, y, is_mean=False) # tf.reduce_sum(tf.square(nextQ - y))
train_op = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(loss)
## Set learning parameters
lambd = .99 # decay factor
e = 0.1 # e-Greedy Exploration, the larger the more random
num_episodes = 10000
with tf.Session() as sess:
tl.layers.initialize_global_variables(sess)
for i in range(num_episodes):
## Reset environment and get first new observation
episode_time = time.time()
s = env.reset() # observation is state, integer 0 ~ 15
| tensorflow.placeholder | 4,074 |
import tensorflow as tf
# add l2 regularization
with tf.name_scope('weight_decay'):
add_weight_decay(params['weight_decay'])
regularization_loss = tf.losses.get_regularization_loss()
# create localization and classification losses
losses = ssd.loss(labels, params)
tf.losses.add_loss(params['localization_loss_weight'] * losses['localization_loss'])
tf.losses.add_loss(params['classification_loss_weight'] * losses['classification_loss'])
tf.summary.scalar('regularization_loss', regularization_loss)
tf.summary.scalar('localization_loss', losses['localization_loss'])
tf.summary.scalar('classification_loss', losses['classification_loss'])
total_loss = tf.losses.get_total_loss(add_regularization_losses=True)
if mode == tf.estimator.ModeKeys.EVAL:
| tensorflow.losses.add_loss | 4,075 |
import tensorflow as tf
if use_bias:
b = tf.get_variable('b', [out_channel], initializer=b_init)
if split == 1:
conv = tf.nn.conv2d(inputdata, w, strides, padding, data_format=data_format)
else:
inputs = tf.split(inputdata, split, channel_axis)
kernels = tf.split(w, split, 3)
outputs = [tf.nn.conv2d(i, k, strides, padding, data_format=data_format)
for i, k in zip(inputs, kernels)]
conv = tf.concat(outputs, channel_axis)
ret = tf.identity(tf.nn.bias_add(conv, b, data_format=data_format)
if use_bias else conv, name=name)
return ret
| tensorflow.nn.conv2d | 4,076 |
import tensorflow as tf
An example with the same label and an augmented version of the image.
"""
image, label = example['image'], example['label']
image = tf.image.random_flip_left_right(image)
image_shape = tf.shape(image)
image = tf.pad(
image, [[random_crop_pad, random_crop_pad],
[random_crop_pad, random_crop_pad], [0, 0]],
mode='REFLECT')
image = tf.image.random_crop(image, image_shape)
return {'image': image, 'label': label}
def auto_augmentation(example,
dataset_name):
"""Applies the AutoAugment policy found for the dataset.
AutoAugment: Learning Augmentation Policies from Data
| tensorflow.image.random_crop | 4,077 |
import tensorflow as tf
import tensorflow as tf
from scipy.io.wavfile import write
from tqdm import tqdm
from utils import *
# In[2]:
def prenet(inputs, num_units=None, is_training=True, scope="prenet"):
if num_units is None:
num_units = [embed_size, embed_size // 2]
with tf.variable_scope(scope):
outputs = tf.layers.dense(inputs, units=num_units[0], activation=tf.nn.relu, name="dense1")
outputs = tf.layers.dropout(
outputs, rate=dropout_rate, training=is_training, name="dropout1"
)
outputs = tf.layers.dense(outputs, units=num_units[1], activation=tf.nn.relu, name="dense2")
outputs = tf.layers.dropout(
outputs, rate=dropout_rate, training=is_training, name="dropout2"
)
return outputs
def highwaynet(inputs, num_units=None, scope="highwaynet"):
if not num_units:
num_units = inputs.get_shape()[-1]
| tensorflow.layers.dense | 4,078 |
import tensorflow as tf
def build_manager(self):
with tf.variable_scope('manager'):
# Calculate manager internal state
| tensorflow.variable_scope | 4,079 |
import tensorflow as tf
return final_loss, cstr_pct
def contra_traj_lossV4(pred, tgt, horizon=12, resample=1, hard_ratio=1.0):
horizon_pred = horizon_sumV1(pred, horizon)
horizon_tgt = horizon_sumV1(tgt, horizon)
pred_flat = tf.reshape(horizon_pred, [-1])
tgt_flat = tf.reshape(horizon_tgt, [-1])
batch = tf.stack([pred_flat, tgt_flat], 1)
sample_func = sample_pair(batch)
def sample_compute(_):
pairs = sample_func()
loss = compute_contra_loss(*pairs, hard_ratio=hard_ratio)
pct = tf.math.count_nonzero(loss, dtype=tf.float32) / tf.size(loss, out_type=tf.float32)
p = tf.cond(tf.random_uniform((), dtype=tf.float32) < 1e-4,
lambda: tf.print('csrt acc ', [pct]),
lambda: tf.no_op())
with tf.control_dependencies([p]):
return tf.reduce_mean(loss)
loss = tf.map_fn(fn=lambda inp: sample_compute(inp), elems=tf.range(resample), dtype=tf.float32,
parallel_iterations=32)
final_loss = tf.reduce_mean(loss)
return final_loss
def contra_traj_lossV1(pred, tgt, temp=10.0):
| tensorflow.size | 4,080 |
import tensorflow as tf
self.hparams.block_dim
],
initializer=tf.initializers.variance_scaling(distribution="uniform"))
# Create the shadow variables if we are using EMA
if self.hparams.ema:
self.ema_count = tf.get_variable(
"ema_count", [self.hparams.num_blocks, self.hparams.block_v_size],
initializer=tf.constant_initializer(0),
trainable=False)
with tf.colocate_with(self.means):
self.ema_means = tf.get_variable(
"ema_means",
initializer=self.means.initialized_value(),
trainable=False)
| tensorflow.constant_initializer | 4,081 |
import tensorflow as tf
H1 = tf.add(tf.matmul(H, W1), b)
H2 = tf.matmul(H, W2)
H = tf.tanh(tf.add(H1 * H2, H1))
W1, W2 = weights[-1]
b = biases[-1]
H1 = tf.add(tf.matmul(H, W1), b)
H2 = tf.matmul(H, W2)
Y = tf.add(H1 * H2, H1)
return Y
def fwd_gradients_0(self, U, x):
g = tf.gradients(U, x, grad_ys=self.dummy_x0_tf)[0]
return tf.gradients(g, self.dummy_x0_tf)[0]
def fwd_gradients_1(self, U, x):
g = tf.gradients(U, x, grad_ys=self.dummy_x1_tf)[0]
return tf.gradients(g, self.dummy_x1_tf)[0]
def net_U0(self, x):
lambda_1 = self.lambda_1
lambda_2 = tf.exp(self.lambda_2)
U = self.neural_net(x, self.weights, self.biases)
U_x = self.fwd_gradients_0(U, x)
U_xx = self.fwd_gradients_0(U_x, x)
U_xxx = self.fwd_gradients_0(U_xx, x)
F = -lambda_1*U*U_x - lambda_2*U_xxx
U0 = U - self.dt*tf.matmul(F, self.IRK_alpha.T)
return U0
def net_U1(self, x):
| tensorflow.gradients | 4,082 |
import tensorflow as tf
maybe_log2 = tf.cast(maybe_log2, logits.dtype.base_dtype)
if logits.get_shape().ndims == 3 and labels.get_shape().ndims < 3:
labels = tf.expand_dims(labels, 2)
loss_on_positives = losses_utils.weighted_surrogate_loss(
labels, logits, surrogate_type, negative_weights=0.0) / maybe_log2
return tf.reduce_sum(weights * (labels - loss_on_positives), 0)
def false_positives_upper_bound(labels, logits, weights, surrogate_type):
"""Calculate an upper bound on the number of false positives.
| tensorflow.reduce_sum | 4,083 |
import tensorflow as tf
use_hvd=FLAGS.use_hvd)
tf.logging.info("***** Running evaluation *****")
tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
eval_input_fn = input_fn_builder(
input_files=validation_input_files,
max_seq_length=FLAGS.max_seq_length,
max_predictions_per_seq=FLAGS.max_predictions_per_seq,
is_training=False,
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.estimator.TrainSpec | 4,084 |
import tensorflow as tf
self.train_step = None
self.post_step = None
self.graph = tf.Graph()
with self.graph.as_default():
self.head_input = tf.placeholder(tf.int32, shape=[None])
self.rel_input = tf.placeholder(tf.int32, shape=[None])
self.tail_input = tf.placeholder(tf.int32, shape=[None])
self.target = tf.placeholder(tf.float32, shape=[None])
def _create_model(self, train_triples):
''' Subclasses must build Graph and set self.train_step '''
raise Exception('subclass must implement')
| tensorflow.placeholder | 4,085 |
import tensorflow as tf
# generates random numbers at graph definition time.
max_offset_height = control_flow_ops.with_dependencies(
asserts, tf.reshape(image_height - crop_height + 1, []))
max_offset_width = control_flow_ops.with_dependencies(
asserts, tf.reshape(image_width - crop_width + 1, []))
offset_height = tf.random_uniform(
[], maxval=max_offset_height, dtype=tf.int32)
offset_width = tf.random_uniform(
[], maxval=max_offset_width, dtype=tf.int32)
| tensorflow.random_uniform | 4,086 |
import tensorflow as tf
inputs=inputs, filters=filters, kernel_size=1, strides=1,
data_format=data_format)
inputs = batch_norm(inputs, training, data_format)
inputs = tf.nn.relu(inputs)
inputs = conv2d_fixed_padding(
inputs=inputs, filters=filters, kernel_size=3, strides=strides,
data_format=data_format)
| tensorflow.nn.relu | 4,087 |
import tensorflow as tf
if other_inputs is not None:
encoder_inputs_ = tf.concat([encoder_inputs_, other_inputs], axis=2)
if encoder.use_dropout:
noise_shape = [1, time_steps, 1] if encoder.pervasive_dropout else [batch_size, time_steps, 1]
encoder_inputs_ = tf.nn.dropout(encoder_inputs_, keep_prob=encoder.word_keep_prob,
noise_shape=noise_shape)
size = tf.shape(encoder_inputs_)[2]
noise_shape = [1, 1, size] if encoder.pervasive_dropout else [batch_size, time_steps, size]
| tensorflow.nn.dropout | 4,088 |
import tensorflow as tf
z_dim = 10
batch_size = 100
n_epochs = 1000
learning_rate = 0.001
beta1 = 0.9
results_path = './Results/Semi_Supervised'
n_labels = 10
n_labeled = 1000
# Placeholders for input data and the targets
x_input = tf.placeholder(dtype=tf.float32, shape=[batch_size, input_dim], name='Input')
x_input_l = tf.placeholder(dtype=tf.float32, shape=[batch_size, input_dim], name='Labeled_Input')
y_input = tf.placeholder(dtype=tf.float32, shape=[batch_size, n_labels], name='Labels')
x_target = tf.placeholder(dtype=tf.float32, shape=[batch_size, input_dim], name='Target')
real_distribution = tf.placeholder(dtype=tf.float32, shape=[batch_size, z_dim], name='Real_distribution')
categorial_distribution = tf.placeholder(dtype=tf.float32, shape=[batch_size, n_labels],
name='Categorical_distribution')
manual_decoder_input = tf.placeholder(dtype=tf.float32, shape=[1, z_dim + n_labels], name='Decoder_input')
| tensorflow.placeholder | 4,089 |
import tensorflow as tf
with tf.compat.v1.name_scope(name, 'count_per_key'):
| tensorflow.compat.v1.name_scope | 4,090 |
import tensorflow.contrib.eager as tfe
class EagerSpinnSNLIClassifierBenchmark(test.Benchmark):
def benchmarkEagerSpinnSNLIClassifier(self):
test_device = "gpu:0" if tfe.num_gpus() else "cpu:0"
with tf.device(test_device):
burn_in_iterations = 2
benchmark_iterations = 10
| tensorflow.contrib.eager.num_gpus | 4,091 |
import tensorflow as tf
# but that is the same as doing a reduce_mean. We do a reduce_mean
# here because it performs better than AveragePooling2D.
axes = [2, 3] if self.data_format == 'channels_first' else [1, 2]
inputs = tf.reduce_mean(inputs, axes, keepdims=True)
inputs = tf.identity(inputs, 'final_reduce_mean')
inputs = tf.reshape(inputs, [-1, self.final_size])
| tensorflow.identity | 4,092 |
import tensorflow as tf
encoder_input_length_ = (encoder_input_length_ + stride - 1) // stride # rounding up
last_backward = encoder_outputs_[:, 0, cell_output_size:]
indices = tf.stack([tf.range(batch_size), encoder_input_length_ - 1], axis=1)
last_forward = tf.gather_nd(encoder_outputs_[:, :, :cell_output_size], indices)
last_forward.set_shape([None, cell_output_size])
if encoder.final_state == 'concat_last': # concats last states of all backward layers (full LSTM states)
| tensorflow.gather_nd | 4,093 |
import tensorflow as tf
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,094 |
import tensorflow as tf
# Update variables
grads_and_vars = list(zip(gradients, variables))
with tf.control_dependencies([collect_op]):
train_op = opt.apply_gradients(grads_and_vars, global_step)
| tensorflow.control_dependencies | 4,095 |
import tensorflow as tf
int(s_w/ns0), int(s_w/ns0/ns1), int(s_w/ns0/ns1/ns2), int(s_w/ns0/ns1/ns2/ns3)
def decode(z, skip_h3, skip_h2, skip_h1, skip_h0):
z_ = lrelu(linear(tf.nn.dropout(z, keep_prob), nf3*s_h3*s_w3, 'd_h0_lin'))
h0 = tf.nn.dropout(tf.reshape(z_, [-1, s_h3, s_w3, nf3]), keep_prob)
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)
| tensorflow.concat | 4,096 |
import tensorflow as tf
tf.summary.scalar(name='Generator Loss', tensor=generator_loss)
tf.summary.scalar(name='Supervised Encoder Loss', tensor=supervised_encoder_loss)
tf.summary.histogram(name='Encoder Gauss Distribution', values=encoder_output_latent)
tf.summary.histogram(name='Real Gauss Distribution', values=real_distribution)
tf.summary.histogram(name='Encoder Categorical Distribution', values=encoder_output_label)
tf.summary.histogram(name='Real Categorical Distribution', values=categorial_distribution)
tf.summary.image(name='Input Images', tensor=input_images, max_outputs=10)
tf.summary.image(name='Generated Images', tensor=generated_images, max_outputs=10)
summary_op = tf.summary.merge_all()
# Saving the model
saver = tf.train.Saver()
step = 0
with tf.Session() as sess:
| tensorflow.summary.image | 4,097 |
import tensorflow as tf
tf.cond(reset_ph, lambda: perturb_vars(original_scope="q_func", perturbed_scope="perturbed_q_func"), lambda: tf.group(*[])),
tf.cond(update_param_noise_scale_ph, lambda: update_scale(), lambda: tf.Variable(0., trainable=False)),
| tensorflow.Variable | 4,098 |
from tensorflow.python.framework import ops
@ops.RegisterShape("All")
@ops.RegisterShape("Any")
| tensorflow.python.framework.ops.RegisterShape | 4,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.