seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
import tensorflow as tf
logits += adder
else:
adder = 0.0
attention_probs = tf.nn.softmax(logits, name="attention_probs")
attention_probs = dropout(attention_probs, dropout_rate)
return tf.matmul(attention_probs, v)
|
tensorflow.nn.softmax
| 9,800 |
import tensorflow as tf
# which has `inputs` and `targets`.
if text_preprocess_fns is not None:
for text_preprocess_fn in text_preprocess_fns:
dataset = text_preprocess_fn(dataset, training)
# Print debugging examples if needed before tokenization.
if debug_print_examples:
def print_examples(x):
if np.random.uniform() < debug_print_examples_rate:
tf.print(x, output_stream=logging.info)
return x
dataset = dataset.map(print_examples)
# Vocabulary for tokenization.
extra_ids = 0
vocab = t5_data().SentencePieceVocabulary(
sentencepiece_model_file=spm_path or t5_data().DEFAULT_SPM_PATH,
extra_ids=extra_ids)
|
tensorflow.print
| 9,801 |
import tensorflow as tf
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
|
tensorflow.sqrt
| 9,802 |
from tensorflow.python.framework import ops
Raises:
TypeError: If `x` cannot be cast to the `bfloat16`.
"""
return cast(x, types.bfloat16, name=name)
ops.Tensor._override_operator("__neg__", neg)
ops.Tensor._override_operator("__abs__", abs)
# __invert__ corresponds to the ~ operator. Here we follow the numpy convention
# ~ marks an elementwise bit-wise inverse. This is only implemented for boolean
# tensors and will throw a TypeError if used on nonboolean arrays
ops.Tensor._override_operator("__invert__", logical_not)
def _OverrideBinaryOperatorHelper(func, op_name):
"""Register operators with different tensor and scalar versions.
Args:
func: the operator
op_name: name of the operator being overridden
"""
def binary_op_wrapper(x, y):
|
tensorflow.python.framework.ops.Tensor._override_operator
| 9,803 |
import tensorflow as tf
features["label_ids"] = create_int_feature([feature.label_id])
features["is_real_example"] = create_int_feature(
[int(feature.is_real_example)])
tf_example = tf.train.Example(features=tf.train.Features(feature=features))
writer.write(tf_example.SerializeToString())
writer.close()
def file_based_input_fn_builder(input_file, seq_length, is_training,
drop_remainder):
"""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),
"label_ids": tf.FixedLenFeature([], tf.int64),
"is_real_example": tf.FixedLenFeature([], tf.int64),
}
def _decode_record(record, name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
|
tensorflow.FixedLenFeature
| 9,804 |
import tensorflow as tf
masked_lm_example_loss = tf.reshape(masked_lm_example_loss, [-1])
masked_lm_ids = tf.reshape(masked_lm_ids, [-1])
masked_lm_weights = tf.reshape(masked_lm_weights, [-1])
masked_lm_accuracy = tf.metrics.accuracy(
labels=masked_lm_ids,
predictions=masked_lm_predictions,
weights=masked_lm_weights)
masked_lm_mean_loss = tf.metrics.mean(
values=masked_lm_example_loss, weights=masked_lm_weights)
next_sentence_log_probs = tf.reshape(
next_sentence_log_probs, [-1, next_sentence_log_probs.shape[-1]])
next_sentence_predictions = tf.argmax(
next_sentence_log_probs, axis=-1, output_type=tf.int32)
next_sentence_labels = tf.reshape(next_sentence_labels, [-1])
next_sentence_accuracy = tf.metrics.accuracy(
labels=next_sentence_labels, predictions=next_sentence_predictions)
next_sentence_mean_loss = tf.metrics.mean(
values=next_sentence_example_loss)
return {
"masked_lm_accuracy": masked_lm_accuracy,
"masked_lm_loss": masked_lm_mean_loss,
"next_sentence_accuracy": next_sentence_accuracy,
"next_sentence_loss": next_sentence_mean_loss,
}
eval_metrics = (metric_fn, [
masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids,
masked_lm_weights, next_sentence_example_loss,
|
tensorflow.metrics.accuracy
| 9,805 |
import tensorflow as tf
# sample mixture indicator from softmax
sel = tf.one_hot(tf.argmax(logit_probs - tf.log(-tf.log(tf.random_uniform(
tf.shape(logit_probs), minval=1e-5, maxval=1. - 1e-5))), 3), depth=nr_mix, dtype=tf.float32)
sel = tf.reshape(sel, xs[:-1] + [1, nr_mix])
# select logistic parameters
means = tf.reduce_sum(l[:, :, :, :, :nr_mix] * sel, 4)
log_scales = tf.maximum(tf.reduce_sum(
l[:, :, :, :, nr_mix:2 * nr_mix] * sel, 4), -7.)
coeffs = tf.reduce_sum(tf.nn.tanh(
l[:, :, :, :, 2 * nr_mix:3 * nr_mix]) * sel, 4)
# sample from logistic & clip to interval
# we don't actually round to the nearest 8bit value when sampling
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))
x0 = tf.minimum(tf.maximum(x[:, :, :, 0], -1.), 1.)
x1 = tf.minimum(tf.maximum(
x[:, :, :, 1] + coeffs[:, :, :, 0] * x0, -1.), 1.)
x2 = tf.minimum(tf.maximum(
x[:, :, :, 2] + coeffs[:, :, :, 1] * x0 + coeffs[:, :, :, 2] * x1, -1.), 1.)
return tf.concat([tf.reshape(x0, xs[:-1] + [1]), tf.reshape(x1, xs[:-1] + [1]), tf.reshape(x2, xs[:-1] + [1])], 3)
|
tensorflow.exp
| 9,806 |
import tensorflow as tf
'centers', [num_classes, num_features],
dtype=tf.float32,
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)
loss = tf.nn.l2_loss(features - centers_batch)
return loss, centers
def correlation_loss(source_samples, target_samples, weight, name='corr_loss'):
"""Adds a similarity loss term, the correlation between two representations.
|
tensorflow.scatter_sub
| 9,807 |
import tensorflow as tf
parsed_tensors[k], default_value='')
else:
parsed_tensors[k] = tf.sparse.to_dense(
parsed_tensors[k], default_value=0)
image = self._decode_image(parsed_tensors)
boxes = self._decode_boxes(parsed_tensors)
areas = self._decode_areas(parsed_tensors)
is_crowds = tf.cond(
tf.greater(tf.shape(parsed_tensors['image/object/is_crowd'])[0], 0),
lambda: tf.cast(parsed_tensors['image/object/is_crowd'], dtype=tf.bool),
lambda: tf.zeros_like(parsed_tensors['image/object/class/label'], dtype=tf.bool)) # pylint: disable=line-too-long
if self._include_mask:
masks = self._decode_masks(parsed_tensors)
decoded_tensors = {
'image': image,
'source_id': parsed_tensors['image/source_id'],
'height': parsed_tensors['image/height'],
'width': parsed_tensors['image/width'],
'groundtruth_classes': parsed_tensors['image/object/class/label'],
'groundtruth_is_crowd': is_crowds,
|
tensorflow.zeros_like
| 9,808 |
from tensorflow.python.framework import ops
math_ops.mul(math_ops.sqrt(var_predictions), math_ops.sqrt(var_labels)),
'pearson_r')
with ops.control_dependencies(
[update_cov, update_var_predictions, update_var_labels]):
update_op = _safe_div(update_cov, math_ops.mul(
math_ops.sqrt(update_var_predictions),
math_ops.sqrt(update_var_labels)), 'update_op')
if metrics_collections:
ops.add_to_collections(metrics_collections, pearson_r)
if updates_collections:
ops.add_to_collections(updates_collections, update_op)
return pearson_r, update_op
# TODO(nsilberman): add a 'normalized' flag so that the user can request
|
tensorflow.python.framework.ops.add_to_collections
| 9,809 |
import tensorflow as tf
top_antecedent_scores = tf.concat([dummy_scores, top_antecedent_scores], 1) # [k, c + 1]
top_antecedent_cluster_ids = tf.gather(top_span_cluster_ids, top_antecedents) # [k, c]
top_antecedent_cluster_ids += tf.to_int32(tf.log(tf.to_float(top_antecedents_mask))) # [k, c]
same_cluster_indicator = tf.equal(top_antecedent_cluster_ids, tf.expand_dims(top_span_cluster_ids, 1)) # [k, c]
non_dummy_indicator = tf.expand_dims(top_span_cluster_ids > 0, 1) # [k, 1]
pairwise_labels = tf.logical_and(same_cluster_indicator, non_dummy_indicator) # [k, c]
dummy_labels = tf.logical_not(tf.reduce_any(pairwise_labels, 1, keepdims=True)) # [k, 1]
top_antecedent_labels = tf.concat([dummy_labels, pairwise_labels], 1) # [k, c + 1]
loss = self.softmax_loss(top_antecedent_scores, top_antecedent_labels) # [k]
loss = tf.reduce_sum(loss) # []
|
tensorflow.expand_dims
| 9,810 |
import tensorflow as tf
return objectives, cstr_pct
def contra_step_lossV1(pred, tgt, temp=10.0):
# Step-wise contrastive loss
pred1, pred2 = tf.split(pred, 2, axis=0)
tgt1, tgt2 = tf.split(tgt, 2, axis=0)
soft_sign = tf.tanh((tgt1 - tgt2) * temp)
loss = tf.maximum(0.0, soft_sign * ((tgt1 - tgt2) - (pred1 - pred2)))
loss = tf.reduce_mean(loss)
return loss
def contra_step_lossV2(pred, tgt):
# Step-wise contrastive loss
pred1, pred2 = tf.split(pred, 2, axis=0)
|
tensorflow.maximum
| 9,811 |
import tensorflow as tf
loss = tf.maximum(0., margin-pred_posi_dif)
cstr_pct = tf.math.count_nonzero(loss, dtype=tf.float32) / tf.cast(tf.reduce_prod(tf.shape(loss)), tf.float32)
final_loss = tf.reduce_mean(loss)
|
tensorflow.shape
| 9,812 |
from tensorflow.python.framework import ops
for i, dim in enumerate(input_shape.dims):
if i in reduction_indices:
returned_dims.append(1)
else:
returned_dims.append(dim)
else:
for i, dim in enumerate(input_shape.dims):
if i not in reduction_indices:
returned_dims.append(dim)
return [tensor_shape.TensorShape(returned_dims)]
@ops.RegisterShape("SegmentMax")
@ops.RegisterShape("SegmentMean")
@ops.RegisterShape("SegmentMin")
@ops.RegisterShape("SegmentProd")
@ops.RegisterShape("SegmentSum")
def _SegmentReductionShape(op):
"""Common shape function for segment reduction ops."""
data_shape = op.inputs[0].get_shape()
segment_ids_shape = op.inputs[1].get_shape()
segment_ids_shape.assert_has_rank(1)
return [tensor_shape.TensorShape([None]).concatenate(data_shape[1:])]
@ops.RegisterShape("SparseSegmentMean")
@ops.RegisterShape("SparseSegmentSum")
def _SparseSegmentReductionShape(op):
|
tensorflow.python.framework.ops.RegisterShape
| 9,813 |
import tensorflow as tf
img_h4 = lrelu(linear(tf.nn.dropout(tf.reshape(img_h3, [self.batch_size, -1]), keep_prob), featsize, 'h4_lin'))
img_z = lrelu(linear(tf.nn.dropout(img_h4, keep_prob), featsize, 'hz_lin'))
return img_h0, img_h1, img_h2, img_h3, img_h4, img_z
with tf.variable_scope("conv") as scope:
srcimg_h0, srcimg_h1, srcimg_h2, srcimg_h3, srcimg_h4, srcimg_z = encode(srcimg)
scope.reuse_variables()
tgtimg_h0, tgtimg_h1, tgtimg_h2, tgtimg_h3, tgtimg_h4, tgtimg_z = encode(tgtimg)
|
tensorflow.variable_scope
| 9,814 |
import tensorflow as tf
# Convolution when number of indices is larger than zero.
def _conv_nonzero():
# Gather patches.
p = tf.gather_nd(x_, blk_indices_)
p_ = tf.reshape(p, [-1, ksize[0] * ksize[1] * ksize[2]])
# Convolution on patches.
w_ = tf.reshape(w, [ksize[0] * ksize[1] * ksize[2], -1])
|
tensorflow.reshape
| 9,815 |
import tensorflow as tf
with tf.Session() as sess:
input0_tensor = tf.get_default_graph().get_tensor_by_name(
"TENSOR_INPUT0:0")
input1_tensor = tf.get_default_graph().get_tensor_by_name(
"TENSOR_INPUT1:0")
output0_tensor = tf.get_default_graph().get_tensor_by_name(
|
tensorflow.get_default_graph
| 9,816 |
import tensorflow as tf
# Initialize parameters
self.lambda_1 = tf.Variable([0.0], dtype=tf.float32)
self.lambda_2 = tf.Variable([-6.0], dtype=tf.float32)
|
tensorflow.Variable
| 9,817 |
import tensorflow as tf
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")
def get_bias(self, name):
return tf.constant(self.data_dict[name][1], name="biases")
def get_fc_weight(self, name):
return tf.constant(self.data_dict[name][0], name="weights")
|
tensorflow.matmul
| 9,818 |
import tensorflow as tf
import tensorflow as tf
import random
from tensorflow.contrib import slim
from npu_bridge.estimator import npu_ops
from tensorflow.core.protobuf.rewriter_config_pb2 import RewriterConfig
tf.app.flags.DEFINE_integer('input_size', 512, '')
tf.app.flags.DEFINE_integer('batch_size_per_gpu', 14, '')
tf.app.flags.DEFINE_integer('num_readers', 16, '')
tf.app.flags.DEFINE_float('learning_rate', 0.0001, '')
tf.app.flags.DEFINE_integer('max_steps', 100000, '')
tf.app.flags.DEFINE_integer('loss_scale', 1024, '')
tf.app.flags.DEFINE_float('moving_average_decay', 0.997, '')
tf.app.flags.DEFINE_string('gpu_list', '1', '')
tf.app.flags.DEFINE_string('checkpoint_path', '/tmp/east_resnet_v1_50_rbox/', '')
tf.app.flags.DEFINE_boolean('restore', False, 'whether to resotre from checkpoint')
tf.app.flags.DEFINE_integer('save_checkpoint_steps', 1000, '')
tf.app.flags.DEFINE_integer('save_summary_steps', 100, '')
tf.app.flags.DEFINE_string('pretrained_model_path', None, '')
tf.app.flags.DEFINE_boolean('allow_mix_precision', False, 'whether to allow mix precision')
tf.app.flags.DEFINE_boolean('auto_tune', False, 'whether to autotune')
tf.app.flags.DEFINE_boolean('use_processed_data', False, 'whether to use processed data')
tf.app.flags.DEFINE_string('processed_data', './processed_dataset/', 'where to save preprocessed datasets')
import model
import icdar
FLAGS = tf.app.flags.FLAGS
|
tensorflow.app.flags.DEFINE_string
| 9,819 |
import tensorflow as tf
)
else:
# vector vector -> concat
dependencies_hidden.append(dependency_final_hidden)
try:
hidden = tf.concat([hidden] + dependencies_hidden, -1)
except:
raise ValueError(
'Shape mismatch while concatenating dependent features of '
'{}: {}. Concatenating the feature activations tensor {} '
'with activation tensors of dependencies: {}. The error is '
|
tensorflow.concat
| 9,820 |
import tensorflow as tf
os.makedirs('./mnist')
with tf.Session() as sess:
if args.model_path == '':
tf.global_variables_initializer().run()
else:
saver.restore(sess, args.model_path)
|
tensorflow.global_variables_initializer
| 9,821 |
import tensorflow as tf
def pointer(inputs, state, hidden, mask, scope="pointer"):
with tf.variable_scope(scope):
u = tf.concat([tf.tile(tf.expand_dims(state, axis=1), [1, tf.shape(inputs)[1], 1]), inputs], axis=2) #[N,PL,2d]
s0 = tf.nn.tanh(dense(u, hidden, use_bias=False, scope="s0"))
|
tensorflow.variable_scope
| 9,822 |
import tensorflow as tf
attack_carlini = attacks.carliniLi.CarliniLi(sess, model_carlini, largest_const=10 ** -3)
elif FLAGS.attack_method == 'carliniL2':
attack_carlini = attacks.carliniL2.CarliniL2(sess, model_carlini, batch_size=10, max_iterations=1000, confidence=0,binary_search_steps=3)
adv_image = tf.placeholder(tf.float32, shape=[hps.batch_size, image_size, image_size, num_channel])
_, logits_nor = model_carlini.predict(images, tsne_logits=True)
|
tensorflow.placeholder
| 9,823 |
import tensorflow as tf
def log_sum_exp(x):
"""numerically stable log_sum_exp implementation that prevents overflow."""
axis = len(x.get_shape()) - 1
m = tf.reduce_max(x, axis)
m2 = tf.reduce_max(x, axis, keep_dims=True)
return m + tf.log(tf.reduce_sum(tf.exp(x - m2), axis))
def log_prob_from_logits(x):
"""numerically stable log_softmax implementation that prevents overflow."""
|
tensorflow.exp
| 9,824 |
import tensorflow as tf
entropy_bottleneck = EntropyBottleneck()
conditional_entropy_model = SymmetricConditional()
checkpoint = tf.train.Checkpoint(analysis_transform=analysis_transform,
hyper_encoder=hyper_encoder,
hyper_decoder=hyper_decoder,
estimator=entropy_bottleneck)
status = checkpoint.restore(tf.train.latest_checkpoint(ckpt_dir))
x = tf.convert_to_tensor(x_color, "float32")
x_coori = tf.convert_to_tensor(x_coori, "float32")
def loop_analysis(element):
x = tf.expand_dims(element[0], 0)
x_coori = tf.expand_dims(element[1], 0)
y = analysis_transform(x_coori,x)
return tf.squeeze(y,axis=0)
|
tensorflow.convert_to_tensor
| 9,825 |
import tensorflow as tf
with tf.variable_scope(name):
return tf.nn.relu(x) - alpha * tf.nn.relu(-x)
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"""
with tf.variable_scope(name):
if reuse:
tf.get_variable_scope().reuse_variables()
else:
assert tf.get_variable_scope().reuse is False
|
tensorflow.truncated_normal_initializer
| 9,826 |
import tensorflow as tf
correct_prediction=tf.equal(tf.argmax(test_inf,1),tf.argmax(test_labels,1))
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
|
tensorflow.cast
| 9,827 |
import tensorflow as tf
def fwd_gradients_0(self, U, x):
g = tf.gradients(U, x, grad_ys=self.dummy_x0_tf)[0]
return tf.gradients(g, self.dummy_x0_tf)[0]
|
tensorflow.gradients
| 9,828 |
import tensorflow as tf
self.mean_sq = tf.reduce_mean(tf.square(x), [0, 1, 2], keep_dims=True)
self.batch_size = int(x.get_shape()[0])
assert x is not None
assert self.mean is not None
assert self.mean_sq is not None
out = tf.nn.relu(self._normalize(x, self.mean, self.mean_sq, "reference"))
self.reference_output = out
def __call__(self, x, update=False):
with tf.variable_scope(self.name) as scope:
if not update:
new_coeff = 1. / (self.batch_size + 1.)
old_coeff = 1. - new_coeff
new_mean = tf.reduce_mean(x, [1, 2], keep_dims=True)
new_mean_sq = tf.reduce_mean(tf.square(x), [1, 2], keep_dims=True)
mean = new_coeff * new_mean + old_coeff * self.mean
mean_sq = new_coeff * new_mean_sq + old_coeff * self.mean_sq
out = tf.nn.relu(self._normalize(x, mean, mean_sq, "live"))
# Update the mean and mean_sq when passing the reference data
else:
self.mean = tf.reduce_mean(x, [0, 1, 2], keep_dims=True)
self.mean_sq = tf.reduce_mean(tf.square(x), [0, 1, 2], keep_dims=True)
out = tf.nn.relu(self._normalize(x, self.mean, self.mean_sq, "reference"))
return out
def _normalize(self, x, mean, mean_sq, message):
|
tensorflow.reduce_mean
| 9,829 |
import tensorflow as tf
self.c = tf.slice(self.c, [0, 0], [N, self.c_maxlen])
self.q = tf.slice(self.q, [0, 0], [N, self.q_maxlen])
self.c_mask = tf.slice(self.c_mask, [0, 0], [N, self.c_maxlen])
self.q_mask = tf.slice(self.q_mask, [0, 0], [N, self.q_maxlen])
self.ch = tf.slice(self.ch, [0, 0, 0], [N, self.c_maxlen, CL])
self.qh = tf.slice(self.qh, [0, 0, 0], [N, self.q_maxlen, CL])
self.y1 = tf.argmax(tf.slice(self.y1, [0, 0], [N, self.c_maxlen]),axis=-1)
self.y2 = tf.argmax(tf.slice(self.y2, [0, 0], [N, self.c_maxlen]),axis=-1)
else:
self.c_maxlen, self.q_maxlen = config.para_limit, config.ques_limit
self.ch_len = tf.reshape(tf.reduce_sum(
tf.cast(tf.cast(self.ch, tf.bool), tf.int32), axis=2), [-1])
self.qh_len = tf.reshape(tf.reduce_sum(
tf.cast(tf.cast(self.qh, tf.bool), tf.int32), axis=2), [-1])
self.forward()
total_params()
if trainable:
self.lr = tf.minimum(config.learning_rate, 0.001 / tf.log(999.) * tf.log(tf.cast(self.global_step, tf.float32) + 1))
self.opt = tf.train.AdamOptimizer(learning_rate = self.lr, beta1 = 0.8, beta2 = 0.999, epsilon = 1e-7)
grads = self.opt.compute_gradients(self.loss)
gradients, variables = zip(*grads)
capped_grads, _ = tf.clip_by_global_norm(
gradients, config.grad_clip)
self.train_op = self.opt.apply_gradients(
zip(capped_grads, variables), global_step=self.global_step)
|
tensorflow.cast
| 9,830 |
import tensorflow as tf
if FLAGS.auto_recover:
hooks.append(tf.data.experimental.CheckpointInputPipelineHook(estimator))
estimator.train(input_fn=train_input_fn, max_steps=FLAGS.num_train_steps, hooks=hooks)
if FLAGS.do_eval:
tf.logging.info("***** Running evaluation *****")
tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
eval_input_fn = input_fn_builder(
input_files=validation_input_files,
max_seq_length=FLAGS.max_seq_length,
|
tensorflow.logging.info
| 9,831 |
import tensorflow as tf
num_attention_heads: number of attention head in attention layer.
name: The name scope of this layer.
Returns:
float logits Tensor.
"""
del num_attention_heads # unused
input_shape = get_shape_list(input_tensor)
hidden_size = input_shape[2]
with tf.variable_scope(name):
w = tf.get_variable(
name="kernel",
shape=[hidden_size, output_size],
initializer=initializer)
b = tf.get_variable(
name="bias", shape=[output_size], initializer=tf.zeros_initializer)
ret = tf.einsum("BFH,HO->BFO", input_tensor, w)
ret += b
|
tensorflow.variable_scope
| 9,832 |
import tensorflow as tf
self.step_ops = [policy_loss, qf1_loss, qf2_loss,
value_loss, qf1, qf2, value_fn, logp_pi,
self.entropy,actor_for_priority,value_for_priority,imitation_for_priority,self.actor_loss_di, policy_train_op, train_values_op]
# Add entropy coefficient optimization operation if needed
if ent_coef_loss is not None:
with tf.control_dependencies([train_values_op]):
ent_coef_op = entropy_optimizer.minimize(ent_coef_loss, var_list=self.log_ent_coef)
self.infos_names += ['ent_coef_loss', 'ent_coef']
self.step_ops += [ent_coef_op, ent_coef_loss, self.ent_coef]
# Monitor losses and entropy in tensorboard
tf.summary.scalar('policy_loss', policy_loss)
tf.summary.scalar('qf1_loss', qf1_loss)
tf.summary.scalar('qf2_loss', qf2_loss)
tf.summary.scalar('value_loss', value_loss)
tf.summary.scalar("Imitation_loss",self.actor_loss_di)
tf.summary.scalar('entropy', self.entropy)
tf.summary.scalar('importance weight',tf.reduce_mean(self.weight_ph))
if ent_coef_loss is not None:
tf.summary.scalar('ent_coef_loss', ent_coef_loss)
tf.summary.scalar('ent_coef', self.ent_coef)
tf.summary.scalar('learning_rate', tf.reduce_mean(self.learning_rate_ph))
# Retrieve parameters that must be saved
self.params = tf_util.get_trainable_vars("model")
self.target_params = tf_util.get_trainable_vars("target/values_fn/vf")
# Initialize Variables and target network
|
tensorflow.summary.scalar
| 9,833 |
import tensorflow as tf
self.assertTrue(endpoint_name in explicit_padding_end_points)
self.assertListEqual(
explicit_padding_end_points[endpoint_name].get_shape().as_list(),
expected_shape)
def testBuildAndCheckAllEndPointsApproximateFaceNet(self):
batch_size = 5
height, width = 128, 128
inputs = tf.random_uniform((batch_size, height, width, 3))
with slim.arg_scope([slim.conv2d, slim.separable_conv2d],
normalizer_fn=slim.batch_norm):
_, end_points = mobilenet_v1.mobilenet_v1_base(
inputs, final_endpoint='Conv2d_13_pointwise', depth_multiplier=0.75)
_, explicit_padding_end_points = mobilenet_v1.mobilenet_v1_base(
inputs, final_endpoint='Conv2d_13_pointwise', depth_multiplier=0.75,
use_explicit_padding=True)
# For the Conv2d_0 layer FaceNet has depth=16
|
tensorflow.random_uniform
| 9,834 |
import tensorflow as tf
learning_rate: epoch_learning_rate,
training_flag: False
}
loss_, acc_ = sess.run([Total_loss, accuracy], feed_dict=test_feed_dict)
test_loss += loss_
test_acc += acc_
test_loss /= test_iteration # average loss
test_acc /= test_iteration # average accuracy
summary = tf.Summary(value=[tf.Summary.Value(tag='test_loss', simple_value=test_loss),
tf.Summary.Value(tag='test_accuracy', simple_value=test_acc)])
return test_acc, test_loss, summary
def resnet_model_fn(inputs, training):
"""Our model_fn for ResNet to be used with our Estimator."""
network = resnet_model.imagenet_resnet_v2(
resnet_size=18, num_classes=class_num, mode='se', data_format=None)
inputs= network(inputs=inputs, is_training=training)
feat = tf.nn.l2_normalize(inputs, 1, 1e-10, name='feat')
|
tensorflow.Summary.Value
| 9,835 |
import tensorflow as tf
`[num_nodes * count1]`, `[num_nodes * count1 * count2]`, ...
weights: A list of `Tensor` of `float`, with shapes
`[num_nodes * count1]`, `[num_nodes * count1 * count2]` ...
types: A list of `Tensor` of `int32`, with shapes
`[num_nodes * count1]`, `[num_nodes * count1 * count2]` ...
"""
neighbors_list = [tf.reshape(nodes, [-1])]
weights_list = []
type_list = []
for hop_edge_types, count in zip(edge_types, counts):
neighbors, weights, types = sample_neighbor(
neighbors_list[-1], hop_edge_types, count, default_node=default_node)
neighbors_list.append(tf.reshape(neighbors, [-1]))
weights_list.append(tf.reshape(weights, [-1]))
type_list.append(tf.reshape(weights, [-1]))
return neighbors_list, weights_list, type_list
def get_multi_hop_neighbor(nodes, edge_types):
"""
Get multi-hop neighbors with adjacent matrix.
Args:
nodes: A 1-D `tf.Tensor` of `int64`.
edge_types: A list of 1-D `tf.Tensor` of `int32`. Specify edge types to
filter outgoing edges in each hop.
Return:
|
tensorflow.reshape
| 9,836 |
from tensorflow.python.ops import math_ops
rank = array_ops.rank(top_k_predictions)
check_rank_op = control_flow_ops.Assert(
math_ops.greater_equal(rank, 2),
['top_k_predictions must have rank 2 or higher, e.g. [batch_size, k].'])
|
tensorflow.python.ops.math_ops.greater_equal
| 9,837 |
import tensorflow as tf
# convolve w and input
conv = tf.nn.conv2d(
name='conv',
input=X,
filter=W,
strides=[1, 1, 1, 1],
padding='VALID')
#add bias of size = out cannels
b = tf.get_variable(
name='b',
shape=[num_filter],
initializer=tf.constant_initializer(0.0))
H = tf.nn.bias_add(
name='H',
value=conv,
bias=b)
# Apply nonlinearity
H = tf.nn.relu(H, name="relu")
# max pool
pooled = tf.nn.max_pool(H,
|
tensorflow.constant_initializer
| 9,838 |
import tensorflow as tf
B1 = euclidean_norm_squared(X, axis=1)/(2+4*y)
return 1/tf.sqrt(1+y) + A*tf.reduce_sum(__phi(A1)) - B*tf.reduce_sum(__phi(B1))
def cw(X, y=None):
D = tf.cast(tf.shape(X)[1], tf.float32)
N = tf.cast(tf.shape(X)[0], tf.float32)
if y is None:
y = silverman_rule_of_thumb(N)
K = 1/(2*D-3)
|
tensorflow.shape
| 9,839 |
import tensorflow as tf
name='x')
self.y = tf.placeholder(tf.float32, [batch_size, out_vocab_size],
name='y')
# The bidirectional rnn code requires seq_lens as int64
self.seq_lens = tf.placeholder(tf.int64, [batch_size], name='seq_lens')
self.example_weights = tf.placeholder(tf.float32, [batch_size],
name='example_weights')
|
tensorflow.placeholder
| 9,840 |
import tensorflow as tf
def _smooth_l1_loss(y_true, y_pred):
t = tf.abs(y_pred - y_true)
return tf.where(t < 1, 0.5 * t ** 2, t - 0.5)
|
tensorflow.abs
| 9,841 |
import tensorflow as tf
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:
|
tensorflow.logging.info
| 9,842 |
import tensorflow as tf
with tf.variable_scope("polyak_model", reuse=True, custom_getter=custom_getter):
self.polyak_model = polyak_model = self.policy(self.sess, self.observation_space, self.action_space,
self.n_envs, self.n_steps + 1,
self.n_envs * (self.n_steps + 1), reuse=True,
**self.policy_kwargs)
with tf.variable_scope("loss", reuse=False):
self.done_ph = tf.placeholder(tf.float32, [self.n_batch]) # dones
self.reward_ph = tf.placeholder(tf.float32, [self.n_batch]) # rewards, not returns
self.mu_ph = tf.placeholder(tf.float32, [self.n_batch, self.n_act]) # mu's
self.action_ph = train_model.pdtype.sample_placeholder([self.n_batch])
self.learning_rate_ph = tf.placeholder(tf.float32, [])
eps = 1e-6
# Notation: (var) = batch variable, (var)s = sequence variable,
# (var)_i = variable index by action at step i
# shape is [n_envs * (n_steps + 1)]
if continuous:
value = train_model.value_flat
else:
value = tf.reduce_sum(train_model.policy_proba * train_model.q_value, axis=-1)
rho, rho_i_ = None, None
|
tensorflow.placeholder
| 9,843 |
from tensorflow.python.platform import tf_logging as logging
fail_on_nan_loss: `bool`, whether to raise exception when loss is NaN.
"""
super(NanLoss, self).__init__(every_n_steps=every_n_steps)
self._loss_tensor = loss_tensor
self._fail_on_nan_loss = fail_on_nan_loss
def every_n_step_begin(self, step):
super(NanLoss, self).every_n_step_begin(step)
return [self._loss_tensor]
def every_n_step_end(self, step, outputs):
super(NanLoss, self).every_n_step_end(step, outputs)
if np.isnan(_extract_output(outputs, self._loss_tensor)):
failure_message = "Model diverged with loss = NaN."
if self._fail_on_nan_loss:
logging.error(failure_message)
raise NanLossDuringTrainingError
else:
logging.warning(failure_message)
# We don't raise an error but we return "should stop" so we stop, but
# without an exception.
return True
class RunHookAdapterForMonitors(session_run_hook.SessionRunHook):
"""Wraps monitors into a SessionRunHook."""
def __init__(self, monitors):
self._monitors = monitors
|
tensorflow.python.platform.tf_logging.error
| 9,844 |
import tensorflow as tf
[1, 1]], dtype=tf.float32)
mask4 = tf.constant([[0, 0],
[0, 0]], dtype=tf.float32)
mask5 = tf.constant([[1, 0],
[1, 0]], dtype=tf.float32)
masks1 = tf.stack([mask0, mask1, mask2])
masks2 = tf.stack([mask3, mask4, mask5])
ious = isu.get_pairwise_iou_matrix(masks1, masks2)
expected_ious = tf.constant([[0.5, 0.0, 1.0/3.0],
[0.75, 0.0, 0.25],
|
tensorflow.stack
| 9,845 |
import tensorflow as tf
multipliers.
label_priors: A Tensor of shape [num_labels] consisting of the prior
probability of each label learned by the loss, if not provided.
true_positives_lower_bound: Lower bound on the number of true positives
given `labels` and `logits`. This is the same lower bound which is used
in the loss expression to be optimized.
false_positives_upper_bound: Upper bound on the number of false positives
given `labels` and `logits`. This is the same upper bound which is used
in the loss expression to be optimized.
Raises:
ValueError: If `surrogate_type` is not `xent` or `hinge`.
"""
with tf.variable_scope(scope, 'tpr_at_fpr', [labels, logits, label_priors], reuse=reuse):
labels, logits, weights, original_shape = _prepare_labels_logits_weights(labels, logits, weights)
num_labels = losses_utils.get_num_labels(logits)
# Convert other inputs to tensors and standardize dtypes.
target_rate = losses_utils.convert_and_cast(target_rate, 'target_rate', logits.dtype)
dual_rate_factor = losses_utils.convert_and_cast(dual_rate_factor, 'dual_rate_factor',
logits.dtype)
# Create lambdas.
lambdas, lambdas_variable = _create_dual_variable(
'lambdas',
|
tensorflow.variable_scope
| 9,846 |
import tensorflow as tf
use_image_if_no_bounding_boxes=True)
is_bad = tf.reduce_sum(tf.cast(tf.equal(bbox_size, jpeg_shape), tf.int32)) >= 2
|
tensorflow.equal
| 9,847 |
import tensorflow as tf
# generates random numbers at graph definition time.
max_offset_height = control_flow_ops.with_dependencies(
asserts, tf.reshape(image_height - crop_height + 1, []))
max_offset_width = control_flow_ops.with_dependencies(
asserts, tf.reshape(image_width - crop_width + 1, []))
offset_height = tf.random_uniform(
[], maxval=max_offset_height, dtype=tf.int32)
offset_width = tf.random_uniform(
|
tensorflow.reshape
| 9,848 |
import tensorflow as tf
# state and target
self.state = tf.placeholder(tf.float32, [None,num_state], "state")
self.target = tf.placeholder(tf.float32, [None,1], name="target")
# layers
l_c = tf.layers.dense(self.state, 100, tf.nn.relu6, kernel_initializer=w_init, name='lc')
self.value_estimate = tf.layers.dense(l_c, 1, kernel_initializer=w_init, name='v') # estimated value for state
# loss and optimizer
self.loss = tf.reduce_mean(tf.square(tf.subtract(self.value_estimate, self.target)))
self.optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
self.train_op = self.optimizer.minimize(
|
tensorflow.layers.dense
| 9,849 |
from tensorflow.python.ops import math_ops
return loss_ops.hinge_loss(logits, target)
super(_BinarySvmTargetColumn, self).__init__(
loss_fn=loss_fn,
n_classes=2,
label_name=label_name,
weight_column_name=weight_column_name)
def logits_to_predictions(self, logits, proba=False):
if proba:
raise ValueError(
"logits to probabilities is not supported for _BinarySvmTargetColumn")
logits = array_ops.concat([array_ops.zeros_like(logits), logits], 1)
return math_ops.argmax(logits, 1)
# TODO(zakaria): use contrib losses.
def _mean_squared_loss(logits, target):
# To prevent broadcasting inside "-".
if len(target.get_shape()) == 1:
target = array_ops.expand_dims(target, dim=[1])
logits.get_shape().assert_is_compatible_with(target.get_shape())
return math_ops.square(logits - math_ops.to_float(target))
def _log_loss_with_two_classes(logits, target):
|
tensorflow.python.ops.math_ops.argmax
| 9,850 |
import tensorflow as tf
encoder_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])
encoder_out, encoder_state = tf.nn.dynamic_rnn(
cell=encoder_cells, inputs=forward, sequence_length=seq_lens, dtype=tf.float32
)
encoder_state = tuple(encoder_state[-1] for _ in range(num_layers))
decoder_cell = attention(encoder_out, seq_lens)
dense_layer = tf.layers.Dense(n_mels * resampled)
training_helper = tf.contrib.seq2seq.TrainingHelper(
inputs=self.decoder_inputs, sequence_length=seq_lens, time_major=False
)
training_decoder = tf.contrib.seq2seq.BasicDecoder(
cell=decoder_cell,
helper=training_helper,
initial_state=decoder_cell.zero_state(batch_size, tf.float32).clone(
cell_state=encoder_state
),
output_layer=dense_layer,
|
tensorflow.contrib.seq2seq.TrainingHelper
| 9,851 |
import tensorflow as tf
_debug(self.conv2)
with tf.variable_scope('conv3_x'):
self.conv3 = self._residual_block('conv3_1', self.conv2, 128, pool_first=True, strides=2)
_debug(self.conv3)
self.conv3 = self._residual_block('conv3_2', self.conv3, 128)
_debug(self.conv3)
with tf.variable_scope('conv4_x'):
self.conv4 = self._residual_block('conv4_1', self.conv3, 256, pool_first=True, strides=2)
_debug(self.conv4)
self.conv4 = self._residual_block('conv4_2', self.conv4, 256)
_debug(self.conv4)
with tf.variable_scope('conv5_x'):
self.conv5 = self._residual_block('conv5_1', self.conv4, 512, pool_first=True, strides=2)
_debug(self.conv5)
self.conv5 = self._residual_block('conv5_2', self.conv5, 512)
_debug(self.conv5)
if self.test_classification:
with tf.variable_scope('logits'):
print('Building unit: logits')
self.score = tf.reduce_mean(self.conv5, axis=[1, 2])
self.score = self._fc('logits_dense', self.score, output_dim=self.num_classes, l2_strength=self.wd)
print('logits-shape: ' + str(self.score.shape.as_list()))
self.feed1 = self.conv4
|
tensorflow.variable_scope
| 9,852 |
import tensorflow as tf
if channels % 4 != 0:
raise ValueError("Number of channels not divisible by 4.")
res = tf.reshape(input_, [batch_size, height, width, channels // 4, 2, 2])
res = tf.transpose(res, [0, 1, 4, 2, 5, 3])
|
tensorflow.reshape
| 9,853 |
import tensorflow as tf
b = tf.get_variable("b", [nh*4], initializer=tf.constant_initializer(0.0))
c, h = tf.split(axis=1, num_or_size_splits=2, value=s)
for idx, (x, m) in enumerate(zip(xs, ms)):
c = c*(1-m)
h = h*(1-m)
z = tf.matmul(x, wx) + tf.matmul(h, wh) + b
i, f, o, u = tf.split(axis=1, num_or_size_splits=4, value=z)
i = tf.nn.sigmoid(i)
f = tf.nn.sigmoid(f)
o = tf.nn.sigmoid(o)
u = tf.tanh(u)
c = f*c + i*u
h = o*tf.tanh(c)
xs[idx] = h
s = tf.concat(axis=1, values=[c, h])
return xs, s
def _ln(x, g, b, e=1e-5, axes=[1]):
u, s = tf.nn.moments(x, axes=axes, keep_dims=True)
x = (x-u)/tf.sqrt(s+e)
x = x*g+b
return x
def lnlstm(xs, ms, s, scope, nh, init_scale=1.0):
nbatch, nin = [v.value for v in xs[0].get_shape()]
|
tensorflow.tanh
| 9,854 |
import tensorflow as tf
src_logits, dst_logits = get_model_logits(src_features, finetune_features,
mode, num_classes,
target_num_classes)
loss, _, _ = get_final_loss(src_logits, src_one_hot_labels, dst_logits,
finetune_one_hot_labels, global_step,
loss_weights, inst_weights)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
src_train_op, _ = get_src_train_op(loss)
with tf.control_dependencies([src_train_op]):
target_avg_pool = get_logits(
target_features, mode, FLAGS.target_dataset, reuse=True)
target_logits = do_cls(
target_avg_pool, target_num_classes, name='final_target_dense')
is_prediction_correct = tf.equal(
tf.argmax(tf.identity(target_logits), axis=1),
tf.argmax(target_one_hot_labels, axis=1))
acc = tf.reduce_mean(tf.cast(is_prediction_correct, tf.float32))
|
tensorflow.control_dependencies
| 9,855 |
import tensorflow as tf
ranking_model_gradients = tf.gradients(self.rank_loss, ranking_model_params)
if self.hparams.max_gradient_norm > 0:
denoise_gradients, denoise_norm = tf.clip_by_global_norm(denoise_gradients,
self.hparams.max_gradient_norm)
ranking_model_gradients, ranking_model_norm = tf.clip_by_global_norm(ranking_model_gradients,
self.hparams.max_gradient_norm * self.hparams.ranker_loss_weight)
self.norm = tf.global_norm(denoise_gradients + ranking_model_gradients)
opt_denoise = self.optimizer_func(self.hparams.learning_rate)
opt_ranker = self.optimizer_func(self.ranker_learning_rate)
denoise_updates = opt_denoise.apply_gradients(zip(denoise_gradients, denoise_params),
|
tensorflow.global_norm
| 9,856 |
import tensorflow as tf
c = tf.matmul(a,b)
c = tf.reshape(c, [-1])
with tf.device('/gpu:2'):
d = tf.matmul(b,a)
flat_d = tf.reshape(d, [-1])
|
tensorflow.device
| 9,857 |
import tensorflow as tf
out_mask = attention_mask * a_mask
else:
ones = tf.ones_like(attention_mask[:1])
mask = (tf.matrix_band_part(ones, -1, 0))
|
tensorflow.ones_like
| 9,858 |
from tensorflow.python.ops import math_ops
# sparse_softmax_cross_entropy_with_logits requires [batch_size] target.
if len(target.get_shape()) == 2:
target = array_ops.squeeze(target, squeeze_dims=[1])
loss_vec = nn.sparse_softmax_cross_entropy_with_logits(
labels=target, logits=logits)
return loss_vec
def _run_metrics(predictions, labels, metrics, weights):
result = {}
labels = math_ops.cast(labels, predictions.dtype)
for name, metric in six.iteritems(metrics or {}):
if weights is not None:
result[name] = metric(predictions, labels, weights=weights)
else:
result[name] = metric(predictions, labels)
return result
|
tensorflow.python.ops.math_ops.cast
| 9,859 |
from tensorflow.python.framework import tensor_shape
# NOTE(mrry): We could in principle work out the shape from the
# gradients and the attrs, but if we do not know orig_input_shape
# statically, then we are unlikely to know the shape of the
# gradients either.
return [tensor_shape.unknown_shape(ndims=4)]
@ops.RegisterShape("Conv2DBackpropFilter")
|
tensorflow.python.framework.tensor_shape.unknown_shape
| 9,860 |
import tensorflow as tf
# x is shaped [batch_size,time_steps,num_inputs]
if is_dynamic_rnn:
lstm_input = tf.transpose(x, perm=[1, 0, 2])
outputs, _ = tf.lite.experimental.nn.dynamic_rnn(
|
tensorflow.transpose
| 9,861 |
import tensorflow as tf
Returns:
A tensor with the clipped kappa log loss.
"""
with tf.name_scope(name):
num_classes = labels.get_shape()[-1].value
labels = tf.cast(labels, predictions.dtype)
if label_smoothing > 0:
smooth_positives = 1.0 - label_smoothing
smooth_negatives = label_smoothing / num_classes
labels = labels * smooth_positives + smooth_negatives
log_loss_res = log_loss_tf(predictions, labels)
kappa_loss_res = kappa_loss(
predictions, labels, y_pow=y_pow, num_ratings=num_classes, batch_size=batch_size)
return kappa_loss_res + log_scale * tf.clip_by_value(log_loss_res, log_cutoff, 10**3)
def cross_entropy_loss(logits, labels, label_smoothing=0.0, weight=1.0, name='cross_entropy_loss'):
"""Define a cross entropy loss with label smoothing.
Args:
predictions: 2D tensor or array, [batch_size, num_classes] predictions of the network .
labels: 2D tensor or array,[batch_size, num_classes] ground truth labels or target labels.
label_smoothing: a float, used to smooth the labels for better generalization
if greater than 0 then smooth the labels.
weight: scale the loss by this factor.
name: Optional scope/name for op_scope.
|
tensorflow.clip_by_value
| 9,862 |
import tensorflow as tf
# localization loss (smooth L1)
mask_pos_b = tf.broadcast_to(mask_pos, tf.shape(loc_true))
loss_loc = _smooth_l1_loss(tf.boolean_mask(loc_true, mask_pos_b),
tf.boolean_mask(loc_pred, mask_pos_b))
loss_loc = tf.reduce_mean(loss_loc)
# classification loss (crossentropy)
# 1. compute max conf across batch for hard negative mining
loss_class = tf.where(mask_neg,
1 - class_pred[:, 0][..., tf.newaxis], 0)
# 2. hard negative mining
loss_class = tf.reshape(loss_class, [num_batch, num_prior])
loss_class_idx = tf.argsort(loss_class, axis=1, direction='DESCENDING')
loss_class_idx_rank = tf.argsort(loss_class_idx, axis=1)
mask_pos_per_batch = tf.reshape(mask_pos, [num_batch, num_prior])
num_pos_per_batch = tf.reduce_sum(
tf.cast(mask_pos_per_batch, tf.float32), 1, keepdims=True)
num_pos_per_batch = tf.maximum(num_pos_per_batch, 1)
num_neg_per_batch = tf.minimum(neg_pos_ratio * num_pos_per_batch,
tf.cast(num_prior, tf.float32) - 1)
mask_hard_neg = tf.reshape(
tf.cast(loss_class_idx_rank, tf.float32) < num_neg_per_batch,
[num_batch * num_prior, 1])
|
tensorflow.reshape
| 9,863 |
import tensorflow as tf
if W_p is None:
W_p = self._make_var('W_p', (1, 1, ch_mul * ch, ch))
X = tf.nn.relu(X)
X = tf.nn.separable_conv2d(X, W_d, W_p, strides=(1, stride, stride, 1), padding='SAME')
if not no_batch_norm:
X = self._add_batch_norm(X, ch, is_train=is_train)
|
tensorflow.nn.separable_conv2d
| 9,864 |
from tensorflow.python.framework import ops
the input rank (i.e. Conv ND, with N = input_rank - 2).
Returns:
A tensor representing the output of the operation.
Raises:
ValueError: If `data_format` is invalid.
ValueError: Both 'rate' and `stride` are not uniformly 1.
"""
if data_format not in [None, 'NWC', 'NCW', 'NHWC', 'NCHW', 'NDHWC', 'NCDHW']:
raise ValueError('Invalid data_format: %r' % (data_format,))
layer_variable_getter = _build_variable_getter({'bias': 'biases', 'kernel': 'weights'})
with variable_scope.variable_scope(scope, 'Conv', [inputs], reuse=reuse, custom_getter=layer_variable_getter) as sc:
inputs = ops.convert_to_tensor(inputs)
input_rank = inputs.get_shape().ndims
if conv_dims is not None and conv_dims + 2 != input_rank:
raise ValueError('Convolution expects input with rank %d, got %d' % (conv_dims + 2, input_rank))
if input_rank == 3:
layer_class = convolutional_layers.Convolution1D
elif input_rank == 4:
layer_class = MyConv2D
elif input_rank == 5:
layer_class = convolutional_layers.Convolution3D
else:
raise ValueError('Convolution not supported for input with rank', input_rank)
|
tensorflow.python.framework.ops.convert_to_tensor
| 9,865 |
import tensorflow as tf
for item in dataset:
flat = tf.nest.flatten(item)
flat = [el.numpy() for el in flat]
yield tf.nest.pack_sequence_as(item, flat)
def _train_and_eval_dataset_v1(problem_name, data_dir, train_shuffle_files,
eval_shuffle_files):
"""Return train and evaluation datasets, feature info and supervised keys."""
with tf.device('cpu:0'):
problem = t2t_problems().problem(problem_name)
hparams = None
if problem_name == 'video_bair_robot_pushing':
hparams = problem.get_hparams()
bair_robot_pushing_hparams(hparams)
train_dataset = problem.dataset(
tf_estimator.ModeKeys.TRAIN,
data_dir,
|
tensorflow.device
| 9,866 |
from tensorflow.contrib.framework import tensor_util
`false_positives`.
Raises:
ValueError: If `predictions` and `labels` have mismatched shapes, or if
`weights` is not `None` and its shape doesn't match `predictions`.
"""
predictions, labels = tensor_util.remove_squeezable_dimensions(
predictions, labels)
predictions.get_shape().assert_is_compatible_with(labels.get_shape())
num_thresholds = len(thresholds)
|
tensorflow.contrib.framework.tensor_util.remove_squeezable_dimensions
| 9,867 |
import tensorflow as tf
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)
img_h = img_h_batch[i]
img_w = img_w_batch[i]
inputs_list.append([img, gtboxes_and_label_h, gtboxes_and_label_r, num_objects, img_h, img_w])
tower_grads = []
biases_regularizer = tf.no_regularizer
weights_regularizer = tf.contrib.layers.l2_regularizer(cfgs.WEIGHT_DECAY)
with tf.variable_scope(tf.get_variable_scope()):
for i in range(num_gpu):
with tf.device('/gpu:%d' % i):
|
tensorflow.reshape
| 9,868 |
import tensorflow as tf
x = tf.layers.conv2d(x, 32, (5, 5), strides=(2, 2),
activation=tf.nn.relu, padding="same")
flat_x = tf.layers.flatten(x)
if self.use_epochs:
epoch = features["epoch"] + tf.zeros([x_shape[0]], dtype=tf.int32)
# Randomly set epoch to 0 in some cases as that's the inference value.
rand = tf.random.uniform([x_shape[0]])
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)
|
tensorflow.random.uniform
| 9,869 |
import tensorflow as tf
config=tf.ConfigProto(device_count={"CPU": 2})) as sess:
with sess.graph.device("/cpu:0"):
v0 = tf.Variable(111, name="v0")
with sess.graph.device("/cpu:1"):
v1 = tf.Variable(222, name="v1")
save = tf.train.Saver({"v0": v0, "v1": v1}, sharded=True)
tf.initialize_all_variables().run()
self.assertEqual(111, v0.eval())
self.assertEqual(222, v1.eval())
save_path = os.path.join(self.get_temp_dir(), "sharded")
|
tensorflow.train.Saver
| 9,870 |
from tensorflow.contrib import slim
):
with slim.arg_scope([slim.batch_norm], **batch_norm_params):
with slim.arg_scope([slim.conv2d], weights_regularizer=regularizer):
with slim.arg_scope(
|
tensorflow.contrib.slim.arg_scope
| 9,871 |
import tensorflow as tf
last_layer = tf.nn.relu(projected)
else:
raise NotImplementedError()
if mode == 'train' and dnn_keep_prob < 1.0:
last_layer = tf.nn.dropout(last_layer, dnn_keep_prob)
last_layer_size = layer_size
print('{}: {}'.format(layer_name, last_layer.get_shape()))
export_feat_tensors[layer_name] = last_layer
dnn_output = last_layer
dnn_output_size = last_layer_size
# Logistic regression
with tf.variable_scope('logit') as scope:
logit_w = tf.get_variable('W', shape=[dnn_output_size, 1], initializer=tf.truncated_normal_initializer(stddev=1.0 / dnn_output_size, dtype=dtype), dtype=dtype)
logit_b = tf.get_variable('b', shape=[1], initializer=tf.constant_initializer(0.0), dtype=dtype)
logits = tf.squeeze(tf.nn.bias_add(tf.matmul(dnn_output, logit_w), logit_b), squeeze_dims=[1])
prediction = tf.nn.sigmoid(logits)
prediction_inspect = tf.reshape(prediction, [batch_size, rnn_nunroll])
prediction_final = tf.squeeze(tf.slice(prediction_inspect, [0, rnn_nunroll - 1], [-1, 1]), squeeze_dims=[1])
print('logit: {}'.format(logits.get_shape()))
# Compute loss
if mode != 'gen':
neg_log_lhoods = tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=targets)
if target_weight_strategy == 'rect':
avg_neg_log_lhood = tf.reduce_mean(neg_log_lhoods)
else:
neg_log_lhoods = tf.multiply(neg_log_lhoods, target_weights)
|
tensorflow.truncated_normal_initializer
| 9,872 |
import tensorflow as tf
if __name__ == '__main__':
import numpy as np
bboxes = tf.placeholder(tf.float32)
bboxes_val = [[10, 10, 20, 22]]
gt_boxes = tf.placeholder(tf.float32)
gt_boxes_val = [[11, 13, 34, 31]]
imshape = tf.placeholder(tf.int32)
imshape_val = (100, 100)
deltas = encode(bboxes, gt_boxes)
decoded_bboxes = decode(bboxes, deltas)
final_decoded_bboxes = clip_boxes(decoded_bboxes, imshape)
with tf.Session() as sess:
final_decoded_bboxes = sess.run(final_decoded_bboxes, feed_dict={
bboxes: bboxes_val,
|
tensorflow.placeholder
| 9,873 |
import tensorflow as tf
if use_tpu:
def tpu_scaffold():
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
return tf.train.Scaffold()
scaffold_fn = tpu_scaffold
else:
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
tf.logging.info("**** Trainable Variables ****")
for var in tvars:
init_string = ""
if var.name in initialized_variable_names:
init_string = ", *INIT_FROM_CKPT*"
tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
|
tensorflow.train.init_from_checkpoint
| 9,874 |
import tensorflow as tf
tf.summary.scalar(name='Autoencoder Loss', tensor=autoencoder_loss)
tf.summary.scalar(name='Discriminator gauss Loss', tensor=dc_g_loss)
tf.summary.scalar(name='Discriminator categorical Loss', tensor=dc_c_loss)
tf.summary.scalar(name='Generator Loss', tensor=generator_loss)
tf.summary.scalar(name='Supervised Encoder Loss', tensor=supervised_encoder_loss)
tf.summary.histogram(name='Encoder Gauss Distribution', values=encoder_output_latent)
tf.summary.histogram(name='Real Gauss Distribution', values=real_distribution)
tf.summary.histogram(name='Encoder Categorical Distribution', values=encoder_output_label)
tf.summary.histogram(name='Real Categorical Distribution', values=categorial_distribution)
tf.summary.image(name='Input Images', tensor=input_images, max_outputs=10)
tf.summary.image(name='Generated Images', tensor=generated_images, max_outputs=10)
summary_op = tf.summary.merge_all()
# Saving the model
saver = tf.train.Saver()
step = 0
|
tensorflow.summary.histogram
| 9,875 |
import tensorflow as tf
def contra_traj_lossV1(pred, tgt, temp=10.0):
# Trajectory-wise contrastive loss
traj_pred = tf.reduce_mean(pred, axis=1)
traj_tgt = tf.reduce_mean(tgt, axis=1)
p1, p2 = tf.split(traj_pred, 2, axis=0)
t1, t2 = tf.split(traj_tgt, 2, axis=0)
soft_sign = tf.tanh((t1 - t2) * temp)
loss = tf.maximum(0.0, soft_sign * ((t1 - t2) - (p1 - p2)))
loss = tf.reduce_mean(loss)
return loss
def horizon_sumV1(input, horizon=12):
bs, epi_len = input.shape[:2]
new_w = epi_len - horizon + 1
weights = np.zeros([epi_len, new_w])
|
tensorflow.reduce_mean
| 9,876 |
import tensorflow as tf
tower_metrics = self._gpu_tower(data, Mode.EVAL)
with tf.device('/cpu:0'):
|
tensorflow.device
| 9,877 |
import tensorflow as tf
Improved Regularization of Convolutional Neural Networks with Cutout
https://arxiv.org/abs/1708.04552
Implementation inspired by:
third_party/cloud_tpu/models/efficientnet/autoaugment.py
Args:
batch: A batch of images and labels.
Returns:
The same batch where cutout has been applied to the images.
"""
length, replace = FLAGS.cutout_length, 0.0
images, labels = batch['image'], batch['label']
num_channels = tf.shape(images)[3]
image_height, image_width = tf.shape(images)[1], tf.shape(images)[2]
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),
|
tensorflow.shape
| 9,878 |
import tensorflow as tf
eKff = expectation(pXnew, kern) # N (psi0)
eKuffu = expectation(pXnew, (kern, feat), (kern, feat)) # N x M x M (psi2)
Luu_tiled = tf.tile(Luu[None, :, :], [num_data, 1, 1]) # remove this line, once issue 216 is fixed
Li_eKuffu = tf.matrix_triangular_solve(Luu_tiled, eKuffu, lower=True)
|
tensorflow.tile
| 9,879 |
import tensorflow as tf
# Each entry on the list corresponds to one decoder step
vocab_score_t = tf.nn.xw_plus_b(output_t, w, b) # apply the linear layer
|
tensorflow.nn.xw_plus_b
| 9,880 |
import tensorflow as tf
# horizon_pred, horizon_tgt = horizon_sumV2(pred, tgt, horizon)
pred_flat1, pred_flat2 = tf.reshape(horizon_pred, [-1, 1]), tf.reshape(horizon_pred, [1, -1])
tgt_flat1, tgt_flat2 = tf.reshape(horizon_tgt, [-1, 1]), tf.reshape(horizon_tgt, [1, -1])
tgt_dif = tgt_flat1 - tgt_flat2
pred_dif = pred_flat1 - pred_flat2
geq = tf.cast(tgt_dif > 0, tf.bool)
tgt_posi_dif = tf.where(geq, tgt_dif, -tgt_dif)
pred_posi_dif = tf.where(geq, pred_dif, -pred_dif)
loss = tf.maximum(0., tgt_posi_dif - pred_posi_dif)
cstr_pct = tf.math.count_nonzero(loss, dtype=tf.float32) / tf.cast(tf.reduce_prod(tf.shape(loss)), tf.float32)
final_loss = tf.reduce_mean(loss)
return final_loss, cstr_pct
|
tensorflow.where
| 9,881 |
import tensorflow as tf
#
# This function gives us the ways to use
# multiple devices (executors) in TensorFlow.
import tensorflow as tf
from tensorflow.python.framework import ops
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,
# we set a parameter in our session:
config = tf.ConfigProto()
|
tensorflow.constant
| 9,882 |
import tensorflow as tf
checkpoint_file = cm.get_best_checkpoint(BEST_CPT_DIR, select_maximum_value=True)
else:
logger.info("Loading latest model...")
checkpoint_file = tf.train.latest_checkpoint(CPT_DIR)
logger.info(checkpoint_file)
graph = tf.Graph()
with graph.as_default():
session_conf = tf.ConfigProto(
allow_soft_placement=args.allow_soft_placement,
log_device_placement=args.log_device_placement)
session_conf.gpu_options.allow_growth = args.gpu_options_allow_growth
sess = tf.Session(config=session_conf)
with sess.as_default():
# Load the saved meta graph and restore variables
saver = tf.train.import_meta_graph("{0}.meta".format(checkpoint_file))
|
tensorflow.ConfigProto
| 9,883 |
import tensorflow as tf
flags.DEFINE_integer(
"iterations_per_loop", 1000, "How many steps to make in each estimator call."
)
flags.DEFINE_integer("max_eval_steps", 100, "Maximum number of eval steps.")
flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
tf.flags.DEFINE_string(
"tpu_name",
None,
"The Cloud TPU to use for training. This should be either the name "
"used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 "
"url.",
)
|
tensorflow.flags.DEFINE_string
| 9,884 |
from tensorflow.python.ops import math_ops
true_negatives, math_ops.reduce_sum(is_true_negative, 1))
false_positives_update_op = state_ops.assign_add(
false_positives, math_ops.reduce_sum(is_false_positive, 1))
|
tensorflow.python.ops.math_ops.reduce_sum
| 9,885 |
import tensorflow as tf
# to the running average when ran.
tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_mean_op)
|
tensorflow.add_to_collection
| 9,886 |
import tensorflow as tf
kernel_initializer=self._kernel_initializer)
c = self._activation(self._candidate_linear([inputs, r_state]))
u = (1.0 - att_score) * u
new_h = u * state + (1 - u) * c
return new_h, new_h
def prelu(_x, scope=''):
"""parametric ReLU activation"""
with tf.variable_scope(name_or_scope=scope, default_name="prelu"):
_alpha = tf.get_variable("prelu_"+scope, shape=_x.get_shape()[-1],
dtype=_x.dtype, initializer=tf.constant_initializer(0.1))
_zero = tf.constant(0,dtype=_x.dtype)
# return tf.maximum(0.0, _x) + _alpha * tf.minimum(0.0, _x)
return tf.maximum(_zero, _x) + _alpha * tf.minimum(_zero, _x)
def calc_auc(raw_arr):
"""Summary
Args:
raw_arr (TYPE): Description
Returns:
TYPE: Description
"""
arr = sorted(raw_arr, key=lambda d:d[0], reverse=True)
|
tensorflow.maximum
| 9,887 |
import tensorflow as tf
# 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)
|
tensorflow.abs
| 9,888 |
import tensorflow as tf
# placeholder for current action
act_t_ph = tf.placeholder(tf.int32, [None])
|
tensorflow.placeholder
| 9,889 |
import tensorflow as tf
def do_cls(avg_pool, num_classes, name='dense'):
"""Applies classification."""
with tf.variable_scope('target_CLS', reuse=tf.AUTO_REUSE):
logits = tf.layers.dense(
inputs=avg_pool,
units=num_classes,
kernel_initializer=tf.random_normal_initializer(stddev=.05),
name=name)
return logits
def get_model_logits(src_features, finetune_features, mode, num_classes,
target_num_classes):
|
tensorflow.random_normal_initializer
| 9,890 |
import tensorflow as tf
indices = helper.make_tensor("indices", TensorProto.INT64, [2, 2], x)
a = helper.make_sparse_tensor(values, indices,[3, 4])
node_def = helper.make_node("Constant", [], ["Y"], sparse_value=a)
output = run_node(node_def, [])
b = tf.sparse_to_dense(output["Y"].indices, output["Y"].dense_shape, output["Y"].values)
result = b.eval(session=tf.Session())
np.testing.assert_equal(result, expected)
|
tensorflow.sparse_to_dense
| 9,891 |
import tensorflow as tf
if train:
if single_file:
dataset_path = os.path.join(dataset_path, 'train_annotated.json')
else:
dataset_path = os.path.join(dataset_path, 'dev_annotated.json')
def load_dataset():
dataset = []
if single_file:
# Opening with GFile allows to use remotely stored files, e.g.
# in a gs bucket.
dataset_handle = tf.io.gfile.GFile(dataset_path, 'r')
for line in dataset_handle:
dataset.append(json.loads(line))
else:
all_files = tf.io.gfile.listdir(dataset_path)
for filename in all_files:
if 'json' in filename:
print('Loading data from file {}'.format(filename))
with tf.io.gfile.GFile(os.path.join(dataset_path, filename)) as f:
for line in f:
dataset.append(json.loads(line))
|
tensorflow.io.gfile.GFile
| 9,892 |
import tensorflow as tf
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import variable_scope as vs
from tensorflow.keras import backend as K
def dice(_x, axis=-1, epsilon=0.000000001, name=''):
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
alphas = tf.get_variable('alpha'+name, _x.get_shape()[-1],
initializer=tf.constant_initializer(0.0),
dtype=_x.dtype)
input_shape = list(_x.get_shape())
reduction_axes = list(range(len(input_shape)))
del reduction_axes[axis]
broadcast_shape = [1] * len(input_shape)
broadcast_shape[axis] = input_shape[axis]
|
tensorflow.constant_initializer
| 9,893 |
import tensorflow as tf
per_example_loss,
logits,
label_ids)
estimator_spec = tf.estimator.EstimatorSpec(mode=mode,
loss=loss,
eval_metric_ops=eval_metric_ops)
|
tensorflow.estimator.EstimatorSpec
| 9,894 |
import tensorflow as tf
config = tf.ConfigProto()
custom_op = config.graph_options.rewrite_options.custom_optimizers.add()
custom_op.name = "NpuOptimizer"
custom_op.parameter_map["use_off_line"].b = True # 在昇腾AI处理器执行训练
config.graph_options.rewrite_options.remapping = RewriterConfig.OFF # 关闭remap开关
if FLAGS.allow_mix_precision:
custom_op.parameter_map["precision_mode"].s = tf.compat.as_bytes("allow_mix_precision")
if FLAGS.auto_tune:
custom_op.parameter_map["auto_tune_mode"].s = tf.compat.as_bytes("RL,GA")
with tf.Session(config=config) as sess:
if FLAGS.restore:
print('continue training from previous checkpoint')
ckpt = tf.train.latest_checkpoint(FLAGS.checkpoint_path)
saver.restore(sess, ckpt)
else:
sess.run(init)
if FLAGS.pretrained_model_path is not None:
variable_restore_op(sess)
data_generator = icdar.get_batch(num_workers=FLAGS.num_readers,
input_size=FLAGS.input_size,
batch_size=FLAGS.batch_size_per_gpu * len(gpus))
start = time.time()
avg_time_per_step1 = 0
performs = []
|
tensorflow.train.latest_checkpoint
| 9,895 |
import tensorflow as tf
even = [2 * i for i in range(25)]
odd = [2 * i + 1 for i in range(25)]
pred1 = tf.gather(horizon_pred, even)
pred2 = tf.gather(horizon_pred, odd)
tgt1 = tf.gather(horizon_tgt, even)
tgt2 = tf.gather(horizon_tgt, odd)
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 apply_optimizers(objectives, trainer, config):
# Make sure all losses are computed and apply loss scales.
processed = []
values = [ob.value for ob in objectives]
|
tensorflow.where
| 9,896 |
import tensorflow as tf
tf.reshape(pred_heatmap * 255., [-1, heatmap_size, heatmap_size]),
tf.reshape(predictions, [-1, heatmap_size, heatmap_size]),
config.left_right_group_map[category][0],
config.left_right_group_map[category][1],
config.left_right_group_map[category][2]],
tf.int64, stateful=True)
with tf.control_dependencies([save_image_op]):
pred_x, pred_y = pred_x * 1., pred_y * 1.
return pred_x, pred_y
def gaussian_blur(inputs, inputs_filters, sigma, data_format, name=None):
with tf.name_scope(name, "gaussian_blur", [inputs]):
data_format_ = 'NHWC' if data_format=='channels_last' else 'NCHW'
if data_format_ == 'NHWC':
inputs = tf.transpose(inputs, [0, 2, 3, 1])
ksize = int(6 * sigma + 1.)
x = tf.expand_dims(tf.range(ksize, delta=1, dtype=tf.float32), axis=1)
y = tf.transpose(x, [1, 0])
kernel_matrix = tf.exp(- ((x - ksize/2.) ** 2 + (y - ksize/2.) ** 2) / (2 * sigma ** 2))
#print(kernel_matrix)
kernel_filter = tf.reshape(kernel_matrix, [ksize, ksize, 1, 1])
kernel_filter = tf.tile(kernel_filter, [1, 1, inputs_filters, 1])
#kernel_filter = tf.transpose(kernel_filter, [1, 0, 2, 3])
outputs = tf.nn.depthwise_conv2d(inputs, kernel_filter, strides=[1, 1, 1, 1], padding='SAME', data_format=data_format_, name='blur')
if data_format_ == 'NHWC':
outputs = tf.transpose(outputs, [0, 3, 1, 2])
return outputs
|
tensorflow.transpose
| 9,897 |
import tensorflow as tf
horizon_tgt = tf.matmul(tgt, cur_weights)
return horizon_pred, horizon_tgt
def contra_traj_lossV2(pred, tgt, horizon=9):
# Step-wise contrastive loss
horizon_pred = horizon_sumV1(pred, horizon)
horizon_tgt = horizon_sumV1(tgt, horizon)
pred1, pred2 = tf.split(horizon_pred, 2, axis=0)
tgt1, tgt2 = tf.split(horizon_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)
|
tensorflow.split
| 9,898 |
from tensorflow.python.framework import ops
return array_ops.unstack(values)
else:
with ops.device(tensors[0].device):
sizes = array_ops.stack(
|
tensorflow.python.framework.ops.device
| 9,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.