seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
import tensorflow as tf
name="relabel_task_optimal", data=relabel_opt_frac, step=global_step)
# What are the average Q values of the original tasks?
if batch_size == num_tasks:
indices = tf.transpose(tf.stack([orig_indices, orig_indices], axis=0))
orig_q_vals = tf.gather_nd(logits_vec, indices)
tf.compat.v2.summary.scalar(
name="orig_q_vals",
data=tf.reduce_mean(orig_q_vals),
step=global_step,
| tensorflow.gather_nd | 3,000 |
import tensorflow as tf
def log_loss_custom(predictions, labels, eps=1e-7, name='log'):
"""Define a log loss.
Args:
predictions: 2D tensor or array, [batch_size, num_classes] predictions of the network .
labels: 2D or array tensor, [batch_size, num_classes] ground truth labels or target labels.
eps: a constant to set upper or lower limit for labels, smoothening factor
name: Optional scope/name for op_scope.
Returns:
A tensor with the log loss.
"""
with tf.name_scope(name):
predictions = tf.to_float(predictions)
labels = tf.to_float(labels)
predictions = tf.clip_by_value(predictions, eps, 1 - eps)
predictions.get_shape().assert_is_compatible_with(labels.get_shape())
loss = -tf.reduce_mean(labels * tf.log(predictions))
return loss
def log_loss_tf(predictions, labels, eps=1e-7, weights=1.0, name='log_loss'):
"""Define a log loss.
Args:
predictions: 2D tensor or array, [batch_size, num_classes] predictions of the network .
| tensorflow.to_float | 3,001 |
from tensorflow.python.framework import ops
tp, tp_update = _streaming_sparse_true_positive_at_k(
predictions_idx=top_k_idx, labels=labels, k=k, class_id=class_id,
weights=weights)
fn, fn_update = _streaming_sparse_false_negative_at_k(
predictions_idx=top_k_idx, labels=labels, k=k, class_id=class_id,
weights=weights)
metric = math_ops.div(tp, math_ops.add(tp, fn), name=scope)
update = math_ops.div(
tp_update, math_ops.add(tp_update, fn_update), name='update')
if metrics_collections:
ops.add_to_collections(metrics_collections, metric)
if updates_collections:
ops.add_to_collections(updates_collections, update)
return metric, update
def _streaming_sparse_precision_at_k(top_k_idx,
labels,
k=None,
class_id=None,
ignore_mask=None,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None):
| tensorflow.python.framework.ops.add_to_collections | 3,002 |
import tensorflow as tf
def _build_word_embeddings(self):
projection_dim = self.options['lstm']['projection_dim']
# the word embeddings
with tf.device("/cpu:0"):
self.embedding_weights = tf.get_variable(
"embedding", [self._n_tokens_vocab, projection_dim],
dtype=DTYPE,
)
self.embedding = tf.nn.embedding_lookup(self.embedding_weights,
| tensorflow.get_variable | 3,003 |
import tensorflow as tf
# Flatten CNN and concat with other features
zack_hack_div_2 = 0
if cnn_rnn_zack:
zack_hack_div_2 = zack_hack // 2
cnn_output = tf.slice(cnn_output, [0, zack_hack_div_2, 0, 0], [-1, rnn_nunroll, -1, -1])
nfeats_conv = reduce(lambda x, y: x * y, [int(x) for x in cnn_output.get_shape()[-2:]])
else:
nfeats_conv = reduce(lambda x, y: x * y, [int(x) for x in cnn_output.get_shape()[-3:]])
feats_conv = tf.reshape(cnn_output, [batch_size * rnn_nunroll, nfeats_conv])
nfeats_tot = nfeats_conv + nfeats
feats_all = tf.concat(1, [feats_conv, feats_other])
print('feats_cnn: {}'.format(feats_conv.get_shape()))
print('feats_all: {}'.format(feats_all.get_shape()))
# Project to RNN size
rnn_output = feats_all
rnn_output_size = nfeats_tot
if do_rnn:
with tf.variable_scope('rnn_proj'):
rnn_proj_w = tf.get_variable('W', [nfeats_tot, rnn_size], initializer=tf.uniform_unit_scaling_initializer(factor=1.0, dtype=dtype), dtype=dtype)
rnn_proj_b = tf.get_variable('b', [rnn_size], initializer=tf.constant_initializer(0.0), dtype=dtype)
| tensorflow.concat | 3,004 |
import tensorflow as tf
tf.constant_initializer(0.0))
biased = tf.reshape(
tf.nn.bias_add(
conv, biases, data_format=self.data_format),
| tensorflow.nn.bias_add | 3,005 |
import tensorflow as tf
print(x_prob.get_shape(), y.get_shape(), tf.reduce_sum(x_prob * y, axis=-1).get_shape())
return -tf.reduce_sum(x_prob * y, axis=-1) # higher the better
| tensorflow.reduce_sum | 3,006 |
import tensorflow as tf
cutout_center_height = tf.random.uniform(
shape=[], minval=0, maxval=image_height,
dtype=tf.int32)
cutout_center_width = tf.random.uniform(
shape=[], minval=0, maxval=image_width,
dtype=tf.int32)
lower_pad = tf.maximum(0, cutout_center_height - length // 2)
upper_pad = tf.maximum(0, image_height - cutout_center_height - length // 2)
left_pad = tf.maximum(0, cutout_center_width - length // 2)
right_pad = tf.maximum(0, image_width - cutout_center_width - length // 2)
cutout_shape = [image_height - (lower_pad + upper_pad),
image_width - (left_pad + right_pad)]
padding_dims = [[lower_pad, upper_pad], [left_pad, right_pad]]
mask = tf.pad(
tf.zeros(cutout_shape, dtype=images.dtype),
| tensorflow.maximum | 3,007 |
import tensorflow as tf
l1 = tf.matmul(images, self.w1)+self.b1
l1=tf.nn.relu(l1)
l2 = tf.matmul(l1, self.w2)+self.b2
l2=tf.nn.relu(l2)
l3=tf.matmul(l2, self.w3)+self.b3
l3=tf.nn.relu(l3)
out=tf.matmul(l3, self.w4)+self.b4
return out
def valid_inference(self,images):
| tensorflow.nn.relu | 3,008 |
import tensorflow as tf
def __init__(
self,
inputs=None,
train_labels=None,
vocabulary_size=80000,
embedding_size=200,
num_sampled=64,
nce_loss_args=None,
E_init=tf.random_uniform_initializer(minval=-1.0, maxval=1.0),
E_init_args=None,
nce_W_init=tf.truncated_normal_initializer(stddev=0.03),
nce_W_init_args=None,
nce_b_init=tf.constant_initializer(value=0.0),
nce_b_init_args=None,
name='word2vec',
):
if nce_loss_args is None:
nce_loss_args = {}
if E_init_args is None:
E_init_args = {}
| tensorflow.truncated_normal_initializer | 3,009 |
import tensorflow as tf
def joint_mse_loss(y_pred, y_true, true_weight):
"""
损失函数想要表达的意思: 输出的特征图数量为关键点的数量,意味着输出的是每一个像素属于各个关键点的置信度
"""
batch_size = y_pred.shape[0]
num_of_joints = y_pred.shape[-1] # 有多少个关键点
y_pred = tf.reshape(y_pred, shape=(batch_size, -1, num_of_joints)) # 合并宽和高
heatmap_pred_list = tf.split(value=y_pred,
num_or_size_splits=num_of_joints,
axis=-1) # 拆分每一个关键点的特征图 [batch_size, -1, 1]
y_true = tf.reshape(y_true, shape=(batch_size, -1, num_of_joints))
heatmap_true_list = tf.split(value=y_true, # y_true执行与y_pred相同的操作
num_or_size_splits=num_of_joints,
| tensorflow.reshape | 3,010 |
import tensorflow as tf
high = constraint[key][1]
constraint_tf[key] = (tf.constant(low, dtype=tf.float64),
tf.constant(high, dtype=tf.float64))
print("N.B.: using direct data entry")
likelihood = sum_pdf(data, nsig, sigmean, sigwidth, nbkg, m0, argpar, constraint_tf['mes'][0], constraint_tf['mes'][1])
nll = tf.neg(tf.reduce_sum(tf.log(likelihood)), name="nll")
variables = tf.all_variables()
grads = tf.gradients(nll, variables)
| tensorflow.log | 3,011 |
from tensorflow.core.framework import function_pb2
Args:
graph: Graph.
inputs: List of tensors. Inputs to the function.
outputs: List of tensors. Outputs of the function.
out_names: Optional list of string names for the outputs.
Returns:
A FunctionDef protocol buffer.
Raises:
ValueError: if out_names is specified and the wrong length.
"""
func = function_pb2.FunctionDef()
func.signature.name = "_"
used_names = set()
func.signature.input_arg.extend([_tensor_to_argdef(i, used_names=used_names)
for i in inputs])
if out_names is None:
used_names = set()
func.signature.output_arg.extend([
_tensor_to_argdef(o, used_names=used_names) for o in outputs])
elif len(outputs) != len(out_names):
raise ValueError(
"Length of out_names (%d) does not match number of outputs (%d): %s" %
(len(out_names), len(outputs), ", ".join(out_names)))
| tensorflow.core.framework.function_pb2.FunctionDef | 3,012 |
import tensorflow as tf
function ensures each probability is at least eps and no more than one
before taking the log.
Args:
y: matrix of true probabilities same size as probs
probs: matrix of probabilities for the minibatch
eps: value to clip the probabilities at
class_weights: vector of relative weights to be assigned to each class
sumd: dimensions along which to sum the x-ent matrix
Returns:
cross entropy loss for each example in the minibatch
"""
adjusted_probs = tf.clip_by_value(probs, eps, 1.0 - eps)
xent_mat = -y * tf.log(adjusted_probs)
if class_weights is not None:
xent_mat *= class_weights
return tf.reduce_sum(xent_mat, sumd)
def _SafeNegEntropy(probs, batch_size, eps=0.0001):
"""Computes negative entropy in a way that will not overflow."""
adjusted_probs = tf.clip_by_value(probs, eps, 1.0 - eps)
entropy = tf.mul(probs, tf.log(adjusted_probs))
return tf.reduce_sum(entropy) / batch_size
| tensorflow.log | 3,013 |
import tensorflow as tf
key = tf.constant('image_000000')
class_label = tf.random_uniform(
| tensorflow.random_uniform | 3,014 |
import tensorflow as tf
bw_result = directional_attention_with_selections(
rep_tensor, rep_mask, dep_selection, head_selection,
'backward', hn, keep_unselected,
'backward_resa', keep_prob, is_train, wd, activation
)
return tf.concat([fw_result, bw_result], -1)
def directional_attention_with_selections(
rep_tensor, rep_mask, dep_selection, head_selection, direction=None, hn=None, keep_unselected=True,
scope=None, keep_prob=1., is_train=None, wd=0., activation='elu'):
bs, sl, vec = tf.shape(rep_tensor)[0], tf.shape(rep_tensor)[1], tf.shape(rep_tensor)[2]
org_ivec = rep_tensor.get_shape().as_list()[2]
ivec = hn or org_ivec
with tf.variable_scope(scope or 'directional_attention_%s' % direction or 'diag'):
# non-linear
rep_map = bn_dense_layer(rep_tensor, ivec, True, 0., 'bn_dense_map', activation,
False, wd, keep_prob, is_train)
# ensure the seletion is right
dep_selection = tf.logical_and(rep_mask, dep_selection)
head_selection = tf.logical_and(rep_mask, head_selection)
rep_dep_tensor, rep_dep_mask, dep_org_idx = reduce_data_rep_max_len(rep_map, dep_selection)
| tensorflow.shape | 3,015 |
import tensorflow as tf
assert var.name == var_name_n_prune_ratio[0], \
'unmatched variable names: %s vs. %s' % (var.name, var_name_n_prune_ratio[0])
prune_ratio = self.__calc_prune_ratio_dyn(var_name_n_prune_ratio[1])
# create a mask and non-masked backup for each variable
name = var.name.replace(':0', '_mask')
mask = tf.get_variable(name, initializer=tf.ones(var.shape), trainable=False)
name = var.name.replace(':0', '_var_bkup')
var_bkup = tf.get_variable(name, initializer=var.initialized_value(), trainable=False)
# create update operations
var_bkup_update_op = var_bkup.assign(tf.where(mask > 0.5, var, var_bkup))
with tf.control_dependencies([var_bkup_update_op]):
mask_thres = tf.contrib.distributions.percentile(tf.abs(var_bkup), prune_ratio * 100)
mask_update_op = mask.assign(tf.cast(tf.abs(var_bkup) > mask_thres, tf.float32))
with tf.control_dependencies([mask_update_op]):
prune_op = var.assign(var_bkup * mask)
# record pruning masks & operations
masks += [mask]
prune_ops += [prune_op]
return masks, tf.group(prune_ops)
| tensorflow.control_dependencies | 3,016 |
import tensorflow as tf
self.ri = tf.placeholder(tf.float32, (None,))
self.s_diff = tf.placeholder(tf.float32, (None, self.g_dim))
def build_perception(self):
self._obs = tf.expand_dims(self.obs, -1) # !
self._obs = tf.expand_dims(self._obs, -1) # !
conv1 = tf.layers.conv2d(inputs=self._obs,
filters=16,
| tensorflow.expand_dims | 3,017 |
from tensorflow.python.ops import math_ops
precision_sum = math_ops.reduce_sum(
relevant_precision_per_k, reduction_indices=(-1,), name='precision_sum')
# Divide by number of relevant items to get average precision. These are
# the "num_relevant_items" and "AveP" terms from the formula above.
num_relevant_items = math_ops.to_double(num_relevant(labels, k))
return math_ops.div(precision_sum, num_relevant_items, name=scope)
def streaming_sparse_average_precision_at_k(predictions,
labels,
k,
| tensorflow.python.ops.math_ops.div | 3,018 |
import tensorflow as tf
if average_across_batch:
cost /= tf.to_float(batch_size)
| tensorflow.to_float | 3,019 |
import tensorflow as tf
# Now we construct the copy model.
batch_size = 8
inp = [tf.placeholder(tf.int32, shape=[None]) for _ in range(8)]
out = [tf.placeholder(tf.int32, shape=[None]) for _ in range(8)]
weights = [tf.ones_like(inp[0], dtype=tf.float32) for _ in range(8)]
with tf.variable_scope("root"):
_, losses = SampleGRUSeq2Seq(inp, out, weights)
updates = []
params = tf.global_variables()
optimizer = tf.train.AdamOptimizer(0.03, epsilon=1e-5)
for i in range(len(buckets)):
full_grads = tf.gradients(losses[i], params)
grads, _ = tf.clip_by_global_norm(full_grads, 30.0)
update = optimizer.apply_gradients(zip(grads, params))
updates.append(update)
sess.run([tf.global_variables_initializer()])
steps = 6
for _ in range(steps):
bucket = random.choice(np.arange(len(buckets)))
| tensorflow.train.AdamOptimizer | 3,020 |
import tensorflow as tf
Returns:
Variable Tensor
"""
if use_xavier:
initializer = tf.contrib.layers.xavier_initializer()
var = _variable_on_cpu(name, shape, initializer)
else:
# initializer = tf.truncated_normal_initializer(stddev=stddev)
with tf.device('/cpu:0'):
var = tf.truncated_normal(shape, stddev=np.sqrt(2 / shape[-1]))
var = tf.round(var * tf.constant(1000, dtype=tf.float32)) / tf.constant(1000, dtype=tf.float32)
var = tf.Variable(var, name='weights')
if wd is not None:
weight_decay = tf.multiply(tf.nn.l2_loss(var), wd, name='weight_loss')
tf.add_to_collection('losses', weight_decay)
return var
def conv1d(inputs,
num_output_channels,
kernel_size,
scope,
stride=1,
padding='SAME',
use_xavier=True,
stddev=1e-3,
weight_decay=0.0,
activation_fn=tf.nn.relu,
| tensorflow.add_to_collection | 3,021 |
import tensorflow as tf
scores = tf.nn.softmax(scores) # [B, 1, T]
# Weighted sum
if mode == 'SUM':
output = tf.matmul(scores, facts) # [B, 1, H]
# output = tf.reshape(output, [-1, tf.shape(facts)[-1]])
else:
scores = tf.reshape(scores, [-1, tf.shape(facts)[1]])
output = facts * tf.expand_dims(scores, -1)
output = tf.reshape(output, tf.shape(facts))
if return_alphas:
return output, scores
return output
def self_attention(facts, ATTENTION_SIZE, mask, stag='null'):
if len(facts.get_shape().as_list()) == 2:
facts = tf.expand_dims(facts, 1)
| tensorflow.shape | 3,022 |
from tensorflow.python.framework import tensor_shape
def _UnsortedSegmentSumShape(op):
"""Shape function for UnsortedSegmentSum."""
data_shape = op.inputs[0].get_shape()
segment_ids_shape = op.inputs[1].get_shape()
mid = segment_ids_shape.ndims
if mid is None:
return [tensor_shape.unknown_shape()]
else:
num_segments = tensor_util.ConstantValue(op.inputs[2])
return [tensor_shape.TensorShape([num_segments]).concatenate(
data_shape[mid:])]
@ops.RegisterShape("LinSpace")
def _LinspaceShape(op):
num = tensor_util.ConstantValue(op.inputs[2])
return [tensor_shape.vector(num)]
| tensorflow.python.framework.tensor_shape.TensorShape | 3,023 |
import tensorflow as tf
'save_summary_steps', 500,
'The frequency with which summaries are saved, in seconds.')
tf.app.flags.DEFINE_integer(
'save_checkpoints_secs', 7200,
'The frequency with which the model is saved, in seconds.')
# model related configuration
tf.app.flags.DEFINE_integer(
'train_image_size', 352,
'The size of the input image for the model to use.')
tf.app.flags.DEFINE_integer(
'resnet_size', 50,
'The size of the ResNet model to use.')
tf.app.flags.DEFINE_integer(
'train_epochs', None,
'The number of epochs to use for training.')
tf.app.flags.DEFINE_integer(
'batch_size', 12,
'Batch size for training and evaluation.')
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 '
'with CPU. If left unspecified, the data format will be chosen '
'automatically based on whether TensorFlow was built for CPU or GPU.')
tf.app.flags.DEFINE_float(
'negative_ratio', 3., 'Negative ratio in the loss function.')
tf.app.flags.DEFINE_float(
'match_threshold', 0.56, 'Matching threshold in the loss function.')
tf.app.flags.DEFINE_float(
'neg_threshold', 0.4, 'Matching threshold for the negtive examples in the loss function.')
| tensorflow.app.flags.DEFINE_integer | 3,024 |
import tensorflow as tf
def __call__(self, global_step):
warmup_lr = self._params.warmup_learning_rate
warmup_steps = self._params.warmup_steps
init_lr = self._params.init_learning_rate
lr_levels = self._params.learning_rate_levels
lr_steps = self._params.learning_rate_steps
linear_warmup = (
warmup_lr + tf.cast(global_step, dtype=tf.float32) / warmup_steps *
(init_lr - warmup_lr))
learning_rate = tf.where(global_step < warmup_steps, linear_warmup, init_lr)
for next_learning_rate, start_step in zip(lr_levels, lr_steps):
learning_rate = tf.where(global_step >= start_step, next_learning_rate,
learning_rate)
return learning_rate
def get_config(self):
return {'_params': self._params.as_dict()}
| tensorflow.where | 3,025 |
import tensorflow as tf
return tf.data.Dataset.from_tensors((images, labels))
def train(defun=False):
model = mnist.create_model(data_format())
if defun:
model.call = tfe.defun(model.call)
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
dataset = random_dataset()
with tf.device(device()):
mnist_eager.train(model, optimizer, dataset,
step_counter=tf.train.get_or_create_global_step())
| tensorflow.train.GradientDescentOptimizer | 3,026 |
import tensorflow as tf
truthoutput_z_ = lrelu(linear(tgtimg_z, self.gf_dim*8*s_h16*s_w16, 'd_h0_lin'))
truthoutput_h0 = tf.reshape(truthoutput_z_, [-1, s_h16, s_w16, self.gf_dim * 8])
truthoutput_h1 = lrelu(deconv2d(tf.concat([truthoutput_h0, tgtctx_h3], 3),
[self.batch_size, s_h8, s_w8, self.gf_dim*4], name='d_h1'))
truthoutput_h2 = lrelu(deconv2d(tf.concat([truthoutput_h1, tgtctx_h2], 3),
[self.batch_size, s_h4, s_w4, self.gf_dim*2], name='d_h2'))
truthoutput_h3 = lrelu(deconv2d(tf.concat([truthoutput_h2, tgtctx_h1], 3),
[self.batch_size, s_h2, s_w2, self.gf_dim*1], name='d_h3'))
truthoutput_h4 = deconv2d(tf.concat([truthoutput_h3, tgtctx_h0], 3),
[self.batch_size, s_h, s_w, self.c_dim], name='d_h4')
self.simloss = tf.reduce_mean((trans_z - tgtimg_z) ** 2) * 1e3
mean, var = tf.nn.moments(tgtimg_z, axes=[0])
print(var.get_shape())
# self.simloss /= tf.reduce_mean(var)
print(tgtimg_z.get_shape())
self.out = output_h4# + contextimg#tf.nn.tanh(h4)
self.out2 = truthoutput_h4
self.recon1 = tf.nn.l2_loss(tgtimg - self.out)
self.recon2 = tf.nn.l2_loss(tgtimg - self.out2)
# self.loss = self.recon1 + self.recon2 + self.simloss
if ablation_type == "None":
self.loss = self.recon1 + self.recon2 + self.simloss
| tensorflow.reduce_mean | 3,027 |
import tensorflow as tf
with tf.Session():
coord = tf.train.Coordinator()
tf.train.start_queue_runners(coord=coord)
# Sleep to make sure the queue runner has started the first run call.
time.sleep(_SLEEP_TIME)
# Session closed.
coord.request_stop()
coord.join()
def test_batcher_closed(self):
with tf.Graph().as_default():
@dynamic_batching.batch_fn
def f(a):
return a
f(tf.constant([1]))
# Intentionally using tf.Session() instead of self.test_session() to have
# control over closing the session. test_session() is a cached session.
with tf.Session():
coord = tf.train.Coordinator()
| tensorflow.Graph | 3,028 |
import tensorflow as tf
in1 = tf.placeholder(tf_input_dtype, [
None,
] + tu.shape_to_tf_shape(input_shape), "TENSOR_INPUT1")
# If the input is a string, then convert each string to the
# equivalent float value.
if tf_input_dtype == tf.string:
in0 = tf.strings.to_number(in0, tf.int32)
in1 = tf.strings.to_number(in1, tf.int32)
add = tf.add(in0, in1, "ADD")
sub = tf.subtract(in0, in1, "SUB")
# Cast or convert result to the output dtype.
if tf_output0_dtype == tf.string:
cast0 = tf.dtypes.as_string(add if not swap else sub, name="TOSTR0")
| tensorflow.strings.to_number | 3,029 |
import tensorflow as tf
return h
def deconv2d(x, shape, output_shape, name, bias=False, stride=2, padding='SAME'):
with tf.variable_scope(name):
W = weight_variable(shape)
h = tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, stride, stride, 1], padding=padding)
if bias:
b = bias_variable([shape[-2]])
h = h + b
return h
def conv3d(x, shape, name, bias=False, stride=2, padding='SAME'):
with tf.variable_scope(name):
W = weight_variable(shape)
h = tf.nn.conv3d(x, W, strides=[1, stride, stride, stride, 1], padding=padding)
if bias:
b = bias_variable([shape[-1]])
h = h + b
return h
def deconv3d(x, shape, output_shape, name, bias=False, stride=2, padding='SAME'):
with tf.variable_scope(name):
W = weight_variable(shape)
h = tf.nn.conv3d_transpose(x, W, output_shape, strides=[1, stride, stride, stride, 1], padding=padding)
if bias:
b = bias_variable([shape[-2]])
h = h + b
return h
| tensorflow.nn.conv3d | 3,030 |
import tensorflow as tf
def build_cnet(self, state_in, name, reuse=False, batch_size=64):
reg = tf.contrib.layers.l2_regularizer(1e-3)
with tf.variable_scope(name, reuse=reuse):
layer_c1 = tf.layers.dense(state_in, 512, tf.nn.relu, kernel_regularizer=reg)
layer_c2 = tf.layers.dense(layer_c1, 256, tf.nn.relu, kernel_regularizer=reg)
lstm_c = tf.nn.rnn_cell.LSTMCell(num_units=256)
lstm_c = tf.nn.rnn_cell.DropoutWrapper(lstm_c, output_keep_prob=self.keep_prob)
state_init_c = lstm_c.zero_state(batch_size=batch_size, dtype=tf.float32)
lstm_cin = tf.expand_dims(layer_c2, axis=1)
out_c, state_final_c = tf.nn.dynamic_rnn(cell=lstm_c, inputs=lstm_cin, initial_state=state_init_c)
cell_out_c = tf.reshape(out_c, [-1, 256])
vf = tf.layers.dense(cell_out_c, 1, kernel_regularizer=reg)
| tensorflow.nn.rnn_cell.DropoutWrapper | 3,031 |
import tensorflow as tf
Clips bounding boxes to image boundaries based on image shape.
Args:
bboxes: Tensor with shape (num_bboxes, 4)
where point order is x1, y1, x2, y2.
imshape: Tensor with shape (2, )
where the first value is height and the next is width.
Returns
Tensor with same shape as bboxes but making sure that none
of the bboxes are outside the image.
"""
with tf.name_scope('BoundingBoxTransform/clip_bboxes'):
bboxes = tf.cast(bboxes, dtype=tf.float32)
imshape = tf.cast(imshape, dtype=tf.float32)
x1, y1, x2, y2 = tf.split(bboxes, 4, axis=1)
width = imshape[1]
height = imshape[0]
x1 = tf.maximum(tf.minimum(x1, width - 1.0), 0.0)
x2 = tf.maximum(tf.minimum(x2, width - 1.0), 0.0)
y1 = tf.maximum(tf.minimum(y1, height - 1.0), 0.0)
y2 = tf.maximum(tf.minimum(y2, height - 1.0), 0.0)
| tensorflow.name_scope | 3,032 |
import tensorflow as tf
indices_batch = np.random.randint(
batch_size, size=num_elements, dtype=np.int64)
indices_value = np.arange(num_elements, dtype=np.int64)
indices = np.asarray(
sorted(zip(indices_batch, indices_value)), dtype=np.int64)
values = ["feature_value_for_embedding_lookup"] * num_elements
shape = np.asarray([batch_size, num_elements], dtype=np.int64)
with tf.Session() as sess:
with tf.device("/cpu:0"):
indices = tf.Variable(indices)
values = tf.Variable(values)
shape = tf.Variable(shape)
st = tf.SparseTensor(indices, values, shape)
st_handles = add_many_sparse_to_tensors_map(st)
st_roundtrip = take_many_sparse_from_tensors_map(
sparse_map_op=st_handles.op, sparse_handles=st_handles)
st_roundtrip_op = st_roundtrip.values.op
| tensorflow.Variable | 3,033 |
import tensorflow as tf
# Weighted sum
if mode == 'SUM':
output = tf.matmul(scores, facts) # [B, 1, H]
# output = tf.reshape(output, [-1, tf.shape(facts)[-1]])
else:
scores = tf.reshape(scores, [-1, tf.shape(facts)[1]])
output = facts * tf.expand_dims(scores, -1)
output = tf.reshape(output, tf.shape(facts))
return output
def din_fcn_attention(query, facts, attention_size, mask, stag='null', mode='SUM', softmax_stag=1, time_major=False, return_alphas=False, forCnn=False):
| tensorflow.shape | 3,034 |
import tensorflow as tf
applied = self.apply_step(variables=variables, deltas=perturbation_deltas)
with tf.control_dependencies(control_inputs=(applied,)):
# Trivial operation to enforce control dependency
| tensorflow.control_dependencies | 3,035 |
import tensorflow as tf
initializer=embeddings_initializer,
dtype=LayersConfig.tf_dtype,
**(embeddings_kwargs or {})
# **embeddings_kwargs
) # **(embeddings_kwargs or {}),
word_embeddings = tf.nn.embedding_lookup(
self.embeddings,
self.inputs,
name='word_embeddings',
)
# Zero out embeddings of pad value
masks = tf.not_equal(self.inputs, pad_value, name='masks')
word_embeddings *= tf.cast(
tf.expand_dims(masks, axis=-1),
# tf.float32,
dtype=LayersConfig.tf_dtype,
)
sum_word_embeddings = tf.reduce_sum(word_embeddings, axis=1)
# Count number of non-padding words in each sentence
sentence_lengths = tf.count_nonzero(
masks,
axis=1,
keep_dims=True,
# dtype=tf.float32,
dtype=LayersConfig.tf_dtype,
name='sentence_lengths',
| tensorflow.expand_dims | 3,036 |
import tensorflow as tf
# define train_op
gen_optimizer = tf.train.RMSPropOptimizer(learning_rate=0.05)
dis_optimizer = tf.train.RMSPropOptimizer(learning_rate=0.05)
| tensorflow.train.RMSPropOptimizer | 3,037 |
import tensorflow as tf
outputs_dict3, _ = tf.nn.seq2seq.one2many_rnn_seq2seq(
enc_inp, dec_inp_dict2, cell, 2, dec_symbols_dict,
embedding_size=2, feed_previous=tf.constant(True))
sess.run([tf.global_variables_initializer()])
| tensorflow.constant | 3,038 |
import tensorflow as tf
if info:
summary = tf.Summary()
for k, v in info.items():
| tensorflow.Summary | 3,039 |
import tensorflow as tf
tf.logging.info("**** Trainable Variables ****")
| tensorflow.logging.info | 3,040 |
import tensorflow as tf
# placeholder for end of episode mask
# this value is 1 if the next state corresponds to the end of an episode,
# in which case there is no Q-value at the next state; at the end of an
# episode, only the current state reward contributes to the target, not the
# next state Q-value (i.e. target is just rew_t_ph, not rew_t_ph + gamma * q_tp1)
done_mask_ph = tf.placeholder(tf.float32, [None])
# casting to float on GPU ensures lower data transfer times.
obs_t_float = tf.cast(obs_t_ph, tf.float32) / 255.0
obs_tp1_float = tf.cast(obs_tp1_ph, tf.float32) / 255.0
# Here, you should fill in your own code to compute the Bellman error. This requires
# evaluating the current and next Q-values and constructing the corresponding error.
# TensorFlow will differentiate this error for you, you just need to pass it to the
# optimizer. See assignment text for details.
# Your code should produce one scalar-valued tensor: total_error
# This will be passed to the optimizer in the provided code below.
# Your code should also produce two collections of variables:
| tensorflow.cast | 3,041 |
import tensorflow as tf
@staticmethod
def lrelu(inputdata, name, alpha=0.2):
"""
:param inputdata:
:param alpha:
:param name:
:return:
"""
with tf.variable_scope(name):
return tf.nn.relu(inputdata) - alpha * tf.nn.relu(-inputdata)
| tensorflow.nn.relu | 3,042 |
import tensorflow as tf
tf.logging.info(message.format(config.logdir))
tf.gfile.MakeDirs(config.logdir)
| tensorflow.gfile.MakeDirs | 3,043 |
import tensorflow as tf
scale=config.init_mean_factor)
logstd_initializer = tf.random_normal_initializer(config.init_logstd, 1e-10)
flat_observations = tf.reshape(observations, [
tf.shape(observations)[0], tf.shape(observations)[1],
functools.reduce(operator.mul, observations.shape.as_list()[2:], 1)])
with tf.variable_scope("network_parameters"):
| tensorflow.shape | 3,044 |
import tensorflow as tf
if mode == 'train' and rnn_keep_prob < 1.0:
cell = tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob=rnn_keep_prob)
if rnn_nlayers > 1:
cell = tf.nn.rnn_cell.MultiRNNCell([cell] * rnn_nlayers)
initial_state = cell.zero_state(batch_size, dtype)
# RNN
| tensorflow.nn.rnn_cell.MultiRNNCell | 3,045 |
import tensorflow as tf
num_examples = len(features)
# This is for demo purposes and does NOT scale to large data sets. We do
# not use Dataset.from_generator() because that uses tf.py_func which is
# not TPU compatible. The right way to load data is with TFRecordReader.
d = tf.data.Dataset.from_tensor_slices({
"input_ids":
tf.constant(
all_input_ids, shape=[num_examples, seq_length],
dtype=tf.int32),
"input_mask":
tf.constant(
all_input_mask,
shape=[num_examples, seq_length],
dtype=tf.int32),
"segment_ids":
tf.constant(
all_segment_ids,
shape=[num_examples, seq_length],
dtype=tf.int32),
"label_ids":
tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32),
})
| tensorflow.constant | 3,046 |
import tensorflow as tf
w //= pool_stride
h //= pool_stride
# Conv 1x1
with tf.variable_scope('conv_0'):
X = self._do_conv(X, w, h, ch, conv_ch, filter_size=1, no_reg=True, is_train=is_train)
ch = conv_ch
# Global conv
with tf.variable_scope('conv_1'):
X = self._do_conv(X, w, h, ch, global_conv_ch, filter_size=w, no_reg=True, is_train=is_train)
ch = global_conv_ch
# Global pooling
X = self._add_global_avg_pool(X, w, h, ch)
# Fully connected
with tf.variable_scope('fully_connected'):
| tensorflow.variable_scope | 3,047 |
import tensorflow as tf
# random flip on a batch of images
def batch_random_flip(input_):
"""Simultaneous horizontal random flip."""
if isinstance(input_, (float, int)):
return input_
shape = input_.get_shape().as_list()
batch_size = shape[0]
height = shape[1]
width = shape[2]
channels = shape[3]
res = tf.split(axis=0, num_or_size_splits=batch_size, value=input_)
res = [elem[0, :, :, :] for elem in res]
res = [tf.image.random_flip_left_right(elem) for elem in res]
res = [tf.reshape(elem, [1, height, width, channels]) for elem in res]
res = tf.concat(axis=0, values=res)
return res
# build a one hot representation corresponding to the integer tensor
# the one-hot dimension is appended to the integer tensor shape
def as_one_hot(input_, n_indices):
"""Convert indices to one-hot."""
shape = input_.get_shape().as_list()
n_elem = numpy.prod(shape)
indices = tf.range(n_elem)
indices = tf.cast(indices, tf.int64)
| tensorflow.reshape | 3,048 |
import tensorflow as tf
A tensor.
"""
if alpha != 0.:
negative_part = tf.nn.relu(-x)
x = tf.nn.relu(x)
if max_value is not None:
max_value = _to_tensor(max_value, x.dtype.base_dtype)
zero = _to_tensor(0., x.dtype.base_dtype)
| tensorflow.nn.relu | 3,049 |
import tensorflow as tf
# Select only unused blocks
with tf.variable_scope('select'):
stacked_blocks = tf.stack(cell_inputs + blocks)
| tensorflow.variable_scope | 3,050 |
import tensorflow as tf
indicators &= (
anchor_match_mining_distance_matrix > anchor_positive_mining_distances)
def find_hard_distances(distance_matrix, indicator_matrix):
distance_matrix = tf.where(
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
hard_negative_mining_distances = find_hard_distances(
anchor_match_mining_distance_matrix, indicators)
| tensorflow.shape | 3,051 |
import tensorflow as tf
use_bias=True):
with tf.variable_scope(name) as scope:
if scale > 1:
X = self.t_conv(name + '_upsample', X, filter, scale, scale, (not norm) and use_bias, "VALID", stddev)
else:
X = self.t_conv(name + '_deconf', 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:
X = tf.layers.dropout(X, dropout, training=is_train)
| tensorflow.contrib.layers.instance_norm | 3,052 |
import tensorflow as tf
def test_generator_grad_norm_progress(self):
stable_stage_num_images = 2
transition_stage_num_images = 3
current_image_id_ph = tf.placeholder(tf.int32, [])
progress = networks.compute_progress(
current_image_id_ph,
stable_stage_num_images,
transition_stage_num_images,
num_blocks=3)
z = tf.random_normal([2, 10], dtype=tf.float32)
x, _ = networks.generator(
z, progress, _num_filters_stub,
networks.ResolutionSchedule(
start_resolutions=(4, 4), scale_base=2, num_resolutions=3))
fake_loss = tf.reduce_sum(tf.square(x))
grad_norms = [
_get_grad_norm(
fake_loss, tf.trainable_variables('.*/progressive_gan_block_1/.*')),
_get_grad_norm(
fake_loss, tf.trainable_variables('.*/progressive_gan_block_2/.*')),
_get_grad_norm(
fake_loss, tf.trainable_variables('.*/progressive_gan_block_3/.*'))
]
grad_norms_output = None
with self.test_session(use_gpu=True) as sess:
sess.run(tf.global_variables_initializer())
x1_np = sess.run(x, feed_dict={current_image_id_ph: 0.12})
x2_np = sess.run(x, feed_dict={current_image_id_ph: 1.8})
| tensorflow.square | 3,053 |
import tensorflow as tf
denom = tf.reduce_sum(weights * tf.matmul(
tf.reshape(hist_rater_a, [num_ratings, 1]), tf.reshape(hist_rater_b, [1, num_ratings])) /
| tensorflow.reshape | 3,054 |
import tensorflow as tf
feature_mat = tf.reshape(feature_mat, [-1, config.n_inputs]) # 9
# New feature_mat's shape: [time_steps*batch_size, n_inputs] # 128 * batch_size, 9
# Linear activation, reshaping inputs to the LSTM's number of hidden:
hidden = tf.nn.relu(tf.matmul(
feature_mat, config.W['hidden']
) + config.biases['hidden'])
# New feature_mat (hidden) shape: [time_steps*batch_size, n_hidden] [128*batch_size, 32]
print("--n_steps--")
print(config.n_steps)
print("--hidden--")
print(hidden)
# Split the series because the rnn cell needs time_steps features, each of shape:
hidden = tf.split(0, config.n_steps/4, hidden) # (0, 128, [128*batch_size, 32])
# New hidden's shape: a list of length "time_step" containing tensors of shape [batch_size, n_hidden]
# Define LSTM cell of first hidden layer:
lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(config.n_hidden, forget_bias=1.0)
# Stack two LSTM layers, both layers has the same shape
lsmt_layers = tf.nn.rnn_cell.MultiRNNCell([lstm_cell] * 2)
# Get LSTM outputs, the states are internal to the LSTM cells,they are not our attention here
outputs, _ = tf.nn.rnn(lsmt_layers, hidden, dtype=tf.float32)
# outputs' shape: a list of lenght "time_step" containing tensors of shape [batch_size, n_hidden]
print("------------------list-------------------")
print(outputs)
| tensorflow.split | 3,055 |
import tensorflow as tf
# match attn_dist[batch_size, passage_length] to sparse one-hot representation [batch_size, passage_length, extended_vsize]
batch_nums = tf.range(0, limit=batch_size) # shape (batch_size)
batch_nums = tf.expand_dims(batch_nums, axis=1) # shape (batch_size, 1)
batch_nums = tf.tile(batch_nums, [1, passage_length]) # shape (batch_size, passage_length)
step_nums = tf.range(0, limit=passage_length) # [passage_length]
step_nums = tf.expand_dims(step_nums, axis=0) # shape (1, passage_length)
step_nums = tf.tile(step_nums, [batch_size, 1]) # shape (batch_size, passage_length)
indices = tf.stack((batch_nums, step_nums, passage_word_idx), axis=2) # shape (batch_size, passage_length, 3)
indices = tf.reshape(indices, [-1, 3]) #[batch_size * passage_length, 3]
indices = tf.cast(indices, tf.int64)
shape = [batch_size, passage_length, extended_vsize]
| tensorflow.tile | 3,056 |
import tensorflow as tf
test_image_batch,test_label_batch=get_test_batch(test_image,test_label,testnum)
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
#init=tf.initialize_all_variables()
def train(train_num=64,test_num=32,lr=1e-4,loop_count=10000,report_step=100,save_step=1000,restore=False):
with tf.Session(config=config) as sess:
| tensorflow.argmax | 3,057 |
import tensorflow as tf
| tensorflow.math.reduce_sum | 3,058 |
import tensorflow as tf
bert_config = modeling.BertConfig.from_json_file(bert_config_file.name)
if FLAGS.max_seq_length > bert_config.max_position_embeddings:
raise ValueError(
"Cannot use sequence length %d because the BERT model "
"was only trained up to sequence length %d" %
(FLAGS.max_seq_length, bert_config.max_position_embeddings))
tf.gfile.MakeDirs(FLAGS.output_dir)
task_name = FLAGS.task_name.lower()
if task_name not in processors:
raise ValueError("Task not found: %s" % (task_name))
processor = processors[task_name]()
| tensorflow.gfile.MakeDirs | 3,059 |
import tensorflow as tf
decayed_learning_rate = (max_lr - learning_rate) *
(floor(global_step / step_size) - global_step / step_size) +
learning_rate
"""
with tf.name_scope(name):
learning_rate = tf.cast(learning_rate, dtype=tf.float32)
global_step = tf.cast(global_step, dtype=tf.float32)
step_size = tf.cast(step_size, dtype=tf.float32)
max_lr = tf.cast(max_lr, dtype=tf.float32)
| tensorflow.cast | 3,060 |
import tensorflow as tf
return tf.contrib.layers.batch_norm(inputs=x,
decay=0.95,
center=True,
scale=True,
is_training=(mode=='train'),
updates_collections=None,
scope=(name+'batch_norm'))
def build_model(self):
features = self.features
captions = self.captions
batch_size = tf.shape(features)[0]
captions_in = captions[:, :self.T]
captions_out = captions[:, 1:]
mask = tf.to_float(tf.not_equal(captions_out, self._null))
# batch normalize feature vectors
features = self._batch_norm(features, mode='train', name='conv_features')
c, h = self._get_initial_lstm(features=features)
x = self._word_embedding(inputs=captions_in)
features_proj = self._project_features(features=features)
loss = 0.0
alpha_list = []
lstm_cell = tf.contrib.rnn.BasicLSTMCell(num_units=self.H)
for t in range(self.T):
| tensorflow.not_equal | 3,061 |
import tensorflow as tf
def parse_function(example_proto):
features = {'member/name': tf.io.FixedLenFeature([], tf.string),
'member/encoded': tf.io.FixedLenFeature([], tf.string),
'member/age': tf.io.FixedLenFeature([], tf.int64),
'member/height': tf.io.VarLenFeature(tf.float32),
'member/prefer_prods': tf.io.VarLenFeature(tf.int64)}
features = tf.io.parse_single_example(example_proto, features)
images = tf.image.decode_png(features['member/encoded'], channels=3)
# 注意png原本有4個channel,但執行到下面的處理會出錯,所以前一行先降成3個channel。
images = tf.image.random_brightness(images, 0.1)
images = tf.image.random_saturation(images, 0.7, 1.3)
images = tf.image.random_contrast(images, 0.6, 1.5)
| tensorflow.io.VarLenFeature | 3,062 |
import tensorflow as tf
return None
for var in self.get_variables_in_scope():
# TODO: different summary types
tf.summary.scalar(var.name, tf.reduce_mean(var))
self._summary_added = True
| tensorflow.reduce_mean | 3,063 |
import tensorflow as tf
else: # pragma: no cover
raise ValueError("Bad dimension for q_sqrt: %s" %
str(q_sqrt.get_shape().ndims))
if full_cov:
fvar = fvar + tf.matmul(LTA, LTA, transpose_a=True) # R x N x N
else:
fvar = fvar + tf.reduce_sum(tf.square(LTA), 1) # R x N
| tensorflow.matmul | 3,064 |
import tensorflow as tf
tf.summary.scalar('Learning rate', m.lr)
latest_ckpt = tf.train.latest_checkpoint(FLAGS.save_path)
| tensorflow.train.latest_checkpoint | 3,065 |
import tensorflow as tf
grid = tf.expand_dims(tf.stack(grid, axis=-1), axis=2) # [gx, gy, 1, 2]
box_xy = (box_xy + tf.cast(grid, dtype)) * stride
box_wh = tf.exp(box_wh) * anchors
box_x1y1 = box_xy - box_wh / 2.
box_x2y2 = box_xy + box_wh / 2.
box = tf.concat([box_x1y1, box_x2y2], axis=-1)
boxes.append(tf.reshape(box, (x_shape[0], -1, 1, 4)))
objects.append(tf.reshape(obj, (x_shape[0], -1, 1)))
classes.append(tf.reshape(cls, (x_shape[0], -1, num_classes)))
boxes = tf.concat(boxes, axis=1)
objects = tf.concat(objects, axis=1)
classes = tf.concat(classes, axis=1)
scores = objects * classes
boxes, scores, classes, valid = tf.image.combined_non_max_suppression(
boxes=boxes,
scores=scores,
max_output_size_per_class=max_outputs,
max_total_size=max_outputs,
iou_threshold=iou_threshold,
score_threshold=score_threshold,
clip_boxes=False
)
| tensorflow.concat | 3,066 |
import tensorflow as tf
# For each of the timestamps its vector of size A from `tmp` is reduced with `v` vector
v_dot_tmp = tf.tensordot(tmp, v, axes=1, name='v_dot_tmp') # (B,T) shape
key_masks = mask # [B, 1, T]
# key_masks = tf.expand_dims(mask, 1) # [B, 1, T]
paddings = tf.ones_like(v_dot_tmp) * (-2 ** 32 + 1)
v_dot_tmp = tf.where(key_masks, v_dot_tmp, paddings) # [B, 1, T]
alphas = tf.nn.softmax(v_dot_tmp, name='alphas') # (B,T) shape
# Output of (Bi-)RNN is reduced with attention vector; the result has (B,D) shape
#output = tf.reduce_sum(facts * tf.expand_dims(alphas, -1), 1)
output = facts * tf.expand_dims(alphas, -1)
output = tf.reshape(output, tf.shape(facts))
# output = output / (facts.get_shape().as_list()[-1] ** 0.5)
if not return_alphas:
return output
else:
return output, alphas
def din_fcn_attention(query, facts, attention_size, mask, stag='null', mode='SUM', softmax_stag=1, time_major=False, return_alphas=False, forCnn=False):
if isinstance(facts, tuple):
# In case of Bi-RNN, concatenate the forward and the backward RNN outputs.
facts = tf.concat(facts, 2)
| tensorflow.shape | 3,067 |
import tensorflow as tf
with tf.device(self.raw_devices[device_num]):
if not use_synthetic_gpu_images:
gpu_compute_stage = data_flow_ops.StagingArea(
[tf.float32, tf.int32],
shapes=[images_shape, labels_shape]
)
# The CPU-to-GPU copy is triggered here.
gpu_compute_stage_op = gpu_compute_stage.put(
[host_images, host_labels])
images, labels = gpu_compute_stage.get()
images = tf.reshape(images, shape=images_shape)
gpu_compute_stage_ops.append(gpu_compute_stage_op)
else:
# Minor hack to avoid H2D copy when using synthetic data
images = tf.truncated_normal(
host_images.get_shape(),
dtype=input_data_type,
stddev=1e-1,
name='synthetic_images')
images = tf.contrib.framework.local_variable(
| tensorflow.reshape | 3,068 |
from tensorflow.python.ops import math_ops
with ops.name_scope(name, 'true_positives', (predictions_idx, labels)):
labels, predictions_idx = _maybe_select_class_id(
labels, predictions_idx, class_id)
tp = set_ops.set_size(set_ops.set_intersection(predictions_idx, labels))
tp = math_ops.to_double(tp)
if weights is not None:
weights = math_ops.to_double(weights)
tp = math_ops.mul(tp, weights)
| tensorflow.python.ops.math_ops.to_double | 3,069 |
from tensorflow.python.ops import math_ops
math_ops.abs(sensitivities - sensitivity), min_val)
indices_at_minval = math_ops.to_int64(indices_at_minval)
indices_at_minval = math_ops.cumsum(indices_at_minval)
tf_index = math_ops.argmax(indices_at_minval, 0)
tf_index = math_ops.cast(tf_index, dtypes.int32)
# Now, we have the implicit threshold, so compute the specificity:
return math_ops.div(tn[tf_index],
tn[tf_index] + fp[tf_index] + kepsilon,
name)
specificity = compute_specificity_at_sensitivity('value')
with ops.control_dependencies(
[tp_update_op, fn_update_op, tn_update_op, fp_update_op]):
| tensorflow.python.ops.math_ops.div | 3,070 |
import tensorflow as tf
# Restore the saved values in the parameter nodes.
save.restore(sess, save_path)
# Check that the parameter nodes have been restored.
self.assertEqual(10.0, v0.eval())
self.assertEqual(20.0, v1.eval())
# Build another graph with 2 nodes, initialized
# differently, and a Restore node for them.
with self.test_session() as sess:
v0_2 = tf.Variable(1000.0, name="v0")
v1_2 = tf.Variable(2000.0, name="v1")
save2 = tf.train.Saver({"v0": v0_2, "v1": v1_2})
tf.initialize_all_variables().run()
# Check that the parameter nodes have been initialized.
self.assertEqual(1000.0, v0_2.eval())
self.assertEqual(2000.0, v1_2.eval())
# Restore the values saved earlier in the parameter nodes.
save2.restore(sess, save_path)
# Check that the parameter nodes have been restored.
self.assertEqual(10.0, v0_2.eval())
self.assertEqual(20.0, v1_2.eval())
def testInt64(self):
save_path = os.path.join(self.get_temp_dir(), "int64")
| tensorflow.initialize_all_variables | 3,071 |
import tensorflow as tf
self.loss = tf.squared_difference(self.value_estimate, self.target)
self.optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
self.train_op = self.optimizer.minimize(
self.loss, global_step=tf.contrib.framework.get_global_step())
def predict(self, state, sess=None):
sess = sess or tf.get_default_session()
state=featurize_state(state);
return sess.run(self.value_estimate, { self.state: [state] })[0][0]
def update(self, state, target, sess=None):
sess = sess or tf.get_default_session()
| tensorflow.get_default_session | 3,072 |
import tensorflow as tf
# Start by setting a seed for repeatability
tf.set_random_seed(hparams.tacotron_random_seed)
| tensorflow.set_random_seed | 3,073 |
import tensorflow as tf
else:
return tf.nn.batch_normalization(inp, moving_mean, moving_variance, offset, scale, 0.01, name='norm')
| tensorflow.nn.batch_normalization | 3,074 |
import tensorflow as tf
def _double_factorial_loop_body(n, result, two):
result = tf.where(tf.greater_equal(n, two), result * n, result)
return n - two, result, two
| tensorflow.greater_equal | 3,075 |
import tensorflow as tf
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_length], tf.int64),
"segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
| tensorflow.FixedLenFeature | 3,076 |
import tensorflow as tf
initializer=tf.constant_initializer(0),
trainable=False)
label = tf.reshape(label, [-1])
centers_batch = tf.gather(centers, label)
diff = (1 - alpha) * (centers_batch - features)
centers = tf.scatter_sub(centers, label, diff)
| tensorflow.gather | 3,077 |
import tensorflow as tf
def summarize_features(features, num_shards=1):
with tf.name_scope("input_stats"):
for (k, v) in six.iteritems(features):
if isinstance(v, tf.Tensor) and v.get_shape().ndims > 1:
tf.summary.scalar("%s_batch" % k, tf.shape(v)[0] // num_shards)
tf.summary.scalar("%s_length" % k, tf.shape(v)[1])
nonpadding = tf.to_float(tf.not_equal(v, 0))
nonpadding_tokens = tf.reduce_sum(nonpadding)
tf.summary.scalar("%s_nonpadding_tokens" % k, nonpadding_tokens)
tf.summary.scalar("%s_nonpadding_fraction" % k,
tf.reduce_mean(nonpadding))
_already_logged = set()
| tensorflow.reduce_sum | 3,078 |
import tensorflow as tf
# Decrease keep prob deeper into network
keep_prob = 1 - layers_ratio * (1 - drop_path_keep_prob)
# Decrease keep prob with increasing steps
steps_per_epoch = math.ceil(N / batch_size)
steps_ratio = tf.minimum(((step + 1) / steps_per_epoch) / drop_path_decay_epochs, 1)
keep_prob = 1 - steps_ratio * (1 - keep_prob)
keep_prob = tf.cast(keep_prob, tf.float32)
# Monitor last layer's keep prob
| tensorflow.minimum | 3,079 |
import tensorflow as tf
def instance_norm(x,name='instance_norm'):
with tf.variable_scope(name):
if reuse:
tf.get_variable_scope().reuse_variables()
else:
assert tf.get_variable_scope().reuse is False
epsilon = 1e-5
mean, var = tf.nn.moments(x, [1, 2], keep_dims=True)
scale = tf.get_variable('scale',[x.get_shape()[-1]],
initializer=tf.truncated_normal_initializer(mean=1.0, stddev=0.02))
offset = tf.get_variable('offset',[x.get_shape()[-1]],initializer=tf.constant_initializer(0.0))
out = scale*tf.div(x-mean, tf.sqrt(var+epsilon)) + offset
return out
def common_conv2d(layer_input,filters,f_size=4,stride=2,padding='SAME',norm=True,name='common_conv2d'):
"""Layers used during downsampling"""
| tensorflow.nn.moments | 3,080 |
import tensorflow as tf
# If TPU is not available, this will fall back to normal Estimator on CPU
# or GPU.
estimator = tf.contrib.tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=model_fn,
config=run_config,
train_batch_size=FLAGS.train_batch_size,
eval_batch_size=FLAGS.eval_batch_size,
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)
if FLAGS.do_eval:
eval_examples = processor.get_dev_examples(FLAGS.data_dir)
eval_file = os.path.join(FLAGS.output_dir, "eval.tf_record")
| tensorflow.logging.info | 3,081 |
import tensorflow as tf
image_width - (left_pad + right_pad)]
padding_dims = [[lower_pad, upper_pad], [left_pad, right_pad]]
mask = tf.pad(
tf.zeros(cutout_shape, dtype=images.dtype),
padding_dims, constant_values=1)
patch = tf.ones_like(images, dtype=images.dtype) * replace,
mask = tf.expand_dims(mask, -1)
mask = tf.tile(mask, [1, 1, num_channels])
images = tf.where(
tf.equal(mask, 0),
patch,
images)
images = tf.squeeze(images, axis=0)
return {'image': images, 'label': labels}
| tensorflow.equal | 3,082 |
import tensorflow as tf
F = -lambda_1*U*U_x + lambda_2*U_xx
U0 = U - self.dt*tf.matmul(F, self.IRK_alpha.T)
| tensorflow.matmul | 3,083 |
from tensorflow.python.ops import variable_scope
value: A tensor representing the concatenated values.
update_op: An operation that concatenates the next values.
Raises:
ValueError: if `values` does not have a statically known rank, `axis` is
not in the valid range or the size of `values` is not statically known
along any axis other than `axis`.
"""
with variable_scope.variable_scope(name, 'streaming_concat', [values]):
# pylint: disable=invalid-slice-index
values_shape = values.get_shape()
if values_shape.dims is None:
raise ValueError('`values` must have known statically known rank')
ndim = len(values_shape)
if axis < 0:
| tensorflow.python.ops.variable_scope.variable_scope | 3,084 |
import tensorflow as tf
lm_embeddings["lstm_outputs1"],
lm_embeddings["lstm_outputs2"]], -1) # [num_sentences, max_sentence_length, 1024, 3]
lm_emb_size = util.shape(lm_emb, 2)
lm_num_layers = util.shape(lm_emb, 3)
with tf.variable_scope("lm_aggregation"):
self.lm_weights = tf.nn.softmax(tf.get_variable("lm_scores", [lm_num_layers], initializer=tf.constant_initializer(0.0)))
self.lm_scaling = tf.get_variable("lm_scaling", [], initializer=tf.constant_initializer(1.0))
flattened_lm_emb = tf.reshape(lm_emb, [num_sentences * max_sentence_length * lm_emb_size, lm_num_layers])
flattened_aggregated_lm_emb = tf.matmul(flattened_lm_emb, tf.expand_dims(self.lm_weights, 1)) # [num_sentences * max_sentence_length * emb, 1]
aggregated_lm_emb = tf.reshape(flattened_aggregated_lm_emb, [num_sentences, max_sentence_length, lm_emb_size])
aggregated_lm_emb *= self.lm_scaling
context_emb_list.append(aggregated_lm_emb)
| tensorflow.constant_initializer | 3,085 |
import tensorflow as tf
h2 = Dense(units=RNN_SIZE)(h1)
self.h3 = tf.nn.relu(h2+concat)
| tensorflow.nn.relu | 3,086 |
import tensorflow as tf
import tensorflow as tf
from garage.experiment import deterministic
from tests.fixtures.logger import NullOutput
class TfTestCase:
def setup_method(self):
self.sess = tf.compat.v1.Session()
self.sess.__enter__()
def teardown_method(self):
self.sess.__exit__(None, None, None)
self.sess.close()
del self.sess
gc.collect()
| tensorflow.compat.v1.Session | 3,087 |
import tensorflow as tf
concat = tf.concat([inp, targets], axis=0)
mask = tf.concat([tf.zeros_like(inp), tf.ones_like(targets)], axis=0)
| tensorflow.zeros_like | 3,088 |
from tensorflow.contrib.learn.python.learn.estimators import estimator_test_utils
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'],
extras={k: v
for k, v in metrics.items() if k in _METRIC_KEYS})
def benchmarkMatrixData(self):
iris = test_data.prepare_iris_data_for_logistic_regression()
cont_feature = feature_column.real_valued_column('feature', dimension=4)
bucketized_feature = feature_column.bucketized_column(
cont_feature, test_data.get_quantile_based_buckets(iris.data, 10))
classifier = dnn_linear_combined.DNNLinearCombinedClassifier(
model_dir=tempfile.mkdtemp(),
linear_feature_columns=(bucketized_feature,),
| tensorflow.contrib.learn.python.learn.estimators.estimator_test_utils.assert_in_range | 3,089 |
import tensorflow as tf
# later on. These do NOT count towards the metric (all tf.metrics
# support a per-instance weight, and these get a weight of 0.0).
while len(eval_examples) % FLAGS.eval_batch_size != 0:
eval_examples.append(classifier_utils.PaddingInputExample())
cached_dir = FLAGS.cached_dir
if not cached_dir:
cached_dir = FLAGS.output_dir
eval_file = os.path.join(cached_dir, task_name + "_eval.tf_record")
if not tf.gfile.Exists(eval_file):
classifier_utils.file_based_convert_examples_to_features(
eval_examples, label_list, FLAGS.max_seq_length, tokenizer,
eval_file, task_name)
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)
| tensorflow.logging.info | 3,090 |
import tensorflow as tf
bench.print_info()
bench.run()
if __name__ == '__main__':
tf.app.run()
| tensorflow.app.run | 3,091 |
import tensorflow as tf
self.c = tf.placeholder(tf.int32, [None, config.test_para_limit],"context")
self.q = tf.placeholder(tf.int32, [None, config.test_ques_limit],"question")
self.ch = tf.placeholder(tf.int32, [None, config.test_para_limit, config.char_limit],"context_char")
self.qh = tf.placeholder(tf.int32, [None, config.test_ques_limit, config.char_limit],"question_char")
| tensorflow.placeholder | 3,092 |
import tensorflow as tf
return
tf_input_dtype = np_to_tf_dtype(input_dtype)
tf_output0_dtype = np_to_tf_dtype(output0_dtype)
tf_output1_dtype = np_to_tf_dtype(output1_dtype)
# Create the model. If non-batching then don't include the batch
# dimension.
tf.reset_default_graph()
if max_batch == 0:
in0 = tf.placeholder(tf_input_dtype, tu.shape_to_tf_shape(input_shape),
"TENSOR_INPUT0")
in1 = tf.placeholder(tf_input_dtype, tu.shape_to_tf_shape(input_shape),
"TENSOR_INPUT1")
else:
in0 = tf.placeholder(tf_input_dtype, [
| tensorflow.reset_default_graph | 3,093 |
import tensorflow as tf
s1 = softmax_mask(tf.squeeze(s, [2]), mask)#[N,PL]
a = tf.expand_dims(tf.nn.softmax(s1), axis=2)#[N,PL,1]
| tensorflow.nn.softmax | 3,094 |
import tensorflow as tf
layer1 = tf.nn.sigmoid(layer0)
layer2 = tf.matmul(layer1, w1) + b1
predictions = layer2
loss = tf.reduce_mean(tf.losses.sparse_softmax_cross_entropy(logits=predictions, labels=y))
grads = tf.gradients(ys=loss, xs=params)
return predictions, loss, grads
def build_training_model(self, x, y):
"""
| tensorflow.gradients | 3,095 |
import tensorflow as tf
with tf.variable_scope('l1'):
n_l1 = 700
# combine the action and states together in this way
w1_s = tf.get_variable('w1_s', [self.s_dim, n_l1], initializer=init_w, trainable=trainable)
w1_a = tf.get_variable('w1_a', [self.a_dim, n_l1], initializer=init_w, trainable=trainable)
b1 = tf.get_variable('b1', [1, n_l1], initializer=init_b, trainable=trainable)
net = tf.nn.relu(tf.matmul(s, w1_s) + tf.matmul(a, w1_a) + b1)
with tf.variable_scope('l2'):
net = tf.layers.dense(net, 20, activation=tf.nn.relu, kernel_initializer=init_w,
bias_initializer=init_b, name='l2', trainable=trainable)
with tf.variable_scope('q'):
q = tf.layers.dense(net, 1, kernel_initializer=init_w, bias_initializer=init_b, trainable=trainable) # Q(s,a)
return q
def learn(self, s, a, r, s_, ISW):
| tensorflow.variable_scope | 3,096 |
import tensorflow as tf
# If TPU is not available, this will fall back to normal Estimator on CPU
# or GPU.
estimator = tf.estimator.Estimator(
model_fn=model_fn,
config=run_config)
if FLAGS.do_train:
tf.logging.info("***** Running training *****")
tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
train_input_fn = input_fn_builder(
input_files=input_files,
max_seq_length=FLAGS.max_seq_length,
max_predictions_per_seq=FLAGS.max_predictions_per_seq,
is_training=True,
| tensorflow.logging.info | 3,097 |
import tensorflow as tf
n_token=xlnet_config.n_token,
d_model=xlnet_config.d_model,
initializer=initializer,
lookup_table=lookup_table,
tie_weight=True,
bi_data=run_config.bi_data,
use_tpu=run_config.use_tpu)
#### Quantity to monitor
monitor_dict = {}
if FLAGS.use_bfloat16:
tgt_mask = tf.cast(tgt_mask, tf.float32)
lm_loss = tf.cast(lm_loss, tf.float32)
total_loss = tf.reduce_sum(lm_loss * tgt_mask) / tf.reduce_sum(tgt_mask)
monitor_dict["total_loss"] = total_loss
return total_loss, new_mems, monitor_dict
def get_loss(FLAGS, features, labels, mems, is_training):
"""Pretraining loss with two-stream attention Transformer-XL."""
if FLAGS.use_bfloat16:
with tf.tpu.bfloat16_scope():
return two_stream_loss(FLAGS, features, labels, mems, is_training)
else:
return two_stream_loss(FLAGS, features, labels, mems, is_training)
| tensorflow.reduce_sum | 3,098 |
import tensorflow as tf
inc.eval()
save.save(sess, filepath, global_step=1)
inc.eval()
save.save(sess, filepath, global_step=2)
with self.test_session() as sess:
# Build a new graph with different initialization.
v0 = tf.Variable(-1.0)
# Create a new saver.
save = tf.train.Saver({"v0": v0})
tf.initialize_all_variables().run()
# Get the most recent checkpoint name from the training history file.
name = tf.train.latest_checkpoint(traindir)
self.assertIsNotNone(name)
# Restore "v0" from that checkpoint.
save.restore(sess, name)
self.assertEqual(v0.eval(), 2.0)
| tensorflow.train.Saver | 3,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.