seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
import tensorflow as tf
ch = shape[1]
new_shape = [1, ch, 1, 1]
if ch is None:
raise ValueError("Input of instancebn require known channel!")
mean, var = tf.nn.moments(inputdata, axis, keep_dims=True)
if not use_affine:
return tf.divide(inputdata - mean, tf.sqrt(var + epsilon), name='output')
beta = tf.get_variable('beta', [ch], initializer=tf.constant_initializer())
beta = tf.reshape(beta, new_shape)
gamma = tf.get_variable('gamma', [ch], initializer=tf.constant_initializer(1.0))
gamma = tf.reshape(gamma, new_shape)
return tf.nn.batch_normalization(inputdata, mean, var, beta, gamma, epsilon, name=name)
@staticmethod
def dropout(inputdata, keep_prob, noise_shape=None, name=None):
"""
:param name:
:param inputdata:
| tensorflow.reshape | 2,600 |
import tensorflow as tf
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)
| tensorflow.reshape | 2,601 |
import tensorflow as tf
return loss, active_loss, summaries
hard_negative_loss, hard_negative_active_loss, hard_negative_summaries = (
compute_loss_and_create_summaries(use_semi_hard=False))
(semi_hard_negative_loss, semi_hard_negative_active_loss,
semi_hard_negative_summaries) = (
compute_loss_and_create_summaries(use_semi_hard=True))
summaries = {
'triplet_loss/Margin':
tf.constant(margin),
'triplet_loss/Anchor/Positive/Distance/Mean':
tf.math.reduce_mean(anchor_positive_distances),
'triplet_mining/Anchor/Positive/Distance/Mean':
tf.math.reduce_mean(anchor_positive_mining_distances),
}
if summarize_percentiles:
summaries.update({
'triplet_loss/Anchor/Positive/Distance/Median':
tfp.stats.percentile(anchor_positive_distances, q=50),
'triplet_mining/Anchor/Positive/Distance/Median':
| tensorflow.constant | 2,602 |
import tensorflow as tf
def test_and_valid(test_loop=1,valid_loop=1,test_num=64,valid_num=64):
feed_dict={
testnum: test_num,
validnum: valid_num
}
with tf.Session(config=config) as sess:
sess.run(init)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
tf.train.Saver().restore(sess,path)
#test
| tensorflow.Session | 2,603 |
import tensorflow as tf
tgtctx_h3 = lrelu(conv2d(tgtctx_h2, self.df_dim*8, name='h3_conv'))
tgtctx_h4 = lrelu(linear(tf.reshape(tgtctx_h3, [self.batch_size, -1]), featsize, 'h4_lin'))
tgtctx_z = linear(tgtctx_h4, featsize, 'hz_lin')
with tf.variable_scope("conv") as scope:
srcimg_h0 = lrelu(conv2d(srcimg, self.df_dim, name='h0_conv'))
srcimg_h1 = lrelu(conv2d(srcimg_h0, self.df_dim*2, name='h1_conv'))
srcimg_h2 = lrelu(conv2d(srcimg_h1, self.df_dim*4, name='h2_conv'))
srcimg_h3 = lrelu(conv2d(srcimg_h2, self.df_dim*8, name='h3_conv'))
print(srcimg_h3.get_shape())
srcimg_h4 = lrelu(linear(tf.reshape(srcimg_h3, [self.batch_size, -1]), featsize, 'h4_lin'))
srcimg_z = lrelu(linear(srcimg_h4, featsize, 'hz_lin'))
scope.reuse_variables()
tgtimg_h0 = lrelu(conv2d(tgtimg, self.df_dim, name='h0_conv'))
tgtimg_h1 = lrelu(conv2d(tgtimg_h0, self.df_dim*2, name='h1_conv'))
tgtimg_h2 = lrelu(conv2d(tgtimg_h1, self.df_dim*4, name='h2_conv'))
tgtimg_h3 = lrelu(conv2d(tgtimg_h2, self.df_dim*8, name='h3_conv'))
tgtimg_h4 = lrelu(linear(tf.reshape(tgtimg_h3, [self.batch_size, -1]), featsize, 'h4_lin'))
| tensorflow.reshape | 2,604 |
import tensorflow as tf
return (loss, i + 1)
# def sample_compute(i):
# batch1 = tf.gather(batch, tf.random.shuffle(index))
# batch2 = tf.gather(batch, tf.random.shuffle(index))
# pred1 = tf.slice(batch1, [0, 0], [num_sam, 1])
# pred2 = tf.slice(batch2, [0, 0], [num_sam, 1])
# tgt1 = tf.slice(batch1, [0, 1], [num_sam, 1])
# tgt2 = tf.slice(batch2, [0, 1], [num_sam, 1])
# loss = compute_contra_loss(pred1, pred2, tgt1, tgt2)
# print(loss)
# return loss
i = tf.constant(0)
loss = tf.constant(0.)
final_loss = tf.while_loop(lambda l, i: i < resample, sample_compute, [loss, i])[0]
# final_loss = tf.scan(sample_compute, tf.range(resample), loss)[-1]
# final_loss = tf.map_fn(fn=lambda inp: sample_compute(inp), elems= tf.range(resample), dtype=tf.float32, parallel_iterations=1)
# print('final', final_loss)
# final_loss = loss
avg_loss = tf.reduce_mean(final_loss) / divider
# p = tf.print('cur_loss', [final_loss, avg_loss])
# with tf.control_dependencies([p]):
# avg_loss = tf.identity(avg_loss)
# print(final_loss, avg_loss)
# p = tf.print('debug loss ', [final_loss, avg_loss])
# with tf.control_dependencies([p]):
# avg_loss = 1. * avg_loss
# print(avg_loss)
# exit()
| tensorflow.while_loop | 2,605 |
import tensorflow as tf
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, '')
| tensorflow.app.flags.DEFINE_float | 2,606 |
import tensorflow as tf
# (T,B,D) => (B,T,D)
facts = tf.array_ops.transpose(facts, [1, 0, 2])
# Trainable parameters
facts_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer
querry_size = query.get_shape().as_list()[-1]
query = tf.layers.dense(query, facts_size, activation=None, name='f1' + stag)
query = prelu(query)
queries = tf.tile(query, [1, tf.shape(facts)[1]])
queries = tf.reshape(queries, tf.shape(facts))
din_all = tf.concat([queries, facts, queries-facts, queries*facts], axis=-1)
d_layer_1_all = tf.layers.dense(din_all, 80, activation=tf.nn.sigmoid, name='f1_att' + stag)
d_layer_2_all = tf.layers.dense(d_layer_1_all, 40, activation=tf.nn.sigmoid, name='f2_att' + stag)
d_layer_3_all = tf.layers.dense(d_layer_2_all, 1, activation=None, name='f3_att' + stag)
d_layer_3_all = tf.reshape(d_layer_3_all, [-1, 1, tf.shape(facts)[1]])
scores = d_layer_3_all
# Mask
if mask is not None:
# key_masks = tf.sequence_mask(facts_length, tf.shape(facts)[1]) # [B, T]
key_masks = tf.expand_dims(mask, 1) # [B, 1, T]
paddings = tf.ones_like(scores) * (-2 ** 32 + 1)
if not forCnn:
scores = tf.where(key_masks, scores, paddings) # [B, 1, T]
| tensorflow.layers.dense | 2,607 |
import tensorflow as tf
# data processing
inputs_list = []
for i in range(num_gpu):
img = tf.expand_dims(img_batch[i], axis=0)
pretrain_zoo = PretrainModelZoo()
if self.cfgs.NET_NAME in pretrain_zoo.pth_zoo or self.cfgs.NET_NAME in pretrain_zoo.mxnet_zoo:
img = img / tf.constant([cfgs.PIXEL_STD])
gtboxes_and_label_r = tf.py_func(backward_convert,
inp=[gtboxes_and_label_batch[i]],
Tout=tf.float32)
gtboxes_and_label_r = tf.reshape(gtboxes_and_label_r, [-1, 6])
gtboxes_and_label_h = get_horizen_minAreaRectangle(gtboxes_and_label_batch[i])
gtboxes_and_label_h = tf.reshape(gtboxes_and_label_h, [-1, 5])
num_objects = num_objects_batch[i]
| tensorflow.py_func | 2,608 |
import tensorflow as tf
'The values of learning_rate decay factor for each segment between boundaries (comma-separated list).')
# checkpoint related configuration
tf.app.flags.DEFINE_string(
'checkpoint_path', './model/resnet50',#None,
'The path to a checkpoint from which to fine-tune.')
tf.app.flags.DEFINE_string(
'checkpoint_model_scope', '',
'Model scope in the checkpoint. None if the same as the trained model.')
tf.app.flags.DEFINE_string(
'model_scope', 'xdet_resnet',
'Model scope name used to replace the name_scope in checkpoint.')
tf.app.flags.DEFINE_string(
'checkpoint_exclude_scopes', 'xdet_resnet/xdet_head, xdet_resnet/xdet_multi_path, xdet_resnet/xdet_additional_conv',#None
'Comma-separated list of scopes of variables to exclude when restoring from a checkpoint.')
tf.app.flags.DEFINE_boolean(
'ignore_missing_vars', True,
| tensorflow.app.flags.DEFINE_string | 2,609 |
import tensorflow as tf
# use the initializers from torch
with argscope([Conv2D, Deconv2D], use_bias=False,
W_init=tf.random_normal_initializer(stddev=0.02)), \
argscope([Conv2D, Deconv2D, InstanceNorm], data_format='NCHW'), \
argscope(LeakyReLU, alpha=0.2):
with tf.variable_scope('gen'):
with tf.variable_scope('B'):
AB = self.generator(A)
with tf.variable_scope('A'):
BA = self.generator(B)
ABA = self.generator(AB)
with tf.variable_scope('B'):
BAB = self.generator(BA)
viz3('A_recon', A, AB, ABA)
viz3('B_recon', B, BA, BAB)
| tensorflow.variable_scope | 2,610 |
import tensorflow as tf
def cw_1d(X, y=None):
def N0(mean, variance):
return 1.0/(tf.sqrt(2.0 * m.pi * variance)) * tf.exp((-(mean**2))/(2*variance))
N = tf.cast(tf.shape(X)[0], tf.float32)
if y is None:
y = silverman_rule_of_thumb(N)
A = tf.subtract(tf.expand_dims(X, 0), tf.expand_dims(X, 1))
return (1.0/(N*N)) * tf.reduce_sum(N0(A, 2*y)) + N0(0.0, 2.0 + 2*y) - (2/N) * tf.reduce_sum(N0(X, 1.0 + 2*y))
| tensorflow.shape | 2,611 |
import tensorflow as tf
inc = tf.matmul(eigvec, tf.reshape(v, [3, 1]))
image = tf.cast(tf.cast(image, tf.float32) + tf.reshape(inc, [3]), image.dtype)
| tensorflow.reshape | 2,612 |
import tensorflow as tf
best_trial_info_file = os.path.join(FLAGS.output_dir, "best_trial.txt")
def _best_trial_info():
"""Returns information about which checkpoints have been evaled so far."""
if tf.gfile.Exists(best_trial_info_file):
with tf.gfile.GFile(best_trial_info_file, "r") as best_info:
global_step, best_metric_global_step, metric_value = (
best_info.read().split(":"))
global_step = int(global_step)
| tensorflow.gfile.Exists | 2,613 |
import tensorflow as tf
print("Optional Shortcut:", shortcut.get_shape())
print("-"*5)
return inputs + shortcut
return inputs
# Three types of downsampling methods described by paper
def downsampling(inputs, downsampling_type, name, optional_shortcut=False, shortcut=None):
# k-maxpooling
if downsampling_type=='k-maxpool':
k = math.ceil(int(inputs.get_shape()[1]) / 2)
pool = tf.nn.top_k(tf.transpose(inputs, [0,2,1]), k=k, name=name, sorted=False)[0]
pool = tf.transpose(pool, [0,2,1])
# Linear
elif downsampling_type=='linear':
pool = tf.layers.conv1d(inputs=inputs, filters=inputs.get_shape()[2], kernel_size=3,
strides=2, padding='same', use_bias=False)
# Maxpooling
else:
pool = tf.layers.max_pooling1d(inputs=inputs, pool_size=3, strides=2, padding='same', name=name)
if optional_shortcut:
| tensorflow.transpose | 2,614 |
from tensorflow.python.training import server_lib
port1 = get_open_port()
port2 = get_open_port()
cs = server_lib.ClusterSpec({
"worker": ["localhost:%s" % port1],
"ps": ["localhost:%s" % port2]
})
worker = server_lib.Server(cs, job_name="worker", start=True)
ps = server_lib.Server(cs, job_name="ps", start=True)
return worker, ps
@contextlib.contextmanager
def _maybeWithDevice(self, device):
| tensorflow.python.training.server_lib.Server | 2,615 |
import tensorflow as tf
# the post-processed predictions to generate masks.
# Generate detections one image at a time.
class_outputs, box_outputs, box_rois = (
mask_rcnn_architecture.faster_rcnn_fn(
fpn_feats, rpn_score_outputs, rpn_box_outputs,
all_anchors, features['image_info'], params,
is_training=False))
batch_size, _, _ = class_outputs.get_shape().as_list()
detections = []
softmax_class_outputs = tf.nn.softmax(class_outputs)
for i in range(batch_size):
detections.append(
anchors.generate_detections_per_image_op(
softmax_class_outputs[i], box_outputs[i], box_rois[i],
features['source_ids'][i], features['image_info'][i],
params['test_detections_per_image'],
params['test_rpn_post_nms_topn'], params['test_nms'],
params['bbox_reg_weights'])
)
| tensorflow.nn.softmax | 2,616 |
import tensorflow as tf
elif activation == 'sigmoid':
layer_out = tf.nn.sigmoid(layer_out)
elif activation == 'tanh':
layer_out = tf.nn.tanh(layer_out)
else:
raise NotImplementedError('activation not recognized')
| tensorflow.nn.tanh | 2,617 |
import tensorflow as tf
if __name__ == "__main__":
tf.test.main()
| tensorflow.test.main | 2,618 |
from tensorflow.python.framework import ops
and substitue the input with a place holder.
Each captured input's corresponding place holder is converted into a
function argument and the caller passes in the captured tensor.
"""
def __init__(self, *args, **kwargs):
super(_FuncGraph, self).__init__(*args, **kwargs)
self._building_function = True
self._outer_graph = ops.get_default_graph()
self._vscope = vs.get_variable_scope()
self._old_custom_getter = self._vscope.custom_getter
self._captured = {}
self.extra_inputs = []
self.extra_args = []
self.extra_vars = []
def getvar(self,
| tensorflow.python.framework.ops.get_default_graph | 2,619 |
import tensorflow as tf
wh = tf.get_variable("wh", [nh, nh*4], initializer=ortho_init(init_scale))
gh = tf.get_variable("gh", [nh*4], initializer=tf.constant_initializer(1.0))
bh = tf.get_variable("bh", [nh*4], initializer=tf.constant_initializer(0.0))
b = tf.get_variable("b", [nh*4], initializer=tf.constant_initializer(0.0))
gc = tf.get_variable("gc", [nh], initializer=tf.constant_initializer(1.0))
bc = tf.get_variable("bc", [nh], initializer=tf.constant_initializer(0.0))
c, h = tf.split(axis=1, num_or_size_splits=2, value=s)
for idx, (x, m) in enumerate(zip(xs, ms)):
c = c*(1-m)
h = h*(1-m)
z = _ln(tf.matmul(x, wx), gx, bx) + _ln(tf.matmul(h, wh), gh, bh) + b
| tensorflow.constant_initializer | 2,620 |
import tensorflow as tf
def print_all_variables(train_only=True):
'''
Print all trainable and non-trainable variables
'''
if train_only:
t_vars = tf.trainable_variables()
print('[*] printing trainable variables')
else:
try:
t_vars = tf.global_variables()
except:
t_vars = tf.all_variables()
print('[*] printing global variables')
for idx, v in enumerate(t_vars):
print(' var {:3}: {:15} {}'.format(idx, str(v.get_shape()), v.name))
| tensorflow.global_variables | 2,621 |
import tensorflow as tf
inputs=inputs, filter_depth=filter_depth1, kernel_size=1,
stride=1, padding="same",
)
x = self.__batch_norm("{}2a".format(bn_name_base), x)
x = tf.nn.relu(x)
x = self.__conv2d(
name="{}2b".format(conv_name_base),
inputs=x, filter_depth=filter_depth2, kernel_size=kernel_size,
| tensorflow.nn.relu | 2,622 |
import tensorflow as tf
facts = tf.expand_dims(facts, 1)
if time_major:
# (T,B,D) => (B,T,D)
facts = tf.array_ops.transpose(facts, [1, 0, 2])
# Trainable parameters
mask = tf.equal(mask, tf.ones_like(mask))
facts_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer
querry_size = query.get_shape().as_list()[-1]
query = tf.layers.dense(query, facts_size, activation=None, name='f1' + stag)
query = prelu(query)
queries = tf.tile(query, [1, tf.shape(facts)[1]])
queries = tf.reshape(queries, tf.shape(facts))
din_all = tf.concat([queries, facts, queries-facts, queries*facts], axis=-1)
d_layer_1_all = tf.layers.dense(din_all, 80, activation=tf.nn.sigmoid, name='f1_att' + stag)
d_layer_2_all = tf.layers.dense(d_layer_1_all, 40, activation=tf.nn.sigmoid, name='f2_att' + stag)
d_layer_3_all = tf.layers.dense(d_layer_2_all, 1, activation=None, name='f3_att' + stag)
d_layer_3_all = tf.reshape(d_layer_3_all, [-1, 1, tf.shape(facts)[1]])
scores = d_layer_3_all
# Mask
# key_masks = tf.sequence_mask(facts_length, tf.shape(facts)[1]) # [B, T]
key_masks = tf.expand_dims(mask, 1) # [B, 1, T]
paddings = tf.ones_like(scores) * (-2 ** 32 + 1)
if not forCnn:
scores = tf.where(key_masks, scores, paddings) # [B, 1, T]
# Scale
# scores = scores / (facts.get_shape().as_list()[-1] ** 0.5)
# Activation
| tensorflow.layers.dense | 2,623 |
import tensorflow as tf
with tf.compat.v1.name_scope(name, 'sum'):
if reduce_instance_dims:
x = tf.reduce_sum(input_tensor=tf_utils.get_values(x))
elif isinstance(x, tf.SparseTensor):
if x.dtype == tf.uint8 or x.dtype == tf.uint16:
x = tf.cast(x, tf.int64)
elif x.dtype == tf.uint32 or x.dtype == tf.uint64:
TypeError('Data type %r is not supported' % x.dtype)
x = tf.sparse.reduce_sum(x, axis=0)
elif isinstance(x, tf.RaggedTensor):
| tensorflow.cast | 2,624 |
import tensorflow as tf
self.yp1 = tf.argmax(tf.reduce_max(outer, axis=2), axis=1)
self.yp2 = tf.argmax(tf.reduce_max(outer, axis=1), axis=1)
losses = tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=logits1, labels=self.y1)
losses2 = tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=logits2, labels=self.y2)
self.loss = tf.reduce_mean(losses + losses2)
if config.l2_norm is not None:
variables = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)
l2_loss = tf.contrib.layers.apply_regularization(regularizer, variables)
self.loss += l2_loss
if config.decay is not None:
self.var_ema = tf.train.ExponentialMovingAverage(config.decay)
ema_op = self.var_ema.apply(tf.trainable_variables())
with tf.control_dependencies([ema_op]):
self.loss = tf.identity(self.loss)
self.assign_vars = []
| tensorflow.contrib.layers.apply_regularization | 2,625 |
import tensorflow as tf
def __init__(self, model_fn, params):
self._model_dir = params.model_dir
# Sets up evaluator.
self._evaluator = factory.evaluator_generator(params.eval)
input_partition_dims = None
num_cores_per_replica = None
if params.use_tpu:
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
params.platform.tpu,
zone=params.platform.tpu_zone,
project=params.platform.gcp_project)
tpu_grpc_url = tpu_cluster_resolver.get_master()
tf.Session.reset(tpu_grpc_url)
# If the input image is transposed (from NHWC to HWCN), the partition
# dimensions also need to be transposed the same way.
def _maybe_transpose(input_partition_dims):
| tensorflow.contrib.cluster_resolver.TPUClusterResolver | 2,626 |
import tensorflow as tf
labeled_boxes_init = tf.gather(
sample['groundtruth_boxes'], axis=1, indices=[1, 0, 3, 2]) * 256.0
for _, metric in self.metrics.items():
if isinstance(metric, ShapeAccuracyMetric):
labels = sample['shapes']
weights = tf.math.sign(labels + 1) # -1 is mapped to zero, else 1
metric.update(labels, detections['shapes_logits'], weights)
elif isinstance(metric, BoxIoUMetric):
scene_id = str(sample['scene_filename'].numpy(), 'utf-8')
# Get ground truth boxes
labeled_boxes = labeled_boxes_init
if metric.threed:
rotations_y = tf.concat([tf_utils.euler_from_rotation_matrix(
tf.reshape(detections['rotations_3d'][i], [3, 3]),
1) for i in range(num_boxes)], axis=0)
rotations_y = tf.reshape(rotations_y, [-1, 1])
labeled_boxes = tf.concat([sample['translations_3d'],
sample['sizes_3d'],
rotations_y], axis=1)
# Get predicted boxes
predicted_boxes = detections['detection_boxes']
if metric.threed:
rotations_y = tf.concat([tf_utils.euler_from_rotation_matrix(
tf.reshape(detections['rotations_3d'][i], [3, 3]),
1) for i in range(num_boxes)], axis=0)
rotations_y = tf.reshape(rotations_y, [-1, 1])
predicted_boxes = tf.concat([detections['translations_3d'],
| tensorflow.reshape | 2,627 |
import tensorflow as tf
def call(
self, inputs: Mapping[str, common_types.TensorType]
) -> Dict[str, common_types.TensorType]:
if self._exported_as_v1 and not ops.executing_eagerly_outside_functions():
tf.compat.v1.logging.warning('Falling back to transform_raw_features...')
return self._tft_output._transform_raw_features_compat_v1( # pylint: disable=protected-access
inputs,
drop_unused_features=True)
else:
| tensorflow.compat.v1.logging.warning | 2,628 |
import tensorflow as tf
inputs=x, filter_depth=filter_depth3, kernel_size=1,
padding="same", stride=1
)
x = self.__batch_norm("{}2c".format(bn_name_base), x)
x = tf.add(x, inputs)
return tf.nn.relu(x)
| tensorflow.add | 2,629 |
import tensorflow as tf
name = 'batch_norm'
with tf.variable_scope(name):
phase_train = tf.convert_to_tensor(phase_train, dtype=tf.bool)
n_out = int(x.get_shape()[3])
beta = tf.Variable(tf.constant(0.0, shape=[n_out], dtype=x.dtype),
name=name+'/beta', trainable=True, dtype=x.dtype)
gamma = tf.Variable(tf.constant(1.0, shape=[n_out], dtype=x.dtype),
name=name+'/gamma', trainable=True, dtype=x.dtype)
batch_mean, batch_var = tf.nn.moments(x, [0,1,2], name='moments')
ema = tf.train.ExponentialMovingAverage(decay=0.9)
def mean_var_with_update():
ema_apply_op = ema.apply([batch_mean, batch_var])
with tf.control_dependencies([ema_apply_op]):
return tf.identity(batch_mean), tf.identity(batch_var)
mean, var = control_flow_ops.cond(phase_train,
mean_var_with_update,
lambda: (ema.average(batch_mean), ema.average(batch_var)))
normed = tf.nn.batch_normalization(x, mean, var, beta, gamma, 1e-3)
return normed
def inception(inp, inSize, ks, o1s, o2s1, o2s2, o3s1, o3s2, o4s1, o4s2, o4s3, poolType, name,
phase_train=True, use_batch_norm=True, weight_decay=0.0):
print('name = ', name)
print('inputSize = ', inSize)
print('kernelSize = {3,5}')
print('kernelStride = {%d,%d}' % (ks,ks))
| tensorflow.identity | 2,630 |
import tensorflow as tf
'weight_decay', 1e-5, 'The weight decay on the model weights.')
tf.app.flags.DEFINE_float(
'mse_weight', 1., 'The weight decay on the model weights.')
tf.app.flags.DEFINE_float(
'momentum', 0.9,
'The momentum for the MomentumOptimizer and RMSPropOptimizer.')
tf.app.flags.DEFINE_float('learning_rate', 1e-4, 'Initial learning rate.')#1e-3
tf.app.flags.DEFINE_float(
'end_learning_rate', 0.000001,
'The minimal end learning rate used by a polynomial decay learning rate.')
tf.app.flags.DEFINE_float(
'warmup_learning_rate', 0.00001,
'The start warm-up learning rate to avoid NAN.')
tf.app.flags.DEFINE_integer(
| tensorflow.app.flags.DEFINE_float | 2,631 |
import tensorflow as tf
# for pred_ind in list(range(len(pred_outputs))):
# bce_loss_list.append(tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=pred_outputs[pred_ind], labels=targets_list[pred_ind]/255., name='loss_{}'.format(pred_ind)), name='loss_mean_{}'.format(pred_ind)))
# mse_loss = tf.multiply(params['mse_weight'] / params['num_stacks'], tf.add_n(bce_loss_list), name='mse_loss')
# tf.summary.scalar('mse', mse_loss)
# tf.losses.add_loss(mse_loss)
# Add weight decay to the loss. We exclude the batch norm variables because
# doing so leads to a small improvement in accuracy.
loss = mse_loss + params['weight_decay'] * tf.add_n([tf.nn.l2_loss(v) for v in tf.trainable_variables() if 'batch_normalization' not in v.name])
total_loss = tf.identity(loss, name='total_loss')
tf.summary.scalar('loss', total_loss)
if mode == tf.estimator.ModeKeys.EVAL:
return tf.estimator.EstimatorSpec(mode=mode, loss=loss, predictions=predictions, eval_metric_ops=metrics)
if mode == tf.estimator.ModeKeys.TRAIN:
global_step = tf.train.get_or_create_global_step()
lr_values = [params['warmup_learning_rate']] + [base_learning_rate * decay for decay in params['lr_decay_factors']]
learning_rate = tf.train.piecewise_constant(tf.cast(global_step, tf.int32),
[params['warmup_steps']] + [int(float(ep)*params['steps_per_epoch']) for ep in params['decay_boundaries']],
| tensorflow.summary.scalar | 2,632 |
from tensorflow.contrib.framework import tensor_util
Returns:
covariance: A `Tensor` representing the current unbiased sample covariance,
`comoment` / (`count` - 1).
update_op: An operation that updates the local variables appropriately.
Raises:
ValueError: If labels and predictions are of different sizes or if either
`metrics_collections` or `updates_collections` are not a list or tuple.
"""
with variable_scope.variable_scope(name, 'covariance', [predictions, labels]):
predictions, labels = tensor_util.remove_squeezable_dimensions(
predictions, labels)
predictions.get_shape().assert_is_compatible_with(labels.get_shape())
count = _create_local('count', [])
mean_prediction = _create_local('mean_prediction', [])
mean_label = _create_local('mean_label', [])
comoment = _create_local('comoment', []) # C_A in update equation
if weights is None:
batch_count = math_ops.to_float(array_ops.size(labels)) # n_B in eqn
| tensorflow.contrib.framework.tensor_util.remove_squeezable_dimensions | 2,633 |
import tensorflow as tf
W = tf.reshape(g, [1, 1, num_filters, 1]) * tf.nn.l2_normalize(V, [0, 1, 3])
# calculate convolutional layer output
x = tf.nn.conv2d_transpose(x, W, target_shape, [1] + list(stride) + [1], padding=pad)
x = tf.nn.bias_add(x, b)
return x
| tensorflow.nn.bias_add | 2,634 |
import tensorflow as tf
o = tf.nn.sigmoid(o)
u = tf.tanh(u)
c = f*c + i*u
h = o*tf.tanh(_ln(c, gc, bc))
xs[idx] = h
s = tf.concat(axis=1, values=[c, h])
return xs, s
def conv_to_fc(x):
nh = np.prod([v.value for v in x.get_shape()[1:]])
| tensorflow.concat | 2,635 |
import tensorflow as tf
tf.summary.histogram('weight', filt)
tf.summary.histogram('bias', conv_biases)
return bias
def conv_bn_relu(self, bottom,name, kernel_size, output_channels, initializer,stride=1, bn=False,training=False,relu=True):
input_channels = bottom.get_shape().as_list()[-1]
with tf.variable_scope(name) as scope:
kernel = self.variable('weights', [kernel_size, kernel_size, input_channels, output_channels], initializer, regularizer=tf.contrib.layers.l2_regularizer(0.0005))
conv = tf.nn.conv2d(bottom, kernel, [1, stride, stride, 1], padding='SAME')
biases = self.variable('biases', [output_channels], tf.constant_initializer(0.0))
conv_layer = tf.nn.bias_add(conv, biases)
if bn:
conv_layer = self.batch_norm_layer('batch_norm_layer',conv_layer,training)
if relu:
conv_layer = tf.nn.relu(conv_layer, name=scope.name)
print('Conv layer {0} -> {1}'.format(bottom.get_shape().as_list(),conv_layer.get_shape().as_list()))
return conv_layer
| tensorflow.nn.conv2d | 2,636 |
from tensorflow.contrib.eager.python import tfe
return self.relu(hidden_states)
def loss(labels, predictions):
"""Computes mean squared loss."""
return tf.reduce_mean(tf.squared_difference(predictions, labels))
def test(model, eval_data):
"""Computes the average loss on eval_data, which should be a Dataset."""
avg_loss = tfe.metrics.Mean("loss")
for (labels, chars, sequence_length) in tfe.Iterator(eval_data):
predictions = model((chars, sequence_length), training=False)
avg_loss(loss(labels, predictions))
print("eval/loss: %.6f\n" % avg_loss.result())
with tf.contrib.summary.always_record_summaries():
tf.contrib.summary.scalar("loss", avg_loss.result())
def train_one_epoch(model, optimizer, train_data, log_interval=10):
"""Trains model on train_data using optimizer."""
| tensorflow.contrib.eager.python.tfe.Iterator | 2,637 |
import tensorflow as tf
def testEmbeddingAttentionDecoder(self):
with self.test_session() as sess:
with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)):
inp = [tf.constant(0.5, shape=[2, 2])] * 2
cell = tf.nn.rnn_cell.GRUCell(2)
enc_outputs, enc_state = tf.nn.rnn(cell, inp, dtype=tf.float32)
attn_states = tf.concat(1, [tf.reshape(e, [-1, 1, cell.output_size])
for e in enc_outputs])
dec_inp = [tf.constant(i, tf.int32, shape=[2]) for i in range(3)]
dec, mem = tf.nn.seq2seq.embedding_attention_decoder(
dec_inp, enc_state, attn_states, cell, num_symbols=4,
embedding_size=2, output_size=3)
sess.run([tf.global_variables_initializer()])
res = sess.run(dec)
self.assertEqual(3, len(res))
self.assertEqual((2, 3), res[0].shape)
res = sess.run([mem])
self.assertEqual((2, 2), res[0].shape)
def testEmbeddingAttentionSeq2Seq(self):
with self.test_session() as sess:
with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)):
enc_inp = [tf.constant(1, tf.int32, shape=[2]) for i in range(2)]
| tensorflow.global_variables_initializer | 2,638 |
import tensorflow as tf
None.
"""
# placeholder of input images. Currently batch size of one is supported.
x = tf.placeholder(tf.float32, [1, None, None, 3]) # n, h, w, c
# Create the tiny face model which weights are loaded from a pretrained model.
model = tiny_face_model.Model(weight_file_path)
| tensorflow.placeholder | 2,639 |
import tensorflow as tf
"""Defines the model function."""
target_num_classes = FLAGS.target_num_classes
global_step = tf.train.get_global_step()
src_features, src_labels = features['src'], tf.cast(labels['src'], tf.int64)
finetune_features = features['finetune']
target_features = features['target']
| tensorflow.cast | 2,640 |
import tensorflow as tf
from distillation import knowledge_distillation as distill
def correlation(x, y):
x = x - tf.reduce_mean(x, axis=-1, keepdims=True)
y = y - tf.reduce_mean(y, axis=-1, keepdims=True)
x = tf.nn.l2_normalize(x, -1)
y = tf.nn.l2_normalize(y, -1)
return -tf.reduce_sum(x*y, axis=-1) # higher the better
def kd(x, y):
x_prob = tf.nn.softmax(x)
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
def mse(x, y):
x = x - tf.reduce_mean(x, axis=-1, keepdims=True)
y = y - tf.reduce_mean(y, axis=-1, keepdims=True)
return tf.reduce_sum((x-y)**2, axis=-1) # lower the better
def kd_distance(x, y, dist_type):
| tensorflow.nn.softmax | 2,641 |
from tensorflow.python.ops import math_ops
weights: `Tensor` whose shape is broadcastable to the the first [D1, ... DN]
dimensions of `predictions_idx` and `labels`.
name: Name of new variable, and namespace for other dependent ops.
Returns:
A tuple of `Variable` and update `Operation`.
Raises:
ValueError: If `weights` is not `None` and has an incomptable shape.
"""
default_name = _at_k_name('true_positive', k, class_id=class_id)
with ops.name_scope(name, default_name, (predictions_idx, labels)) as scope:
tp = _sparse_true_positive_at_k(
predictions_idx=predictions_idx, labels=labels, class_id=class_id,
weights=weights)
batch_total_tp = math_ops.to_double(math_ops.reduce_sum(tp))
var = contrib_variables.local_variable(
array_ops.zeros([], dtype=dtypes.float64), name=scope)
return var, state_ops.assign_add(var, batch_total_tp, name='update')
def _sparse_false_positive_at_k(predictions_idx,
labels,
class_id=None,
weights=None):
"""Calculates false positives for precision@k.
If `class_id` is specified, calculate binary true positives for `class_id`
only.
| tensorflow.python.ops.math_ops.reduce_sum | 2,642 |
import tensorflow as tf
pi = act_limit * mlp_dropout(x, list(hidden_sizes)+[act_dim], activation, output_activation)
with tf.variable_scope('q'):
q = tf.squeeze(mlp_dropout(tf.concat([x,a], axis=-1), list(hidden_sizes)+[1], activation, None, dropout_rate), axis=1)
with tf.variable_scope('q', reuse=True):
| tensorflow.concat | 2,643 |
import tensorflow as tf
# `is_training` is unknown.
is_training_const = utils.constant_value(is_training)
if is_training_const is None or is_training_const:
update_mean_op, update_second_moment_op = utils.smart_cond(
is_training,
build_update_ops,
build_no_ops,
)
# Every new connection creates a new op which adds its contribution
# to the running average when ran.
tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_mean_op)
tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_second_moment_op)
def _build(self, input_batch, is_training=True, test_local_stats=True):
"""Connects the BatchNorm module into the graph.
Args:
input_batch: A Tensor of arbitrary dimension. By default, the final
dimension is not reduced over when computing the minibatch statistics.
is_training: A boolean to indicate if the module should be connected in
training mode, meaning the moving averages are updated. By default
`True`. Can be a Tensor.
test_local_stats: A boolean to indicate if local batch statistics should
| tensorflow.add_to_collection | 2,644 |
import tensorflow as tf
# Default initial value of ent_coef when learned
init_value = 1.0
if '_' in self.ent_coef:
init_value = float(self.ent_coef.split('_')[1])
assert init_value > 0., "The initial value of ent_coef must be greater than 0"
self.log_ent_coef = tf.get_variable('log_ent_coef', dtype=tf.float32,
initializer=np.log(init_value).astype(np.float32))
self.ent_coef = tf.exp(self.log_ent_coef)
else:
# Force conversion to float
# this will throw an error if a malformed string (different from 'auto')
# is passed
self.ent_coef = float(self.ent_coef)
with tf.variable_scope("target", reuse=False):
| tensorflow.exp | 2,645 |
import tensorflow as tf
outputs = tf.nn.bias_add(outputs, biases)
if bn:
outputs = tf.layers.batch_normalization(outputs, momentum=0.99, epsilon=1e-6, training=is_training)
if activation_fn is not None:
outputs = tf.nn.leaky_relu(outputs, alpha=0.2)
| tensorflow.layers.batch_normalization | 2,646 |
import tensorflow as tf
x = tf.layers.dense(flat_x, 128, activation=tf.nn.relu, name="dense1")
logits = tf.layers.dense(
x, self.hparams.problem.num_actions, name="dense2"
)
logits = tf.expand_dims(logits, axis=1)
logits = clip_logits(logits, self.hparams)
value = tf.layers.dense(x, 1, name="value")
return {"target_policy": logits, "target_value": value}
@registry.register_model
class DenseBitwiseCategoricalPolicy(PolicyBase):
"""Dense network with bitwise input and categorical output."""
| tensorflow.layers.dense | 2,647 |
import tensorflow as tf
ones = tf.ones_like(x_t_flat)
grid = tf.concat([d_t_flat, y_t_flat, x_t_flat, ones], 0)
return grid
def _transform(theta, input_dim, out_size, z_near, z_far):
with tf.variable_scope('_transform'):
num_batch = input_dim.get_shape().as_list()[0]
num_channels = input_dim.get_shape().as_list()[4]
theta = tf.reshape(theta, (-1, 4, 4))
theta = tf.cast(theta, 'float32')
| tensorflow.variable_scope | 2,648 |
import tensorflow as tf
self.summary_tags += tag
self.summary_placeholders[tag] = tf.placeholder('float32', None, name=tag)
| tensorflow.placeholder | 2,649 |
import tensorflow as tf
[batch_size, <= decode_length] if beam_size == 1 or
[batch_size, top_beams, <= decode_length]
"scores": None
"logits": `Tensor` of shape [batch_size, time, 1, 1, vocab_size].
"losses": a dictionary: {loss-name (string): floating point `Scalar`}
}
"""
if not features:
features = {}
inputs_old = None
if "inputs" in features and len(features["inputs"].shape) < 4:
inputs_old = features["inputs"]
features["inputs"] = tf.expand_dims(features["inputs"], 2)
if not self.has_input:
features["partial_targets"] = tf.to_int64(features["inputs"])
# Save the targets in a var and reassign it after the tf.while loop to avoid
# having targets being in a 'while' frame. This ensures targets when used
# in metric functions stays in the same frame as other vars.
targets_old = features.get("targets", None)
target_modality = self._problem_hparams.target_modality
def infer_step(recent_output, recent_logits, unused_loss):
"""Inference step."""
| tensorflow.expand_dims | 2,650 |
from tensorflow.python.platform import tf_logging as logging
self._tensors = []
graph = ops.get_default_graph()
graph_def = graph.as_graph_def()
for node in graph_def.node:
if node.op in self._ignore_ops:
continue
logging.info("op=%s name=%s.", node.op, node.name)
try:
self._tensors.append(graph.get_tensor_by_name(node.name + ":0"))
except KeyError:
pass
| tensorflow.python.platform.tf_logging.info | 2,651 |
import tensorflow as tf
theta = tf.reshape(theta, (-1, 4, 4))
theta = tf.cast(theta, 'float32')
out_depth = out_size[0]
out_height = out_size[1]
out_width = out_size[2]
grid = _meshgrid(out_depth, out_height, out_width, z_near, z_far)
grid = tf.expand_dims(grid, 0)
grid = tf.reshape(grid, [-1])
grid = tf.tile(grid, tf.stack([num_batch]))
grid = tf.reshape(grid, tf.stack([num_batch, 4, -1]))
# Transform A x (x_t', y_t', 1, d_t)^T -> (x_s, y_s, z_s, 1).
t_g = tf.matmul(theta, grid)
z_s = tf.slice(t_g, [0, 0, 0], [-1, 1, -1])
y_s = tf.slice(t_g, [0, 1, 0], [-1, 1, -1])
x_s = tf.slice(t_g, [0, 2, 0], [-1, 1, -1])
z_s_flat = tf.reshape(z_s, [-1])
y_s_flat = tf.reshape(y_s, [-1])
x_s_flat = tf.reshape(x_s, [-1])
input_transformed = _interpolate(input_dim, x_s_flat, y_s_flat, z_s_flat,
out_size)
output = tf.reshape(
| tensorflow.matmul | 2,652 |
import tensorflow as tf
sampled2 = get_stn(image)
# For visualization in tensorboard
with tf.name_scope('visualization'):
padded1 = tf.pad(sampled1, [[0, 0], [HALF_DIFF, HALF_DIFF], [HALF_DIFF, HALF_DIFF], [0, 0]])
padded2 = tf.pad(sampled2, [[0, 0], [HALF_DIFF, HALF_DIFF], [HALF_DIFF, HALF_DIFF], [0, 0]])
img_orig = tf.concat([image[:, :, :, 0], image[:, :, :, 1]], 1) # b x 2h x w
transform1 = tf.concat([padded1[:, :, :, 0], padded1[:, :, :, 1]], 1)
transform2 = tf.concat([padded2[:, :, :, 0], padded2[:, :, :, 1]], 1)
stacked = tf.concat([img_orig, transform1, transform2], 2, 'viz')
tf.summary.image('visualize',
tf.expand_dims(stacked, -1), max_outputs=30)
sampled = tf.concat([sampled1, sampled2], 3, 'sampled_concat')
logits = (LinearWrap(sampled)
.FullyConnected('fc1', out_dim=256, nl=tf.nn.relu)
.FullyConnected('fc2', out_dim=128, nl=tf.nn.relu)
.FullyConnected('fct', out_dim=19, nl=tf.identity)())
tf.nn.softmax(logits, name='prob')
cost = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=label)
cost = tf.reduce_mean(cost, name='cross_entropy_loss')
| tensorflow.expand_dims | 2,653 |
import tensorflow as tf
channel_axis = 3 if data_format == 'channels_last' else 1
in_channel = in_shape[channel_axis]
assert in_channel is not None, "[Deconv2D] Input cannot have unknown channel!"
padding = padding.upper()
if w_init is None:
w_init = tf.contrib.layers.variance_scaling_initializer()
if b_init is None:
b_init = tf.constant_initializer()
ret = tf.layers.conv2d_transpose(inputs=inputdata, filters=out_channel,
kernel_size=kernel_size,
strides=stride, padding=padding,
data_format=data_format,
activation=activation, use_bias=use_bias,
kernel_initializer=w_init,
bias_initializer=b_init, trainable=trainable,
name=name)
return ret
@staticmethod
| tensorflow.layers.conv2d_transpose | 2,654 |
import tensorflow as tf
self.logger.info("applying optimize %s" % self.optim_type)
trainable_vars = tf.trainable_variables()
if self.config.clip_weight:
# clip_weight
tvars = tf.trainable_variables()
grads = tf.gradients(self.loss, tvars)
grads, _ = tf.clip_by_global_norm(grads, clip_norm=self.config.max_norm_grad)
grad_var_pairs = zip(grads, tvars)
| tensorflow.trainable_variables | 2,655 |
import tensorflow as tf
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])
| tensorflow.nn.sigmoid | 2,656 |
import tensorflow as tf
dataset = problem.dataset(mode=tf.estimator.ModeKeys.TRAIN,
data_dir=algorithmic.TinyAlgo.data_dir,
shuffle_files=False)
tensor1 = dataset.make_one_shot_iterator().get_next()["targets"]
tensor2 = dataset.make_one_shot_iterator().get_next()["targets"]
with tf.Session() as sess:
self.assertTrue(assert_tensors_equal(sess, tensor1, tensor2, 20))
def testNoShufflePreprocess(self):
problem = algorithmic.TinyAlgo()
dataset1 = problem.dataset(mode=tf.estimator.ModeKeys.TRAIN,
| tensorflow.Session | 2,657 |
import tensorflow as tf
scaffold_fn=scaffold_fn)
elif mode == tf.estimator.ModeKeys.EVAL:
def metric_fn(per_example_loss, label_ids, logits, is_real_example):
predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)
accuracy = tf.metrics.accuracy(
labels=label_ids, predictions=predictions, weights=is_real_example)
loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example)
| tensorflow.argmax | 2,658 |
import tensorflow as tf
def main(args):
# pass the args as params so the model_fn can use
# the TPU specific args
params = vars(args)
if args.use_tpu:
# additional configs required for using TPUs
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(args.tpu)
tpu_config = tf.contrib.tpu.TPUConfig(
num_shards=8, # using Cloud TPU v2-8
iterations_per_loop=args.save_checkpoints_steps)
# use the TPU version of RunConfig
config = tf.contrib.tpu.RunConfig(
| tensorflow.contrib.cluster_resolver.TPUClusterResolver | 2,659 |
import tensorflow as tf
height = tf.to_float(height)
width = tf.to_float(width)
smallest_side = tf.to_float(smallest_side)
scale = tf.cond(tf.greater(height, width),
lambda: smallest_side / width,
lambda: smallest_side / height)
new_height = tf.to_int32(height * scale)
new_width = tf.to_int32(width * scale)
return new_height, new_width
def _aspect_preserving_resize(image, smallest_side):
"""Resize images preserving the original aspect ratio.
Args:
image: A 3-D image `Tensor`.
| tensorflow.to_int32 | 2,660 |
import tensorflow as tf
context_word_emb = context_word_emb[sentence_offset:sentence_offset + max_training_sentences, :, :]
head_word_emb = head_word_emb[sentence_offset:sentence_offset + max_training_sentences, :, :]
lm_emb = lm_emb[sentence_offset:sentence_offset + max_training_sentences, :, :, :]
char_index = char_index[sentence_offset:sentence_offset + max_training_sentences, :, :]
text_len = text_len[sentence_offset:sentence_offset + max_training_sentences]
speaker_ids = speaker_ids[word_offset: word_offset + num_words]
gold_spans = np.logical_and(gold_ends >= word_offset, gold_starts < word_offset + num_words)
gold_starts = gold_starts[gold_spans] - word_offset
gold_ends = gold_ends[gold_spans] - word_offset
cluster_ids = cluster_ids[gold_spans]
return tokens, context_word_emb, head_word_emb, lm_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids
def get_candidate_labels(self, candidate_starts, candidate_ends, labeled_starts, labeled_ends, labels):
same_start = tf.equal(tf.expand_dims(labeled_starts, 1), tf.expand_dims(candidate_starts, 0)) # [num_labeled, num_candidates]
same_end = tf.equal(tf.expand_dims(labeled_ends, 1), tf.expand_dims(candidate_ends, 0)) # [num_labeled, num_candidates]
same_span = tf.logical_and(same_start, same_end) # [num_labeled, num_candidates]
candidate_labels = tf.matmul(tf.expand_dims(labels, 0), tf.to_int32(same_span)) # [1, num_candidates]
candidate_labels = tf.squeeze(candidate_labels, 0) # [num_candidates]
return candidate_labels
def get_dropout(self, dropout_rate, is_training):
return 1 - (tf.to_float(is_training) * dropout_rate)
def coarse_to_fine_pruning(self, top_span_emb, top_span_mention_scores, c):
k = util.shape(top_span_emb, 0)
top_span_range = tf.range(k) # [k]
antecedent_offsets = tf.expand_dims(top_span_range, 1) - tf.expand_dims(top_span_range, 0) # [k, k]
antecedents_mask = antecedent_offsets >= 1 # [k, k]
| tensorflow.expand_dims | 2,661 |
import tensorflow as tf
output_dim: The PCA output dimension (number of eigenvectors to return).
dtype: Tensorflow dtype of entries in the returned matrix.
name: (Optional) A name for this operation.
Raises:
ValueError: if input is not a rank-2 Tensor.
Returns:
A 2D `Tensor` (matrix) M of shape (input_dim, output_dim).
"""
if not isinstance(x, tf.Tensor):
raise TypeError('Expected a Tensor, but got %r' % x)
with tf.compat.v1.name_scope(name, 'pca'):
x.shape.assert_has_rank(2)
input_dim = x.shape.as_list()[1]
shape = (input_dim, output_dim)
(result,) = _apply_cacheable_combiner(
PCACombiner(shape, output_dim, dtype.as_numpy_dtype), x)
return result
def _maybe_annotate_vocab_metadata(vocab_filename: str,
unfiltered_vocabulary_size: tf.Tensor,
filtered_vocabulary_size: tf.Tensor):
| tensorflow.compat.v1.name_scope | 2,662 |
import tensorflow as tf
intermediate_act_fn=get_activation(config.hidden_act),
hidden_dropout_prob=config.hidden_dropout_prob,
attention_probs_dropout_prob=config.attention_probs_dropout_prob,
initializer_range=config.initializer_range,
do_return_all_layers=True)
self.sequence_output = self.all_encoder_layers[-1]
# The "pooler" converts the encoded sequence tensor of shape
# [batch_size, seq_length, hidden_size] to a tensor of shape
# [batch_size, hidden_size]. This is necessary for segment-level
# (or segment-pair-level) classification tasks where we need a fixed
# dimensional representation of the segment.
with tf.variable_scope("pooler"):
# We "pool" the model by simply taking the hidden state corresponding
# to the first token. We assume that this has been pre-trained
first_token_tensor = tf.squeeze(self.sequence_output[:, 0:1, :], axis=1)
self.pooled_output = tf.layers.dense(
first_token_tensor,
config.hidden_size,
activation=tf.tanh,
kernel_initializer=create_initializer(config.initializer_range))
def get_pooled_output(self):
return self.pooled_output
| tensorflow.variable_scope | 2,663 |
import tensorflow as tf
images,labels=tf.train.batch([image,label],batch_size=batch_size)
return tf.reshape(images,[batch_size,4096]),tf.reshape(labels,[batch_size])
def get_valid_batch(image,label,batch_size):
images,labels=tf.train.batch([image,label],batch_size=batch_size)
return tf.reshape(images,[batch_size,4096]),tf.reshape(labels,[batch_size])
class trainwork(object):
def __init__(self):
with tf.variable_scope('scop'):
self.w1=tf.get_variable('w1', [4096,1024],initializer=tf.contrib.layers.xavier_initializer_conv2d())
self.w2=tf.get_variable('w2', [1024,classnum],initializer=tf.contrib.layers.xavier_initializer_conv2d())
self.b1 = tf.get_variable('b1', [1024],initializer=tf.constant_initializer(0.0))
self.b2 = tf.get_variable('b2', [classnum],initializer=tf.constant_initializer(0.0))
def inference(self,images):
images=tf.cast(images,tf.float32)/255.0
l1 = tf.matmul(images, self.w1)+self.b1
l1=tf.nn.relu(l1)
out = tf.matmul(l1, self.w2)+self.b2
| tensorflow.contrib.layers.xavier_initializer_conv2d | 2,664 |
import tensorflow as tf
dilations=(1, dilation, dilation, 1))
x = x * mask_ratio
if use_bias:
bias = tf.get_variable("bias" + id, [channels], initializer=tf.constant_initializer(0.0))
x = tf.nn.bias_add(x, bias)
return x * update_mask
| tensorflow.constant_initializer | 2,665 |
import tensorflow as tf
q_tp1_best_using_online_net = tf.argmax(double_q_values, axis=1)
q_tp1_best = tf.reduce_sum(target_policy.q_values * tf.one_hot(q_tp1_best_using_online_net, n_actions), axis=1)
else:
q_tp1_best = tf.reduce_max(target_policy.q_values, axis=1)
q_tp1_best_masked = (1.0 - done_mask_ph) * q_tp1_best
| tensorflow.reduce_max | 2,666 |
import tensorflow as tf
'norm_grads']
if self.trust_region:
self.run_ops = run_ops + [norm_grads_q, norm_grads_policy, avg_norm_grads_f, avg_norm_k, avg_norm_g,
avg_norm_k_dot_g, avg_norm_adj]
self.names_ops = names_ops + ['norm_grads_q', 'norm_grads_policy', 'avg_norm_grads_f', 'avg_norm_k',
'avg_norm_g', 'avg_norm_k_dot_g', 'avg_norm_adj']
self.train_model = train_model
self.step_model = step_model
self.step = step_model.step
self.proba_step = step_model.proba_step
self.initial_state = step_model.initial_state
tf.global_variables_initializer().run(session=self.sess)
self.summary = tf.summary.merge_all()
def _train_step(self, obs, actions, rewards, dones, mus, states, masks, steps, writer=None):
"""
applies a training step to the model
:param obs: ([float]) The input observations
:param actions: ([float]) The actions taken
:param rewards: ([float]) The rewards from the environment
:param dones: ([bool]) Whether or not the episode is over (aligned with reward, used for reward calculation)
:param mus: ([float]) The logits values
:param states: ([float]) The states (used for recurrent policies)
:param masks: ([bool]) Whether or not the episode is over (used for recurrent policies)
:param steps: (int) the number of steps done so far (can be None)
:param writer: (TensorFlow Summary.writer) the writer for tensorboard
| tensorflow.summary.merge_all | 2,667 |
import tensorflow as tf
mapper = fbresnet_mapper(isTrain)
if parallel is None:
parallel = min(40, multiprocessing.cpu_count() // 2) # assuming hyperthreading
imglist = get_imglist(datadir, name)
N = len(imglist)
filenames = tf.constant([k[0] for k in imglist], name='filenames')
labels = tf.constant([k[1] for k in imglist], dtype=tf.int32, name='labels')
ds = tf.data.Dataset.from_tensor_slices((filenames, labels))
if isTrain:
| tensorflow.constant | 2,668 |
import tensorflow as tf
futures.append(tp.apply_async(session.run, [output]))
for i, future in enumerate(futures):
result = future.get()
self.assertAllEqual([[i * 2] * 5], result)
def test_input_batch_size_should_be_one(self):
with self.test_session() as session:
@dynamic_batching.batch_fn
def f(a):
return a
output = f(tf.constant([1, 2]))
coord = tf.train.Coordinator()
tf.train.start_queue_runners(coord=coord)
with self.assertRaises(tf.errors.CancelledError):
session.run(output)
with self.assertRaisesRegexp(tf.errors.InvalidArgumentError,
'requires batch size 1'):
coord.join()
def test_run_after_error_should_be_cancelled(self):
with self.test_session() as session:
@dynamic_batching.batch_fn
| tensorflow.train.Coordinator | 2,669 |
import tensorflow.contrib.graph_editor as ge
deps[o] = set(op.inputs)
sorted_ts = toposort(deps)
# only keep the tensors from our original list
ts_sorted_lists = []
for l in sorted_ts:
keep = list(set(l).intersection(ts))
if keep:
ts_sorted_lists.append(keep)
return ts_sorted_lists
def fast_backward_ops(within_ops, seed_ops, stop_at_ts):
bwd_ops = set(ge.get_backward_walk_ops(seed_ops, stop_at_ts=stop_at_ts))
ops = bwd_ops.intersection(within_ops).difference([t.op for t in stop_at_ts])
return list(ops)
@contextlib.contextmanager
def capture_ops():
"""Decorator to capture ops created in the block.
with capture_ops() as ops:
# create some ops
print(ops) # => prints ops created.
"""
micros = int(time.time()*10**6)
| tensorflow.contrib.graph_editor.get_backward_walk_ops | 2,670 |
import tensorflow as tf
adv_image = tf.placeholder(tf.float32, shape=[hps.batch_size, image_size, image_size,
num_channel]) ############MNIST and CIFAR10 are different ar here
predict = tf.placeholder(tf.float32, shape=[hps.batch_size, 10])
predict_nor, tsne_logit_nor = models(hps, image, FLAGS.RCE_train, logits=False, tsne_logits=True)
predict_adv, tsne_logit_adv = models(hps, adv_image, FLAGS.RCE_train, logits=False, tsne_logits=True)
# Calculate entropy
argmax_y_onehot = tf.one_hot(tf.argmax(predict, 1), 10, on_value=0.0, off_value=1.0, axis=-1)
normalized_y_nonmaximal = tf.reduce_sum(predict * argmax_y_onehot, 1)
entropy = tf.reduce_sum(-tf.log(predict) * predict * argmax_y_onehot, 1) / normalized_y_nonmaximal + tf.log(
normalized_y_nonmaximal)
for k in range(10):
adv_image_craft = adv_craft_func(hps, image, FLAGS.attack_method, eps=0.02 * k + 0.02, RCE_train=FLAGS.RCE_train)
#adv_image_craft = adv_craft_func(hps, image, FLAGS.attack_method, eps=0.04,RCE_train=FLAGS.RCE_train)
sess.run(tf.global_variables_initializer())
| tensorflow.reduce_sum | 2,671 |
import tensorflow as tf
Returns:
A tensor with the kappa loss.
"""
with tf.name_scope(name):
labels = tf.to_float(labels)
repeat_op = tf.to_float(
tf.tile(tf.reshape(tf.range(0, num_ratings), [num_ratings, 1]), [1, num_ratings]))
repeat_op_sq = tf.square((repeat_op - tf.transpose(repeat_op)))
weights = repeat_op_sq / tf.to_float((num_ratings - 1)**2)
pred_ = predictions**y_pow
try:
pred_norm = pred_ / \
(eps + tf.reshape(tf.reduce_sum(pred_, 1), [-1, 1]))
except Exception:
pred_norm = pred_ / \
(eps + tf.reshape(tf.reduce_sum(pred_, 1), [batch_size, 1]))
hist_rater_a = tf.reduce_sum(pred_norm, 0)
hist_rater_b = tf.reduce_sum(labels, 0)
conf_mat = tf.matmul(tf.transpose(pred_norm), labels)
nom = tf.reduce_sum(weights * conf_mat)
denom = tf.reduce_sum(weights * tf.matmul(
tf.reshape(hist_rater_a, [num_ratings, 1]), tf.reshape(hist_rater_b, [1, num_ratings])) /
| tensorflow.reduce_sum | 2,672 |
import tensorflow.contrib.graph_editor as ge
for op in all_ops:
for o in op.outputs:
deps[o] = set(op.inputs)
sorted_ts = toposort(deps)
# only keep the tensors from our original list
ts_sorted_lists = []
for l in sorted_ts:
keep = list(set(l).intersection(ts))
if keep:
ts_sorted_lists.append(keep)
return ts_sorted_lists
def fast_backward_ops(within_ops, seed_ops, stop_at_ts):
bwd_ops = set(ge.get_backward_walk_ops(seed_ops, stop_at_ts=stop_at_ts))
ops = bwd_ops.intersection(within_ops).difference([t.op for t in stop_at_ts])
return list(ops)
@contextlib.contextmanager
def capture_ops():
"""Decorator to capture ops created in the block.
with capture_ops() as ops:
# create some ops
print(ops) # => prints ops created.
"""
micros = int(time.time()*10**6)
scope_name = str(micros)
op_list = []
| tensorflow.contrib.graph_editor.get_backward_walk_ops | 2,673 |
import tensorflow as tf
other_tensors = [tf.reshape(monitor_dict[key], [1]) for key in metric_names]
return host_call_fn, [global_step_tensor] + other_tensors
def two_stream_loss(FLAGS, features, labels, mems, is_training):
"""Pretraining loss with two-stream attention Transformer-XL."""
#### Unpack input
mem_name = "mems"
mems = mems.get(mem_name, None)
inp_k = tf.transpose(features["input_k"], [1, 0])
inp_q = tf.transpose(features["input_q"], [1, 0])
seg_id = tf.transpose(features["seg_id"], [1, 0])
inp_mask = None
perm_mask = tf.transpose(features["perm_mask"], [1, 2, 0])
if FLAGS.num_predict is not None:
# [num_predict x tgt_len x bsz]
target_mapping = tf.transpose(features["target_mapping"], [1, 2, 0])
else:
target_mapping = None
# target for LM loss
tgt = tf.transpose(features["target"], [1, 0])
# target mask for LM loss
| tensorflow.transpose | 2,674 |
import tensorflow as tf
tf.train.init_from_checkpoint(ckpt_dir,
{'main_level/agent/online/network_0/': 'main_level/agent/online/network_0'})
tf.train.init_from_checkpoint(ckpt_dir,
{'main_level/agent/online/network_1/': 'main_level/agent/online/network_1'})
# Create a new session with a new tf graph.
sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
sess.run(tf.global_variables_initializer()) # initialize the checkpoint.
# This is the node that will accept the input.
input_nodes = tf.get_default_graph().get_tensor_by_name('main_level/agent/main/online/' + \
'network_0/observation/observation:0')
# This is the node that will produce the output.
output_nodes = tf.get_default_graph().get_operation_by_name('main_level/agent/main/online/' + \
| tensorflow.global_variables_initializer | 2,675 |
from tensorflow.python.summary import summary
(", ".join(OPTIMIZER_SUMMARIES), summ))
if learning_rate is not None and learning_rate_decay_fn is not None:
if global_step is None:
raise ValueError("global_step is required for learning_rate_decay_fn.")
lr = learning_rate_decay_fn(lr, global_step)
if "learning_rate" in summaries:
summary.scalar("learning_rate", lr)
# Create optimizer, given specified parameters.
if isinstance(optimizer, six.string_types):
if lr is None:
raise ValueError("Learning rate is None, but should be specified if "
| tensorflow.python.summary.summary.scalar | 2,676 |
import tensorflow as tf
with tf.variable_scope("loss"):
if is_training:
# I.e., 0.1 dropout
output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
logits = tf.reduce_sum(tf.multiply(output_layer,output_weights),-1)
logits = tf.add(logits, output_bias)
| tensorflow.nn.dropout | 2,677 |
import tensorflow as tf
block_ch *= 2
w >>= 1
h >>= 1
with tf.variable_scope('reduction_cell'):
if use_dynamic_arch:
self._add_dynamic_cell(reduction_arch, layers, w, h, block_ch, drop_path_keep_prob, is_train)
else:
self._add_static_cell(reduction_arch, layers, w, h, block_ch, drop_path_keep_prob, is_train,
is_reduction=True)
else:
with tf.variable_scope('normal_cell'):
if use_dynamic_arch:
self._add_dynamic_cell(normal_arch, layers, w, h, block_ch, drop_path_keep_prob, is_train)
else:
self._add_static_cell(normal_arch, layers, w, h, block_ch, drop_path_keep_prob, is_train)
# Maybe add auxiliary heads
if l in aux_head_layers:
with tf.variable_scope('aux_head'):
aux_logits = self._add_aux_head(*layers[-1], K, is_train)
aux_logits_list.append(aux_logits)
| tensorflow.variable_scope | 2,678 |
import tensorflow as tf
shape[1] = hparams.max_length
v.set_shape(shape)
else:
shape = logits.get_shape().as_list()
if shape[0] is None:
shape[0] = params["batch_size"]
if shape[1] is None:
shape[1] = hparams.max_length
logits.set_shape(shape)
assert "training" in losses_dict
# Summarize losses
with tf.name_scope("losses"):
for loss_name, loss_val in losses_dict.items():
tf.summary.scalar(loss_name, loss_val)
# Accumulate losses
loss = sum(losses_dict.values())
# EVAL mode
if mode == tf.estimator.ModeKeys.EVAL:
return model.estimator_spec_eval(features, logits, labels, loss,
losses_dict)
# TRAIN mode
assert mode == tf.estimator.ModeKeys.TRAIN
num_async_replicas = (1 if (use_tpu or not config) else
config.t2t_device_info["num_async_replicas"])
return model.estimator_spec_train(
| tensorflow.summary.scalar | 2,679 |
import tensorflow as tf
y_w_diff = y[:, :, 1:] - y[:, :, :-1]
h_diff = tf.abs(tf.abs(x_h_diff) - tf.abs(y_h_diff))
w_diff = tf.abs(tf.abs(x_w_diff) - tf.abs(y_w_diff))
return h_diff + tf.transpose(w_diff)
def leaky_relu(x, leak=0.2, name='leaky_relu'):
with tf.variable_scope(name):
f1 = 0.5 * (1 + leak)
f2 = 0.5 * (1 - leak)
return f1 * x + f2 * abs(x)
def linear(x, shape, name, bias=False):
| tensorflow.variable_scope | 2,680 |
import tensorflow as tf
m = mlp(n, 'mlp', nx*4, train=train)
h = norm(n+m, 'ln_2')
return h
def embed(X, we):
#X [-1,,2]
we = convert_gradient_to_tensor(we)
e = tf.gather(we, X)
h = tf.reduce_sum(e, 2)
return h
def clf(x, ny, w_init=tf.random_normal_initializer(stddev=0.02), b_init=tf.constant_initializer(0), train=False):
with tf.variable_scope('clf'):
nx = shape_list(x)[-1]
w = tf.get_variable("w", [nx, ny], initializer=w_init)
b = tf.get_variable("b", [ny], initializer=b_init)
return tf.matmul(x, w)+b
def model(X, M, Y, train=False, reuse=False):
with tf.variable_scope('model', reuse=reuse):
we = tf.get_variable("we", [n_vocab+n_special+n_ctx, n_embd], initializer=tf.random_normal_initializer(stddev=0.02))
we = dropout(we, embd_pdrop, train)
| tensorflow.constant_initializer | 2,681 |
import tensorflow as tf
if len(facts.get_shape().as_list()) == 2:
facts = tf.expand_dims(facts, 1)
if time_major:
# (T,B,D) => (B,T,D)
facts = tf.array_ops.transpose(facts, [1, 0, 2])
# Trainable parameters
facts_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer
querry_size = query.get_shape().as_list()[-1]
query = tf.layers.dense(query, facts_size, activation=None, name='f1' + stag)
| tensorflow.array_ops.transpose | 2,682 |
import tensorflow as tf
act: (tf.Variable, bool, float, bool, float, bool) -> tf.Variable
function to select and action given observation.
` See the top of the file for details.
"""
if param_noise_filter_func is None:
param_noise_filter_func = default_param_noise_filter
with tf.variable_scope(scope, reuse=reuse):
observations_ph = make_obs_ph("observation")
stochastic_ph = tf.placeholder(tf.bool, (), name="stochastic")
update_eps_ph = tf.placeholder(tf.float32, (), name="update_eps")
update_param_noise_threshold_ph = tf.placeholder(tf.float32, (), name="update_param_noise_threshold")
update_param_noise_scale_ph = tf.placeholder(tf.bool, (), name="update_param_noise_scale")
reset_ph = tf.placeholder(tf.bool, (), name="reset")
eps = tf.get_variable("eps", (), initializer=tf.constant_initializer(0))
param_noise_scale = tf.get_variable("param_noise_scale", (), initializer=tf.constant_initializer(0.01), trainable=False)
param_noise_threshold = tf.get_variable("param_noise_threshold", (), initializer=tf.constant_initializer(0.05), trainable=False)
| tensorflow.placeholder | 2,683 |
import tensorflow as tf
# Check that the parameter nodes have been restored.
self.assertEqual(np.int64(15), v.eval())
def testSomeErrors(self):
with tf.Graph().as_default():
v0 = tf.Variable([10.0], name="v0")
v1 = tf.Variable([20.0], name="v1")
v2 = tf.Variable([20.0], name="v2")
v2._set_save_slice_info(tf.Variable.SaveSliceInfo("v1", [1], [0], [1]))
# By default the name used for "v2" will be "v1" and raise an error.
with self.assertRaisesRegexp(ValueError, "same name: v1"):
tf.train.Saver([v0, v1, v2])
# The names are different and will work.
tf.train.Saver({"vee1": v1, "other": [v2]})
def testBasicsWithListOfVariables(self):
save_path = os.path.join(self.get_temp_dir(), "basics_with_list")
with self.test_session(graph=tf.Graph()) as sess:
# Build a graph with 2 parameter nodes, and Save and
# Restore nodes for them.
v0 = tf.Variable(10.0, name="v0")
| tensorflow.train.Saver | 2,684 |
import tensorflow as tf
d_c_real = discriminator_categorical(categorial_distribution)
d_c_fake = discriminator_categorical(encoder_output_label, reuse=True)
# Semi-Supervised Classification Phase
with tf.variable_scope(tf.get_variable_scope()):
encoder_output_label_, _ = encoder(x_input_l, reuse=True, supervised=True)
# Generate output images
| tensorflow.get_variable_scope | 2,685 |
import tensorflow as tf
# Record a short training history.
tf.initialize_all_variables().run()
| tensorflow.initialize_all_variables | 2,686 |
import tensorflow as tf
def metric_fn(per_example_loss, label_ids, logits):
predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)
precision = tf_metrics.precision(label_ids,predictions,11,[1,2,4,5,6,7,8,9],average="macro")
recall = tf_metrics.recall(label_ids,predictions,11,[1,2,4,5,6,7,8,9],average="macro")
f = tf_metrics.f1(label_ids,predictions,11,[1,2,4,5,6,7,8,9],average="macro")
loss = tf.metrics.mean(per_example_loss)
return {
"eval_precision":precision,
"eval_recall":recall,
"eval_f": f,
"eval_loss": loss,
}
eval_metrics = (metric_fn, [per_example_loss, label_ids, logits])
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
eval_metrics=eval_metrics,
scaffold_fn=scaffold_fn)
else:
raise ValueError("Only TRAIN and EVAL modes are supported: %s" % (mode))
return output_spec
return model_fn
def main(_):
| tensorflow.contrib.tpu.TPUEstimatorSpec | 2,687 |
import tensorflow as tf
Raises:
NotImplementedError: If an unsupported optimizer is requested.
"""
# TODO(user): gradient clipping (see Minimize)
if optimizer == 'adagrad':
train_op = tf.train.AdagradOptimizer(learning_rate)
elif optimizer == 'adam':
train_op = tf.train.AdamOptimizer(learning_rate)
elif optimizer == 'momentum':
train_op = tf.train.MomentumOptimizer(learning_rate, momentum)
elif optimizer == 'rmsprop':
| tensorflow.train.AdagradOptimizer | 2,688 |
import tensorflow as tf
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., (tgt_larg - tgt_small) - (pred_larg - pred_small))
if hard_ratio < 1.0:
hard_num = tf.cast(tools.shape(pred1)[0] * hard_ratio, tf.int32)
| tensorflow.maximum | 2,689 |
import tensorflow as tf
return output_tensor
def reshape_from_matrix(output_tensor, orig_shape_list):
"""Reshapes a rank 2 tensor back to its original rank >= 2 tensor."""
if len(orig_shape_list) == 2:
return output_tensor
output_shape = get_shape_list(output_tensor)
orig_dims = orig_shape_list[0:-1]
width = output_shape[-1]
return tf.reshape(output_tensor, orig_dims + [width])
def assert_rank(tensor, expected_rank, name=None):
"""Raises an exception if the tensor rank is not of the expected rank.
Args:
tensor: A tf.Tensor to check the rank of.
expected_rank: Python integer or list of integers, expected rank.
name: Optional name of the tensor for the error message.
Raises:
ValueError: If the expected shape doesn't match the actual shape.
| tensorflow.reshape | 2,690 |
import tensorflow as tf
def __call__(self, global_step):
global_step = tf.cast(global_step, dtype=tf.float32)
warmup_lr = self._params.warmup_learning_rate
warmup_steps = self._params.warmup_steps
init_lr = self._params.init_learning_rate
total_steps = self._total_steps
linear_warmup = (
warmup_lr + global_step / warmup_steps * (init_lr - warmup_lr))
cosine_learning_rate = (
init_lr * (tf.cos(np.pi * (global_step - warmup_steps) /
(total_steps - warmup_steps)) + 1.0) / 2.0)
learning_rate = tf.where(global_step < warmup_steps, linear_warmup,
cosine_learning_rate)
return learning_rate
def get_config(self):
return {'_params': self._params.as_dict()}
def learning_rate_generator(total_steps, params):
"""The learning rate function generator."""
if params.type == 'step':
return StepLearningRateWithLinearWarmup(total_steps, params)
| tensorflow.where | 2,691 |
import tensorflow as tf
new_shape = [1, 1, 1, ch]
else:
axis = [2, 3]
ch = shape[1]
new_shape = [1, ch, 1, 1]
if ch is None:
raise ValueError("Input of instancebn require known channel!")
mean, var = tf.nn.moments(inputdata, axis, keep_dims=True)
if not use_affine:
return tf.divide(inputdata - mean, tf.sqrt(var + epsilon), name='output')
beta = tf.get_variable('beta', [ch], initializer=tf.constant_initializer())
beta = tf.reshape(beta, new_shape)
gamma = tf.get_variable('gamma', [ch], initializer=tf.constant_initializer(1.0))
gamma = tf.reshape(gamma, new_shape)
return tf.nn.batch_normalization(inputdata, mean, var, beta, gamma, epsilon, name=name)
@staticmethod
def dropout(inputdata, keep_prob, noise_shape=None, name=None):
"""
:param name:
:param inputdata:
:param keep_prob:
| tensorflow.constant_initializer | 2,692 |
import tensorflow as tf
ops.append(s.assign_add(g))
update_counter = tf.assign_add(counter, 1, name='update_counter')
update_slot_op = tf.group(update_counter, *ops, name='update_slot')
| tensorflow.group | 2,693 |
import tensorflow as tf
else:
return tower_preds
def _train_graph(self, data):
tower_losses, tower_gradvars, update_ops = self._gpu_tower(data, Mode.TRAIN)
# Perform the consolidation on CPU
gradvars = []
with tf.device('/cpu:0'):
# Average losses and gradients
with tf.name_scope('tower_averaging'):
all_grads = {}
for grad, var in itertools.chain(*tower_gradvars):
if grad is not None:
all_grads.setdefault(var, []).append(grad)
for var, grads in all_grads.items():
if len(grads) == 1:
avg_grad = grads[0]
else:
avg_grad = tf.multiply(tf.add_n(grads), 1. / len(grads))
| tensorflow.name_scope | 2,694 |
import tensorflow as tf
"metadata.")
tf.flags.DEFINE_string(
"gcp_project", None,
| tensorflow.flags.DEFINE_string | 2,695 |
import tensorflow.contrib.layers as layers
with tf.variable_scope("convnet"):
# original architecture
out = layers.convolution2d(out, num_outputs=32, kernel_size=8, stride=4, activation_fn=tf.nn.relu)
out = layers.convolution2d(out, num_outputs=64, kernel_size=4, stride=2, activation_fn=tf.nn.relu)
out = layers.convolution2d(out, num_outputs=64, kernel_size=3, stride=1, activation_fn=tf.nn.relu)
out = layers.flatten(out)
with tf.variable_scope("action_value"):
out = layers.fully_connected(out, num_outputs=512, activation_fn=tf.nn.relu)
out = layers.fully_connected(out, num_outputs=num_actions, activation_fn=None)
return out
def atari_learn(env,
session,
num_timesteps):
# This is just a rough estimate
| tensorflow.contrib.layers.fully_connected | 2,696 |
import tensorflow as tf
labels: (tf.Tensor) A tensor of the same shape as `output`. A value >= 1 means a
relevant example.
propensity: No use.
name: A string used as the name for this variable scope.
Returns:
(tf.Tensor) A single value tensor containing the loss.
"""
loss = None
with tf.name_scope(name, "softmax_loss",[output]):
label_dis = labels / tf.reduce_sum(labels, 1, keep_dims=True)
loss = tf.nn.softmax_cross_entropy_with_logits(logits=output, labels=label_dis) * tf.reduce_sum(labels, 1)
return tf.reduce_sum(loss) / tf.reduce_sum(labels)
def get_normalized_weights(self, propensity):
"""Computes listwise softmax loss with propensity weighting.
Args:
propensity: (tf.Tensor) A tensor of the same shape as `output` containing the weight of each element.
| tensorflow.name_scope | 2,697 |
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):
if isinstance(facts, tuple):
# In case of Bi-RNN, concatenate the forward and the backward RNN outputs.
facts = tf.concat(facts, 2)
if len(facts.get_shape().as_list()) == 2:
facts = tf.expand_dims(facts, 1)
if time_major:
# (T,B,D) => (B,T,D)
facts = tf.array_ops.transpose(facts, [1, 0, 2])
# Trainable parameters
mask = tf.equal(mask, tf.ones_like(mask))
facts_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer
querry_size = query.get_shape().as_list()[-1]
query = tf.layers.dense(query, facts_size, activation=None, name='f1' + stag)
query = prelu(query)
queries = tf.tile(query, [1, tf.shape(facts)[1]])
| tensorflow.concat | 2,698 |
import tensorflow as tf
max_src_len = tf.shape(reconstructed_weights)[1]
batch_size = tf.shape(reconstructed_weights)[0]
attn_loss = tf.matmul(reconstructed_weights, attention_weights) - tf.eye(max_src_len)
src_mask = tf.sequence_mask(encoder_input_length[0], maxlen=max_src_len, dtype=tf.float32)
src_mask = tf.einsum('ij,ik->ijk', src_mask, src_mask)
attn_loss *= tf.to_float(src_mask) # don't take padding words into account
attn_loss = tf.norm(attn_loss) / tf.to_float(batch_size)
xent_loss += reconstruction_attn_weight * attn_loss
attention_weights = [attention_weights, reconstructed_weights]
| tensorflow.einsum | 2,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.