seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
import tensorflow as tf
self.vf_new_params = [oldp.assign(p) for p, oldp in zip(vf_params, vf_old_params)]
self.sess.run(tf.global_variables_initializer())
# Tensorboard
if summary_dir is not None:
self.writer = tf.summary.FileWriter(summary_dir)
tf.summary.scalar('Loss/Policy', loss_pg)
tf.summary.scalar('Loss/Value', loss_vf)
tf.summary.scalar('Loss/Entropy', loss_entropy)
tf.summary.scalar('Loss/Total', loss)
tf.summary.scalar('Var/Epsilon', epsilon_decay)
tf.summary.scalar('Var/Policy Mode', tf.reduce_mean(pi.mode()))
tf.summary.scalar('Var/Policy Sigma', tf.reduce_mean(pi.stddev()))
tf.summary.scalar('Var/Value', tf.reduce_mean(self.vf))
self.summarise = tf.summary.merge(tf.get_collection(tf.GraphKeys.SUMMARIES))
# AC net
def build_anet(self, state_in, name, reuse=False, batch_size=64):
reg = None
with tf.variable_scope(name, reuse=reuse):
layer_a1 = tf.layers.dense(state_in, 512, tf.nn.relu, kernel_regularizer=reg)
layer_a2 = tf.layers.dense(layer_a1, 256, tf.nn.relu, kernel_regularizer=reg)
lstm_a = tf.nn.rnn_cell.LSTMCell(num_units=256)
lstm_a = tf.nn.rnn_cell.DropoutWrapper(lstm_a, output_keep_prob=self.keep_prob)
state_init_a = lstm_a.zero_state(batch_size=batch_size, dtype=tf.float32)
lstm_ain = tf.expand_dims(layer_a2, axis=1)
out_a, state_final_a = tf.nn.dynamic_rnn(cell=lstm_a, inputs=lstm_ain, initial_state=state_init_a)
cell_out_a = tf.reshape(out_a, [-1, 256])
| tensorflow.get_collection | 10,900 |
import tensorflow as tf
num = (1 - self.alpha) * dxt + tf.tensordot(self.alpha * dxt ,
tf.transpose(
tf.matmul(tf.abs(self.W_rec) * self.rec_Connectivity,self.Dale_rec)),
axes=1) * \
tf.where(tf.greater(xt, 0), tf.ones_like(xt), tf.zeros_like(xt))
denom = dxt
# sum over hidden units
num = tf.reduce_sum(tf.square(num), axis=2)
denom = tf.reduce_sum(tf.square(denom), axis=2)
bounded = tf.where(tf.greater(denom, 1e-20), tf.div(num, 1.0 * denom), tf.ones_like(num))
nelems = tf.reduce_mean(tf.where(tf.greater(denom, 1e-20), 1.0 * tf.ones_like(num), 1.0 * tf.zeros_like(num)), axis=1)
# sum mean over each batch by time steps
Omega = tf.square(bounded - 1.0)
Omega = tf.reduce_sum(tf.reduce_mean(Omega, axis=1)) / (1.0 * tf.reduce_sum(nelems))
out = tf.gradients(Omega, self.W_rec)
out[0] = tf.Print(out[0], [out[0], self.W_rec, Omega], "omega grads")
out[0] = tf.verify_tensor_all_finite(out[0], "dead omega grad")
return out, test
| tensorflow.zeros_like | 10,901 |
import tensorflow as tf
# self.bc_loss = 0.5 * tf.reduce_mean(tf.contrib.keras.backend.categorical_crossentropy(self.optimal_actions_onehot,self.policy))
# self.next_loc_loss_il = 0.2 * tf.reduce_sum(tf.sqrt(tf.square(self.next_loc_mean[:-1,:] - self.il_nextloc)))
# self.imitation_loss = self.bc_loss #+ self.next_loc_loss_il
# Get gradients from local network using local losses and
# normalize the gradients using clipping
local_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope+'/qvalues')
self.gradients = tf.gradients(self.loss, local_vars)
self.var_norms = tf.global_norm(local_vars)
grads, self.grad_norms = tf.clip_by_global_norm(self.gradients, GRAD_CLIP)
# Apply local gradients to global network
global_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, GLOBAL_NET_SCOPE+'/qvalues')
self.apply_grads = trainer.apply_gradients(zip(grads, global_vars))
| tensorflow.gradients | 10,902 |
import tensorflow as tf
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)
| tensorflow.shape | 10,903 |
import tensorflow as tf
target_names = ['class sg', 'class bm', 'class wd', 'class wt', 'class wj', 'class wo', 'class ym', 'class shq', 'class shj',
'class no', 'class yh', 'class fb']
init = tf.initialize_all_variables()
config=tf.ConfigProto()
config.gpu_options.allow_growth=True
#init=tf.initialize_all_variables()
def train(train_num=64,test_num=32,lr=1e-4,loop_count=10000,report_step=100,save_step=1000,restore=False):
with tf.Session(config=config) as sess:
sess.run(init)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
if restore:
tf.train.Saver().restore(sess,path)
feed_dict={
testnum: test_num,
trainnum: train_num,
learnrate:lr
| tensorflow.Session | 10,904 |
import tensorflow as tf
def test_run_after_error_should_be_cancelled(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)
| tensorflow.constant | 10,905 |
import tensorflow as tf
rho_max_init = tf.log(tf.exp(sigma_max) - 1.0)
| tensorflow.exp | 10,906 |
import tensorflow as tf
return features_proj
def _attention_layer(self, features, features_proj, h, reuse=False):
with tf.variable_scope('attention_layer', reuse=reuse):
w = tf.get_variable('w', [self.H, self.D], initializer=self.weight_initializer)
b = tf.get_variable('b', [self.D], initializer=self.const_initializer)
w_att = tf.get_variable('w_att', [self.D, 1], initializer=self.weight_initializer)
| tensorflow.get_variable | 10,907 |
import tensorflow as tf
# dims for normalization
width = tf.to_float(tf.shape(image)[2])
| tensorflow.shape | 10,908 |
import tensorflow as tf
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):
| tensorflow.convert_to_tensor | 10,909 |
import tensorflow as tf
# predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)
# ones=tf.get_variable('ones',shape=logits.shape,initializer=tf.ones_initializer)
# zeros=tf.get_variable('zeros',shape=logits.shape,initializer=tf.zeros_initializer)
predictions=tf.where(logits>=0,tf.ones(tf.shape(logits)),tf.zeros(tf.shape(logits)))
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)
return {
"eval_accuracy": accuracy,
"eval_loss": loss,
}
eval_metrics = (metric_fn,
[per_example_loss, label_ids, logits, is_real_example])
output_spec = tf.estimator.EstimatorSpec(
mode=mode,
loss=total_loss,
eval_metric_ops=eval_metrics,
scaffold=scaffold_fn)
else:
output_spec = tf.estimator.EstimatorSpec(
mode=mode,
predictions={"probabilities": probabilities},
scaffold=scaffold_fn
)
return output_spec
return model_fn
| tensorflow.estimator.EstimatorSpec | 10,910 |
from tensorflow.python.training import moving_averages
def build_update_ops():
"""Builds the exponential moving average update ops."""
update_mean_op = moving_averages.assign_moving_average(
variable=self._moving_mean,
value=mean,
decay=self._decay_rate,
| tensorflow.python.training.moving_averages.assign_moving_average | 10,911 |
import tensorflow as tf
class_feature_map = slim.conv2d(net, class_feature_map_depth, [1, 1],
activation_fn=None,
scope='class_predictions')
class_predictions_with_background = ops.position_sensitive_crop_regions(
class_feature_map,
boxes=tf.reshape(proposal_boxes, [-1, self._box_code_size]),
box_ind=get_box_indices(proposal_boxes),
crop_size=self._crop_size,
num_spatial_bins=self._num_spatial_bins,
global_pool=True)
| tensorflow.reshape | 10,912 |
from tensorflow.python.framework import ops
dimensions of `predictions_idx` and `labels`.
Returns:
A [D1, ... DN] `Tensor` of false positive counts.
"""
with ops.name_scope(None, 'false_positives', (predictions_idx, labels)):
labels, predictions_idx = _maybe_select_class_id(labels,
predictions_idx,
class_id)
fp = set_ops.set_size(set_ops.set_difference(
| tensorflow.python.framework.ops.name_scope | 10,913 |
import tensorflow as tf
return None
def apply_attack_loop(hps):
#Construct graph
images, labels = input_name.build_input(
FLAGS.dataset, FLAGS.eval_data_path, hps.batch_size, FLAGS.mode)#FLAGS.mode='attack', batch_size=200
Res = model_name.ResNet(hps, images, FLAGS.mode, Reuse=False)
Res.build_graph()
saver = tf.train.Saver()
#Open session and restore checkpoint
sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
tf.train.start_queue_runners(sess)
ckpt_state = tf.train.get_checkpoint_state(FLAGS.log_root) # Choose dir according to rt
tf.logging.info('Loading checkpoint %s', ckpt_state.model_checkpoint_path)
| tensorflow.train.Saver | 10,914 |
import tensorflow as tf
tf.summary.image(name, im, max_outputs=50)
# 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)
with tf.variable_scope('discrim'):
with tf.variable_scope('A'):
A_dis_real = self.discriminator(A)
A_dis_fake = self.discriminator(BA)
with tf.variable_scope('B'):
B_dis_real = self.discriminator(B)
| tensorflow.variable_scope | 10,915 |
import tensorflow as tf
if is_max_pool:
x = tf.nn.max_pool3d(x, ksize=kernel_size, strides=strides, padding='VALID', name=layer_name)
| tensorflow.nn.max_pool3d | 10,916 |
import tensorflow as tf
def main():
if not tf.io.gfile.exists(a.output_dir):
tf.io.gfile.makedirs(a.output_dir)
if a.operation == "edges" and a.crop:
| tensorflow.io.gfile.makedirs | 10,917 |
import tensorflow as tf
'depth_renders': tf.io.FixedLenFeature([20, 224, 224, 1], tf.float32),
'mesh_name': tf.io.FixedLenFeature([], tf.string),
'near_surface_samples': tf.io.FixedLenFeature([100000, 4], tf.float32),
'grid': tf.io.FixedLenFeature([32, 32, 32], tf.float32),
| tensorflow.io.FixedLenFeature | 10,918 |
import tensorflow as tf
# run_config = tf.estimator.RunConfig(
# experimental_distribute=tf.contrib.distribute.DistributeConfig(
# train_distribute=distribution,
# remote_cluster={
# 'worker': ['localhost:5000', 'localhost:5001'],
# },
# )
# )
os.environ["TF_CONFIG"] = json.dumps(
{
"cluster": {"worker": worker},
"task": {"type": "worker", "index": task_index},
}
)
strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
run_config = tf.estimator.RunConfig(
save_summary_steps=1,
train_distribute=strategy,
model_dir=FLAGS.output_dir,
save_checkpoints_steps=FLAGS.save_ckpt_steps,
log_step_count_steps=1,
)
else:
distribution = tf.contrib.distribute.MirroredStrategy(
num_gpus=FLAGS.num_gpus
)
run_config = tf.estimator.RunConfig(train_distribute=distribution)
| tensorflow.distribute.experimental.MultiWorkerMirroredStrategy | 10,919 |
import tensorflow as tf
def norm(layer, norm_type='batch_norm', decay=0.9, id=0, is_training=True, activation_fn=tf.nn.relu, prefix='conv_'):
if norm_type != 'batch_norm' and norm_type != 'layer_norm':
return tf.nn.relu(layer)
with tf.variable_scope('norm_layer_%s%d' % (prefix, id)) as vs:
if norm_type == 'batch_norm':
if is_training:
try:
layer = tf.contrib.layers.batch_norm(layer, is_training=True, center=True,
scale=False, decay=decay, activation_fn=activation_fn, updates_collections=None, scope=vs) # updates_collections=None
except ValueError:
layer = tf.contrib.layers.batch_norm(layer, is_training=True, center=True,
scale=False, decay=decay, activation_fn=activation_fn, updates_collections=None, scope=vs, reuse=True) # updates_collections=None
else:
layer = tf.contrib.layers.batch_norm(layer, is_training=False, center=True,
scale=False, decay=decay, activation_fn=activation_fn, updates_collections=None, scope=vs, reuse=True) # updates_collections=None
elif norm_type == 'layer_norm': # layer_norm
# Take activation_fn out to apply lrelu
try:
layer = activation_fn(tf.contrib.layers.layer_norm(layer, center=True,
scale=False, scope=vs)) # updates_collections=None
| tensorflow.contrib.layers.batch_norm | 10,920 |
import tensorflow as tf
training_loss = target_modality.loss_sharded(
sharded_logits, sharded_features["targets"], dp)
training_loss *= problem_hparams.loss_multiplier
losses["training"] = training_loss
return new_sharded_logits, losses
# Run the above conditionally.
prob = hparams.scheduled_sampling_prob
prob *= common_layers.inverse_exp_decay(
hparams.scheduled_sampling_warmup_steps, min_value=0.001)
sharded_logits, losses = tf.cond(
tf.less(tf.random_uniform([]), prob), sampled_results,
lambda: (sharded_logits, losses))
return sharded_logits, losses
def average_sharded_losses(sharded_losses):
"""Average losses across datashards.
Args:
sharded_losses: list<dict<str loss_name, Tensor loss>>. The loss
can be a single Tensor or a 2-tuple (numerator and denominator).
| tensorflow.random_uniform | 10,921 |
import tensorflow as tf
# 6. 有时,我们希望代码健壮到可以决定运行多少GPU合适。TensorFlow有内建函数可以探测到。如果我们期望代码在GPU内存合适时利用GPU计算能力,并分配指定操作给GPU,那么该功能是有益的
if tf.test.is_built_with_cuda(): pass
# 7. 我们希望分配指定操作给GPU。下面是一个示例代码,做了一些简单的计算,并将它们分配给主CPU和两个副GPU
with tf.device('/cpu:0'):
a = tf.constant([1.0, 3.0, 5.0], shape=[1,3])
b = tf.constant([2.0, 4.0, 6.0], shape=[3, 1])
with tf.device('/gpu:0'):
c = tf.matmul(a,b)
c = tf.reshape(c, [-1])
with tf.device('/gpu:1'):
d = tf.matmul(b, a)
flat_d = tf.reshape(d, [-1])
combined = tf.multiply(c, flat_d)
print(sess.run(combined))
| tensorflow.reshape | 10,922 |
import tensorflow as tf
def loop_hyper_deocder(z):
z = tf.expand_dims(z, 0)
| tensorflow.expand_dims | 10,923 |
import tensorflow as tf
z_t = tf.transpose(z_t, [2, 0, 1])
z_t = 1 / z_t
d_t = 1 / z_t
x_t /= z_t
y_t /= z_t
x_t_flat = tf.reshape(x_t, (1, -1))
y_t_flat = tf.reshape(y_t, (1, -1))
d_t_flat = tf.reshape(d_t, (1, -1))
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.ones_like | 10,924 |
import tensorflow as tf
argmax_results = tf.image.resize_nearest_neighbor(
tf.expand_dims(argmax_results, 3),
tf.shape(images)[1:3],
align_corners=True,
name='resize_prediction')
predictions[output] = tf.squeeze(argmax_results, 3)
#predictions[output + PROB_SUFFIX] = tf.image.resize_bilinear(
# tf.nn.softmax(logits),
# tf.shape(images)[1:3],
# align_corners=True,
| tensorflow.squeeze | 10,925 |
import tensorflow as tf
depth_bottleneck,
1,
1,
stride,
stride,
input_layer=input_layer,
num_channels_in=in_size)
self.conv(depth_bottleneck, 3, 3, 1, 1, mode='SAME_RESNET')
res = self.conv(depth, 1, 1, 1, 1, activation=None)
output = tf.nn.relu(shortcut + res)
self.top_layer = output
self.top_size = depth
return output
def inception_module(self, name, cols, input_layer=None, in_size=None):
if input_layer is None:
input_layer = self.top_layer
if in_size is None:
| tensorflow.nn.relu | 10,926 |
import tensorflow as tf
with tf.variable_scope("temp_conv") as scope:
filter_shape = [3, embedding_size, 4, 64]
W = tf.get_variable(name='W_1', shape=filter_shape,
initializer=he_normal,
regularizer=regularizer)
paddings = [[0, 0], [1, 1], [0, 0], [0, 0]]
cnn_inputs = tf.pad(cnn_inputs, paddings, "CONSTANT")
#print("cnn_inputs shape:", cnn_inputs.shape)
inputs = tf.nn.conv2d(cnn_inputs, W, strides=[1, 1, 1, 1], padding="VALID", name="first_conv")
inputs = tf.layers.batch_normalization(inputs, axis=-1, training=self.is_training)
inputs = tf.nn.relu(inputs, name="first_relu")
#print("temp cnn output shape:", inputs.shape)
inputs = tf.squeeze(inputs, axis=2)
#print("squeeze shape", inputs.shape)
#inputs = tf.nn.relu(inputs)
print("Temp Conv", inputs.get_shape())
self.layers.append(inputs)
| tensorflow.layers.batch_normalization | 10,927 |
import tensorflow as tf
h_att = tf.nn.relu(features_proj + tf.expand_dims(tf.matmul(h, w), 1) + b) # (N, L, D)
out_att = tf.reshape(tf.matmul(tf.reshape(h_att, [-1, self.D]), w_att), [-1, self.L]) # (N, L)
alpha = tf.nn.softmax(out_att)
context = tf.reduce_sum(features * tf.expand_dims(alpha, 2), 1, name='context') #(N, D)
return context, alpha
def _selector(self, context, h, reuse=False):
with tf.variable_scope('selector', reuse=reuse):
w = tf.get_variable('w', [self.H, 1], initializer=self.weight_initializer)
b = tf.get_variable('b', [1], initializer=self.const_initializer)
beta = tf.nn.sigmoid(tf.matmul(h, w) + b, 'beta') # (N, 1)
context = tf.multiply(beta, context, name='selected_context')
return context, beta
def _decode_lstm(self, x, h, context, dropout=False, reuse=False):
with tf.variable_scope('logits', reuse=reuse):
| tensorflow.get_variable | 10,928 |
import tensorflow as tf
tf.expand_dims(areas1, 1) + tf.expand_dims(areas2, 0) - intersections)
return tf.where(
tf.equal(intersections, 0.0),
tf.zeros_like(intersections), tf.truediv(intersections, unions))
| tensorflow.equal | 10,929 |
import tensorflow as tf
img = np.expand_dims(np.asarray(img), axis = 0)
# Create a placeholder for the input image
input_node = tf.placeholder(tf.float32, shape=(None, height, width, channels))
# Construct the network
net = models.ResNet50UpProj({'data': input_node}, batch_size)
with tf.Session() as sess:
# Load the converted parameters
print('Loading the model')
net.load(model_data_path, sess)
uninitialized_vars = []
for var in tf.global_variables():
| tensorflow.Session | 10,930 |
import tensorflow as tf
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(
serialized_example,
features={
'wav_raw': tf.FixedLenFeature([], tf.string),
'noisy_raw': tf.FixedLenFeature([], tf.string),
})
wave = tf.decode_raw(features['wav_raw'], tf.int32)
| tensorflow.FixedLenFeature | 10,931 |
import tensorflow as tf
class TfGraphTestCase:
def setup_method(self):
tf.reset_default_graph()
self.graph = tf.Graph()
for c in self.graph.collections:
| tensorflow.reset_default_graph | 10,932 |
import tensorflow as tf
output_ta = tf.TensorArray(dtype=tf.float32,
size=0,
dynamic_size=True,
element_shape=(facts[:, 0, :].get_shape()))
_, output_op, _ = tf.while_loop(cond, body, [facts, output_ta, 0])
self_attention = output_op.stack()
self_attention = tf.transpose(self_attention, perm = [1, 0, 2])
return self_attention
| tensorflow.while_loop | 10,933 |
from tensorflow.python.framework import constant_op
else:
return control_flow_ops.with_dependencies([
check_ops.assert_less(
constant_op.constant(2., dtype=self.dtype), self.alpha,
message="variance not defined for components of alpha <= 2"),
], var)
| tensorflow.python.framework.constant_op.constant | 10,934 |
import tensorflow as tf
label_priors = losses_utils.convert_and_cast(
label_priors, name='label_priors', dtype=labels.dtype.base_dtype)
return tf.squeeze(label_priors)
| tensorflow.squeeze | 10,935 |
import tensorflow as tf
res = tf.concat(x_labels, axis=-1)
return tf.to_float(res)
| tensorflow.to_float | 10,936 |
import tensorflow as tf
filename = os.path.join(test_dir, "metafile")
with self.test_session(graph=tf.Graph()):
# Creates a graph.
tf.Variable(10.0, name="v0")
# Exports the graph as binary format.
tf.train.export_meta_graph(filename, as_text=False)
with self.test_session(graph=tf.Graph()):
# Imports the binary format graph.
saver = tf.train.import_meta_graph(filename)
# Exports the graph as text format.
saver.export_meta_graph(filename, as_text=True)
with self.test_session(graph=tf.Graph()):
# Imports the text format graph.
tf.train.import_meta_graph(filename)
# Writes wrong contents to the file.
tf.train.write_graph(saver.as_saver_def(), os.path.dirname(filename),
os.path.basename(filename))
with self.test_session(graph=tf.Graph()):
# Import should fail.
with self.assertRaisesWithPredicateMatch(
IOError, lambda e: "Cannot parse file"):
tf.train.import_meta_graph(filename)
# Deletes the file
gfile.Remove(filename)
with self.assertRaisesWithPredicateMatch(
IOError, lambda e: "does not exist"):
| tensorflow.train.import_meta_graph | 10,937 |
import tensorflow as tf
d_layer_4_dim = 16
num_block_layers = 3
dense_layer_depth = 16
def lstm_network(input, scope='lstm_network'):
with tf.variable_scope(scope):
# tf.nn.rnn_cell
lstm_cell1 = tf.contrib.rnn.BasicLSTMCell(lstm_hidden_size_layer1, forget_bias=1.0)
lstm_cell2 = tf.contrib.rnn.BasicLSTMCell(lstm_hidden_size_layer2, forget_bias=1.0)
lstm_cells = tf.contrib.rnn.MultiRNNCell(cells=[lstm_cell1, lstm_cell2], state_is_tuple=True)
# tf.nn.rnn_cell
# lstm_cell1 = tf.nn.rnn_cell.LSTMCell(lstm_hidden_size_layer1, forget_bias=1.0)
# lstm_cell2 = tf.nn.rnn_cell.LSTMCell(lstm_hidden_size_layer2, forget_bias=1.0)
#lstm_cells = tf.nn.rnn_cell.MultiRNNCell(cells=[lstm_cell1, lstm_cell2], state_is_tuple=True)
| tensorflow.contrib.rnn.BasicLSTMCell | 10,938 |
import tensorflow as tf
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]
fast_antecedent_scores = tf.expand_dims(top_span_mention_scores, 1) + tf.expand_dims(top_span_mention_scores, 0) # [k, k]
fast_antecedent_scores += tf.log(tf.to_float(antecedents_mask)) # [k, k]
fast_antecedent_scores += self.get_fast_antecedent_scores(top_span_emb) # [k, k]
_, top_antecedents = tf.nn.top_k(fast_antecedent_scores, c, sorted=False) # [k, c]
top_antecedents_mask = util.batch_gather(antecedents_mask, top_antecedents) # [k, c]
top_fast_antecedent_scores = util.batch_gather(fast_antecedent_scores, top_antecedents) # [k, c]
top_antecedent_offsets = util.batch_gather(antecedent_offsets, top_antecedents) # [k, c]
return top_antecedents, top_antecedents_mask, top_fast_antecedent_scores, top_antecedent_offsets
def distance_pruning(self, top_span_emb, top_span_mention_scores, c):
k = util.shape(top_span_emb, 0)
top_antecedent_offsets = tf.tile(tf.expand_dims(tf.range(c) + 1, 0), [k, 1]) # [k, c]
| tensorflow.expand_dims | 10,939 |
import tensorflow as tf
self.summarise = tf.summary.merge(tf.get_collection(tf.GraphKeys.SUMMARIES))
# AC net
def build_anet(self, state_in, name, reuse=False, batch_size=64):
reg = None
with tf.variable_scope(name, reuse=reuse):
layer_a1 = tf.layers.dense(state_in, 512, tf.nn.relu, kernel_regularizer=reg)
layer_a2 = tf.layers.dense(layer_a1, 256, tf.nn.relu, kernel_regularizer=reg)
lstm_a = tf.nn.rnn_cell.LSTMCell(num_units=256)
lstm_a = tf.nn.rnn_cell.DropoutWrapper(lstm_a, output_keep_prob=self.keep_prob)
state_init_a = lstm_a.zero_state(batch_size=batch_size, dtype=tf.float32)
lstm_ain = tf.expand_dims(layer_a2, axis=1)
out_a, state_final_a = tf.nn.dynamic_rnn(cell=lstm_a, inputs=lstm_ain, initial_state=state_init_a)
cell_out_a = tf.reshape(out_a, [-1, 256])
mu = tf.layers.dense(cell_out_a, self.a_dim, tf.nn.tanh, kernel_regularizer=reg)
sigma = tf.layers.dense(cell_out_a, self.a_dim, tf.nn.softplus, kernel_regularizer=reg)
# sigma = tf.get_variable(name='pi_sigma', shape=self.a_dim, initializer=tf.constant_initializer(0.5))
sigma = tf.clip_by_value(sigma, 0.0, 1.0)
norm_dist = tf.distributions.Normal(loc=mu * self.a_bound, scale=sigma)
params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=name)
return norm_dist, params, state_init_a, state_final_a
def build_cnet(self, state_in, name, reuse=False, batch_size=64):
reg = tf.contrib.layers.l2_regularizer(1e-3)
with tf.variable_scope(name, reuse=reuse):
layer_c1 = tf.layers.dense(state_in, 512, tf.nn.relu, kernel_regularizer=reg)
layer_c2 = tf.layers.dense(layer_c1, 256, tf.nn.relu, kernel_regularizer=reg)
lstm_c = tf.nn.rnn_cell.LSTMCell(num_units=256)
lstm_c = tf.nn.rnn_cell.DropoutWrapper(lstm_c, output_keep_prob=self.keep_prob)
state_init_c = lstm_c.zero_state(batch_size=batch_size, dtype=tf.float32)
| tensorflow.layers.dense | 10,940 |
import tensorflow as tf
per_example_loss=per_example_loss)
# Now we construct the copy model.
inp = [tf.placeholder(tf.int32, shape=[None]) for _ in range(8)]
out = [tf.placeholder(tf.int32, shape=[None]) for _ in range(8)]
weights = [tf.ones_like(inp[0], dtype=tf.float32) for _ in range(8)]
with tf.variable_scope("root"):
_, losses1 = SampleGRUSeq2Seq(inp, out, weights, per_example_loss=False)
# Now check that we did not accidentally set reuse.
self.assertEqual(False, tf.get_variable_scope().reuse)
| tensorflow.ones_like | 10,941 |
import tensorflow as tf
def dense_maxnorm_update(var_matrix, maxnorm=1.0):
'''Dense update operation that ensures all rows in var_matrix
do not have a Euclidean norm greater than maxnorm. Rows that exceed
it are scaled to length.
Args:
var_matrix: 2D mutable tensor (Variable) to operate on
maxnorm: the maximum Euclidean norm
Returns:
An operation that will update var_matrix when run in a Session
'''
row_norms = tf.sqrt(tf.reduce_sum(tf.square(var_matrix), 1))
scaling = maxnorm / tf.maximum(row_norms, maxnorm)
scaled = var_matrix * tf.expand_dims(scaling, 1)
return tf.assign(var_matrix, scaled)
def dense_maxnorm(var_matrix, maxnorm=1.0):
'''Similar to dense_maxnorm_update(), except this returns a new Tensor
instead of an operation that modifies var_matrix.
Args:
var_matrix: 2D tensor (Variable)
maxnorm: the maximum Euclidean norm
| tensorflow.square | 10,942 |
import tensorflow as tf
w = tf.get_variable('w', [self.fc2.get_shape()[1], num_classes], initializer=initializer,
regularizer=regularizer)
b = tf.get_variable('b', [num_classes], initializer=tf.constant_initializer(1.0))
self.fc3 = tf.matmul(self.fc2, w) + b
# Calculate Mean cross-entropy loss
with tf.name_scope("loss"):
self.predictions = tf.argmax(self.fc3, 1, name="predictions")
losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.fc3, labels=self.input_y)
regularization_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)
self.loss = tf.reduce_mean(losses) + sum(regularization_losses)
# Accuracy
with tf.name_scope("accuracy"):
correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1))
self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy")
| tensorflow.argmax | 10,943 |
import tensorflow as tf
pos = files[0].name.find(cases[0])
pattern = files[0].name[:pos] + 'AB%sDEF.GH*'
self.assertEqual(set(tf.matching_files(pattern % 'z').eval()),
self._subset(files, [1]))
self.assertEqual(set(tf.matching_files(pattern % '?').eval()),
self._subset(files, [0, 1, 3, 4]))
self.assertEqual(set(tf.matching_files(pattern % '*').eval()),
self._subset(files, [0, 1, 2, 3, 4, 5]))
self.assertEqual(set(tf.matching_files(pattern % '[cxz]').eval()),
self._subset(files, [0, 1]))
self.assertEqual(set(tf.matching_files(pattern % '[0-9]').eval()),
self._subset(files, [3, 4]))
if __name__ == '__main__':
tf.test.main()
| tensorflow.matching_files | 10,944 |
import tensorflow as tf
assert not self._exported_as_v1
# TODO(b/149997088): Raise an exception once we no longer support using
# the Keras layer with estimator based Trainer.
tf.compat.v1.logging.warning('Loading a TF2 SavedModel but eager mode '
'seems disabled.')
# If exported as TF2 SavedModel but not invoked in eager mode,
| tensorflow.compat.v1.logging.warning | 10,945 |
from tensorflow.python.ops import array_ops
keep_prob = ops.convert_to_tensor(
keep_prob, dtype=x.dtype, name="keep_prob")
keep_prob.get_shape().assert_is_compatible_with(tensor_shape.scalar())
noise_shape = noise_shape or array_ops.shape(x)
# uniform [keep_prob, 1.0 + keep_prob)
random_tensor = keep_prob
random_tensor += random_ops.random_uniform(
| tensorflow.python.ops.array_ops.shape | 10,946 |
import tensorflow as tf
if FLAGS.do_train:
tf.logging.info("***** Running training *****")
| tensorflow.logging.info | 10,947 |
import tensorflow as tf
# tf.decode_raw does not support bool as a decode type. As a result it is
# necessary to decode to int8 (7 of the bits will be ignored) and then
# cast to bool.
return tf.reshape(tf.cast(tf.decode_raw(data_bytes, tf.int8), tf.bool),
(batch_size,))
if self._is_training:
mask_start_index = tf.decode_raw(
features[rconst.MASK_START_INDEX], tf.int32)[0]
valid_point_mask = tf.less(tf.range(batch_size), mask_start_index)
return {
movielens.USER_COLUMN: users,
movielens.ITEM_COLUMN: items,
| tensorflow.decode_raw | 10,948 |
import tensorflow as tf
activation = map
# print(activation.get_shape().as_list())
return activation
def batch_norm_conv(x, b_train, scope):
with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
n_out = x.get_shape().as_list()[-1]
beta = tf.get_variable('beta', initializer=tf.constant(0.0, shape=[n_out]))
gamma = tf.get_variable('gamma', initializer=tf.constant(1.0, shape=[n_out]))
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 = tf.cond(b_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
| tensorflow.train.ExponentialMovingAverage | 10,949 |
import tensorflow as tf
Ref: http://stackoverflow.com/questions/33949786/how-could-i-use-batch-normalization-in-tensorflow/33950177
"""
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,
| tensorflow.train.ExponentialMovingAverage | 10,950 |
import tensorflow as tf
image: A 3-D image `Tensor`.
smallest_side: A python integer or scalar `Tensor` indicating the size of
the smallest side after resize.
Returns:
resized_image: A 3-D tensor containing the resized image.
"""
smallest_side = tf.convert_to_tensor(smallest_side, dtype=tf.int32)
shape = tf.shape(image)
height = shape[0]
width = shape[1]
new_height, new_width = _smallest_size_at_least(height, width, smallest_side)
image = tf.expand_dims(image, 0)
resized_image = tf.image.resize_bilinear(image, [new_height, new_width],
align_corners=False)
resized_image = tf.squeeze(resized_image)
resized_image.set_shape([None, None, 3])
return resized_image
def preprocess_for_train(image,
output_height,
output_width,
resize_side_min=_RESIZE_SIDE_MIN,
resize_side_max=_RESIZE_SIDE_MAX):
"""Preprocesses the given image for training.
| tensorflow.image.resize_bilinear | 10,951 |
import tensorflow as tf
return tf.reshape(x, [-1] + sh[1:-1] + [num_units])
def dense(x, num_units, scope="dense", training=True, ema=None, init=False, bias_initializer=tf.constant_initializer(0.)):
with tf.variable_scope(scope):
V = tf.get_variable('V', shape=[int(x.get_shape()[1]), num_units], dtype=tf.float32,
initializer=tf.random_normal_initializer(0, 0.05), trainable=True)
g = tf.get_variable('g', shape=[num_units], dtype=tf.float32,
initializer=tf.constant_initializer(1.), trainable=True)
b = tf.get_variable('b', shape=[num_units], dtype=tf.float32,
initializer=bias_initializer, trainable=True)
def maybe_avg(v):
if ema is not None and not init:
v = tf.cond(training, lambda: v, lambda: ema.average(v))
return v
if init:
| tensorflow.get_variable | 10,952 |
import tensorflow as tf
log("Tacotron training set to a maximum of {} steps".format(args.tacotron_train_steps))
# Memory allocation on the GPU as needed
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.allow_soft_placement = True
| tensorflow.ConfigProto | 10,953 |
import tensorflow as tf
v_grads_and_vars = v_grad_clip_fn(grads_and_vars)
v_grads, _ = zip(*v_grads_and_vars)
v_grads_true = tf.clip_by_value(grads,
hparams["kwargs"]["clip_value_min"],
hparams["kwargs"]["clip_value_max"])
with self.test_session() as sess:
sess.run(tf.global_variables_initializer())
gn_grads_, gn_grads_true_, v_grads_, v_grads_true_ = sess.run(
[gn_grads, gn_grads_true, v_grads, v_grads_true])
np.testing.assert_array_equal(gn_grads_, gn_grads_true_)
np.testing.assert_array_equal(v_grads_, v_grads_true_)
def test_get_train_op(self):
| tensorflow.global_variables_initializer | 10,954 |
import tensorflow as tf
ul_u_eval_train = placeholder_like(ul_images_eval_train, "ul_u_eval_train")
ul_u_eval_test = placeholder_like(images_eval_test, "ul_u_eval_test")
with tf.device(FLAGS.device):
lr = tf.placeholder(tf.float32, shape=[], name="learning_rate")
mom = tf.placeholder(tf.float32, shape=[], name="momentum")
| tensorflow.device | 10,955 |
import tensorflow as tf
with tf.contrib.summary.record_summaries_every_n_global_steps(
100, global_step=step):
tf.contrib.summary.scalar(prefix + name, scalar, step=step)
return tf.contrib.summary.all_summary_ops()
global_step_tensor = tf.reshape(tf.train.get_or_create_global_step(), [1])
other_tensors = [tf.reshape(monitor_dict[key], [1]) for key in metric_names]
return host_call_fn, [global_step_tensor] + other_tensors
| tensorflow.train.get_or_create_global_step | 10,956 |
import tensorflow as tf
logits, feat = resnet_model_fn(x, training=training_flag)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_labels, logits=logits))
Focal_loss = tf.reduce_mean(focal_loss(one_hot_labels, logits, alpha=0.5))
l2_loss = weight_decay * tf.add_n([tf.nn.l2_loss(v) for v in tf.trainable_variables()])
Center_loss, Centers = center_loss(feat, tf.cast(label, dtype=tf.int32), 0.95, class_num)
Total_loss = cost + l2_loss
optimizer = tf.train.MomentumOptimizer(learning_rate=learning_rate, momentum=momentum, use_nesterov=True)
# Batch norm requires update_ops to be added as a train_op dependency.
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
train_op = optimizer.minimize(Total_loss)
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_labels, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# val_dir = '/data0/AIChallenger/ai_challenger_scene_validation_20170908/scene_validation_images_20170908/'
# annotations = '/data0/AIChallenger/ai_challenger_scene_validation_20170908/scene_validation_annotations_20170908.json'
# # a DataFlow you implement to produce [tensor1, tensor2, ..] lists from whatever sources:
| tensorflow.get_collection | 10,957 |
import tensorflow as tf
# Call A2C net
pi, self.pi_params = self.build_anet(batch['state'], 'pi')
pi_eval, _ = self.build_anet(self.state, 'pi', reuse=True)
self.vf, self.vf_params = self.build_cnet(batch['state'], 'vf')
self.vf_eval, _ = self.build_cnet(self.state, 'vf', reuse=True)
self.sample_action = tf.squeeze(pi_eval.sample(1), axis=0)
self.eval_action = pi_eval.mode()
self.global_step = tf.train.get_or_create_global_step()
self.saver = tf.train.Saver()
# Loss functions and training
loss_pg = - tf.reduce_mean(pi.log_prob(batch['actions']) * batch['advantage']) - 0.01 * tf.reduce_mean(pi.entropy())
loss_vf = 0.5 * tf.reduce_mean(tf.square(batch['rewards'] - self.vf))
self.a_grads = tf.gradients(loss_pg, self.pi_params)
self.c_grads = tf.gradients(loss_vf, self.vf_params)
self.a_grads, _ = tf.clip_by_global_norm(self.a_grads, 20.0)
self.c_grads, _ = tf.clip_by_global_norm(self.c_grads, 20.0)
opt = tf.train.AdamOptimizer(self.LR)
self.update_a_op = opt.apply_gradients(zip(self.a_grads, self.pi_params))
| tensorflow.train.Saver | 10,958 |
import tensorflow as tf
def body(self, features):
observations = features["inputs"]
x = tf.transpose(observations, [0, 2, 3, 1, 4])
x_shape = common_layers.shape_list(x)
x = tf.reshape(x, x_shape[:-2] + [-1])
dropout = getattr(self.hparams, "dropout_ppo", 0.0)
with tf.variable_scope("feed_forward_cnn_small"):
x = tf.cast(x, tf.float32) / 255.0
x = tf.nn.dropout(x, rate=dropout)
x = tf.layers.conv2d(
x, 32, (4, 4), strides=(2, 2), name="conv1",
activation=common_layers.belu, padding="SAME")
x = tf.nn.dropout(x, rate=dropout)
x = tf.layers.conv2d(
x, 64, (4, 4), strides=(2, 2), name="conv2",
activation=common_layers.belu, padding="SAME")
x = tf.nn.dropout(x, rate=dropout)
x = tf.layers.conv2d(
x, 128, (4, 4), strides=(2, 2), name="conv3",
activation=common_layers.belu, padding="SAME")
flat_x = tf.layers.flatten(x)
flat_x = tf.nn.dropout(flat_x, rate=dropout)
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"
| tensorflow.layers.conv2d | 10,959 |
import tensorflow as tf
def cw_sampling(X, y=None):
def phi_sampling(s, D):
return tf.pow(1.0 + 4.0*s/(2.0*D-3), -0.5)
D = tf.cast(tf.shape(X)[1], tf.float32)
N = tf.cast(tf.shape(X)[0], tf.float32)
D_int = tf.cast(D, tf.int32)
N_int = tf.cast(N, tf.int32)
if y is None:
y = silverman_rule_of_thumb(N)
YDistr = tf.contrib.distributions.MultivariateNormalDiag(loc=tf.zeros(D_int, tf.float32),
scale_diag=tf.ones(D_int, tf.float32))
Y = YDistr.sample(N_int)
T = 1.0/(2.0*N*tf.sqrt(m.pi*y))
A0 = euclidean_norm_squared(tf.subtract(tf.expand_dims(X, 0), tf.expand_dims(X, 1)), axis=2)
A = tf.reduce_sum(phi_sampling(A0/(4*y), D))
B0 = euclidean_norm_squared(tf.subtract(tf.expand_dims(Y, 0), tf.expand_dims(Y, 1)), axis=2)
B = tf.reduce_sum(phi_sampling(B0/(4*y), D))
C0 = euclidean_norm_squared(tf.subtract(tf.expand_dims(X, 0), tf.expand_dims(Y, 1)), axis=2)
C = tf.reduce_sum(phi_sampling(C0/(4*y), D))
| tensorflow.ones | 10,960 |
import tensorflow as tf
enc_outputs, enc_state = tf.nn.rnn(cell, inp, dtype=tf.float32)
attn_states = tf.concat(1, [tf.reshape(e, [-1, 1, cell.output_size])
for e in enc_outputs])
dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3
dec, mem = tf.nn.seq2seq.attention_decoder(
dec_inp, enc_state,
| tensorflow.constant | 10,961 |
import tensorflow as tf
if params['data_format'] == 'channels_first':
cls_pred = tf.transpose(cls_pred, [0, 2, 3, 1])
location_pred = tf.transpose(location_pred, [0, 2, 3, 1])
bboxes_pred = labels['decode_fn'](location_pred)#(tf.reshape(location_pred, tf.shape(location_pred).as_list()[0:-1] + [-1, 4]))
cls_pred = tf.reshape(cls_pred, [-1, params['num_classes']])
location_pred = tf.reshape(location_pred, [-1, 4])
glabels = tf.reshape(glabels, [-1])
gscores = tf.reshape(gscores, [-1])
gtargets = tf.reshape(gtargets, [-1, 4])
# raw mask for positive > 0.5, and for negetive < 0.3
| tensorflow.reshape | 10,962 |
import tensorflow as tf
def import_ops(self):
if self._is_training:
self._train_op = tf.get_collection_ref('train_op')[0]
self._lr = tf.get_collection_ref('lr')[0]
| tensorflow.get_collection_ref | 10,963 |
import tensorflow as tf
from alpharotate.libs.utils.coordinate_convert import coordinate_present_convert
from alpharotate.utils.pretrain_zoo import PretrainModelZoo
os.environ["CUDA_VISIBLE_DEVICES"] = cfgs.GPU_GROUP
class TrainR3DetDCL(Train):
def get_gtboxes_and_label(self, gtboxes_and_label_h, gtboxes_and_label_r, num_objects):
return gtboxes_and_label_h[:int(num_objects), :].astype(np.float32), \
gtboxes_and_label_r[:int(num_objects), :].astype(np.float32)
def main(self):
with tf.Graph().as_default() as graph, tf.device('/cpu:0'):
num_gpu = len(cfgs.GPU_GROUP.strip().split(','))
global_step = slim.get_or_create_global_step()
lr = self.warmup_lr(cfgs.LR, global_step, cfgs.WARM_SETP, num_gpu)
tf.summary.scalar('lr', lr)
optimizer = tf.train.MomentumOptimizer(lr, momentum=cfgs.MOMENTUM)
r3det_dcl = build_whole_network.DetectionNetworkR3DetDCL(cfgs=self.cfgs,
is_training=True)
with tf.name_scope('get_batch'):
if cfgs.IMAGE_PYRAMID:
| tensorflow.device | 10,964 |
from tensorflow.python.framework import ops
dimension of the input tensor.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
name: Optional name for the returned tensor.
Returns:
A `Tensor` with the same type as `value`.
Raises:
ValueError: If input/output depth does not match `filter`'s shape, or if
padding is other than `'VALID'` or `'SAME'`.
"""
with ops.op_scope([value, filter, output_shape], name,
"conv2d_transpose") as name:
value = ops.convert_to_tensor(value, name="value")
filter = ops.convert_to_tensor(filter, name="filter")
if not value.get_shape()[3].is_compatible_with(filter.get_shape()[3]):
raise ValueError(
"input channels does not match filter's input channels, "
"{} != {}".format(value.get_shape()[3], filter.get_shape()[3]))
output_shape_ = ops.convert_to_tensor(output_shape, name="output_shape")
if not output_shape_.get_shape().is_compatible_with(tensor_shape.vector(4)):
raise ValueError("output_shape must have shape (4,), got {}"
.format(output_shape_.get_shape()))
if isinstance(output_shape, (list, np.ndarray)):
| tensorflow.python.framework.ops.convert_to_tensor | 10,965 |
import tensorflow as tf
self.embedded_characters = tf.nn.embedding_lookup(self.embedding_W, self.input_x)
embedded_text_expand = tf.expand_dims(self.embedded_characters, -1)
with tf.device('/cpu:0'), tf.name_scope("embedding_tags"):
W_tags = tf.get_variable("embed_W_tags", [tags_vocab_size, embedding_size], initializer=initializer)
embedded_tags = tf.nn.embedding_lookup(W_tags, self.input_tags)
embedded_tags_expanded = tf.expand_dims(embedded_tags, -1)
with tf.device('/cpu:0'), tf.name_scope("embedding_deps"):
W_deps = tf.get_variable("embed_W_deps", [deps_vocab_size, embedding_size], initializer=initializer)
embedded_deps = tf.nn.embedding_lookup(W_deps, self.input_deps)
embedded_deps_expanded = tf.expand_dims(embedded_deps, -1)
with tf.device('/cpu:0'), tf.name_scope("embedding_head"):
W_head = tf.get_variable("embed_W_head", [num_quantized_chars, embedding_size], initializer=initializer)
embedded_head = tf.nn.embedding_lookup(W_head, self.input_head)
embedded_head_expanded = tf.expand_dims(embedded_head, -1)
| tensorflow.get_variable | 10,966 |
import tensorflow as tf
with tf.variable_scope("loss", reuse=False):
# Take the min of the two Q-Values (Double-Q Learning)
min_qf_pi = tf.minimum(qf1_pi, qf2_pi)
| tensorflow.minimum | 10,967 |
from tensorflow.python.ops import array_ops
with self._name_scope(name, values=[x, sample_shape]):
x = ops.convert_to_tensor(x, name="x")
sample_shape = ops.convert_to_tensor(sample_shape, name="sample_shape")
x = distribution_util.rotate_transpose(x, shift=1)
if self._is_all_constant_helper(self.batch_ndims, self.event_ndims):
if self._batch_ndims_is_0 or self._event_ndims_is_0:
b = ((min(-2, -1 - self._event_ndims_static),)
if self._batch_ndims_is_0 else ())
e = (-1,) if self._event_ndims_is_0 else ()
x = array_ops.squeeze(x, squeeze_dims=b + e)
_, batch_shape, event_shape = self.get_shape(x)
else:
s = (x.get_shape().as_list() if x.get_shape().is_fully_defined()
else array_ops.shape(x))
batch_shape = array_ops.slice(s, (1,), (self.batch_ndims,))
# Since sample_dims=1 and is left-most, we add 1 to the number of
# batch_ndims to get the event start dim.
event_start = array_ops.where(
self._batch_ndims_is_0, 2, 1 + self.batch_ndims)
event_shape = array_ops.slice(s, (event_start,), (self.event_ndims,))
new_shape = array_ops.concat(0, (sample_shape, batch_shape, event_shape))
x = array_ops.reshape(x, shape=new_shape)
return x
@contextlib.contextmanager
def _name_scope(self, name=None, values=None):
| tensorflow.python.ops.array_ops.shape | 10,968 |
import tensorflow as tf
learning_rate=learning_rate,
clip_gradients=params.clip_grad_norm or None,
optimizer=opt,
colocate_gradients_with_ops=True
)
zero_op = tf.no_op("zero_op")
collect_op = tf.no_op("collect_op")
else:
grads_and_vars = opt.compute_gradients(
loss, colocate_gradients_with_ops=True)
| tensorflow.no_op | 10,969 |
import tensorflow as tf
export_path = image_classifier.export_saved_model(
export_dir_base=FLAGS.export_dir,
serving_input_receiver_fn=build_image_serving_input_receiver_fn(
serving_shape),
as_text=True)
if FLAGS.add_warmup_requests:
write_warmup_requests(
export_path,
FLAGS.model_name,
hparams.image_size,
batch_sizes=FLAGS.inference_batch_sizes)
if __name__ == '__main__':
tf.logging.set_verbosity(tf.logging.INFO)
app.run(main)
| tensorflow.logging.set_verbosity | 10,970 |
import tensorflow as tf
[self.batch_size, s_h2, s_w2, self.gf_dim*1], name='d_h3'))
output_h4 = deconv2d(tf.concat([output_h3, tgtctx_h0], 3),
[self.batch_size, s_h, s_w, self.c_dim], name='d_h4')
scope.reuse_variables()
truthoutput_z_ = lrelu(linear(tgtimg_z, self.gf_dim*8*s_h16*s_w16, 'd_h0_lin'))
truthoutput_h0 = tf.reshape(truthoutput_z_, [-1, s_h16, s_w16, self.gf_dim * 8])
truthoutput_h1 = lrelu(deconv2d(tf.concat([truthoutput_h0, tgtctx_h3], 3),
[self.batch_size, s_h8, s_w8, self.gf_dim*4], name='d_h1'))
truthoutput_h2 = lrelu(deconv2d(tf.concat([truthoutput_h1, tgtctx_h2], 3),
[self.batch_size, s_h4, s_w4, self.gf_dim*2], name='d_h2'))
truthoutput_h3 = lrelu(deconv2d(tf.concat([truthoutput_h2, tgtctx_h1], 3),
[self.batch_size, s_h2, s_w2, self.gf_dim*1], name='d_h3'))
truthoutput_h4 = deconv2d(tf.concat([truthoutput_h3, tgtctx_h0], 3),
[self.batch_size, s_h, s_w, self.c_dim], name='d_h4')
self.simloss = tf.reduce_mean((trans_z - tgtimg_z) ** 2) * 1e3
mean, var = tf.nn.moments(tgtimg_z, axes=[0])
print(var.get_shape())
| tensorflow.concat | 10,971 |
import tensorflow as tf
kernel_initializer=xlnet_model.get_initializer())
logits = tf.reshape(logits, [bsz_per_core, 4])
one_hot_target = tf.one_hot(label, 4)
per_example_loss = -tf.reduce_sum(
tf.nn.log_softmax(logits) * one_hot_target, -1)
total_loss = tf.reduce_mean(per_example_loss)
return total_loss, per_example_loss, logits
| tensorflow.reduce_mean | 10,972 |
import tensorflow as tf
outputs, _ = tf.lite.experimental.nn.dynamic_rnn(
lstm_layer, lstm_input, dtype="float32")
outputs = tf.unstack(outputs, axis=0)
else:
lstm_input = tf.unstack(x, self.time_steps, 1)
outputs, _ = tf.nn.static_rnn(lstm_layer, lstm_input, dtype="float32")
# Compute logits by multiplying outputs[-1] of shape [batch_size,num_units]
| tensorflow.unstack | 10,973 |
import tensorflow as tf
self.r: batch.r,
self.local_network.state_in[0]: batch.features[0],
self.local_network.state_in[1]: batch.features[1],
}
fetched = sess.run(fetches, feed_dict=feed_dict)
if should_compute_summary:
self.summary_writer.add_summary(tf.Summary.FromString(fetched[0]), fetched[-1])
self.summary_writer.flush()
self.local_steps += 1
| tensorflow.Summary.FromString | 10,974 |
import tensorflow as tf
# Flatten CNN and concat with other features
zack_hack_div_2 = 0
if cnn_rnn_zack:
zack_hack_div_2 = zack_hack // 2
cnn_output = tf.slice(cnn_output, [0, zack_hack_div_2, 0, 0], [-1, rnn_nunroll, -1, -1])
nfeats_conv = reduce(lambda x, y: x * y, [int(x) for x in cnn_output.get_shape()[-2:]])
else:
nfeats_conv = reduce(lambda x, y: x * y, [int(x) for x in cnn_output.get_shape()[-3:]])
feats_conv = tf.reshape(cnn_output, [batch_size * rnn_nunroll, nfeats_conv])
nfeats_tot = nfeats_conv + nfeats
feats_all = tf.concat(1, [feats_conv, feats_other])
print('feats_cnn: {}'.format(feats_conv.get_shape()))
print('feats_all: {}'.format(feats_all.get_shape()))
# Project to RNN size
rnn_output = feats_all
| tensorflow.reshape | 10,975 |
import tensorflow as tf
if model_io_config.fix_lm == True:
scope = model_config.scope + "_finetuning"
else:
scope = model_config.scope
with tf.variable_scope(scope, reuse=model_reuse):
(loss,
per_example_loss,
logits) = classifier.classifier(model_config,
model.get_pooled_output(),
num_labels,
label_ids,
dropout_prob)
label_loss = tf.reduce_sum(per_example_loss * features["label_ratio"]) / (1e-10+tf.reduce_sum(features["label_ratio"]))
tf.get_variable_scope().reuse_variables()
(tgt_loss,
tgt_per_example_loss,
tgt_logits) = classifier.classifier(model_config,
features["distillation_feature"],
num_labels,
label_ids,
dropout_prob)
if mode == tf.estimator.ModeKeys.TRAIN:
distillation_api = distill.KnowledgeDistillation(kargs.get("disitllation_config", Bunch({
"logits_ratio_decay":"constant",
"logits_ratio":0.5,
| tensorflow.get_variable_scope | 10,976 |
import tensorflow as tf
with tf.variable_scope('X1'):
X1 = self._add_op_dynamic(cell_inputs, blocks, idx1, op1, w, h, block_ch, is_train=is_train)
X1 = self._add_drop_path(X1, drop_path_keep_prob)
with tf.variable_scope('X2'):
X2 = self._add_op_dynamic(cell_inputs, blocks, idx2, op2, w, h, block_ch, is_train=is_train)
X2 = self._add_drop_path(X2, drop_path_keep_prob)
X = tf.add_n([X1, X2])
blocks.append(X)
(X, comb_ch) = self._combine_cell_blocks_dynamic(cell_inputs, blocks, cell_arch, w, h, block_ch, is_train)
X = tf.reshape(X, (-1, w, h, comb_ch)) # Sanity shape check
layers.append((X, w, h, comb_ch))
def _add_static_cell(self, cell_arch, layers, w, h, block_ch, drop_path_keep_prob, is_train=False, is_reduction=False):
b = CELL_NUM_BLOCKS
# Calibrate inputs as necessary to last input layer's dimensions and add them to hidden states
cell_inputs = [layers[-2] if len(layers) > 1 else layers[-1], layers[-1]]
(_, w_inp_last, h_inp_last, _) = cell_inputs[-1]
for (i, (inp, w_inp, h_inp, ch_inp)) in enumerate(cell_inputs):
with tf.variable_scope('input_{}_calibrate'.format(i)):
inp = self._calibrate(inp, w_inp, h_inp, ch_inp, w_inp_last, h_inp_last, block_ch, is_train=is_train)
# Apply conv 1x1 on last input
| tensorflow.reshape | 10,977 |
import tensorflow as tf
"""
target_global_step = get_global_step('train_rl_global_step')
rl_reward = acc
rl_step_baseline = rl_reward
rl_baseline_momentum = 0.9
rl_entropy_regularization = 0.001
def update_rl_baseline():
return model_utils.update_exponential_moving_average(
rl_step_baseline, momentum=rl_baseline_momentum)
rl_baseline = update_rl_baseline()
rl_advantage = rl_reward - rl_baseline
rl_empirical_loss = -tf.stop_gradient(rl_advantage) * log_prob
rl_entropy_loss = -rl_entropy_regularization * rl_entropy
enable_rl_optimizer = tf.cast(
tf.greater_equal(target_global_step, FLAGS.first_pretrain_steps),
tf.float32)
rl_learning_rate = FLAGS.rl_learning_rate * enable_rl_optimizer
rl_learning_rate = tf.train.piecewise_constant(
target_global_step, [800,],
[rl_learning_rate, rl_learning_rate * 0.1])
optimizer = tf.train.AdamOptimizer(rl_learning_rate)
target_train_op = optimizer.minimize(
| tensorflow.stop_gradient | 10,978 |
import tensorflow as tf
bboxes = np.vstack((bboxes, tmp_bboxes)) # <class 'tuple'>: (5265, 5)
# non maximum suppression
# refind_idx = util.nms(bboxes, nms_thresh)
refind_idx = tf.image.non_max_suppression(tf.convert_to_tensor(bboxes[:, :4], dtype=tf.float32),
tf.convert_to_tensor(bboxes[:, 4], dtype=tf.float32),
max_output_size=bboxes.shape[0], iou_threshold=nms_thresh)
refind_idx = sess.run(refind_idx)
| tensorflow.convert_to_tensor | 10,979 |
import tensorflow as tf
path='save/'
ckpt_name = 'save/model.ckpt'
fname = 'model.tf'
dst_nodes = ['output/predictions']
saver = tf.train.Saver()
# Create a session and init
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print("training started!!")
print("******************")
# Now iterate over our dataset n_epoch times
for epoch_i in range(epoch):
this_loss = 0
| tensorflow.Session | 10,980 |
import tensorflow as tf
self.assertAllEqual([[3, 5]], result)
self.assertAllEqual([1], batch_size)
def test_two(self):
with self.test_session() as session:
@dynamic_batching.batch_fn
def f(a, b):
batch_size = tf.shape(a)[0]
return a + b, tf.tile([batch_size], [batch_size])
output0 = f(tf.constant([1]), tf.constant([2]))
output1 = f(tf.constant([2]), tf.constant([3]))
tp = pool.ThreadPool(2)
f0 = tp.apply_async(session.run, [output0])
f1 = tp.apply_async(session.run, [output1])
# Make sure both inputs are in the batcher before starting it.
time.sleep(_SLEEP_TIME)
tf.train.start_queue_runners()
| tensorflow.constant | 10,981 |
from tensorflow.contrib.framework import deprecated
def _at_k_name(name, k=None, class_id=None):
if k is not None:
name = '%s_at_%d' % (name, k)
else:
name = '%s_at_k' % (name)
if class_id is not None:
name = '%s_class%d' % (name, class_id)
return name
@deprecated('2016-11-08', 'Please use `streaming_sparse_recall_at_k`, '
'and reshape labels from [batch_size] to [batch_size, 1].')
@deprecated_args(IGNORE_MASK_DATE, IGNORE_MASK_INSTRUCTIONS, 'ignore_mask')
def streaming_recall_at_k(predictions, labels, k, ignore_mask=None,
weights=None, metrics_collections=None,
updates_collections=None, name=None):
"""Computes the recall@k of the predictions with respect to dense labels.
The `streaming_recall_at_k` function creates two local variables, `total` and
`count`, that are used to compute the recall@k frequency. This frequency is
ultimately returned as `recall_at_<k>`: an idempotent operation that simply
| tensorflow.contrib.framework.deprecated | 10,982 |
import tensorflow as tf
parser.add_argument('--max_train_step', type=int, default=50000, help='the maximum training step')
parser.add_argument('--model_path', type=str, default='', help='the path of checkpoint file')
args = parser.parse_args()
def model():
x = tf.placeholder(tf.float32, [None, 784], name='x')
gt = tf.placeholder(tf.float32, [None, 10], name='groundtruth')
with tf.variable_scope('layer1'):
w1 = tf.get_variable('weight1', [784, 1024], initializer=tf.random_normal_initializer())
b1 = tf.get_variable('bias1', [1024], initializer=tf.constant_initializer(0.0))
h1 = tf.nn.relu(tf.matmul(x, w1) + b1)
with tf.variable_scope('layer2'):
w2 = tf.get_variable('weight2', [1024, 1024], initializer=tf.random_normal_initializer())
b2 = tf.get_variable('bias2', [1024], initializer=tf.constant_initializer(0.0))
h2 = tf.nn.relu(tf.matmul(h1, w2) + b2)
with tf.variable_scope('layer3'):
w3 = tf.get_variable('weight3', [1024, 10], initializer=tf.random_normal_initializer())
b3 = tf.get_variable('bias3', [10], initializer=tf.constant_initializer(0.0))
y = tf.matmul(h2, w3) + b3
# losses
| tensorflow.matmul | 10,983 |
import tensorflow as tf
alpha_std = tf.exp(alpha_logstd)
# Compute epsilon from {n_samples} standard Gaussian
# epsilon = tf.random_normal([n_samples, 1, n_out*2, n_out])
epsilon = tf.random_uniform([n_samples, 1, n_basis, n_out])
hyp_params = tf.get_variable('hyp_params_layer'+str(h),
shape=[2],
initializer=tf.random_normal_initializer())
l1, l2 = tf.nn.sigmoid(hyp_params[0]), tf.exp(hyp_params[1])
epsilon = tf.sinh(epsilon*l2)/tf.cosh(epsilon*l2)**l1/l2
# Compute A_{h+1}
A = tf.tile(alpha_mean+epsilon*alpha_std, [1, tf.shape(X)[0], 1, 1])
# Compute z_{h}A_{h+1}
Z1 = tf.matmul(Z, A[:,:,:n_basis//2,:])/tf.sqrt(n_basis*.5)
Z2 = tf.matmul(Z, A[:,:,n_basis//2:,:])/tf.sqrt(n_basis*.5)
# Compute u_{h+1} and v_{h+1}
U, V = tf.cos(Z1)+tf.cos(Z2), tf.sin(Z1)+tf.sin(Z2)
Z = tf.concat([U, V], 3)/tf.sqrt(n_out*1.)
KL += tf.reduce_mean(alpha_std**2+alpha_mean**2-2*alpha_logstd-1)/2.
# Output layer
else:
F = tf.squeeze(tf.layers.dense(Z, n_out), [2])
return F, KL | tensorflow.sin | 10,984 |
import tensorflow as tf
ignored_matches = tf.logical_and(
ignored_matches,
tf.less(
matched_iou, self._config_dict['foreground_iou_threshold']))
| tensorflow.less | 10,985 |
import tensorflow as tf
'''
def gaussian_pdf(mean, loc_std, sample):
Z = 1.0 / (loc_std * tf.sqrt(2.0 * np.pi))
a = - tf.square(sample - mean) / (2.0 * tf.square(loc_std))
return Z * tf.exp(a)
class ACNet:
def __init__(self, scope, GRID_SIZE, a_size, trainer,TRAINING, GLOBAL_NET_SCOPE):
| tensorflow.exp | 10,986 |
import tensorflow as tf
self._on_training_abort(sess)
def inference(self, max=10^6):
self.fetch_datasets()
self.build_ae_model()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# nut.print_model_info()
# nut.list_checkpoint_vars(self.get_latest_checkpoint().replace(EMB_SUFFIX, ''))
self.saver = tf.train.Saver()
| tensorflow.Session | 10,987 |
import tensorflow as tf
for layer in range(self.config["contextualization_layers"]):
with tf.variable_scope("layer_{}".format(layer)):
with tf.variable_scope("fw_cell"):
cell_fw = util.CustomLSTMCell(self.config["contextualization_size"], num_sentences, self.lstm_dropout)
with tf.variable_scope("bw_cell"):
| tensorflow.variable_scope | 10,988 |
import tensorflow as tf
# state, target and action
self.state = tf.placeholder(tf.float32, [None,400], name="state")
self.target = tf.placeholder(tf.float32,[None,1], name="target")
self.a_his = tf.placeholder(tf.float32, [None, num_action], name="action_hist")
# layers
# wrap output
self.mu = self.mu * action_bound[1];
self.sigma = self.sigma + 1e-5
self.normal_dist = tf.contrib.distributions.Normal(self.mu, self.sigma)
self.action = tf.squeeze(self.normal_dist.sample(1),axis=0);
self.action = tf.clip_by_value(self.action, action_bound[0], action_bound[1])
# Loss and train op
self.loss = -self.normal_dist.log_prob(self.a_his) * self.target
# Add cross entropy cost to encourage exploration
self.loss -= entropy_beta * self.normal_dist.entropy()
self.optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
self.grads_and_vars = self.optimizer.compute_gradients(self.loss)
self.grads=[];
self.vars=[];
for i in range(len(self.grads_and_vars)):
self.grads.append(self.grads_and_vars[i][0]);
self.vars.append(self.grads_and_vars[i][1]);
| tensorflow.clip_by_value | 10,989 |
import tensorflow as tf
next_sentence_log_probs) = get_next_sentence_output(
bert_config, model.get_pooled_output(), next_sentence_labels, clip)
total_loss = masked_lm_loss + next_sentence_loss
tvars = tf.trainable_variables()
initialized_variable_names = {}
scaffold_fn = None
if init_checkpoint:
(assignment_map, initialized_variable_names
) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)
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,
init_string)
| tensorflow.train.init_from_checkpoint | 10,990 |
import tensorflow as tf
def force_cpu():
'''Force CPU on a GPU system
'''
import keras.backend as K
import tensorflow as tf
config = tf.ConfigProto(device_count={'GPU': 0})
session = tf.Session(config=config)
K.set_session(session)
| tensorflow.Session | 10,991 |
import tensorflow as tf
tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y))
# Optimization
opt = tf.train.AdamOptimizer(
learning_rate=self.learning_rate).minimize(loss)
| tensorflow.train.AdamOptimizer | 10,992 |
import tensorflow as tf
# I.e., 0.1 dropout
output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
logits = tf.matmul(output_layer, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
probabilities = tf.nn.softmax(logits, axis=-1)
log_probs = tf.nn.log_softmax(logits, axis=-1)
| tensorflow.nn.bias_add | 10,993 |
import tensorflow as tf
#print(predictions1)
predictions2 = tf.argmax(input=predictions1, axis=1)
predictions = sess.run(predictions2)
top1 += batch_size - (np.count_nonzero(predictions - np_labels))
#print(top1/num_processed_images)
#print(num_processed_images)
#print(predictions)
#accuracy1 = tf.reduce_sum(
# tf.nn.in_top_k(tf.cast(tf.Variable(predictions2), tf.float32),
# tf.cast((tf.constant(np_labels), 1), tf.float32)))
accuracy1 = tf.reduce_sum(
input_tensor=tf.cast(tf.nn.in_top_k(predictions=tf.constant(predictions1),
targets=tf.constant(np_labels), k=1), tf.float32))
accuracy5 = tf.reduce_sum(
input_tensor=tf.cast(tf.nn.in_top_k(predictions=tf.constant(predictions1),
targets=tf.constant(np_labels), k=5), tf.float32))
np_accuracy1, np_accuracy5 = sess.run([accuracy1, accuracy5])
##print(labels)
total_accuracy1 += np_accuracy1
total_accuracy5 += np_accuracy5
print("Processed %d images. (Top1 accuracy, Top5 accuracy) = (%0.4f, %0.4f)" \
% (num_processed_images, total_accuracy1/num_processed_images,
| tensorflow.constant | 10,994 |
from tensorflow.python.ops import sparse_ops
t1 = constant_op.constant([[359], [359 + 1024]])
t2 = constant_op.constant([list(range(10)), list(range(10))])
cross = sparse_feature_cross_op.sparse_feature_cross(
[t2, t1], hashed_output=True, num_buckets=1024)
cross_dense = sparse_ops.sparse_tensor_to_dense(cross)
with session.Session():
values = cross_dense.eval()
self.assertTrue(numpy.equal(values[0], values[1]).all())
| tensorflow.python.ops.sparse_ops.sparse_tensor_to_dense | 10,995 |
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
| tensorflow.app.flags.DEFINE_string | 10,996 |
import tensorflow as tf
# during inference, compute the end logits based on beam search
start_top_log_probs, start_top_index = tf.nn.top_k(
start_log_probs, k=FLAGS.start_n_top)
start_index = tf.one_hot(start_top_index,
depth=seq_len, axis=-1, dtype=tf.float32)
start_features = tf.einsum("lbh,bkl->bkh", output, start_index)
end_input = tf.tile(output[:, :, None],
[1, 1, FLAGS.start_n_top, 1])
start_features = tf.tile(start_features[None],
[seq_len, 1, 1, 1])
end_input = tf.concat([end_input, start_features], axis=-1)
end_logits = tf.layers.dense(
end_input,
xlnet_config.d_model,
kernel_initializer=initializer,
activation=tf.tanh,
name="dense_0")
end_logits = tf.contrib.layers.layer_norm(end_logits,
begin_norm_axis=-1)
end_logits = tf.layers.dense(
end_logits,
1,
kernel_initializer=initializer,
| tensorflow.layers.dense | 10,997 |
import tensorflow as tf
name="parameterized_shape" + shape_str,
iters=num_iters,
wall_time=p_dt)
self.report_benchmark(
name="naive_shape" + shape_str, iters=num_iters, wall_time=n_dt)
if __name__ == "__main__":
tf.test.main()
| tensorflow.test.main | 10,998 |
import tensorflow as tf
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])
| tensorflow.cast | 10,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.