seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
from tensorflow.contrib.framework import deprecated
@deprecated(
"2016-11-12", "This file will be removed after the deprecation date."
| tensorflow.contrib.framework.deprecated | 13,500 |
from tensorflow.contrib.rnn import GRUCell
for i in range(4):
highway_input = highwaynet(highway_input, 'highway_%d' % (i + 1), half_depth)
rnn_input = highway_input
# Bidirectional RNN
outputs, states = tf.nn.bidirectional_dynamic_rnn(
GRUCell(half_depth),
GRUCell(half_depth),
rnn_input,
sequence_length=input_lengths,
dtype=tf.float32)
return tf.concat(outputs, axis=2) # Concat forward and backward
| tensorflow.contrib.rnn.GRUCell | 13,501 |
import tensorflow as tf
scaffold_fn=scaffold_fn)
elif mode == tf.estimator.ModeKeys.EVAL:
def metric_fn(masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids,
masked_lm_weights, next_sentence_example_loss,
next_sentence_log_probs, next_sentence_labels):
"""Computes the loss and accuracy of the model."""
masked_lm_log_probs = tf.reshape(masked_lm_log_probs,
[-1, masked_lm_log_probs.shape[-1]])
masked_lm_predictions = tf.argmax(
masked_lm_log_probs, axis=-1, output_type=tf.int32)
masked_lm_example_loss = tf.reshape(masked_lm_example_loss, [-1])
masked_lm_ids = tf.reshape(masked_lm_ids, [-1])
masked_lm_weights = tf.reshape(masked_lm_weights, [-1])
masked_lm_accuracy = tf.metrics.accuracy(
labels=masked_lm_ids,
predictions=masked_lm_predictions,
weights=masked_lm_weights)
masked_lm_mean_loss = tf.metrics.mean(
values=masked_lm_example_loss, weights=masked_lm_weights)
next_sentence_log_probs = tf.reshape(
next_sentence_log_probs, [-1, next_sentence_log_probs.shape[-1]])
next_sentence_predictions = tf.argmax(
next_sentence_log_probs, axis=-1, output_type=tf.int32)
next_sentence_labels = tf.reshape(next_sentence_labels, [-1])
next_sentence_accuracy = tf.metrics.accuracy(
labels=next_sentence_labels, predictions=next_sentence_predictions)
| tensorflow.metrics.accuracy | 13,502 |
import tensorflow as tf
vars_to_restore_imagenet = {}
ckpt_var_names = tf.contrib.framework.list_variables(imagenet_ckpt)
ckpt_var_names = [name for (name, unused_shape) in ckpt_var_names]
model_vars = tf.global_variables()
for v in model_vars:
if 'global_step' in v.op.name: continue
| tensorflow.global_variables | 13,503 |
import tensorflow as tf
files = [tempfile.NamedTemporaryFile(prefix=c) for c in cases]
with self.test_session():
# Test exact match without wildcards.
for f in files:
self.assertEqual(tf.matching_files(f.name).eval(),
tf.compat.as_bytes(f.name))
# We will look for files matching "ABxDEF.GH*" where "x" is some wildcard.
pos = files[0].name.find(cases[0])
pattern = files[0].name[:pos] + 'AB%sDEF.GH*'
| tensorflow.compat.as_bytes | 13,504 |
import tensorflow as tf
return feature_loss
def _tower_loss_semi_supervised(self, inputs, targets, gpu_idx=0, num_classes=11,
is_fm_loss=False):
with tf.variable_scope("train_specific"):
avg_error_rate = tf.get_variable(
'avg_error_rate', [], initializer=tf.constant_initializer(0.), trainable=False)
num_error_rate = tf.get_variable(
'num_error_rate', [], initializer=tf.constant_initializer(0.), trainable=False)
batch_size_train = self.cnf['batch_size_train']
batch_size_val = self.cnf['batch_size_test']
self.end_points_G = self.model.generator([batch_size_train, 100], True, None, batch_size_val)
if gpu_idx == 0:
G_means = tf.reduce_mean(self.end_points_G['softmax'], 0, keep_dims=True)
| tensorflow.constant_initializer | 13,505 |
import tensorflow as tf
next_states, next_tasks = self._task_distribution.split(
experience.observation[:, 1])
rewards, dones = self._task_distribution.evaluate(states,
experience.action[:, 0],
tasks)
# Strictly speaking, we don't need to relabel the next rewards and next
# dones because they end up being thrown away. Only the current rewards
# and dones end up being important.
next_rewards, next_dones = self._task_distribution.evaluate(
next_states, experience.action[:, 1], next_tasks)
new_rewards = tf.concat([rewards[:, None], next_rewards[:, None]], axis=1)
new_dones = tf.concat([dones[:, None], next_dones[:, None]], axis=1)
# 0 if episode is done, 1 if episode is continuing
new_discount = 1.0 - tf.cast(new_dones, tf.float32)
assert new_rewards.shape == experience.reward.shape
assert new_discount.shape == experience.discount.shape
experience = experience.replace(reward=new_rewards, discount=new_discount)
return experience
def _soft_relabel(self, experience):
"""Reassigns tasks to each state and next state.
Does not recompute the rewards or done flags.
Args:
experience: The experience that we want to relabel with inverse RL.
Returns:
| tensorflow.cast | 13,506 |
import tensorflow as tf
ops.reset_default_graph()
# To find out where placement occurs, set 'log_device_placement'
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
# Runs the op.
print(sess.run(c))
# If we load a graph and want device placement to be forgotten,
| tensorflow.matmul | 13,507 |
import tensorflow as tf
a = tf.minimum(m_bound, m0)
x = 1 - tf.pow(a / m0, 2)
primitive = -0.5 * m0 * m0 * (tf.exp(c * x) * tf.sqrt(x) / c + 0.5 / tf.pow(-c, 1.5) * tf.sqrt(pi) * tf.erf(gradsafe_sqrt(-c * x)))
# We have to safeguard the sqrt, because otherwise the analytic
| tensorflow.exp | 13,508 |
import tensorflow as tf
tf.summary.scalar("stop_token_loss", model.stop_token_loss)
tf.summary.scalar("loss", model.loss)
| tensorflow.summary.scalar | 13,509 |
import tensorflow as tf
"input_mask": tf.FixedLenFeature([seq_length], tf.int64),
"segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
"label_ids": tf.FixedLenFeature([], tf.int64),
"is_real_example": tf.FixedLenFeature([], tf.int64),
| tensorflow.FixedLenFeature | 13,510 |
import tensorflow as tf
x = tf.reshape(x, [tf.reduce_prod(s[:-1]), sh[-1]])
x = dense(x, num_units, **kwargs)
return tf.reshape(x, [-1] + sh[1:-1] + [num_units])
def dense(x, num_units, scope="dense", training=True, ema=None, init=False, bias_initializer=tf.constant_initializer(0.)):
with tf.variable_scope(scope):
V = tf.get_variable('V', shape=[int(x.get_shape()[1]), num_units], dtype=tf.float32,
initializer=tf.random_normal_initializer(0, 0.05), trainable=True)
g = tf.get_variable('g', shape=[num_units], dtype=tf.float32,
initializer=tf.constant_initializer(1.), trainable=True)
b = tf.get_variable('b', shape=[num_units], dtype=tf.float32,
initializer=bias_initializer, trainable=True)
def maybe_avg(v):
if ema is not None and not init:
| tensorflow.random_normal_initializer | 13,511 |
import tensorflow as tf
examples_per_sec, sec_per_batch))
if step % 100 == 0:
summary_str = sess.run(summary_op)
summary_writer.add_summary(summary_str, step)
# Save the model checkpoint periodically.
if step % 1000 == 0 or (step + 1) == FLAGS.max_steps:
checkpoint_path = os.path.join(FLAGS.train_dir, 'model.ckpt')
saver.save(sess, checkpoint_path, global_step=step)
def main(argv=None): # pylint: disable=unused-argument
cifar10.maybe_download_and_extract()
if tf.gfile.Exists(FLAGS.train_dir):
tf.gfile.DeleteRecursively(FLAGS.train_dir)
tf.gfile.MakeDirs(FLAGS.train_dir)
train()
if __name__ == '__main__':
tf.app.run()
| tensorflow.gfile.DeleteRecursively | 13,512 |
import tensorflow as tf
self.assertEqual((2, 2), res[0][1].c.shape)
self.assertEqual((2, 2), res[0][1].h.shape)
# pylint: disable=unused-variable,invalid-name
def testDynamicAttentionDecoderStateIsTuple(self):
with self.test_session() as sess:
with tf.variable_scope(
"root", initializer=tf.constant_initializer(0.5)):
cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True)
cell = tf.nn.rnn_cell.MultiRNNCell(cells=[cell] * 2,
state_is_tuple=True)
inp = tf.constant(0.5, shape=[2, 2, 2])
enc_outputs, enc_state = tf.nn.rnn(cell, inp, dtype=tf.float32)
attn_states = tf.concat(1, [tf.reshape(e, [-1, 1, cell.output_size])
for e in enc_outputs])
dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3
| tensorflow.nn.rnn_cell.BasicLSTMCell | 13,513 |
import tensorflow.contrib as contrib
else:
stitch1_1, stitch1_2 = fc1_1, fc1_2
fc2_1 = contrib.layers.fully_connected(stitch1_1, 32, scope="fc2_1")
fc2_2 = contrib.layers.fully_connected(stitch1_2, 32, scope="fc2_2")
if cross_stitch_enabled:
with tf.variable_scope("cross_stitch_2"):
| tensorflow.contrib.layers.fully_connected | 13,514 |
import tensorflow as tf
input_props.append((tf.bool, [])) # Is training.
input_props.append((tf.int32, [None])) # Gold starts.
input_props.append((tf.int32, [None])) # Gold ends.
input_props.append((tf.int32, [None])) # Cluster ids.
self.queue_input_tensors = [tf.placeholder(dtype, shape) for dtype, shape in input_props]
dtypes, shapes = zip(*input_props)
queue = tf.PaddingFIFOQueue(capacity=10, dtypes=dtypes, shapes=shapes)
self.enqueue_op = queue.enqueue(self.queue_input_tensors)
self.input_tensors = queue.dequeue()
self.predictions, self.loss = self.get_predictions_and_loss(*self.input_tensors)
self.global_step = tf.Variable(0, name="global_step", trainable=False)
self.reset_global_step = tf.assign(self.global_step, 0)
learning_rate = tf.train.exponential_decay(self.config["learning_rate"], self.global_step,
self.config["decay_frequency"], self.config["decay_rate"], staircase=True)
trainable_params = tf.trainable_variables()
gradients = tf.gradients(self.loss, trainable_params)
gradients, _ = tf.clip_by_global_norm(gradients, self.config["max_gradient_norm"])
optimizers = {
"adam" : tf.train.AdamOptimizer,
"sgd" : tf.train.GradientDescentOptimizer
}
optimizer = optimizers[self.config["optimizer"]](learning_rate)
| tensorflow.Variable | 13,515 |
from tensorflow.contrib.layers.python.layers import utils
def build_no_ops():
return (tf.no_op(), tf.no_op())
# Only make the ops if we know that `is_training=True`, or the value of
# `is_training` is unknown.
is_training_const = utils.constant_value(is_training)
if is_training_const is None or is_training_const:
update_mean_op, update_variance_op = utils.smart_cond(
is_training,
build_update_ops,
build_no_ops,
)
# Every new connection creates a new op which adds its contribution
| tensorflow.contrib.layers.python.layers.utils.smart_cond | 13,516 |
import tensorflow as tf
predict_batch_size=FLAGS.predict_batch_size)
if FLAGS.do_train:
train_file = os.path.join(FLAGS.output_dir, "train.tf_record")
file_based_convert_examples_to_features(
train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file)
tf.logging.info("***** Running training *****")
tf.logging.info(" Num examples = %d", len(train_examples))
tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
tf.logging.info(" Num steps = %d", num_train_steps)
train_input_fn = file_based_input_fn_builder(
input_file=train_file,
seq_length=FLAGS.max_seq_length,
is_training=True,
drop_remainder=True)
estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
| tensorflow.logging.info | 13,517 |
import tensorflow as tf
def wmt_preprocess(dataset, training, max_length=-1, max_eval_length=-1):
"""Preprocessing for LM1B: filter out targets exceeding maximum length."""
def train_right_length(example, target):
l = tf.maximum(tf.shape(example['inputs'])[0], tf.shape(target)[0])
return tf.less(l, max_length + 1)
def eval_right_length(example, target):
| tensorflow.shape | 13,518 |
import tensorflow as tf
padding=padding, kernel_initializer=init, name='tr_conv' + id, use_bias=use_bias)
# Traditional U-Net
def build_Unet_Arch(self, input_data, name="Unet_Arch"):
self.base_number_of_features = 32
with tf.variable_scope(name):
# Encoder definition
o_c1 = self.general_conv2d(input_data, self.base_number_of_features, 3, stride = 1, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_conv2d_1')
o_mp1 = tf.layers.max_pooling2d(o_c1, 2, 2, name = name + '_maxpooling_1')
o_c2 = self.general_conv2d(o_mp1, self.base_number_of_features * 2, 3, stride = 1, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_conv2d_2')
o_mp2 = tf.layers.max_pooling2d(o_c2, 2, 2, name = name + '_maxpooling_2')
| tensorflow.variable_scope | 13,519 |
import tensorflow as tf
if v.op.name in self.pretrained_weights.keys():
assign_op = v.assign(self.pretrained_weights[v.op.name])
sess.run(assign_op)
print(v.op.name + " - loaded successfully")
print("All pretrained weights of resnet18 is loaded")
def _residual_block(self, name, x, filters, pool_first=False, strides=1, dilation=1):
print('Building residual unit: %s' % name)
with tf.variable_scope(name):
# get input channels
in_channel = x.shape.as_list()[-1]
# Shortcut connection
shortcut = tf.identity(x)
if pool_first:
if in_channel == filters:
if strides == 1:
shortcut = tf.identity(x)
else:
shortcut= tf.pad(x, tf.constant([[0,0],[1,1],[1,1],[0,0]]), "CONSTANT")
shortcut = tf.nn.max_pool(shortcut, [1, strides, strides, 1], [1, strides, strides, 1], 'VALID')
else:
shortcut = self._conv('shortcut_conv', x, padding='VALID',
num_filters=filters, kernel_size=(1, 1), stride=(strides, strides),
bias=self.bias)
| tensorflow.identity | 13,520 |
from tensorflow.python.ops import array_ops
if self._gate_linear is None:
bias_ones = self._bias_initializer
if self._bias_initializer is None:
bias_ones = init_ops.constant_initializer(1.0, dtype=inputs.dtype)
with vs.variable_scope("gates"): # Reset gate and update gate.
self._gate_linear = _Linear(
[inputs, state],
2 * self._num_units,
True,
bias_initializer=bias_ones,
kernel_initializer=self._kernel_initializer)
value = math_ops.sigmoid(self._gate_linear([inputs, state]))
r, u = array_ops.split(value=value, num_or_size_splits=2, axis=1)
r_state = r * state
if self._candidate_linear is None:
with vs.variable_scope("candidate"):
self._candidate_linear = _Linear(
[inputs, r_state],
self._num_units,
True,
bias_initializer=self._bias_initializer,
kernel_initializer=self._kernel_initializer)
c = self._activation(self._candidate_linear([inputs, r_state]))
u = (1.0 - att_score) * u
| tensorflow.python.ops.array_ops.split | 13,521 |
import tensorflow as tf
with tf.control_dependencies([ema_op]):
self.loss = tf.identity(self.loss)
self.shadow_vars = []
self.global_vars = []
for var in tf.global_variables():
v = self.var_ema.average(var)
if v:
self.shadow_vars.append(v)
self.global_vars.append(var)
| tensorflow.global_variables | 13,522 |
import tensorflow as tf
band: str,
soft_onehot: Nonlinearity = Nonlinearity.SIGMOID
):
batch_size, twice_window_size, channels = map(int, initial_layer_features.shape)
nonlinearity = nonlinearity_fcn(soft_onehot)
if channels == 3:
scales = cutoff_data.dflux_dt_dflux_dtime_scales(band)
cutoffs = cutoff_data.dflux_dt_dflux_dtime_cutoffs(band)
cutoffs_batch_window = tf.expand_dims(tf.expand_dims(cutoffs, 0), 0)
scales_batch_window = tf.expand_dims(
tf.expand_dims(tf.expand_dims(scales, 0), 0), -1
)
init_layer_per_cutoff = tf.expand_dims(initial_layer_features, -1)
graph_typecheck.assert_shape(
cutoffs_batch_window, [1, 1, channels, cutoff_data.embedding_size]
)
graph_typecheck.assert_shape(scales_batch_window, [1, 1, channels, 1])
| tensorflow.expand_dims | 13,523 |
import tensorflow as tf
logits = tf.multiply(logits, 1.0 / math.sqrt(float(get_shape_list(q)[-1])))
if bias is not None:
# `attention_mask` = [B, T]
from_shape = get_shape_list(q)
if len(from_shape) == 4:
broadcast_ones = tf.ones([from_shape[0], 1, from_shape[2], 1], tf.float32)
elif len(from_shape) == 5:
# from_shape = [B, N, Block_num, block_size, depth]#
broadcast_ones = tf.ones([from_shape[0], 1, from_shape[2], from_shape[3],
1], tf.float32)
bias = tf.matmul(broadcast_ones,
tf.cast(bias, tf.float32), transpose_b=True)
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
# masked positions, this operation will create a tensor which is 0.0 for
| tensorflow.ones | 13,524 |
from tensorflow.python.framework import ops
The operation that initializes v.
"""
with ops.op_scope([v, init], None, v.op.name + "/"):
with ops.name_scope(name) as scope:
with ops.device(v.device or ops.get_default_graph().get_default_device()):
if callable(init):
| tensorflow.python.framework.ops.name_scope | 13,525 |
import tensorflow as tf
def valid_inference(self,images):
images=tf.cast(images,tf.float32)/255.0
l1 = tf.matmul(images, self.w1)+self.b1
l1=tf.nn.relu(l1)
out = tf.matmul(l1, self.w2)+self.b2
return out
def softmax_loss(self,predicts,labels):
predicts=tf.nn.softmax(predicts)
labels=tf.one_hot(labels,classnum)
loss=-tf.reduce_sum(labels*tf.log(predicts))
return loss
def optimer(self,loss,lr=0.001):
train_step=tf.train.GradientDescentOptimizer(lr).minimize(loss)
return train_step
path=r'C:\JC\test\train_model.ckpt'
| tensorflow.one_hot | 13,526 |
import tensorflow as tf
dep_idxs = tf.tile(tf.expand_dims(dep_org_idx, 1), [1, sl_head, 1])
head_idxs = tf.tile(tf.expand_dims(head_org_idx, 2), [1, 1, sl_dep])
if direction is None:
direct_mask = tf.not_equal(head_idxs, dep_idxs) # [bs, slh, sld]
else:
if direction == 'forward':
direct_mask = tf.greater(head_idxs, dep_idxs) # [bs, slh, sld]
else:
direct_mask = tf.less(head_idxs, dep_idxs) # [bs, slh, sld]
# [bs, slh, slh]
rep_mask_tile = tf.logical_and(tf.expand_dims(rep_dep_mask, 1), tf.expand_dims(rep_head_mask, 2))
attn_mask = tf.logical_and(direct_mask, rep_mask_tile) # [bs, slh, sld]
# tensor tile
rep_map_tile = tf.tile(tf.expand_dims(rep_dep_tensor, 1), [1, sl_head, 1, 1]) # bs,slh,sld,vec
with tf.variable_scope('attention'): # bs,sl,sl,vec
f_bias = tf.get_variable('f_bias', [ivec], tf.float32, tf.constant_initializer(0.))
| tensorflow.less | 13,527 |
import tensorflow as tf
fn=combine_fn,
default_accumulator_value=default_accumulator_value,
reduce_instance_dims=reduce_instance_dims,
key=key_vocab,
key_vocabulary_filename=key_vocabulary_filename)
if key_vocabulary_filename is not None:
return key_values
key, minus_x_min, x_max = key_values
return (
key,
tf.cast(0 - minus_x_min, output_dtype),
tf.cast(x_max, output_dtype))
def _sum_combine_fn_and_dtype(
input_dtype: tf.DType
) -> Tuple[tf.DType, Callable[[np.ndarray], np.ndarray]]:
output_dtype = _SUM_OUTPUT_DTYPE_MAP.get(input_dtype)
if output_dtype is None:
raise TypeError('Tensor type %r is not supported' % input_dtype)
return output_dtype, functools.partial(
| tensorflow.cast | 13,528 |
import tensorflow as tf
# Convolution on patches.
w_ = tf.reshape(w, [ksize[0] * ksize[1] * ksize[2], -1])
q = tf.matmul(p_, w_)
# Center locations.
blk_indices_crop = blk_indices[:, 0, 0, :]
# Project back to an image.
y = tf.scatter_nd(blk_indices_crop, q, out_shape)
return y
with tf.control_dependencies([assert_shape, assert_strides]):
return tf.cond(
tf.equal(tf.size(blk_indices_), 0), lambda: tf.zeros(out_shape, dtype=x.dtype),
_conv_nonzero)
def mask_conv2d(x, w, mask, strides, padding):
"""Masked 2D convolution. Used to check 2D sparse convolution.
:param x: [Tensor] Convolution feature map, 4D, dtype float32.
:param w: [Tensor] Convolution kernel, 4D, dtype float32.
:param mask: [Tensor] Binary mask, 3D or 4D, [N, H, W] or [N, H, W, 1], dtype float32.
| tensorflow.control_dependencies | 13,529 |
import tensorflow as tf
return tf.keras.layers.StackedRNNCells([
tf.lite.experimental.nn.TFLiteLSTMCell(
self.num_units, use_peepholes=True, forget_bias=1.0, name="rnn1"),
tf.lite.experimental.nn.TFLiteLSTMCell(
self.num_units, num_proj=8, forget_bias=1.0, name="rnn2"),
tf.lite.experimental.nn.TFLiteLSTMCell(
| tensorflow.lite.experimental.nn.TFLiteLSTMCell | 13,530 |
import tensorflow as tf
b_init_args = {}
if self.inputs.get_shape().ndims != 2:
raise Exception("The input dimension must be rank 2, please reshape or flatten it")
n_in = int(self.inputs.get_shape()[-1])
with tf.variable_scope(name):
W = tf.get_variable(name='W', shape=(n_in, n_units), initializer=W_init, dtype=LayersConfig.tf_dtype, **W_init_args)
if b_init is not None:
try:
b = tf.get_variable(name='b', shape=(n_units), initializer=b_init, dtype=LayersConfig.tf_dtype, **b_init_args)
except Exception: # If initializer is a constant, do not specify shape.
b = tf.get_variable(name='b', initializer=b_init, dtype=LayersConfig.tf_dtype, **b_init_args)
self.outputs = act(tf.matmul(self.inputs, W) + b)
else:
| tensorflow.get_variable | 13,531 |
import tensorflow as tf
conv = tf.nn.conv2d(bottom, filt, [1, 1, 1, 1], padding='SAME')
conv_biases = self.get_bias(name)
bias = tf.nn.bias_add(conv, conv_biases)
relu = tf.nn.relu(bias)
return relu
def fc_layer(self, bottom, name):
with tf.variable_scope(name):
shape = bottom.get_shape().as_list()
dim = 1
for d in shape[1:]:
dim *= d
x = tf.reshape(bottom, [-1, dim])
weights = self.get_fc_weight(name)
biases = self.get_bias(name)
# Fully connected layer. Note that the '+' operation automatically
# broadcasts the biases.
fc = tf.nn.bias_add(tf.matmul(x, weights), biases)
return fc
def get_conv_filter(self, name):
return tf.constant(self.data_dict[name][0], name="filter")
| tensorflow.reshape | 13,532 |
import tensorflow as tf
if self.has_inputs:
data_fields["inputs"] = tf.VarLenFeature(tf.int64)
# hack: ignoring true targets and putting dist_targets in targets
data_items_to_decoders = {
"inputs": tf.contrib.slim.tfexample_decoder.Tensor("inputs"),
"targets": tf.contrib.slim.tfexample_decoder.Tensor("dist_targets"),
}
return (data_fields, data_items_to_decoders)
def get_or_create_vocab(self, data_dir, tmp_dir, force_get=False):
"""Get vocab for distill problems."""
| tensorflow.contrib.slim.tfexample_decoder.Tensor | 13,533 |
import tensorflow as tf
for grad, var in avg_grads
]
else:
clipped_grads = avg_grads
if FLAGS.optimizer == 'momentum':
opt = tf.train.MomentumOptimizer(
learning_rate, FLAGS.momentum, use_nesterov=True)
elif FLAGS.optimizer == 'sgd':
opt = tf.train.GradientDescentOptimizer(learning_rate)
elif FLAGS.optimizer == 'rmsprop':
opt = tf.train.RMSPropOptimizer(learning_rate, FLAGS.rmsprop_decay,
| tensorflow.train.MomentumOptimizer | 13,534 |
import tensorflow as tf
img_name_batch, img_batch, gtboxes_and_label_batch, num_objects_batch, img_h_batch, img_w_batch = \
self.reader.next_batch(dataset_name=cfgs.DATASET_NAME,
batch_size=cfgs.BATCH_SIZE * num_gpu,
shortside_len=shortside_len,
is_training=True)
# data processing
inputs_list = []
for i in range(num_gpu):
img = tf.expand_dims(img_batch[i], axis=0)
pretrain_zoo = PretrainModelZoo()
if self.cfgs.NET_NAME in pretrain_zoo.pth_zoo or self.cfgs.NET_NAME in pretrain_zoo.mxnet_zoo:
img = img / tf.constant([cfgs.PIXEL_STD])
gtboxes_and_label_r = tf.py_func(backward_convert,
inp=[gtboxes_and_label_batch[i]],
Tout=tf.float32)
gtboxes_and_label_r = tf.reshape(gtboxes_and_label_r, [-1, 6])
gtboxes_and_label_h = get_horizen_minAreaRectangle(gtboxes_and_label_batch[i])
gtboxes_and_label_h = tf.reshape(gtboxes_and_label_h, [-1, 5])
num_objects = num_objects_batch[i]
num_objects = tf.cast(tf.reshape(num_objects, [-1, ]), tf.float32)
| tensorflow.constant | 13,535 |
import tensorflow as tf
state = tf.concat([state, context, pos, new_weights], axis=1)
return state, logits
def _time_step(time, input_, input_symbol, pos, state, output, outputs, states, weights, attns, prev_weights,
samples, context):
if decoder.conditional_rnn:
with tf.variable_scope('conditional_1'):
output, state = update(state, input_)
elif decoder.update_first:
output, state = update(state, input_, None, input_symbol)
context, new_weights = look(time, output, input_, pos=pos, prev_weights=prev_weights, context=context)
| tensorflow.variable_scope | 13,536 |
import tensorflow as tf
train_steps_per_epoch = int(
math.ceil(hparams.num_train_images / float(hparams.train_batch_size)))
eval_steps = hparams.num_eval_images // hparams.eval_batch_size
eval_batch_size = (None if mode == 'train' else
hparams.eval_batch_size)
model = model_lib.AmoebaNetEstimatorModel(hparams, model_dir)
if hparams.use_tpu:
run_config = build_run_config()
image_classifier = tf.contrib.tpu.TPUEstimator(
model_fn=model.model_fn,
use_tpu=True,
config=run_config,
params=estimator_parmas,
predict_batch_size=eval_batch_size,
train_batch_size=hparams.train_batch_size,
eval_batch_size=eval_batch_size,
export_to_tpu=FLAGS.export_to_tpu,
experimental_exported_model_uses_all_cores=FLAGS
| tensorflow.contrib.tpu.TPUEstimator | 13,537 |
import tensorflow as tf
def testInitRequiredAssignSub(self):
with self.test_session():
p = tf.Variable(tf.fill([1024, 1024], 1),
tf.int32)
a = tf.assign_sub(p, tf.fill([1024, 1024], 0))
with self.assertRaisesOpError("use uninitialized"):
a.op.run()
# NOTE(mrry): See also
# dense_update_ops_no_tsan_test.AssignOpTest, which contains a benign
# data race and must run without TSAN.
def testParallelUpdateWithLocking(self):
with self.test_session() as sess:
zeros_t = tf.fill([1024, 1024], 0.0)
ones_t = tf.fill([1024, 1024], 1.0)
p = tf.Variable(zeros_t)
adds = [tf.assign_add(p, ones_t, use_locking=True)
for _ in range(20)]
p.initializer.run()
def run_add(add_op):
sess.run(add_op)
threads = [
self.checkedThread(target=run_add, args=(add_op,)) for add_op in adds]
for t in threads:
t.start()
for t in threads:
| tensorflow.fill | 13,538 |
from tensorflow.python.ops import array_ops
check_ops.assert_type(mask, dtypes.bool)
if weights is None:
weights = array_ops.ones_like(mask, dtype=dtypes.float32)
weights = math_ops.cast(math_ops.logical_not(mask), weights.dtype) * weights
| tensorflow.python.ops.array_ops.ones_like | 13,539 |
from tensorflow.python.framework import ops
# normalize
res = (input_ - used_mean) / tf.sqrt(used_var + epsilon)
# de-normalize
if scale:
res *= gamma
res += beta
# update variables
if train:
with tf.name_scope(name, "AssignMovingAvg", [mean, cur_mean, decay]):
with ops.colocate_with(mean):
new_mean = tf.assign_sub(
mean,
tf.check_numerics(decay * (mean - cur_mean), "NaN in moving mean."))
with tf.name_scope(name, "AssignMovingAvg", [var, cur_var, decay]):
with ops.colocate_with(var):
new_var = tf.assign_sub(
var,
tf.check_numerics(decay * (var - cur_var),
"NaN in moving variance."))
| tensorflow.python.framework.ops.colocate_with | 13,540 |
import tensorflow as tf
grl = tf.reshape(grl, (-1, samples.get_shape().as_list()[1]))
grl = fc(grl, 100, True, None, activation=relu, name='fc1')
logits = fc(grl, 1, True, None, activation=None, name='fc2')
domain_predictions = tf.sigmoid(logits)
domain_loss = tf.losses.log_loss(domain_selection_mask, domain_predictions, weights=weight)
domain_accuracy = util.accuracy_tf(domain_selection_mask, tf.round(domain_predictions))
assert_op = tf.Assert(tf.is_finite(domain_loss), [domain_loss])
with tf.control_dependencies([assert_op]):
tag_loss = 'losses/domain_loss'
| tensorflow.losses.log_loss | 13,541 |
import tensorflow as tf
[1], minval=0, maxval=NUMBER_OF_CLASSES, dtype=tf.int32)
box_label = tf.random_uniform(
| tensorflow.random_uniform | 13,542 |
import tensorflow as tf
def _mask_by_length(t, length):
maxlen = t.get_shape().as_list()[1]
mask = tf.sequence_mask(length, maxlen=maxlen)
mask = tf.expand_dims(tf.cast(mask, tf.float32), -1)
return t * mask
def _scale_l2(x, norm_length):
alpha = tf.reduce_max(tf.abs(x), (1, 2), keep_dims=True) + 1e-12
l2_norm = alpha * tf.sqrt(tf.reduce_sum(tf.pow(x / alpha, 2), (1, 2), keep_dims=True) + 1e-6)
x_unit = x / l2_norm
return norm_length * x_unit
def _end_of_seq_mask(tokens, vocab_size):
"""Generate a mask for the EOS token (1.0 on EOS, 0.0 otherwise).
Args:
| tensorflow.pow | 13,543 |
from tensorflow.python.platform import tf_logging as logging
input_feature_key=self._input_feature_key,
use_deprecated_input_fn=self._use_deprecated_input_fn)
except RuntimeError:
# Currently we are not syncronized with saving checkpoints, which leads to
# runtime errors when we are calling export on the same global step.
# Exports depend on saved checkpoints for constructing the graph and
# getting the global step from the graph instance saved in the checkpoint.
# If the checkpoint is stale with respect to current step, the global step
# is taken to be the last saved checkpoint's global step and exporter
# doesn't export the same checkpoint again with the following error.
logging.info("Skipping exporting because the existing checkpoint has "
"already been exported. "
"Consider exporting less frequently.")
def end(self, session=None):
super(ExportMonitor, self).end(session=session)
latest_path = saver_lib.latest_checkpoint(self._estimator.model_dir)
if latest_path is None:
logging.info("Skipping export at the end since model has not been saved "
"yet.")
| tensorflow.python.platform.tf_logging.info | 13,544 |
import tensorflow as tf
# Step-wise contrastive loss
pred1, pred2 = tf.split(pred, 2, axis=0)
tgt1, tgt2 = tf.split(tgt, 2, axis=0)
geq = tf.cast((tgt1 - tgt2) > 0, tf.bool)
tgt_larg = tf.where(geq, tgt1, tgt2)
tgt_small = tf.where(geq, tgt2, tgt1)
pred_larg = tf.where(geq, pred1, pred2)
pred_small = tf.where(geq, pred2, pred1)
loss = tf.maximum(0.0, (tgt_larg - tgt_small) - (pred_larg - pred_small))
loss = tf.reduce_mean(loss)
return loss
def contra_step_lossV3(pred, tgt, margin=1.0):
| tensorflow.where | 13,545 |
import tensorflow as tf
viz3('B_recon', B, BA, BAB)
with tf.variable_scope('discrim'):
with tf.variable_scope('A'):
| tensorflow.variable_scope | 13,546 |
import tensorflow as tf
'a',
py_utils.WeightParams(shape=[], init=py_utils.WeightInit.Constant(0)))
var_a = task.theta.a
# Make a NaN gradient.
var_grads = py_utils.NestedMap(a=(var_a, 0. * tf.log(0.)))
has_nan_or_inf, grad_scale, final_var_grads = task.ScaleGradients(var_grads)
with self.session():
tf.global_variables_initializer().run()
with self.assertRaisesRegexp(tf.errors.InvalidArgumentError,
'is not finite'):
self.assertTrue(has_nan_or_inf.eval())
self.assertEqual(0., grad_scale.eval())
# The final gradient must be finite.
self.assertFalse(tf.is_nan(final_var_grads.a[1]).eval())
self.assertTrue(tf.is_finite(final_var_grads.a[1]).eval())
class TeacherTask(base_model.BaseTask):
@base_layer.initializer
def __init__(self, params):
super(TeacherTask, self).__init__(params)
p = self.params
with tf.variable_scope(p.name):
self.CreateVariable('x',
py_utils.WeightParams(
shape=[], init=py_utils.WeightInit.Constant(0)))
| tensorflow.is_nan | 13,547 |
import tensorflow as tf
epoch = tf.where(rand < 0.1, tf.zeros_like(epoch), epoch)
# Embed the epoch number.
emb_epoch = common_layers.embedding(epoch, 32, 32) # [batch, 32]
flat_x = tf.concat([flat_x, emb_epoch], axis=1)
flat_x = tf.layers.dropout(flat_x, rate=dropout)
x = tf.layers.dense(flat_x, 128, activation=tf.nn.relu)
logits = tf.layers.dense(
x, self.hparams.problem.num_actions, name="dense2"
)
| tensorflow.layers.dense | 13,548 |
import tensorflow as tf
weight: the weight of the MMD loss.
scope: optional name scope for summary tags.
Returns:
a scalar tensor representing the MMD loss value.
"""
with tf.name_scope(name):
sigmas = [
1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1, 5, 10, 15, 20, 25, 30, 35, 100, 1e3, 1e4, 1e5, 1e6
]
gaussian_kernel = partial(util.gaussian_kernel_matrix, sigmas=tf.constant(sigmas))
loss_value = maximum_mean_discrepancy(source_samples, target_samples, kernel=gaussian_kernel)
loss_value = tf.maximum(1e-4, loss_value) * weight
assert_op = tf.Assert(tf.is_finite(loss_value), [loss_value])
with tf.control_dependencies([assert_op]):
tag = 'MMD_Loss'
barrier = tf.no_op(tag)
return loss_value
def dann_loss(source_samples, target_samples, weight, name='dann_loss'):
"""Adds the domain adversarial (DANN) loss.
Args:
source_samples: a tensor of shape [num_samples, num_features].
target_samples: a tensor of shape [num_samples, num_features].
weight: the weight of the loss.
scope: optional name scope for summary tags.
| tensorflow.control_dependencies | 13,549 |
import tensorflow as tf
tf.summary.scalar("stop_token_loss", model.stop_token_loss)
tf.summary.scalar("loss", model.loss)
tf.summary.scalar("learning_rate", model.learning_rate) # Control learning rate decay speed
if hparams.tacotron_teacher_forcing_mode == "scheduled":
tf.summary.scalar("teacher_forcing_ratio", model.ratio) # Control teacher forcing
# ratio decay when mode = "scheduled"
gradient_norms = [tf.norm(grad) for grad in model.gradients]
tf.summary.histogram("gradient_norm", gradient_norms)
tf.summary.scalar("max_gradient_norm", tf.reduce_max(gradient_norms)) # visualize
# gradients (in case of explosion)
return tf.summary.merge_all()
| tensorflow.norm | 13,550 |
import tensorflow as tf
sdf_values += tf.math.sign(tf.nn.relu(interpolated + self.tol))
status2 = False
if status2:
a = 2
values = interpolated
inter = tf.reshape(values, [self.resolution,
self.resolution,
self.resolution])
inter = tf.transpose(tf.reduce_max(inter, axis=a))
im = axs[fig_obj_count, mtype * 2 + 0].matshow(inter.numpy())
plt.colorbar(im, ax=axs[fig_obj_count, mtype * 2 + 0])
print(mtype, fig_obj_count, 0)
values = tf.math.sign(tf.nn.relu(interpolated + self.tol))
inter = tf.reshape(values, [self.resolution,
self.resolution,
self.resolution])
| tensorflow.reduce_max | 13,551 |
import tensorflow as tf
matched_gt_boxes)
matched_gt_classes = tf.where(
background_indicator,
tf.zeros_like(matched_gt_classes),
matched_gt_classes)
matched_gt_indices = tf.where(
| tensorflow.zeros_like | 13,552 |
import tensorflow as tf
batch_size = tf.shape(observations_ph.get())[0]
random_actions = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=num_actions, dtype=tf.int64)
chose_random = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=1, dtype=tf.float32) < eps
stochastic_actions = tf.where(chose_random, random_actions, deterministic_actions)
output_actions = tf.cond(stochastic_ph, lambda: stochastic_actions, lambda: deterministic_actions)
update_eps_expr = eps.assign(tf.cond(update_eps_ph >= 0, lambda: update_eps_ph, lambda: eps))
updates = [
update_eps_expr,
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)),
update_param_noise_threshold_expr,
]
act = U.function(inputs=[observations_ph, stochastic_ph, update_eps_ph, reset_ph, update_param_noise_threshold_ph, update_param_noise_scale_ph],
outputs=output_actions,
givens={update_eps_ph: -1.0, stochastic_ph: True, reset_ph: False, update_param_noise_threshold_ph: False, update_param_noise_scale_ph: False},
updates=updates)
return act
| tensorflow.Variable | 13,553 |
import tensorflow as tf
while len(eval_examples) % FLAGS.eval_batch_size != 0:
eval_examples.append(PaddingInputExample())
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 (%d actual, %d padding)",
len(eval_examples), num_actual_eval_examples,
len(eval_examples) - num_actual_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:
assert len(eval_examples) % FLAGS.eval_batch_size == 0
eval_steps = int(len(eval_examples) // FLAGS.eval_batch_size)
eval_drop_remainder = True if FLAGS.use_tpu else False
| tensorflow.logging.info | 13,554 |
import tensorflow as tf
var = tf.Variable(other_value, name=var_name)
save = tf.train.Saver({var_name: var})
save.restore(sess, save_path)
self.assertAllClose(var_value, var.eval())
def testCacheRereadsFile(self):
save_path = os.path.join(self.get_temp_dir(), "cache_rereads")
# Save and reload one Variable named "var0".
self._SaveAndLoad("var0", 0.0, 1.0, save_path)
# Save and reload one Variable named "var1" in the same file.
# The cached readers should know to re-read the file.
self._SaveAndLoad("var1", 1.1, 2.2, save_path)
def testGPU(self):
if not tf.test.is_built_with_cuda():
return
save_path = os.path.join(self.get_temp_dir(), "gpu")
with tf.Session("", graph=tf.Graph()) as sess:
with sess.graph.device("/gpu:0"):
v0_1 = tf.Variable(123.45)
save = tf.train.Saver({"v0": v0_1})
tf.initialize_all_variables().run()
save.save(sess, save_path)
with tf.Session("", graph=tf.Graph()) as sess:
with sess.graph.device("/gpu:0"):
v0_2 = tf.Variable(543.21)
save = tf.train.Saver({"v0": v0_2})
| tensorflow.test.is_built_with_cuda | 13,555 |
import tensorflow as tf
self._activation_fn = tf.nn.relu
self._embedding_initializers = {
'embeddings': tf.truncated_normal_initializer(stddev=0.01),
}
self._embedding_regularizers = {}
self._initializers = {
"w": tf.contrib.layers.xavier_initializer(),
}
self._regularizers = {
'w': tf.contrib.layers.l2_regularizer(config.l2)
}
self._construct_placeholders()
| tensorflow.contrib.layers.xavier_initializer | 13,556 |
import tensorflow as tf
# Generates a new MetaGraphDef.
new_saver.export_meta_graph()
# Restores from checkpoint.
new_saver.restore(sess, saver0_ckpt)
# Addes loss and train.
labels = tf.constant(0, tf.int32, shape=[100], name="labels")
batch_size = tf.size(labels)
labels = tf.expand_dims(labels, 1)
indices = tf.expand_dims(tf.range(0, batch_size), 1)
concated = tf.concat(1, [indices, labels])
onehot_labels = tf.sparse_to_dense(
concated, tf.pack([batch_size, 10]), 1.0, 0.0)
logits = tf.get_collection("logits")[0]
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits,
onehot_labels,
name="xentropy")
loss = tf.reduce_mean(cross_entropy, name="xentropy_mean")
tf.scalar_summary(loss.op.name, loss)
# Creates the gradient descent optimizer with the given learning rate.
optimizer = tf.train.GradientDescentOptimizer(0.01)
| tensorflow.pack | 13,557 |
import tensorflow as tf
tf.app.flags.DEFINE_float('ws_prune_ratio', 0.75, 'WS: target pruning ratio')
tf.app.flags.DEFINE_string('ws_prune_ratio_prtl', 'optimal',
'WS: pruning ratio protocol (\'uniform\' | \'heurist\' | \'optimal\')')
tf.app.flags.DEFINE_integer('ws_nb_rlouts', 200, 'WS: # of roll-outs for the RL agent')
tf.app.flags.DEFINE_integer('ws_nb_rlouts_min', 50,
'WS: minimal # of roll-outs for the RL agent to start training')
tf.app.flags.DEFINE_string('ws_reward_type', 'single-obj',
'WS: reward type (\'single-obj\' OR \'multi-obj\')')
tf.app.flags.DEFINE_float('ws_lrn_rate_rg', 3e-2, 'WS: learning rate for layerwise regression')
tf.app.flags.DEFINE_integer('ws_nb_iters_rg', 20, 'WS: # of iterations for layerwise regression')
tf.app.flags.DEFINE_float('ws_lrn_rate_ft', 3e-4, 'WS: learning rate for global fine-tuning')
tf.app.flags.DEFINE_integer('ws_nb_iters_ft', 400, 'WS: # of iterations for global fine-tuning')
| tensorflow.app.flags.DEFINE_string | 13,558 |
import tensorflow as tf
cdf_min = tf.nn.sigmoid(min_in)
log_cdf_plus = plus_in - tf.nn.softplus(plus_in)
log_one_minus_cdf_min = -tf.nn.softplus(min_in)
cdf_delta = cdf_plus - cdf_min
mid_in = inv_stdv * centered_inputs
log_pdf_mid = mid_in - log_scales - 2. * tf.nn.softplus(mid_in)
log_probs = tf.select(
inputs < -0.999, log_cdf_plus,
tf.select(
inputs > 0.999, log_one_minus_cdf_min,
tf.select(cdf_delta > 1e-5, tf.log(tf.maximum(cdf_delta, 1e-12)),
log_pdf_mid - np.log(127.5))))
log_probs = tf.reduce_sum(log_probs, 3) + \
log_prob_from_logits(logit_probs)
if sum_all:
return -tf.reduce_sum(log_sum_exp(log_probs))
else:
return -tf.reduce_sum(log_sum_exp(log_probs), [1, 2])
| tensorflow.maximum | 13,559 |
import tensorflow as tf
def _project_features(self, features):
with tf.variable_scope('project_features'):
w = tf.get_variable('w', [self.D, self.D], initializer=self.weight_initializer)
features_flat = tf.reshape(features, [-1, self.D])
features_proj = tf.matmul(features_flat, w)
features_proj = tf.reshape(features_proj, [-1, self.L, self.D])
return features_proj
def _attention_layer(self, features, features_proj, h, reuse=False):
with tf.variable_scope('attention_layer', reuse=reuse):
w = tf.get_variable('w', [self.H, self.D], initializer=self.weight_initializer)
b = tf.get_variable('b', [self.D], initializer=self.const_initializer)
w_att = tf.get_variable('w_att', [self.D, 1], initializer=self.weight_initializer)
h_att = tf.nn.relu(features_proj + tf.expand_dims(tf.matmul(h, w), 1) + b) # (N, L, D)
out_att = tf.reshape(tf.matmul(tf.reshape(h_att, [-1, self.D]), w_att), [-1, self.L]) # (N, L)
alpha = tf.nn.softmax(out_att)
context = tf.reduce_sum(features * tf.expand_dims(alpha, 2), 1, name='context') #(N, D)
return context, alpha
def _selector(self, context, h, reuse=False):
with tf.variable_scope('selector', reuse=reuse):
w = tf.get_variable('w', [self.H, 1], initializer=self.weight_initializer)
b = tf.get_variable('b', [1], initializer=self.const_initializer)
beta = tf.nn.sigmoid(tf.matmul(h, w) + b, 'beta') # (N, 1)
context = tf.multiply(beta, context, name='selected_context')
return context, beta
def _decode_lstm(self, x, h, context, dropout=False, reuse=False):
with tf.variable_scope('logits', reuse=reuse):
| tensorflow.reshape | 13,560 |
import tensorflow as tf
"segment_ids":
tf.constant(
| tensorflow.constant | 13,561 |
import tensorflow as tf
self.train_step = self.opt.minimize(self.loss)
if self.maxnorm is not None:
# Post-processing to limit embedding vars to L2 ball
rel_maxnorm = self.maxnorm * self.rel_maxnorm_mult
unique_ent_indices = tf.unique(tf.concat(0, [self.head_input, self.tail_input]))[0]
unique_rel_indices = tf.unique(self.rel_input)[0]
entity_constraint = self._norm_constraint_op(self.entity_embedding_vars,
unique_ent_indices,
self.maxnorm)
rel_constraint = self._norm_constraint_op(self.rel_embedding_vars,
| tensorflow.unique | 13,562 |
import tensorflow as tf
def weight_variable(shape):
"""weight_variable generates a weight variable of a given shape."""
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial, name='weights')
def bias_variable(shape):
"""bias_variable generates a bias variable of a given shape."""
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial, name='biases')
def deepnn(x, train):
"""deepnn builds the graph for a deep net for classifying CIFAR10 images.
Args:
x: an input tensor with the dimensions (N_examples, 3072), where 3072 is the
number of pixels in a standard CIFAR10 image.
| tensorflow.Variable | 13,563 |
from tensorflow.python.framework import ops
mean = _safe_div(total, count, 'value')
with ops.control_dependencies([total_compute_op, count_compute_op]):
update_op = _safe_div(total, count, 'update_op')
if metrics_collections:
ops.add_to_collections(metrics_collections, mean)
if updates_collections:
ops.add_to_collections(updates_collections, update_op)
return mean, update_op
def streaming_mean_tensor(values, weights=None, metrics_collections=None,
updates_collections=None, name=None):
"""Computes the element-wise (weighted) mean of the given tensors.
| tensorflow.python.framework.ops.add_to_collections | 13,564 |
from tensorflow.python.framework import ops
x: `Tensor` numerator of real numeric type.
y: `Tensor` numerator of real numeric type.
name: A name for the operation (optional).
Returns:
`x / y` rounded down (except possibly for integers in C).
Raises:
TypeError: If the inputs are complex.
"""
with ops.op_scope([x, y], name, "floordiv") as name:
x = ops.convert_to_tensor(x, name="x")
dtype = x.dtype
if dtype.is_floating:
return floor(div(x, y), name=name)
else:
if not dtype.is_integer:
raise TypeError("Expected floating point or integer, got %r" % dtype)
return div(x, y, name=name)
_OverrideBinaryOperatorHelper(add, "add")
| tensorflow.python.framework.ops.convert_to_tensor | 13,565 |
import tensorflow.contrib.graph_editor as ge
break
copied_sgv, info = ge.copy_with_input_replacements(ge.sgv(ops_to_copy), {})
| tensorflow.contrib.graph_editor.sgv | 13,566 |
import tensorflow as tf
logits=self.end_points_D['class_logits'], labels=tf.to_int64(targets))
self.test_loss = 1. - \
tf.reduce_mean(tf.to_float(tf.nn.in_top_k(
self.end_points_D_val['logits'], targets, 1)))
self.error_rate = 1. - \
tf.reduce_mean(tf.to_float(tf.nn.in_top_k(
self.end_points_D['class_logits'], targets, 1)))
if gpu_idx == 0:
update = tf.assign(num_error_rate, num_error_rate + 1.)
with tf.control_dependencies([update]):
tc = tf.maximum(.01, 1. / num_error_rate)
update = tf.assign(avg_error_rate, (1. - tc) * avg_error_rate + tc * self.error_rate)
with tf.control_dependencies([update]):
self.d_loss_class = tf.identity(self.d_loss_class)
self.d_loss_fake = tf.nn.sigmoid_cross_entropy_with_logits(
logits=self.end_points_D['D_on_G_logits'],
| tensorflow.assign | 13,567 |
import tensorflow as tf
elif method=='tgsm':
print('Attacking method is tgsm')
adversarial_sample = attacks.tgsm.tgsm(models, images, hps, RCE_train, y=None,
eps=eps/10, epochs=10, clip_min=-0.5, clip_max=0.5)
elif method=='jsma':
print('Attacking method is jsma')
if target_labels==None:
print('Target label is the argmin label')
model_target_y = models(hps, images, FLAGS.RCE_train, logits=False)
target_y64 = tf.argmin(model_target_y,axis=1)
else:
target_y64=target_labels
target_y = tf.cast(target_y64, tf.int32)
adversarial_sample = attacks.jsma.jsma(models, images, hps, RCE_train, target_y,epochs=epoch_jsma, eps=eps,
clip_min=-0.5, clip_max=0.5, pair=False, min_proba=0.0)
elif method=='smda':
print('Attacking method is smda')
if target_labels==None:
print('Target label is the argmin label')
model_target_y = models(hps, images, FLAGS.RCE_train, logits=False)
target_y64 = tf.argmin(model_target_y,axis=1)
else:
target_y64=target_labels
target_y = tf.cast(target_y64, tf.int32)
| tensorflow.cast | 13,568 |
import tensorflow as tf
print (policy.parameters())
print (warmup_policy.parameters())
sync_warmup_policy = tf.group(*[tf.assign(w_v, p_v) for w_v, p_v in zip(warmup_policy.parameters(), policy.parameters())])
# batched noises
noise = OUNoise(env.action_space, theta=FLAGS.OUNoise.theta, sigma=FLAGS.OUNoise.sigma, shape=(1, dim_action))
vfn = MLPVFunction(dim_state, [64, 64], normalizers.state)
warmup_vfn = MLPVFunction(dim_state, [64, 64], normalizers.state)
sync_warmup_vfn = tf.group(*[tf.assign(w_v, p_v) for w_v, p_v in zip(warmup_vfn.parameters(), vfn.parameters())])
model = DynamicsModel(dim_state, dim_action, normalizers, FLAGS.model.hidden_sizes)
lazy_model = DynamicsModel(dim_state, dim_action, normalizers, FLAGS.model.hidden_sizes)
warmup_model = DynamicsModel(dim_state, dim_action, normalizers, FLAGS.model.hidden_sizes)
sync_warmup_model = tf.group(*[tf.assign(w_v, p_v) for w_v, p_v in zip(warmup_model.parameters(), model.parameters())])
shadow_models = [DynamicsModel(dim_state, dim_action, normalizers, FLAGS.model.hidden_sizes) for n in range(FLAGS.warmup.n_shadow_models)]
| tensorflow.assign | 13,569 |
import tensorflow as tf
print("------------------pred_Y-------------------")
print(pred_Y)
# Loss,train_step,evaluation
l2 = config.lambda_loss_amount * \
sum(tf.nn.l2_loss(tf_var) for tf_var in tf.trainable_variables())
# Softmax loss and L2
cost = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(pred_Y, Y)) + l2
train_step = tf.train.AdamOptimizer(
| tensorflow.nn.l2_loss | 13,570 |
import tensorflow as tf
correct = tf.equal(
tf.cast(tf.zeros_like(label_ids, dtype=tf.int32), tf.int32),
tf.cast(pred_label, tf.int32)
)
te_accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))
except:
te_accuracy = tf.constant(0.0)
st_accuracy = tf.constant(0.0)
try:
st_accuracy = tf.reduce_mean(distillation_loss["src_f1_prob"])
te_accuracy = tf.reduce_mean(distillation_loss["tgt_f1_prob"])
except:
te_accuracy = tf.constant(0.0)
st_accuracy = tf.constant(0.0)
return {
"train":{
"loss":loss,
"logits":logits,
"train_op":train_op,
"cross_entropy":label_loss,
| tensorflow.reduce_mean | 13,571 |
import tensorflow as tf
def training(self, cost):
optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate)
# train_op = optimizer.minimize(cost)
trainables = tf.trainable_variables()
grads = tf.gradients(cost, trainables)
grads, _ = tf.clip_by_global_norm(grads, clip_norm=self.clip_norm)
capped_gvs = zip(grads, trainables)
train_op = optimizer.apply_gradients(capped_gvs)
return train_op
| tensorflow.gradients | 13,572 |
import tensorflow as tf
return features
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
processors = {
"cola": ColaProcessor,
| tensorflow.logging.set_verbosity | 13,573 |
import tensorflow as tf
with tf.variable_scope(name) as scope:
if scale > 1:
X = self.conv(name + '_downsample', X, filter, scale, scale, (not norm) and use_bias, "VALID", stddev)
else:
X = self.conv(name + '_conf', X, filter, f_size, 1, (not norm) and use_bias, "VALID", stddev)
if norm == 'I':
X = tf.contrib.layers.instance_norm(X, scope=scope, reuse=reuse)
elif norm == 'B':
X = tf.layers.batch_normalization(X, reuse=reuse, training=is_train, name=name)
elif norm == 'G':
X = tf.contrib.layers.group_norm(X, groups=16, scope=scope, reuse=reuse)
if dropout > 0.0:
| tensorflow.contrib.layers.instance_norm | 13,574 |
import tensorflow as tf
else:
q = tf.nn.softmax(q_logits)
p = tf.nn.softmax(p_logits)
kl = tf.reduce_sum(q * (tf.log(q) - tf.log(p)), 1)
num_labels = tf.reduce_sum(weights)
num_labels = tf.where(tf.equal(num_labels, 0.), 1., num_labels)
| tensorflow.log | 13,575 |
import tensorflow as tf
"""Tensorflow Example proto decoder."""
def __init__(self, include_mask=False):
self._include_mask = include_mask
self._keys_to_features = {
'image/encoded':
tf.io.FixedLenFeature((), tf.string),
'image/source_id':
tf.io.FixedLenFeature((), tf.string),
'image/height':
tf.io.FixedLenFeature((), tf.int64),
'image/width':
tf.io.FixedLenFeature((), tf.int64),
'image/object/bbox/xmin':
tf.io.VarLenFeature(tf.float32),
'image/object/bbox/xmax':
tf.io.VarLenFeature(tf.float32),
'image/object/bbox/ymin':
tf.io.VarLenFeature(tf.float32),
'image/object/bbox/ymax':
| tensorflow.io.FixedLenFeature | 13,576 |
import tensorflow as tf
"[Optional] GCE zone where the Cloud TPU is located in. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
tf.flags.DEFINE_string(
"gcp_project", None,
"[Optional] Project name for the Cloud TPU-enabled project. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
flags.DEFINE_integer(
"num_tpu_cores", 8,
"Only used if `use_tpu` is True. Total number of TPU cores to use.")
class InputExample(object):
"""A single training/test example for simple sequence classification."""
| tensorflow.flags.DEFINE_string | 13,577 |
from tensorflow.contrib.learn.python.learn.estimators import estimator_test_utils
'loss',
'precision/positive_threshold_0.500000_mean',
'recall/positive_threshold_0.500000_mean',
}
class DNNLinearCombinedClassifierBenchmark(test.Benchmark):
def _assertSingleClassMetrics(self, metrics):
estimator_test_utils.assert_in_range(0.9, 1.0, 'auc', metrics)
estimator_test_utils.assert_in_range(0.9, 1.0,
'accuracy/threshold_0.500000_mean',
metrics)
estimator_test_utils.assert_in_range(
0.9, 1.0, 'precision/positive_threshold_0.500000_mean', metrics)
estimator_test_utils.assert_in_range(
0.9, 1.0, 'recall/positive_threshold_0.500000_mean', metrics)
self._assertCommonMetrics(metrics)
def _assertCommonMetrics(self, metrics):
estimator_test_utils.assert_in_range(_ITERS, _ITERS + 5, 'global_step',
metrics)
estimator_test_utils.assert_in_range(0.9, 1.0, 'accuracy', metrics)
estimator_test_utils.assert_in_range(0.0, 0.2, 'loss', metrics)
self.report_benchmark(
iters=metrics['global_step'],
| tensorflow.contrib.learn.python.learn.estimators.estimator_test_utils.assert_in_range | 13,578 |
import tensorflow as tf
def _build_net(self): # we use parameter sharing among agents
with tf.variable_scope(self.name):
# ------------------ all inputs ------------------------
self.S = tf.placeholder(tf.float32, [None, self.num_global_s], name='S') # input Global State
self.s = tf.placeholder(tf.float32, [None, self.num_s], name='s1') # input state for agent1
self.S_ = tf.placeholder(tf.float32, [None, self.num_global_s], name='S_') # input Next Global State
self.s_ = tf.placeholder(tf.float32, [None, self.num_s], name='s1_') # input next state for agent1
self.R = tf.placeholder(tf.float32, [None, ], name='R') # input Reward
self.a = tf.placeholder(tf.float32, [None, self.num_a], name='a') # input Action onehot for agent1
self.done = tf.placeholder(tf.float32, [None, ], name='done') # input Done info ???
self.q_m_ = tf.placeholder(tf.float32, [None, ], name='q_value_next_max')
| tensorflow.placeholder | 13,579 |
import tensorflow as tf
w = tf.get_variable("w", [nin, nh], initializer=ortho_init(init_scale))
print("w is "+str(w))
b = tf.get_variable("b", [nh], initializer=tf.constant_initializer(init_bias))
return tf.matmul(x, w)+b
def batch_to_seq(h, nbatch, nsteps, flat=False):
if flat:
h = tf.reshape(h, [nbatch, nsteps])
else:
h = tf.reshape(h, [nbatch, nsteps, -1])
return [tf.squeeze(v, [1]) for v in tf.split(axis=1, num_or_size_splits=nsteps, value=h)]
def seq_to_batch(h, flat = False):
shape = h[0].get_shape().as_list()
if not flat:
assert(len(shape) > 1)
nh = h[0].get_shape()[-1].value
return tf.reshape(tf.concat(axis=1, values=h), [-1, nh])
| tensorflow.reshape | 13,580 |
import tensorflow as tf
tf.add_to_collection('mu_sigma_bn', sigma)
beta = tf.get_variable('beta', batch_mean.shape, dtype=tf.float32,
initializer=tf.zeros_initializer())
gamma = tf.get_variable('gamma', batch_var.shape, dtype=tf.float32,
initializer=tf.ones_initializer())
# BN when training
update = 1.0 - decay
update_mu = mu.assign_sub(update * (mu - batch_mean))
update_sigma = sigma.assign_sub(update * (sigma - batch_var))
tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_mu)
tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_sigma)
mean, var = tf.cond(self.train_flag, lambda: (batch_mean, batch_var), lambda: (mu, sigma))
bn = tf.nn.batch_normalization(x, mean, var, beta, gamma, 1e-5)
tf.add_to_collection('debug_layers', bn)
return bn
| tensorflow.cond | 13,581 |
import tensorflow as tf
u = tf.random_uniform(tf.shape(means), minval=1e-5, maxval=1. - 1e-5)
x = means + tf.exp(log_scales) * (tf.log(u) - tf.log(1. - u))
| tensorflow.log | 13,582 |
from tensorflow.python.ops import gen_nn_ops
" {}".format(padding))
return gen_nn_ops.conv2d_backprop_input(input_sizes=output_shape_,
filter=filter,
| tensorflow.python.ops.gen_nn_ops.conv2d_backprop_input | 13,583 |
import tensorflow as tf
regularization_penalty_pi = tf.contrib.layers.apply_regularization(regularizerpi, all_trainable_weights_pi)
policy_loss = policy_kl_loss + regularization_penalty_pi + self.actor_loss_di
# Target for value fn regression
# We update the vf towards the min of two Q-functions in order to
# reduce overestimation bias from function approximation error.
v_backup = tf.stop_gradient(min_qf_pi - self.ent_coef * logp_pi)
value_loss = 0.5 * tf.reduce_mean(((value_fn - v_backup) ** 2)*self.weight_ph)
#value_for_priority = tf.reduce_mean((value_fn - v_backup) ** 2,1)
regularizervf = tf.contrib.layers.l1_l2_regularizer(scale_l1=0.0, scale_l2=1e-5, scope='model/values_fn')
all_trainable_weights_vf = tf_util.get_trainable_vars('model/values_fn')
regularization_penalty_vf = tf.contrib.layers.apply_regularization(regularizervf, all_trainable_weights_vf)
if self.n_step:
values_losses = qf1_loss + qf2_loss + value_loss + regularization_penalty_vf + qf1_loss_n + qf2_loss_n
else:
values_losses = qf1_loss + qf2_loss + value_loss + regularization_penalty_vf
# Policy train op
# (has to be separate from value train op, because min_qf_pi appears in policy_loss)
policy_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate_ph)
policy_train_op = policy_optimizer.minimize(policy_loss, var_list=tf_util.get_trainable_vars('model/pi'))
# Value train op
value_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate_ph)
| tensorflow.contrib.layers.apply_regularization | 13,584 |
import tensorflow as tf
# Center each group using the mean.
# shape = (
# cur_batch_size,
# image_size,
# image_size,
# num_channels
# )
centered_image = tf.subtract(
x=X, y=mean, name="centered_image"
)
print_obj(
"ungrouped_minibatch_stddev",
"centered_image",
centered_image
| tensorflow.subtract | 13,585 |
import tensorflow as tf
tf.summary.histogram("gradient_norm", gradient_norms)
tf.summary.scalar("max_gradient_norm", tf.reduce_max(gradient_norms)) # visualize
# gradients (in case of explosion)
return tf.summary.merge_all()
def add_eval_stats(summary_writer, step, linear_loss, before_loss, after_loss, stop_token_loss,
loss):
values = [
tf.Summary.Value(tag="Tacotron_eval_model/eval_stats/eval_before_loss",
simple_value=before_loss),
tf.Summary.Value(tag="Tacotron_eval_model/eval_stats/eval_after_loss",
simple_value=after_loss),
tf.Summary.Value(tag="Tacotron_eval_model/eval_stats/stop_token_loss",
simple_value=stop_token_loss),
tf.Summary.Value(tag="Tacotron_eval_model/eval_stats/eval_loss", simple_value=loss),
]
if linear_loss is not None:
values.append(tf.Summary.Value(tag="Tacotron_eval_model/eval_stats/eval_linear_loss",
simple_value=linear_loss))
test_summary = tf.Summary(value=values)
summary_writer.add_summary(test_summary, step)
def time_string():
return datetime.now().strftime("%Y-%m-%d %H:%M")
| tensorflow.Summary.Value | 13,586 |
import tensorflow as tf
dtype=tensor.dtype.base_dtype,
name='loss_weight')
loss = tf.multiply(weight, tf.nn.l2_loss(tensor), name='value')
return loss
def lppool(inpOp, pnorm, kH, kW, dH, dW, padding, name):
with tf.variable_scope(name):
if pnorm == 2:
pwr = tf.square(inpOp)
else:
pwr = tf.pow(inpOp, pnorm)
subsamp = tf.nn.avg_pool(pwr,
ksize=[1, kH, kW, 1],
strides=[1, dH, dW, 1],
padding=padding)
subsamp_sum = tf.multiply(subsamp, kH*kW)
if pnorm == 2:
out = tf.sqrt(subsamp_sum)
| tensorflow.pow | 13,587 |
import tensorflow as tf
tf.stop_gradient(indicator_matrix), distance_matrix,
tf.fill(tf.shape(distance_matrix), distance_matrix.dtype.max))
hard_distances = tf.math.reduce_min(distance_matrix, axis=-1)
return hard_distances
| tensorflow.math.reduce_min | 13,588 |
import tensorflow as tf
input_score_maps = tf.placeholder(tf.float32, shape=[None, None, None, 1], name='input_score_maps')
if FLAGS.geometry == 'RBOX':
input_geo_maps = tf.placeholder(tf.float32, shape=[None, None, None, 5], name='input_geo_maps')
else:
input_geo_maps = tf.placeholder(tf.float32, shape=[None, None, None, 8], name='input_geo_maps')
input_training_masks = tf.placeholder(tf.float32, shape=[None, None, None, 1], name='input_training_masks')
global_step = tf.get_variable('global_step', [], initializer=tf.constant_initializer(0), trainable=False)
learning_rate = tf.train.exponential_decay(FLAGS.learning_rate, global_step, decay_steps=10000, decay_rate=0.94, staircase=True)
# add summary
tf.summary.scalar('learning_rate', learning_rate)
opt = tf.train.AdamOptimizer(learning_rate)
opt = MixedPrecisionOptimizer(opt, scale=FLAGS.loss_scale)
from npu_bridge.estimator.npu.npu_optimizer import NPUDistributedOptimizer
opt = NPUDistributedOptimizer(opt)
# split
input_images_split = tf.split(input_images, len(gpus))
input_score_maps_split = tf.split(input_score_maps, len(gpus))
input_geo_maps_split = tf.split(input_geo_maps, len(gpus))
input_training_masks_split = tf.split(input_training_masks, len(gpus))
tower_grads = []
| tensorflow.train.AdamOptimizer | 13,589 |
import tensorflow as tf
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:
pred_indices_ = tf.squeeze(pred_indices)
image_ = tf.squeeze(image) * 255.
pred_heatmap = tf.one_hot(pred_indices_, heatmap_size*heatmap_size, on_value=1., off_value=0., axis=-1, dtype=tf.float32)
pred_heatmap = tf.reshape(pred_heatmap, [-1, heatmap_size, heatmap_size])
if data_format == 'channels_first':
image_ = tf.transpose(image_, perm=(1, 2, 0))
| tensorflow.cast | 13,590 |
import tensorflow as tf
test_inf=work.test_inference(test_image_batch)
test_labels=tf.one_hot(test_label_batch,classnum)
test_pre = tf.reshape(test_inf, [testnum, classnum])
correct_prediction=tf.equal(tf.argmax(test_inf,1),tf.argmax(test_labels,1))
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
test_pre = tf.argmax(test_pre, 1)
test_true = tf.argmax(test_labels, 1)
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()
config.gpu_options.allow_growth=True
| tensorflow.reshape | 13,591 |
import tensorflow as tf
vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
tpu_cluster_resolver = None
if FLAGS.use_tpu and FLAGS.tpu_name:
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
run_config = tf.contrib.tpu.RunConfig(
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))
train_examples = None
num_train_steps = None
num_warmup_steps = None
if FLAGS.do_train:
train_examples = processor.get_train_examples(FLAGS.data_dir)
num_train_steps = int(
len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)
num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)
| tensorflow.contrib.tpu.TPUConfig | 13,592 |
import tensorflow as tf
identity = (registry.Modalities.GENERIC, None)
if self.has_inputs:
p.input_modality["inputs_segmentation"] = identity
p.input_modality["inputs_position"] = identity
p.input_modality["targets_segmentation"] = identity
p.input_modality["targets_position"] = identity
def example_reading_spec(self):
data_fields = {"targets": tf.VarLenFeature(tf.int64)}
if self.has_inputs:
data_fields["inputs"] = tf.VarLenFeature(tf.int64)
if self.packed_length:
if self.has_inputs:
data_fields["inputs_segmentation"] = tf.VarLenFeature(tf.int64)
data_fields["inputs_position"] = tf.VarLenFeature(tf.int64)
data_fields["targets_segmentation"] = tf.VarLenFeature(tf.int64)
data_fields["targets_position"] = tf.VarLenFeature(tf.int64)
data_items_to_decoders = None
| tensorflow.VarLenFeature | 13,593 |
import tensorflow as tf
self.e_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Critic/eval_net')
self.t_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Critic/target_net')
with tf.variable_scope('target_q'):
self.target_q = R + self.gamma * self.q_
with tf.variable_scope('abs_TD'):
| tensorflow.variable_scope | 13,594 |
import tensorflow as tf
for sample in range(self.num_samples):
with tf.control_dependencies(control_inputs=deltas):
perturbations = [
tf.random_normal(shape=util.shape(variable)) * learning_rate
for variable in variables
]
perturbation_deltas = [
pert - prev_pert
for pert, prev_pert in zip(perturbations, previous_perturbations)
]
applied = self.apply_step(variables=variables, deltas=perturbation_deltas)
previous_perturbations = perturbations
with tf.control_dependencies(control_inputs=(applied,)):
perturbed_loss = fn_loss(**arguments)
direction = tf.sign(x=(unperturbed_loss - perturbed_loss))
deltas = [
delta + direction * perturbation
for delta, perturbation in zip(deltas, perturbations)
]
else:
# TensorFlow while loop
def body(deltas, previous_perturbations):
with tf.control_dependencies(control_inputs=deltas):
perturbations = [
tf.random_normal(shape=util.shape(variable)) * learning_rate
for variable in variables
]
perturbation_deltas = [
| tensorflow.sign | 13,595 |
import tensorflow as tf
init_state_initializer = tf.constant_initializer(weights['init_state'])
W_in_initializer = tf.constant_initializer(weights['W_in'])
W_rec_initializer = tf.constant_initializer(weights['W_rec'])
W_out_initializer = tf.constant_initializer(weights['W_out'])
| tensorflow.constant_initializer | 13,596 |
import tensorflow as tf
with self._write_locks[index % rconst.NUM_FILE_SHARDS]:
self._writers[index % rconst.NUM_FILE_SHARDS].write(example_bytes)
else:
if self._is_training:
mask_start_index = data.pop(rconst.MASK_START_INDEX)
batch_size = data[movielens.ITEM_COLUMN].shape[0]
data[rconst.VALID_POINT_MASK] = np.less(np.arange(batch_size),
mask_start_index)
data = (data, data.pop("labels"))
self._result_queue.put(data)
def start_construction(self):
if self._stream_files:
tf.gfile.MakeDirs(self.current_data_root)
template = os.path.join(self.current_data_root, rconst.SHARD_TEMPLATE)
self._writers = [tf.io.TFRecordWriter(template.format(i))
for i in range(rconst.NUM_FILE_SHARDS)]
def end_construction(self):
if self._stream_files:
[writer.close() for writer in self._writers]
self._writers = []
self._result_queue.put(self.current_data_root)
self._epochs_completed += 1
def data_generator(self, epochs_between_evals):
| tensorflow.gfile.MakeDirs | 13,597 |
import tensorflow as tf
if filter_type == "laplacian":
supports.append(calculate_scaled_laplacian(adj_mx,
lambda_max=None))
for support in supports:
self._supports.append(self._build_sparse_matrix(support))
@staticmethod
def _build_sparse_matrix(L):
L = L.tocoo()
indices = np.column_stack((L.row, L.col))
L = tf.SparseTensor(indices, L.data, L.shape)
return tf.sparse_reorder(L)
@property
def output_size(self):
output_size = self._num_nodes * self._num_units
if self._num_proj is not None:
output_size = self._num_nodes * self._num_proj
return output_size
| tensorflow.SparseTensor | 13,598 |
import tensorflow as tf
# This works because we use sparse_softmax_cross_entropy
nclass = 1001
else:
nclass = 1001
input_shape = [batch_size, image_size, image_size, input_nchan]
images = tf.truncated_normal(
input_shape,
dtype=input_data_type,
stddev=1e-1,
name='synthetic_images')
| tensorflow.truncated_normal | 13,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.