seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
import tensorflow as tf
values_per_ex = sum(values_per_step)/dec_lens # shape (batch_size); normalized value for each batch member
return tf.reduce_mean(values_per_ex) # overall average
|
tensorflow.reduce_mean
| 8,700 |
import tensorflow as tf
# padding
pred_scores = padding(pred_scores, n_cands)
true_scores = padding(tf.reshape(cand_scores, (1, -1)), n_cands)
true_bestscore = tf.reduce_max(true_scores, axis=-1, keepdims=True)
assert all(true_bestscore.numpy() == np.take_along_axis(true_scores.numpy(), best_cands.numpy().reshape((-1, 1)), axis=1))
kacc = []
for k in top_k:
pred_top_k = tf.nn.top_k(pred_scores, k=k)[1].numpy()
pred_top_k_true_scores = np.take_along_axis(true_scores.numpy(), pred_top_k, axis=1)
kacc.append(np.mean(np.any(pred_top_k_true_scores == true_bestscore.numpy(), axis=1)))
kacc = np.asarray(kacc)
batch_size = int(n_cands.shape[0])
mean_kacc += kacc * batch_size
n_samples_processed += batch_size
mean_kacc /= n_samples_processed
|
tensorflow.nn.top_k
| 8,701 |
import tensorflow as tf
GLOBAL_STEP = tf.Variable(0, trainable=False)
INCREASE_GS = GLOBAL_STEP.assign(tf.add(GLOBAL_STEP, 1))
|
tensorflow.add
| 8,702 |
import tensorflow as tf
dtype=tf.float32,
shape=[len(vocab), size_layers],
initializer=tf.truncated_normal_initializer(mean=0.0, stddev=0.01),
)
lookup_table = tf.concat((tf.zeros(shape=[1, size_layers]), lookup_table[1:, :]), 0)
forward = tf.nn.embedding_lookup(lookup_table, self.X)
self.Y = tf.placeholder(tf.float32, (None, None, n_mels * resampled))
self.decoder_inputs = tf.concat((tf.zeros_like(self.Y[:, :1, :]), self.Y[:, :-1, :]), 1)
self.decoder_inputs = self.decoder_inputs[:, :, -n_mels:]
self.Z = tf.placeholder(tf.float32, (None, None, fourier_window_size // 2 + 1))
batch_size = tf.shape(self.X)[0]
|
tensorflow.placeholder
| 8,703 |
import tensorflow as tf
name: A string used as the name for this variable scope.
Returns:
(tf.Tensor) A single value tensor containing the loss.
(tf.Tensor) A tensor containing the propensity weights.
"""
loss = None
with tf.name_scope(name, "click_weighted_pairwise_loss",[output]):
sliced_output = tf.unstack(output, axis=1)
sliced_label = tf.unstack(labels, axis=1)
sliced_propensity = tf.unstack(propensity_weights, axis=1)
for i in range(len(sliced_output)):
for j in range(i+1, len(sliced_output)):
cur_label_weight = tf.math.sign(sliced_label[i] - sliced_label[j])
cur_propensity = sliced_propensity[i] * sliced_label[i] + sliced_propensity[j] * sliced_label[j]
cur_pair_loss = -tf.exp(sliced_output[i]) / (tf.exp(sliced_output[i]) + tf.exp(sliced_output[j]))
if loss == None:
loss = cur_label_weight * cur_pair_loss * cur_propensity
|
tensorflow.unstack
| 8,704 |
import tensorflow as tf
file_based_convert_examples_to_features(
train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file)
tf.logging.info("***** Running training *****")
tf.logging.info(" Num examples = %d", len(train_examples))
|
tensorflow.logging.info
| 8,705 |
import tensorflow.contrib.graph_editor as ge
with tf.name_scope(scope_name):
yield op_list
g = tf.get_default_graph()
op_list.extend(ge.select_ops(scope_name+"/.*", graph=g))
def _to_op(tensor_or_op):
if hasattr(tensor_or_op, "op"):
|
tensorflow.contrib.graph_editor.select_ops
| 8,706 |
import tensorflow as tf
# (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_trans_shine' + 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, facts_size, activation=tf.nn.sigmoid, name='f1_shine_att' + stag)
d_layer_2_all = tf.layers.dense(d_layer_1_all, facts_size, activation=tf.nn.sigmoid, name='f2_shine_att' + stag)
d_layer_2_all = tf.reshape(d_layer_2_all, tf.shape(facts))
output = d_layer_2_all
return output
|
tensorflow.shape
| 8,707 |
import tensorflow as tf
def no_attention(state, hidden_states, *args, **kwargs):
batch_size = tf.shape(state)[0]
weighted_average = tf.zeros(shape=tf.stack([batch_size, 0]))
weights = tf.zeros(shape=[batch_size, tf.shape(hidden_states)[1]])
return weighted_average, weights
def average_attention(hidden_states, encoder_input_length, *args, **kwargs):
# attention with fixed weights (average of all hidden states)
lengths = tf.to_float(tf.expand_dims(encoder_input_length, axis=1))
mask = tf.sequence_mask(encoder_input_length, maxlen=tf.shape(hidden_states)[1])
weights = tf.to_float(mask) / lengths
weighted_average = tf.reduce_sum(hidden_states * tf.expand_dims(weights, axis=2), axis=1)
return weighted_average, weights
def last_state_attention(hidden_states, encoder_input_length, *args, **kwargs):
weights = tf.one_hot(encoder_input_length - 1, tf.shape(hidden_states)[1])
weights = tf.to_float(weights)
weighted_average = tf.reduce_sum(hidden_states * tf.expand_dims(weights, axis=2), axis=1)
return weighted_average, weights
|
tensorflow.to_float
| 8,708 |
import tensorflow.contrib.slim as slim
method=1)
tf.summary.image('Compare/final_detection_gpu:%d' % i, detections_in_img)
loss_dict = outputs[-1]
total_loss_dict, total_losses = self.loss_dict(loss_dict, num_gpu)
if i == num_gpu - 1:
regularization_losses = tf.get_collection(
tf.GraphKeys.REGULARIZATION_LOSSES)
# weight_decay_loss = tf.add_n(slim.losses.get_regularization_losses())
total_losses = total_losses + tf.add_n(regularization_losses)
tf.get_variable_scope().reuse_variables()
grads = optimizer.compute_gradients(total_losses)
if cfgs.GRADIENT_CLIPPING_BY_NORM is not None:
grads = slim.learning.clip_gradient_norms(grads, cfgs.GRADIENT_CLIPPING_BY_NORM)
tower_grads.append(grads)
self.log_printer(r3det_gwd, optimizer, global_step, tower_grads, total_loss_dict, num_gpu, graph)
if __name__ == '__main__':
trainer = TrainR3DetGWD(cfgs)
trainer.main()
|
tensorflow.contrib.slim.learning.clip_gradient_norms
| 8,709 |
import tensorflow as tf
weight_decay, tf.float32,
[], 'weight_decay'
)
trainable_vars = tf.trainable_variables()
kernels = [
v for v in trainable_vars
if ('weights' in v.name or 'kernel' in v.name) and 'depthwise_weights' not in v.name
]
for K in kernels:
x = tf.multiply(weight_decay, tf.nn.l2_loss(K))
tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES, x)
class RestoreMovingAverageHook(tf.train.SessionRunHook):
def __init__(self, model_dir):
super(RestoreMovingAverageHook, self).__init__()
self.model_dir = model_dir
|
tensorflow.nn.l2_loss
| 8,710 |
import tensorflow as tf
else:
term2 = 0.5 * (param_eta + param_omega) * tf.log(tf.matrix_determinant(2 * np.pi * (param_eta + param_omega) * HaaInv))
dual = param_eta * self.epsilon - param_omega * beta + \
term1 + term2 + tf.reduce_mean(
0.5 * (tf.reduce_sum(tf.matmul(ha, HaaInv) * ha, axis=1) - hss))
# Symbolic dual gradient
dual_grad = tf.gradients(xs=[param_eta, param_omega], ys=dual)
|
tensorflow.matmul
| 8,711 |
from tensorflow.python.ops import state_ops
def _apply_dense(self, grad, var):
lr_t = math_ops.cast(self._lr_t, var.dtype.base_dtype)
g_t = grad
g_t_1 = self.get_slot(var, "g")
g_t = g_t_1.assign(g_t)
var_update = state_ops.assign_sub(var,
2. * lr_t * g_t - lr_t * g_t_1) # Adam would be lr_t * g_t
return control_flow_ops.group(*[var_update, g_t])
def _apply_sparse(self, grad, var):
raise NotImplementedError("Sparse gradient updates are not supported.")
|
tensorflow.python.ops.state_ops.assign_sub
| 8,712 |
from tensorflow.python.ops import math_ops
Returns:
mean_average_precision: Scalar `float64` `Tensor` with the mean average
precision values.
update: `Operation` that increments variables appropriately, and whose
value matches `metric`.
"""
default_name = _at_k_name('average_precision', k)
with ops.name_scope(name, default_name, (predictions, labels)) as scope:
# Calculate per-example average precision, and apply weights.
average_precision = sparse_average_precision_at_k(
predictions=predictions, labels=labels, k=k)
if weights is not None:
weights = math_ops.to_double(weights)
average_precision = math_ops.mul(average_precision, weights)
# Create accumulation variables and update ops for max average precision and
# total average precision.
with ops.name_scope(None, 'max', (average_precision,)) as max_scope:
# `max` is the max possible precision. Since max for any row is 1.0:
# - For the unweighted case, this is just the number of rows.
# - For the weighted case, it's the sum of the weights broadcast across
# `average_precision` rows.
max_var = contrib_variables.local_variable(
array_ops.zeros([], dtype=dtypes.float64), name=max_scope)
if weights is None:
batch_max = math_ops.to_double(
array_ops.size(average_precision, name='batch_max'))
|
tensorflow.python.ops.math_ops.mul
| 8,713 |
import tensorflow as tf
generator_inputs = features
real_data = labels
gan_model = tf.contrib.gan.gan_model(generator_fn, discriminator_fn, real_data, generator_inputs)
predictions = gan_model.generated_data
loss = None
train_op = None
if mode == tf.estimator.ModeKeys.TRAIN:
# define loss
gan_loss = tf.contrib.gan.gan_loss(gan_model, add_summaries=False)
loss = gan_loss.generator_loss
# define train_op
gen_optimizer = tf.train.RMSPropOptimizer(learning_rate=0.05)
dis_optimizer = tf.train.RMSPropOptimizer(learning_rate=0.05)
# wrapper to make the optimizer work with TPUs
if params['use_tpu']:
gen_optimizer = tf.contrib.tpu.CrossShardOptimizer(gen_optimizer)
dis_optimizer = tf.contrib.tpu.CrossShardOptimizer(dis_optimizer)
|
tensorflow.contrib.gan.gan_loss
| 8,714 |
import tensorflow as tf
n_h_mixer: integer
"""
agent_qs_reshaped = tf.reshape(agent_qs, [-1, 1, n_agents])
# n_h_mixer * n_agents because result will be reshaped into matrix
hyper_w_1 = get_variable('hyper_w_1', [state_dim, n_h_mixer*n_agents])
hyper_w_final = get_variable('hyper_w_final', [state_dim, n_h_mixer])
hyper_b_1 = tf.get_variable('hyper_b_1', [state_dim, n_h_mixer])
hyper_b_final_l1 = tf.layers.dense(inputs=state, units=n_h_mixer, activation=tf.nn.relu,
use_bias=False, name='hyper_b_final_l1')
hyper_b_final = tf.layers.dense(inputs=hyper_b_final_l1, units=1, activation=None,
use_bias=False, name='hyper_b_final')
# First layer
w1 = tf.abs(tf.matmul(state, hyper_w_1))
b1 = tf.matmul(state, hyper_b_1)
w1_reshaped = tf.reshape(w1, [-1, n_agents, n_h_mixer]) # reshape into batch of matrices
b1_reshaped = tf.reshape(b1, [-1, 1, n_h_mixer])
# [batch, 1, n_h_mixer]
hidden = tf.nn.elu(tf.matmul(agent_qs_reshaped, w1_reshaped) + b1_reshaped)
# Second layer
|
tensorflow.layers.dense
| 8,715 |
import tensorflow as tf
C = tf.tile(tf.expand_dims(self.c_embed_encoding, 2), [1, 1, self.max_q_len, 1])
Q = tf.tile(tf.expand_dims(self.q_embed_encoding, 1), [1, self.max_p_len, 1, 1])
S = trilinear([C, Q, C * Q], input_keep_prob=1.0 - self.dropout)
mask_q = tf.expand_dims(self.q_mask, 1)
S_ = tf.nn.softmax(mask_logits(S, mask=mask_q))
mask_c = tf.expand_dims(self.c_mask, 2)
S_T = tf.transpose(tf.nn.softmax(mask_logits(S, mask=mask_c), dim=1), (0, 2, 1))
self.c2q = tf.matmul(S_, self.q_embed_encoding)
self.q2c = tf.matmul(tf.matmul(S_, S_T), self.c_embed_encoding)
self.attention_outputs = [self.c_embed_encoding, self.c2q, self.c_embed_encoding * self.c2q,
self.c_embed_encoding * self.q2c]
N, PL, QL, CL, d, dc, nh = self._params()
if self.config.fix_pretrained_vector:
dc = self.char_mat.get_shape()[-1]
with tf.variable_scope("Model_Encoder_Layer"):
|
tensorflow.matmul
| 8,716 |
import tensorflow as tf
sl_indices = tf.range(block_len, dtype=tf.int32)
sl_col, sl_row = tf.meshgrid(sl_indices, sl_indices)
if direction == 'forward':
direct_mask = tf.greater(sl_row, sl_col) # bl,bl
else:
direct_mask = tf.greater(sl_col, sl_row) # bl,bl
direct_mask_tile = tf.tile(
tf.expand_dims(tf.expand_dims(direct_mask, 0), 0), [bs, bn, 1, 1]) # bs,bn,bl,bl
rep_mask_tile_1 = tf.tile(tf.expand_dims(rep_mask_split, 2), [1, 1, bl, 1]) # bs,bn,bl,bl
rep_mask_tile_2 = tf.tile(tf.expand_dims(rep_mask_split, 3), [1, 1, 1, bl]) # bs,bn,bl,bl
rep_mask_tile = tf.logical_and(rep_mask_tile_1, rep_mask_tile_2)
attn_mask = tf.logical_and(direct_mask_tile, rep_mask_tile, name='attn_mask') # bs,bn,bl,bl
# attention
|
tensorflow.expand_dims
| 8,717 |
from tensorflow.python.ops import math_ops
`values`, or if either `metrics_collections` or `updates_collections` are
not a list or tuple.
"""
is_below_threshold = math_ops.to_float(math_ops.less(values, threshold))
return streaming_mean(is_below_threshold, _mask_weights(ignore_mask, weights),
metrics_collections,
|
tensorflow.python.ops.math_ops.less
| 8,718 |
import tensorflow as tf
n_bits_x = self.hparams.n_bits_x
n_bins = 2**n_bits_x
x = tf.cast(x, dtype=tf.float32)
if n_bits_x < 8:
x = tf.floor(x / 2 ** (8 - n_bits_x))
x = x / n_bins - 0.5
return x
|
tensorflow.floor
| 8,719 |
import tensorflow as tf
Returns:
Corresponding number expressed in base.
"""
x_l = tf.to_int32(tf.expand_dims(x_int, axis=-1))
x_labels = []
for i in range(num_bits):
x_labels.append(
tf.floormod(
tf.floordiv(tf.to_int32(x_l),
tf.to_int32(base)**i), tf.to_int32(base)))
res = tf.concat(x_labels, axis=-1)
return tf.to_float(res)
def embed(self, x):
"""Embedding function that takes discrete latent and returns embedding.
Args:
x: Input to the discretization bottleneck.
Returns:
|
tensorflow.to_int32
| 8,720 |
from tensorflow.python.framework import ops
"""
super(LoggingTrainable, self).__init__(every_n, first_n)
self._scope = scope
def every_n_step_begin(self, step):
super(LoggingTrainable, self).every_n_step_begin(step)
# Get a list of trainable variables at the begining of every N steps.
# We cannot get this in __init__ because train_op has not been generated.
trainables = ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES,
scope=self._scope)
self._names = {}
for var in trainables:
self._names[var.name] = var.value().name
return list(self._names.values())
def every_n_step_end(self, step, outputs):
|
tensorflow.python.framework.ops.get_collection
| 8,721 |
import tensorflow as tf
token_type_table = tf.get_variable(
name=token_type_embedding_name,
shape=[token_type_vocab_size, width],
initializer=create_initializer(initializer_range))
# This vocab will be small so we always do one-hot here, since it is always
# faster for a small vocabulary.
flat_token_type_ids = tf.reshape(token_type_ids, [-1])
one_hot_ids = tf.one_hot(flat_token_type_ids, depth=token_type_vocab_size)
token_type_embeddings = tf.matmul(one_hot_ids, token_type_table)
token_type_embeddings = tf.reshape(token_type_embeddings,
[batch_size, seq_length, width])
output += token_type_embeddings
if use_position_embeddings:
assert_op = tf.assert_less_equal(seq_length, max_position_embeddings)
with tf.control_dependencies([assert_op]):
full_position_embeddings = tf.get_variable(
name=position_embedding_name,
|
tensorflow.reshape
| 8,722 |
from tensorflow.python.ops import array_ops
if predictions_rank > 1:
predictions = array_ops.reshape(predictions, [-1])
labels_rank = labels.get_shape().ndims
if labels_rank > 1:
labels = array_ops.reshape(labels, [-1])
weights = _mask_weights(ignore_mask, weights)
if weights is not None:
weights_rank = weights.get_shape().ndims
|
tensorflow.python.ops.array_ops.reshape
| 8,723 |
import tensorflow as tf
name: Optional scope/name for op_scope.
Returns:
A tensor with the clipped kappa log loss.
"""
with tf.name_scope(name):
num_classes = labels.get_shape()[-1].value
labels = tf.cast(labels, predictions.dtype)
if label_smoothing > 0:
smooth_positives = 1.0 - label_smoothing
|
tensorflow.name_scope
| 8,724 |
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
def din_fcn_shine(query, facts, attention_size, mask, stag='null', mode='SUM', softmax_stag=1, time_major=False, return_alphas=False):
if isinstance(facts, tuple):
# In case of Bi-RNN, concatenate the forward and the backward RNN outputs.
|
tensorflow.transpose
| 8,725 |
import tensorflow as tf
tf.constant(
all_masked_lm_positions,
shape=[num_examples, max_predictions_per_seq],
dtype=tf.int32),
"masked_lm_ids":
tf.constant(
all_masked_lm_ids,
shape=[num_examples, max_predictions_per_seq],
dtype=tf.int32)
})
|
tensorflow.constant
| 8,726 |
import tensorflow as tf
sp_returns = base._LIB_OP.get_full_neighbor(nodes, edge_types)
return tf.SparseTensor(*sp_returns[:3]), tf.SparseTensor(*sp_returns[3:6]), \
|
tensorflow.SparseTensor
| 8,727 |
import tensorflow as tf
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.nn.batch_normalization
| 8,728 |
import tensorflow as tf
output_predict_file = os.path.join(FLAGS.output_dir, "test_results.tsv")
with tf.gfile.GFile(output_predict_file, "w") as writer:
num_written_lines = 0
|
tensorflow.gfile.GFile
| 8,729 |
import tensorflow as tf
if var is not None:
tf.summary.scalar(name, var, [collection])
|
tensorflow.summary.scalar
| 8,730 |
import tensorflow as tf
[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,
name="dense_1")
end_logits = tf.reshape(end_logits, [seq_len, -1, FLAGS.start_n_top])
end_logits = tf.transpose(end_logits, [1, 2, 0])
end_logits_masked = end_logits * (
1 - p_mask[:, None]) - 1e30 * p_mask[:, None]
end_log_probs = tf.nn.log_softmax(end_logits_masked, -1)
end_top_log_probs, end_top_index = tf.nn.top_k(
end_log_probs, k=FLAGS.end_n_top)
end_top_log_probs = tf.reshape(
end_top_log_probs,
[-1, FLAGS.start_n_top * FLAGS.end_n_top])
end_top_index = tf.reshape(
end_top_index,
[-1, FLAGS.start_n_top * FLAGS.end_n_top])
if is_training:
|
tensorflow.reshape
| 8,731 |
import tensorflow as tf
train_input = PTBInput(config=config, data=train_data, name="TrainInput")
with tf.variable_scope("Model", reuse=None, initializer=initializer):
m = PTBModel(is_training=True, config=config, input_=train_input)
tf.summary.scalar("Training Loss", m.cost)
tf.summary.scalar("Learning Rate", m.lr)
with tf.name_scope("Valid"):
valid_input = PTBInput(config=config, data=valid_data, name="ValidInput")
|
tensorflow.summary.scalar
| 8,732 |
import tensorflow as tf
"""
adjusted_probs = tf.clip_by_value(probs, eps, 1.0 - eps)
xent_mat = -y * tf.log(adjusted_probs)
if class_weights is not None:
xent_mat *= class_weights
return tf.reduce_sum(xent_mat, sumd)
def _SafeNegEntropy(probs, batch_size, eps=0.0001):
"""Computes negative entropy in a way that will not overflow."""
adjusted_probs = tf.clip_by_value(probs, eps, 1.0 - eps)
entropy = tf.mul(probs, tf.log(adjusted_probs))
return tf.reduce_sum(entropy) / batch_size
|
tensorflow.clip_by_value
| 8,733 |
import tensorflow as tf
if decoder.cell_type.lower() == 'lstm' and decoder.use_lstm_full_state:
initial_output = initial_state
else:
# Last layer's state is the right-most part. Output is the left-most part of an LSTM's state.
initial_output = initial_state[:, -cell_output_size:]
time = tf.constant(0, dtype=tf.int32, name='time')
outputs = tf.TensorArray(dtype=tf.float32, size=time_steps)
samples = tf.TensorArray(dtype=tf.int64, size=time_steps)
inputs = tf.TensorArray(dtype=tf.int64, size=time_steps).unstack(tf.to_int64(tf.transpose(decoder_inputs)))
states = tf.TensorArray(dtype=tf.float32, size=time_steps)
weights = tf.TensorArray(dtype=tf.float32, size=time_steps)
attns = tf.TensorArray(dtype=tf.float32, size=time_steps)
initial_symbol = inputs.read(0) # first symbol is BOS
initial_input = embed(initial_symbol)
initial_pos = tf.zeros([batch_size], tf.float32)
initial_weights = tf.zeros(tf.shape(attention_states[align_encoder_id])[:2])
zero_context = tf.zeros(shape=tf.shape(attention_states[align_encoder_id][:,0])) # FIXME
with tf.variable_scope('decoder_{}'.format(decoder.name)):
initial_context, _ = look(0, initial_output, initial_input, pos=initial_pos, prev_weights=initial_weights,
context=zero_context)
initial_data = tf.concat([initial_state, initial_context, tf.expand_dims(initial_pos, axis=1), initial_weights],
|
tensorflow.TensorArray
| 8,734 |
import tensorflow as tf
print(args)
return args
if __name__ == "__main__":
args = parse_args()
if args.gpu==1:
os.environ['CUDA_VISIBLE_DEVICES']="0"
else:
os.environ['CUDA_VISIBLE_DEVICES']=""
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 1.0
config.gpu_options.allow_growth = True
config.log_device_placement=True
sess = tf.Session(config=config)
if args.command == "compress":
rootdir, filename = os.path.split(args.input)
if not args.output:
args.output = filename.split('.')[0]
print(args.output)
|
tensorflow.ConfigProto
| 8,735 |
import tensorflow as tf
self.logits = [mask_logits(start_logits, mask = self.c_mask),
mask_logits(end_logits, mask = self.c_mask)]
logits1, logits2 = [l for l in self.logits]
outer = tf.matmul(tf.expand_dims(tf.nn.softmax(logits1), axis=2),
tf.expand_dims(tf.nn.softmax(logits2), axis=1))
outer = tf.matrix_band_part(outer, 0, config.ans_limit)
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
|
tensorflow.nn.sparse_softmax_cross_entropy_with_logits
| 8,736 |
import tensorflow as tf
return h
def minibatch_discrimination(x, n_kernels, dim_per_kernel, name):
with tf.variable_scope(name):
batch_size, nf = x.get_shape().as_list()
h = linear(x, [nf, n_kernels*dim_per_kernel], 'h1')
activation = tf.reshape(h, (batch_size, n_kernels, dim_per_kernel))
big = tf.eye(batch_size)
big = tf.expand_dims(big, 1)
abs_dif = tf.reduce_sum(tf.abs(tf.expand_dims(activation, 3) - tf.expand_dims(tf.transpose(activation, [1, 2, 0]), 0)), 2)
mask = 1. - big
masked = tf.exp(-abs_dif) * mask
def half(tens, second):
m, n, _ = tens.get_shape().as_list()
return tf.slice(tens, [0, 0, second*(batch_size/2)], [m, n, batch_size/2])
f1 = tf.reduce_sum(half(masked, 0), 2) / tf.reduce_sum(half(mask, 0))
f2 = tf.reduce_sum(half(masked, 1), 2) / tf.reduce_sum(half(mask, 1))
return tf.concat([x, f1, f2], 1)
|
tensorflow.expand_dims
| 8,737 |
import tensorflow as tf
c = tf.to_int32(tf.reshape(c, shape=new_shape))
h1_shape = shape_x
h1_shape.append(self.hparams.hidden_size)
h1 = tf.zeros(dtype=tf.float32, shape=h1_shape)
c_int = self.bit_to_int(
c, num_bits=int(self.hparams.z_size / self.hparams.num_blocks), base=2)
|
tensorflow.zeros
| 8,738 |
import tensorflow as tf
# Select only unused blocks
with tf.variable_scope('select'):
stacked_blocks = tf.stack(cell_inputs + blocks)
out_blocks = tf.gather(stacked_blocks, unused_indices, axis=0)
out_blocks = tf.transpose(out_blocks, (1, 2, 3, 0, 4))
# Combine to constant channels
with tf.variable_scope('combine'):
W = self._make_var('W', (ni, block_ch * block_ch))
W = tf.gather(W, unused_indices, axis=0)
W = tf.reshape(W, (1, 1, num_out_blocks * block_ch, block_ch))
X = tf.reshape(out_blocks, (-1, w, h, num_out_blocks * block_ch))
X = tf.nn.relu(X)
X = tf.nn.conv2d(X, W, (1, 1, 1, 1), padding='SAME')
X = self._add_batch_norm(X, block_ch, is_train=is_train)
return (X, block_ch)
def _add_op(self, cell_inputs, blocks, input_idx, op, w, h, ch, is_reduction=False, is_train=False):
ni = len(cell_inputs + blocks)
inputs = cell_inputs + blocks
op_map = self._get_op_map()
# Just build output for select operation
X = inputs[input_idx]
op_no = OPS[op]
|
tensorflow.nn.conv2d
| 8,739 |
import tensorflow as tf
batch_size = tf.shape(policy.obs_ph)[0]
n_actions = ac_space.nvec if isinstance(ac_space, MultiDiscrete) else ac_space.n
random_actions = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=n_actions, dtype=tf.int64)
chose_random = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=1, dtype=tf.float32) < eps
perturbed_stochastic_actions = tf.where(chose_random, random_actions, perturbed_deterministic_actions)
stochastic_actions = tf.where(chose_random, random_actions, deterministic_actions)
perturbed_output_actions = tf.cond(stochastic_ph, lambda: perturbed_stochastic_actions,
lambda: deterministic_actions)
output_actions = tf.cond(stochastic_ph, lambda: stochastic_actions, lambda: deterministic_actions)
|
tensorflow.where
| 8,740 |
import tensorflow as tf
if a.operation == "edges" and a.crop:
try:
if not tf.io.gfile.exists(a.crop_dir):
tf.io.gfile.makedirs(a.crop_dir)
except Exception as e:
raise Exception("invalid crop_dir: {:s}".format(e))
src_paths = []
dst_paths = []
skipped = 0
for src_path in im.find(a.input_dir):
name, _ = os.path.splitext(os.path.basename(src_path))
dst_path = os.path.join(a.output_dir, name + ".png")
if tf.io.gfile.exists(dst_path):
skipped += 1
else:
src_paths.append(src_path)
dst_paths.append(dst_path)
print("skipping %d files that already exist" % skipped)
global total
total = len(src_paths)
print("processing %d files" % total)
global start
|
tensorflow.io.gfile.exists
| 8,741 |
import tensorflow as tf
with tf.variable_scope('mixing_net'):
# [batch, n_agents]
self.q_concat = tf.reshape(self.q_selected, [-1, self.n_agents])
self.q_concat_ =tf.reshape(self.q_m_, [-1, self.n_agents])
with tf.variable_scope('eval_hyper'):
self.Q_tot = Qmix_mixer(self.q_concat, self.S, self.num_global_s, self.n_agents, 32)
with tf.variable_scope('target_hyper'):
self.Q_tot_ = Qmix_mixer(self.q_concat_, self.S_, self.num_global_s, self.n_agents, 32)
|
tensorflow.variable_scope
| 8,742 |
import tensorflow as tf
mvalid = PTBModel(is_training=False, config=config, input_=valid_input)
tf.summary.scalar("Validation Loss", mvalid.cost)
with tf.name_scope("Test"):
test_input = PTBInput(
config=eval_config, data=test_data, name="TestInput")
with tf.variable_scope("Model", reuse=True, initializer=initializer):
mtest = PTBModel(is_training=False, config=eval_config,
input_=test_input)
models = {"Train": m, "Valid": mvalid, "Test": mtest}
for name, model in models.iteritems():
model.export_ops(name)
metagraph = tf.train.export_meta_graph()
if tf.__version__ < "1.1.0" and FLAGS.num_gpus > 1:
raise ValueError("num_gpus > 1 is not supported for TensorFlow versions "
"below 1.1.0")
soft_placement = False
if FLAGS.num_gpus > 1:
soft_placement = True
util.auto_parallel(metagraph, m)
with tf.Graph().as_default():
tf.train.import_meta_graph(metagraph)
for model in models.values():
model.import_ops()
|
tensorflow.train.export_meta_graph
| 8,743 |
import tensorflow as tf
# sum.fitTo(*data,"Extended") ;
# convert to tf constants, otherwise you'll get complaints about float32s...
constraint_tf = {}
for key in constraint.keys():
low = constraint[key][0]
high = constraint[key][1]
constraint_tf[key] = (tf.constant(low, dtype=tf.float64),
tf.constant(high, dtype=tf.float64))
print("N.B.: using direct data entry")
likelihood = sum_pdf(data, nsig, sigmean, sigwidth, nbkg, m0, argpar, constraint_tf['mes'][0], constraint_tf['mes'][1])
nll = tf.neg(tf.reduce_sum(tf.log(likelihood)), name="nll")
|
tensorflow.constant
| 8,744 |
import tensorflow as tf
"masked_lm_positions":
tf.FixedLenFeature([max_predictions_per_seq], tf.int64),
"masked_lm_ids":
tf.FixedLenFeature([max_predictions_per_seq], tf.int64),
"masked_lm_weights":
tf.FixedLenFeature([max_predictions_per_seq], tf.float32),
|
tensorflow.FixedLenFeature
| 8,745 |
import tensorflow as tf
in_loss_box = tf.pow(in_box_diff, 2) * (sigma_2 / 2.) * smoothL1_sign + (abs_in_box_diff - (0.5 / sigma_2)) * (1. - smoothL1_sign)
out_loss_box = bbox_outside_weights * in_loss_box
loss_box = tf.reduce_mean(tf.reduce_sum(
out_loss_box,
axis=dim
))
return loss_box
def _add_losses(self, sigma_rpn=3.0):
with tf.variable_scope('loss_' + self._tag):
# RPN, class loss
rpn_cls_score = tf.reshape(self._predictions['rpn_cls_score_reshape'], [-1, 2])
rpn_label = tf.reshape(self._anchor_targets['rpn_labels'], [-1])
# 得到前景和背景anchor的index
rpn_select = tf.where(tf.not_equal(rpn_label, -1))
rpn_cls_score = tf.reshape(tf.gather(rpn_cls_score, rpn_select), [-1, 2])
rpn_label = tf.reshape(tf.gather(rpn_label, rpn_select), [-1])
|
tensorflow.variable_scope
| 8,746 |
import tensorflow as tf
# y_true [batch_size, num_anchor, num_classes+1]
# y_pred [batch_size, num_anchor, num_classes]
labels = y_true
anchor_state = y_true[:, :, -1] # -1 是需要忽略的, 0 是背景, 1 是存在目标
classification = y_pred
# 找出存在目标的先验框
indices_for_object = tf.where(keras.backend.equal(anchor_state, 1))
labels_for_object = tf.gather_nd(labels, indices_for_object)
classification_for_object = tf.gather_nd(classification, indices_for_object)
cls_loss_for_object = keras.backend.binary_crossentropy(labels_for_object, classification_for_object)
# 找出实际上为背景的先验框
indices_for_back = tf.where(keras.backend.equal(anchor_state, 0))
labels_for_back = tf.gather_nd(labels, indices_for_back)
classification_for_back = tf.gather_nd(classification, indices_for_back)
# 计算每一个先验框应该有的权重
cls_loss_for_back = keras.backend.binary_crossentropy(labels_for_back, classification_for_back)
# 标准化,实际上是正样本的数量
normalizer_pos = tf.where(keras.backend.equal(anchor_state, 1))
normalizer_pos = keras.backend.cast(keras.backend.shape(normalizer_pos)[0], keras.backend.floatx())
normalizer_pos = keras.backend.maximum(keras.backend.cast_to_floatx(1.0), normalizer_pos)
normalizer_neg = tf.where(keras.backend.equal(anchor_state, 0))
normalizer_neg = keras.backend.cast(keras.backend.shape(normalizer_neg)[0], keras.backend.floatx())
normalizer_neg = keras.backend.maximum(keras.backend.cast_to_floatx(1.0), normalizer_neg)
|
tensorflow.gather_nd
| 8,747 |
import tensorflow as tf
import numpy as np
import tensorflow as tf
from collections import deque
def sample(logits):
noise = tf.random_uniform(tf.shape(logits))
return tf.argmax(logits - tf.log(-tf.log(noise)), 1)
def cat_entropy(logits):
a0 = logits - tf.reduce_max(logits, 1, keepdims=True)
ea0 = tf.exp(a0)
z0 = tf.reduce_sum(ea0, 1, keepdims=True)
p0 = ea0 / z0
return tf.reduce_sum(p0 * (tf.log(z0) - a0), 1)
def cat_entropy_softmax(p0):
return - tf.reduce_sum(p0 * tf.log(p0 + 1e-6), axis = 1)
|
tensorflow.reduce_max
| 8,748 |
import tensorflow as tf
dtype=tf.float32, input_size=input_size)
return cell
batch_size = tf.shape(encoder_inputs_)[0]
time_steps = tf.shape(encoder_inputs_)[1]
if embeddings is not None:
flat_inputs = tf.reshape(encoder_inputs_, [tf.multiply(batch_size, time_steps)])
flat_inputs = tf.nn.embedding_lookup(embeddings, flat_inputs)
encoder_inputs_ = tf.reshape(flat_inputs,
tf.stack([batch_size, time_steps, flat_inputs.get_shape()[1].value]))
if pos_embeddings is not None:
pos_inputs_ = tf.range(time_steps, dtype=tf.int32)
pos_inputs_ = tf.nn.embedding_lookup(pos_embeddings, pos_inputs_)
pos_inputs_ = tf.tile(tf.expand_dims(pos_inputs_, axis=0), [batch_size, 1, 1])
encoder_inputs_ = tf.concat([encoder_inputs_, pos_inputs_], axis=2)
if other_inputs is not None:
encoder_inputs_ = tf.concat([encoder_inputs_, other_inputs], axis=2)
if encoder.use_dropout:
noise_shape = [1, time_steps, 1] if encoder.pervasive_dropout else [batch_size, time_steps, 1]
encoder_inputs_ = tf.nn.dropout(encoder_inputs_, keep_prob=encoder.word_keep_prob,
noise_shape=noise_shape)
size = tf.shape(encoder_inputs_)[2]
|
tensorflow.nn.embedding_lookup
| 8,749 |
import tensorflow as tf
filters = tf.get_variable('zero_conv_weights' + id, initializer=init, shape=[size[0], size[1], in_ch, channels])
filters = filters - tf.reduce_mean(filters, axis=[0, 1, 2], keepdims=True)
if padding == "PARTIAL":
with tf.variable_scope('mask'):
_, h, w, _ = input.get_shape().as_list()
slide_window = size[0] * size[1]
mask = tf.ones(shape=[1, h, w, 1])
update_mask = tf.layers.conv2d(mask, filters=1, name='mask' + id,
kernel_size=size, kernel_initializer=tf.constant_initializer(1.0),
strides=stride, padding="SAME", use_bias=False, trainable=False,
dilation_rate=(dilation, dilation))
mask_ratio = slide_window / (update_mask + 1e-8)
update_mask = tf.clip_by_value(update_mask, 0.0, 1.0)
mask_ratio = mask_ratio * update_mask
with tf.variable_scope('parconv'):
x = tf.nn.conv2d(input, filters, strides=[1, stride, stride, 1], padding="SAME", name='zero-conv_' + id,
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
x = tf.nn.conv2d(input, filters, strides=[1, stride, stride, 1], padding=padding, name='zero-conv_' + id,
dilations=(1, dilation, dilation, 1))
|
tensorflow.clip_by_value
| 8,750 |
import tensorflow as tf
1,
])
src_features = tf.gather(src_features, indices, axis=0)
src_features = tf.stop_gradient(src_features)
src_labels = tf.gather(src_labels, indices)
inst_weights = bs * inst_weights / tf.reduce_sum(inst_weights)
src_one_hot_labels = tf.one_hot(tf.cast(src_labels, tf.int64), num_classes)
src_logits, dst_logits = get_model_logits(src_features, finetune_features,
mode, num_classes,
target_num_classes)
loss, _, _ = get_final_loss(src_logits, src_one_hot_labels, dst_logits,
finetune_one_hot_labels, global_step,
loss_weights, inst_weights)
|
tensorflow.cast
| 8,751 |
import tensorflow as tf
tf.get_variable_scope().reuse_variables()
else:
assert tf.get_variable_scope().reuse is False
|
tensorflow.get_variable_scope
| 8,752 |
from tensorflow.python.ops import array_ops
def _move_tensors(tensors, device):
"""Moves a list of tensors to a device by concatenating/splitting them."""
# Reset the device setting to avoid weird interactions with device merging
# logic.
with ops.device(None):
if all(tensor.shape == tensor_shape.scalar() for tensor in tensors):
with ops.device(tensors[0].device):
values = array_ops.stack(tensors)
with ops.device(device):
return array_ops.unstack(values)
else:
with ops.device(tensors[0].device):
sizes = array_ops.stack(
[array_ops.shape(tensor)[0] for tensor in tensors])
values = array_ops.concat(tensors, axis=0)
|
tensorflow.python.ops.array_ops.stack
| 8,753 |
from tensorflow.contrib import metrics as contrib_metrics
def metric_fn(per_example_loss, label_ids, logits, is_real_example):
"""Compute Pearson correlations for STS-B."""
# Display labels and predictions
concat1 = contrib_metrics.streaming_concat(logits)
concat2 = contrib_metrics.streaming_concat(label_ids)
|
tensorflow.contrib.metrics.streaming_concat
| 8,754 |
import tensorflow as tf
with tf.variable_scope(name, reuse=reuse):
layer_c1 = tf.layers.dense(state_in, 512, tf.nn.relu, kernel_regularizer=reg)
layer_c2 = tf.layers.dense(layer_c1, 256, tf.nn.relu, kernel_regularizer=reg)
lstm_c = tf.nn.rnn_cell.LSTMCell(num_units=256)
lstm_c = tf.nn.rnn_cell.DropoutWrapper(lstm_c, output_keep_prob=self.keep_prob)
state_init_c = lstm_c.zero_state(batch_size=batch_size, dtype=tf.float32)
lstm_cin = tf.expand_dims(layer_c2, axis=1)
out_c, state_final_c = tf.nn.dynamic_rnn(cell=lstm_c, inputs=lstm_cin, initial_state=state_init_c)
cell_out_c = tf.reshape(out_c, [-1, 256])
vf = tf.layers.dense(cell_out_c, 1, kernel_regularizer=reg)
params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=name)
return vf, params, state_init_c, state_final_c
# Update the network
|
tensorflow.nn.dynamic_rnn
| 8,755 |
import tensorflow as tf
sess.run(v0)
with self.assertRaisesOpError("uninitialized value v1"):
sess.run(v1)
save = tf.train.Saver({"save_prefix/v0": v0, "save_prefix/v1": v1})
save.restore(sess, save_path)
# Check that the parameter nodes have been restored.
|
tensorflow.train.Saver
| 8,756 |
import tensorflow as tf
from __future__ import print_function
import tensorflow as tf
import numpy as np
import TensorflowUtils as utils
import read_MITSceneParsingData as scene_parsing
import datetime
import BatchDatsetReader as dataset
from six.moves import xrange
import os.path as osp
FLAGS = tf.flags.FLAGS
tf.flags.DEFINE_integer("batch_size", "2", "batch size for training")
tf.flags.DEFINE_string("logs_dir", r"E:\work\01-Myproject\imag_division\FCN.tensorflow-master\logs", "path to logs directory")
tf.flags.DEFINE_string("data_dir", r"E:\work\01-Myproject\imag_division\FCN.tensorflow-master\Data_zoo\STEM", "path to dataset")
tf.flags.DEFINE_float("learning_rate", "1e-4", "Learning rate for Adam Optimizer")
tf.flags.DEFINE_string("model_dir", r"E:\work\01-Myproject\imag_division\FCN.tensorflow-master\Model_zoo", "Path to vgg model mat")
tf.flags.DEFINE_bool('debug', "False", "Debug mode: True/ False")
tf.flags.DEFINE_string('mode', "train", "Mode train/ test/ visualize")
MODEL_URL = 'http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat'
MAX_ITERATION = 100 #最大步数
NUM_OF_CLASSESS = 3 #分类数目
IMAGE_SIZE = 2048 #图像大小
|
tensorflow.flags.DEFINE_string
| 8,757 |
import tensorflow as tf
for i in range(len(pw_list)):
tf.summary.scalar('Inverse Propensity weights %d' % i, tf.reduce_mean(pw_list[i]), collections=['train'])
tf.summary.scalar('Rank Loss', tf.reduce_mean(self.rank_loss), collections=['train'])
# Compute examination loss
self.relevance_weights = self.get_normalized_weights(self.logits_to_prob(train_output))
self.exam_loss = self.loss_func(self.propensity, reshaped_train_labels, self.relevance_weights)
rw_list = tf.unstack(self.relevance_weights, axis=1) # Compute propensity weights
for i in range(len(rw_list)):
tf.summary.scalar('Relevance weights %d' % i, tf.reduce_mean(rw_list[i]), collections=['train'])
tf.summary.scalar('Exam Loss', tf.reduce_mean(self.exam_loss), collections=['train'])
# Gradients and SGD update operation for training the model.
self.loss = self.exam_loss + self.hparams.ranker_loss_weight * self.rank_loss
# Select optimizer
self.optimizer_func = tf.train.AdagradOptimizer
if self.hparams.grad_strategy == 'sgd':
|
tensorflow.reduce_mean
| 8,758 |
import tensorflow as tf
return DummyVariableStore()
def scheduled_sampling(hparams, problem_hparams, dp, sharded_logits, losses,
sharded_features, transformed_features, model):
"""Scheduled sampling."""
target_modality = problem_hparams.target_modality
def sample(x):
"""Multinomial sampling from a n-dimensional tensor."""
vocab_size = target_modality.top_dimensionality
samples = tf.multinomial(tf.reshape(x, [-1, vocab_size]), 1)
reshaped_samples = tf.reshape(samples, common_layers.shape_list(x)[:-1])
return tf.to_int32(reshaped_samples)
def mix_gold_sampled(gold_targets, sampled_targets):
return tf.where(
tf.less(
tf.random_uniform(common_layers.shape_list(sampled_targets)),
hparams.scheduled_sampling_gold_mixin_prob), gold_targets,
sampled_targets)
def sampled_results():
"""Generate scheduled sampling results."""
sampled_targets = dp(sample, sharded_logits)
new_targets = dp(mix_gold_sampled, sharded_features["targets"],
|
tensorflow.to_int32
| 8,759 |
import tensorflow as tf
export_outputs = {"predict_export_outputs": tf.estimator.export.PredictOutput(outputs = predictions)}
# 4. Return EstimatorSpec
return tf.estimator.EstimatorSpec(
mode = mode,
predictions = predictions_dict,
loss = loss,
train_op = train_op,
eval_metric_ops = eval_metric_ops,
export_outputs = export_outputs)
# Create serving input function
def serving_input_fn():
feature_placeholders = {
TIMESERIES_COL: tf.placeholder(tf.float32, [None, N_INPUTS])
}
features = {
key: tf.expand_dims(tensor, -1)
for key, tensor in feature_placeholders.items()
}
features[TIMESERIES_COL] = tf.squeeze(features[TIMESERIES_COL], axis = [2])
return tf.estimator.export.ServingInputReceiver(features, feature_placeholders)
# Create custom estimator's train and evaluate function
def train_and_evaluate(output_dir, use_keras):
if use_keras:
|
tensorflow.placeholder
| 8,760 |
import tensorflow as tf
result = estimator.evaluate(
input_fn=eval_input_fn, steps=FLAGS.max_eval_steps)
output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt")
with tf.gfile.GFile(output_eval_file, "w") as writer:
tf.logging.info("***** Eval results *****")
for key in sorted(result.keys()):
tf.logging.info(" %s = %s", key, str(result[key]))
writer.write("%s = %s\n" % (key, str(result[key])))
if FLAGS.do_train_eval:
tf.logging.info("***** Running training *****")
tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
train_input_fn = input_fn_builder(
input_files=input_files,
max_seq_length=FLAGS.max_seq_length,
max_predictions_per_seq=FLAGS.max_predictions_per_seq,
is_training=True,
batch_size=FLAGS.train_batch_size,
use_hvd=FLAGS.use_hvd)
tf.logging.info("***** Running evaluation *****")
tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
eval_input_fn = input_fn_builder(
input_files=validation_input_files,
|
tensorflow.logging.info
| 8,761 |
import tensorflow as tf
with g.gradient_override_map({'Conv3D': 'SymmetricConv3D'}):
activities = tf.nn.conv3d(
|
tensorflow.nn.conv3d
| 8,762 |
import tensorflow as tf
vx = tf.contrib.lookup.MutableHashTable(key_dtype=tf.string,
value_dtype=tf.int64,
default_value=-1)
vz = tf.contrib.lookup.MutableHashTable(key_dtype=tf.string,
value_dtype=tf.int64,
default_value=-1)
vx_keys = tf.reshape(tf.Variable([], collections=[], dtype=tf.string), (-1, 1))
|
tensorflow.contrib.lookup.MutableHashTable
| 8,763 |
import tensorflow as tf
lambda: self_attention_for_selected_head(
head_selection, head_org_idx, sl_head, rep_head_mask,
dep_selection, dep_org_idx, sl_dep, rep_dep_mask,
rep_map, rep_dep_tensor, keep_prob, is_train, direction, ivec
)
)
if keep_unselected:
input_idx = tf.tile(tf.expand_dims(tf.range(sl), 0), [bs, 1])
pooling_result = tf.cond(
tf.equal(sl_unhead, 0),
lambda: tf.zeros([bs, 0, hn], tf.float32),
lambda: mean_pooling_for_unselected_head(
unhead_org_idx, sl_unhead, rep_unhead_mask,
input_idx, sl, rep_mask, rep_map, None) # todo: point !
)
|
tensorflow.range
| 8,764 |
import tensorflow as tf
def file_based_input_fn_builder(input_file, seq_length, is_training, drop_remainder):
name_to_features = {
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_length], tf.int64),
"segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
"label_ids": tf.FixedLenFeature([seq_length], tf.int64),
}
def _decode_record(record, name_to_features):
example = tf.parse_single_example(record, name_to_features)
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
t = tf.to_int32(t)
example[name] = t
return example
def input_fn(params):
batch_size = params["batch_size"]
d = tf.data.TFRecordDataset(input_file)
if is_training:
d = d.repeat()
d = d.shuffle(buffer_size=100)
d = d.apply(tf.contrib.data.map_and_batch(
lambda record: _decode_record(record, name_to_features),
batch_size=batch_size,
drop_remainder=drop_remainder
|
tensorflow.to_int32
| 8,765 |
import tensorflow as tf
for stride in encoder.time_pooling[:encoder.layers - 1]:
encoder_input_length_ = (encoder_input_length_ + stride - 1) // stride # rounding up
last_backward = encoder_outputs_[:, 0, cell_output_size:]
indices = tf.stack([tf.range(batch_size), encoder_input_length_ - 1], axis=1)
last_forward = tf.gather_nd(encoder_outputs_[:, :, :cell_output_size], indices)
last_forward.set_shape([None, cell_output_size])
if encoder.final_state == 'concat_last': # concats last states of all backward layers (full LSTM states)
encoder_state_ = tf.concat(encoder_states_, axis=1)
elif encoder.final_state == 'average':
mask = tf.sequence_mask(encoder_input_length_, maxlen=tf.shape(encoder_outputs_)[1], dtype=tf.float32)
mask = tf.expand_dims(mask, axis=2)
encoder_state_ = tf.reduce_sum(mask * encoder_outputs_, axis=1) / tf.reduce_sum(mask, axis=1)
elif encoder.final_state == 'average_inputs':
mask = tf.sequence_mask(encoder_input_length_, maxlen=tf.shape(encoder_inputs_)[1], dtype=tf.float32)
mask = tf.expand_dims(mask, axis=2)
encoder_state_ = tf.reduce_sum(mask * encoder_inputs_, axis=1) / tf.reduce_sum(mask, axis=1)
elif encoder.bidir and encoder.final_state == 'last_both':
encoder_state_ = tf.concat([last_forward, last_backward], axis=1)
elif encoder.final_state == 'none':
encoder_state_ = tf.zeros(shape=[batch_size, 0])
elif encoder.bidir and not encoder.final_state == 'last_forward': # last backward hidden state
encoder_state_ = last_backward
else: # last forward hidden state
encoder_state_ = last_forward
if encoder.bidir and encoder.bidir_projection:
encoder_outputs_ = dense(encoder_outputs_, cell_output_size, use_bias=False, name='bidir_projection')
|
tensorflow.shape
| 8,766 |
import tensorflow as tf
):
with tf.name_scope('pooling_for_un_head'):
undep_idxs = tf.tile(tf.expand_dims(dep_org_idx, 1), [1, sl_unhead, 1]) # [bs, sluh, sld]
unhead_idxs = tf.tile(tf.expand_dims(unhead_org_idx, 2), [1, 1, sl_dep]) # [bs, sluh, sld]
if direction is None:
direct_mask_un = tf.not_equal(unhead_idxs, undep_idxs) # [bs, sluh, sld]
else:
if direction == 'forward':
direct_mask_un = tf.greater(unhead_idxs, undep_idxs) # [bs, sluh, sld]
else:
direct_mask_un = tf.less(unhead_idxs, undep_idxs) # [bs, sluh, sld]
# [bs, sluh, sld]
rep_mask_tile_un = tf.logical_and(tf.expand_dims(rep_dep_mask, 1), tf.expand_dims(rep_unhead_mask, 2))
pooling_mask = tf.logical_and(direct_mask_un, rep_mask_tile_un) # [bs, sluh, sld]
# data for pooling
pooling_data = tf.tile(tf.expand_dims(rep_dep_tensor, 1), [1, sl_unhead, 1, 1]) # bs,sluh,sld,hn
# execute mean pooling based on pooling_mask[bs, sluh, sld] and pooling_data[bs,sluh,sld,hn]
pooling_data = mask_for_high_rank(pooling_data, pooling_mask) # [bs,sluh,sld,hn]
|
tensorflow.less
| 8,767 |
import tensorflow as tf
"precision for calculating sufficient statistics.")
self._mean_shape = input_batch.get_shape().as_list()
for index in reduction_indices:
self._mean_shape[index] = 1
use_batch_stats = is_training | test_local_stats
# Use the legacy moving second moment if the flag is set.
if self._use_legacy_moving_second_moment:
tf.logging.warning(
"nn.BatchNorm `use_legacy_second_moment=True` is deprecated.")
mean, variance, second_moment = self._build_statistics_second_moment(
input_batch,
reduction_indices,
use_batch_stats)
self._build_update_ops_second_moment(mean, second_moment, is_training)
else:
|
tensorflow.logging.warning
| 8,768 |
import tensorflow as tf
returns_post_warmup = testeval(policy, runners['collect'])
if test:
test_returns.append(returns_post_warmup)
test_summary['warmup'].append(returns_post_warmup)
print ("warmupprocess:", test_summary['warmupprocess'][TEST_TASK_NUM])
logger.info('Sync warmup policy and vfn and model')
tf.get_default_session().run([sync_warmup_policy, sync_warmup_vfn, sync_warmup_model])
for p in warmup_policy.parameters(): p.invalidate()
for p in warmup_vfn.parameters(): p.invalidate()
for p in warmup_model.parameters(): p.invalidate()
for p in policy.parameters(): p.invalidate()
task.parameters().invalidate()
pol_params, warm_params = tf.get_default_session().run([nn.utils.parameters_to_vector(policy.parameters()), nn.utils.parameters_to_vector(warmup_policy.parameters())])
print ("After WARMUP, pol_params_norm:", np.linalg.norm(pol_params), "warm_params_norm:", np.linalg.norm(warm_params))
mod, warm_mod = tf.get_default_session().run([nn.utils.parameters_to_vector(model.parameters()), nn.utils.parameters_to_vector(warmup_model.parameters())])
print ("mod_norm:", np.linalg.norm(mod), "warm_mod_norm:", np.linalg.norm(warm_mod))
eval_rollout(runners['train'], warmup_policy, 'Use warmup policy to collect data from virtual env')
warmup_collect_virt = []
eval_rollout(runners['train'], policy, 'Use policy to collect data from virtual env')
warmup_collect_real = []
logger.info('--------------------------------------------- SLBO for %d outer stages -----------------------------------------' % slbo_n_stages)
for T in range(slbo_n_stages):
logger.info('-------- Starting Stage %d ---------', T)
|
tensorflow.get_default_session
| 8,769 |
import tensorflow as tf
tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
input_ids = features["input_ids"]
input_mask = features["input_mask"]
segment_ids = features["segment_ids"]
label_ids = features["label_ids"]
is_real_example = None
if "is_real_example" in features:
is_real_example = tf.cast(features["is_real_example"], dtype=tf.float32)
else:
is_real_example = tf.ones(label_ids.shape[0], dtype=tf.float32)
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
(total_loss, per_example_loss, logits, probabilities) = create_model(
bert_config, is_training, input_ids, input_mask, segment_ids, label_ids,
|
tensorflow.cast
| 8,770 |
import tensorflow as tf
with tf.variable_scope('input_{}_conv'.format(i)):
inp = self._do_conv(inp, w_inp_last, h_inp_last, block_ch, block_ch, is_train=is_train)
cell_inputs[i] = inp
blocks = []
for bi in range(b):
with tf.variable_scope('block_{}'.format(bi)):
idx1 = cell_arch[bi][0]
op1 = cell_arch[bi][1]
idx2 = cell_arch[bi][2]
op2 = cell_arch[bi][3]
with tf.variable_scope('X1'):
X1 = self._add_op(cell_inputs, blocks, idx1, op1, w, h, block_ch,
is_reduction=is_reduction, is_train=is_train)
X1 = self._add_drop_path(X1, drop_path_keep_prob)
with tf.variable_scope('X2'):
X2 = self._add_op(cell_inputs, blocks, idx2, op2, w, h, block_ch,
is_reduction=is_reduction, is_train=is_train)
X2 = self._add_drop_path(X2, drop_path_keep_prob)
X = tf.add_n([X1, X2])
blocks.append(X)
|
tensorflow.variable_scope
| 8,771 |
import tensorflow as tf
update_op = tf.group(update_op, *ops, name=name)
return update_op
@contextmanager
def _maybe_colocate(self, var):
G = tf.get_default_graph()
if self._colocate:
with G.colocate_with(var):
yield
else:
|
tensorflow.get_default_graph
| 8,772 |
import tensorflow as tf
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:
ds = ds.shuffle(N, reshuffle_each_iteration=True).repeat()
|
tensorflow.constant
| 8,773 |
import tensorflow as tf
def _MergeRight():
return tf.concat(
[_MergeOneToken(tokens, best_id), candidates[best_id + 2:]], axis=0)
right_candidates = tf.cond(
tf.greater_equal(best_id,
tf.size(tokens) - 1), lambda: empty, _MergeRight)
candidates = tf.concat([left_candidates, right_candidates], axis=0)
return tokens, candidates
return tf.while_loop(
_ShouldMerge,
_MergeCandidates, (tokens, candidates),
parallel_iterations=1,
back_prop=False)[0]
def Encode(self, text):
"""Converts string `text` to integer ids and the encoded string.
Encoding includes prefixing the beginning-of-word token to each word.
Returns:
|
tensorflow.while_loop
| 8,774 |
import tensorflow as tf
def __init__(self, args, embedding_init):
self.learning_rate = args.learning_rate
self.num_hidden = args.num_hidden
self.num_classes = args.num_classes
self.dropout_output = args.dropout_output
self.dropout_input = args.dropout_input
self.clip_norm = args.clip_norm
self.embedding_init = embedding_init
self.x = tf.placeholder(tf.int32, [None, None], 'input')
self.y = tf.placeholder(tf.int32, [None, self.num_classes], 'labels')
self.seq_len = tf.placeholder(tf.int64, [None], 'input_length')
def inference(self, forward_only=None):
embed_inputs = tf.nn.embedding_lookup(self.embedding_init, self.x) ## (batch_size, seq_len, 100)
with tf.variable_scope('hidden', reuse=forward_only):
with tf.variable_scope('lstm_cell'):
lstm_cell = tf.nn.rnn_cell.LSTMCell(num_units=self.num_hidden, use_peepholes=False,
|
tensorflow.placeholder
| 8,775 |
from tensorflow.python.layers import core as core_layers
if input_layer is None:
input_layer = self.top_layer
else:
self.top_size = None
name = 'dropout' + str(self.counts['dropout'])
with tf.variable_scope(name):
if not self.phase_train:
keep_prob = 1.0
dropout = core_layers.dropout(input_layer, keep_prob)
self.top_layer = dropout
return dropout
def batch_norm(self, input_layer=None, **kwargs):
"""Adds a Batch Normalization layer."""
if input_layer is None:
input_layer = self.top_layer
|
tensorflow.python.layers.core.dropout
| 8,776 |
import tensorflow as tf
with tf.variable_scope("input", reuse=False):
# Create policy and target TF objects
self.policy_tf = self.policy(self.sess, self.observation_space, self.action_space,
**self.policy_kwargs)
self.target_policy = self.policy(self.sess, self.observation_space, self.action_space,
**self.policy_kwargs)
# Initialize Placeholders
self.observations_ph = self.policy_tf.obs_ph
# Normalized observation for pixels
self.processed_obs_ph = self.policy_tf.processed_obs
self.next_observations_ph = self.target_policy.obs_ph
self.processed_next_obs_ph = self.target_policy.processed_obs
self.action_target = self.target_policy.action_ph
self.terminals_ph = tf.placeholder(tf.float32, shape=(None, 1), name='terminals')
self.rewards_ph = tf.placeholder(tf.float32, shape=(None, 1), name='rewards')
self.is_demo_ph = tf.placeholder(tf.float32, shape=(None, 1), name='is_demonstrations')
self.weight_ph = tf.placeholder(tf.float32, shape=(None, 1), name='importance_weight')
self.actions_ph = tf.placeholder(tf.float32, shape=(None,) + self.action_space.shape,
name='actions')
self.learning_rate_ph = tf.placeholder(tf.float32, [], name="learning_rate_ph")
if self.n_step:
self.next_observations_ph_n = self.target_policy.obs_ph
self.processed_next_obs_ph_n = self.target_policy.processed_obs
self.rewards_ph_n = tf.placeholder(tf.float32, shape=(None, 1), name='n_step_rewards')
self.terminals_ph_n = tf.placeholder(tf.float32, shape=(None, 1), name='n_step_terminals')
|
tensorflow.placeholder
| 8,777 |
import tensorflow as tf
targets = x['targets']
pad = tf.expand_dims(tf.zeros_like(inp[0]), axis=0)
concat = tf.concat([inp, pad, targets], axis=0)
mask = tf.concat([tf.zeros_like(inp), pad, tf.ones_like(targets)], axis=0)
x['inputs'] = concat
x['targets'] = concat
|
tensorflow.ones_like
| 8,778 |
import tensorflow as tf
def input_fn(params):
"""The actual input function."""
# batch_size = params["batch_size"]
name_to_features = {
"input_ids":
tf.FixedLenFeature([max_seq_length], tf.int64),
"input_mask":
tf.FixedLenFeature([max_seq_length], tf.int64),
"segment_ids":
tf.FixedLenFeature([max_seq_length], tf.int64),
"masked_lm_positions":
tf.FixedLenFeature([max_predictions_per_seq], tf.int64),
"masked_lm_ids":
tf.FixedLenFeature([max_predictions_per_seq], tf.int64),
"masked_lm_weights":
tf.FixedLenFeature([max_predictions_per_seq], tf.float32),
"next_sentence_labels":
tf.FixedLenFeature([1], tf.int64),
}
# For training, we want a lot of parallel reading and shuffling.
# For eval, we want no shuffling and parallel reading doesn't matter.
if is_training:
d = tf.data.Dataset.from_tensor_slices(tf.constant(input_files))
|
tensorflow.FixedLenFeature
| 8,779 |
import tensorflow as tf
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)]
dec_inp = [tf.constant(i, tf.int32, shape=[2]) for i in range(3)]
cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True)
dec, mem = tf.nn.seq2seq.embedding_attention_seq2seq(
enc_inp, dec_inp, cell, num_encoder_symbols=2,
num_decoder_symbols=5, embedding_size=2)
sess.run([tf.global_variables_initializer()])
res = sess.run(dec)
self.assertEqual(3, len(res))
self.assertEqual((2, 5), res[0].shape)
res = sess.run([mem])
self.assertEqual((2, 2), res[0].c.shape)
self.assertEqual((2, 2), res[0].h.shape)
|
tensorflow.constant
| 8,780 |
import tensorflow as tf
if clip_at_zero:
pred_x, pred_y = pred_x * tf.cast(pred_max>0, tf.float32), pred_y * tf.cast(pred_max>0, tf.float32)
pred_x = pred_x * tf.cast(pred_max>0, tf.float32) + tf.cast(pred_max<=0, tf.float32) * (width / 2.)
pred_y = pred_y * tf.cast(pred_max>0, tf.float32) + tf.cast(pred_max<=0, tf.float32) * (height / 2.)
if config.PRED_DEBUG:
pred_indices_ = tf.squeeze(pred_indices)
image_ = tf.squeeze(image) * 255.
pred_heatmap = tf.one_hot(pred_indices_, heatmap_size*heatmap_size, on_value=1., off_value=0., axis=-1, dtype=tf.float32)
pred_heatmap = tf.reshape(pred_heatmap, [-1, heatmap_size, heatmap_size])
if data_format == 'channels_first':
image_ = tf.transpose(image_, perm=(1, 2, 0))
save_image_op = tf.py_func(save_image_with_heatmap,
[image_, height, width,
heatmap_size,
tf.reshape(pred_heatmap * 255., [-1, heatmap_size, heatmap_size]),
tf.reshape(predictions, [-1, heatmap_size, heatmap_size]),
config.left_right_group_map[category][0],
config.left_right_group_map[category][1],
config.left_right_group_map[category][2]],
|
tensorflow.reshape
| 8,781 |
import tensorflow as tf
'''
if isinstance(ob_space, Discrete):
input_x = tf.placeholder(shape=(batch_size,), dtype=tf.int32, name=name)
processed_x = tf.to_float(tf.one_hot(input_x, ob_space.n))
return input_x, processed_x
elif isinstance(ob_space, Box):
input_shape = (batch_size,) + ob_space.shape
input_x = tf.placeholder(shape=input_shape, dtype=ob_space.dtype, name=name)
processed_x = tf.to_float(input_x)
return input_x, processed_x
else:
raise NotImplementedError
|
tensorflow.placeholder
| 8,782 |
import tensorflow as tf
global first
first = True
classnum=12
testnum = tf.placeholder(tf.int32)
trainnum = tf.placeholder(tf.int32)
validnum = tf.placeholder(tf.int32)
learnrate = tf.placeholder(tf.float32)
def getinputs(path):
filename_queue=tf.train.string_input_producer([path])
|
tensorflow.placeholder
| 8,783 |
import tensorflow as tf
stddev=1e-2,
strides=[1, 1, 1, 1],
padding="SAME",
nonlinearity=None,
bias=False,
weight_norm=False,
scale=False):
"""Convolutional layer."""
with tf.variable_scope(name) as scope:
weights = variable_on_cpu(
"weights",
filter_size + [dim_in, dim_out],
tf.random_uniform_initializer(
minval=-stddev, maxval=stddev))
# weight normalization
if weight_norm:
|
tensorflow.variable_scope
| 8,784 |
import tensorflow as tf
def contra_traj_lossV7(pred, tgt, horizon=12, temp=100):
horizon_pred, horizon_tgt = horizon_sumV1(pred, horizon), horizon_sumV1(tgt, horizon)
# horizon_pred, horizon_tgt = horizon_sumV2(pred, tgt, horizon)
pred_flat1, pred_flat2 = tf.reshape(horizon_pred, [-1, 1]), tf.reshape(horizon_pred, [1, -1])
tgt_flat1, tgt_flat2 = tf.reshape(horizon_tgt, [-1, 1]), tf.reshape(horizon_tgt, [1, -1])
tgt_dif = tgt_flat1 - tgt_flat2
pred_dif = pred_flat1 - pred_flat2
geq = tf.cast(tgt_dif > 0, tf.bool)
tgt_posi_dif = tf.where(geq, tgt_dif, -tgt_dif)
pred_posi_dif = tf.where(geq, pred_dif, -pred_dif)
loss = tf.maximum(0., tgt_posi_dif - pred_posi_dif)
cstr_pct = tf.math.count_nonzero(loss, dtype=tf.float32) / tf.cast(tf.reduce_prod(tf.shape(loss)), tf.float32)
unorm_w = tf.exp((tgt_flat1 + tgt_flat2)/temp)
loss = unorm_w * loss / (tf.reduce_sum(unorm_w))
a = tf.print(tf.reduce_sum(unorm_w))
with tf.control_dependencies([a]):
final_loss = tf.reduce_sum(loss)
return final_loss, cstr_pct
def contra_traj_lossV8(pred, tgt, horizon=12):
horizon_pred, horizon_tgt = horizon_sumV1(pred, horizon), horizon_sumV1(tgt, horizon)
# horizon_pred, horizon_tgt = horizon_sumV2(pred, tgt, horizon)
|
tensorflow.math.count_nonzero
| 8,785 |
import tensorflow.contrib.graph_editor as ge
xs = [xs]
bwd_ops = ge.get_backward_walk_ops([y.op for y in ys],
inclusive=True)
debug_print("bwd_ops: %s", bwd_ops)
# forward ops are all ops that are candidates for recomputation
fwd_ops = ge.get_forward_walk_ops([x.op for x in xs],
inclusive=True,
within_ops=bwd_ops)
debug_print("fwd_ops: %s", fwd_ops)
# exclude ops with no inputs
fwd_ops = [op for op in fwd_ops if op.inputs]
|
tensorflow.contrib.graph_editor.get_forward_walk_ops
| 8,786 |
import tensorflow as tf
@classmethod
def from_tfrecord_files(cls, input_files, **kwargs) -> tf.data.Dataset:
dataset = utils.read_tfrecord_files(input_files, **kwargs)
d = cls(examples=None, **kwargs)
# parse example
features = {
d.input_ids: tf.io.VarLenFeature(tf.int64),
d.token_type_ids: tf.io.VarLenFeature(tf.int64),
d.attention_mask: tf.io.VarLenFeature(tf.int64),
d.labels: tf.io.VarLenFeature(tf.int64),
}
dataset = dataset.map(
lambda x: tf.io.parse_example(x, features),
num_parallel_calls=utils.AUTOTUNE,
).prefetch(utils.AUTOTUNE)
dataset = dataset.map(
|
tensorflow.io.VarLenFeature
| 8,787 |
import tensorflow as tf
1.0, dtype=tf.float32,
shape=[len(self.groundtruth_lists(fields.BoxListFields.boxes)), 1])
location_losses = self._localization_loss(
prediction_dict['box_encodings'], batch_reg_targets,
weights=weights)
cls_losses = self._classification_loss(
prediction_dict['class_predictions_with_background'], batch_cls_targets,
weights=weights)
loss_dict = {
'localization_loss': tf.reduce_sum(location_losses),
'classification_loss': tf.reduce_sum(cls_losses),
}
return loss_dict
def regularization_losses(self):
"""Returns a list of regularization losses for this model.
Returns a list of regularization losses for this model that the estimator
needs to use during training/optimization.
Returns:
A list of regularization loss tensors.
|
tensorflow.reduce_sum
| 8,788 |
import tensorflow as tf
self.assertEqual(3, len(res))
self.assertEqual((2, 2), res[0].shape)
# Test that previous-feeding model ignores inputs after the first.
dec_inp2 = [tf.constant(0, tf.int32, shape=[2]) for _ in range(3)]
with tf.variable_scope("other"):
d3, _ = tf.nn.seq2seq.embedding_rnn_seq2seq(
enc_inp, dec_inp2, cell, num_encoder_symbols=2,
num_decoder_symbols=5, embedding_size=2,
feed_previous=tf.constant(True))
sess.run([tf.global_variables_initializer()])
tf.get_variable_scope().reuse_variables()
d1, _ = tf.nn.seq2seq.embedding_rnn_seq2seq(
enc_inp, dec_inp, cell, num_encoder_symbols=2,
num_decoder_symbols=5, embedding_size=2, feed_previous=True)
d2, _ = tf.nn.seq2seq.embedding_rnn_seq2seq(
enc_inp, dec_inp2, cell, num_encoder_symbols=2,
num_decoder_symbols=5, embedding_size=2, feed_previous=True)
res1 = sess.run(d1)
res2 = sess.run(d2)
res3 = sess.run(d3)
self.assertAllClose(res1, res2)
|
tensorflow.get_variable_scope
| 8,789 |
from tensorflow.contrib import slim
[slim.conv2d, slim.separable_conv2d],
weights_initializer=weights_init,
activation_fn=tf.nn.relu6,
normalizer_fn=normalizer_fn,
):
with slim.arg_scope([slim.batch_norm], **batch_norm_params):
with slim.arg_scope([slim.conv2d], weights_regularizer=regularizer):
with slim.arg_scope(
[slim.separable_conv2d], weights_regularizer=depthwise_regularizer
) as sc:
|
tensorflow.contrib.slim.arg_scope
| 8,790 |
import tensorflow as tf
reg += self.L2_out * tf.reduce_mean(tf.square(tf.abs(self.W_out) * self.output_Connectivity))
# L2 firing rate regularization
reg += self.L2_firing_rate * tf.reduce_mean(tf.square(tf.nn.relu(self.states)))
# susillo regularization
|
tensorflow.nn.relu
| 8,791 |
import tensorflow as tf
ep_reward += sum(reward_n)
obs_glob = [obs[0] + obs[1]]
obs_glob_next = [obs_n[0] + obs_n[1]]
self.store(obs_glob + obs + action + [sum(reward_n)] + obs_glob_next + obs_n + [all(done_n)])
obs = obs_n
self.learn()
self.write_summary_scalar("ep_reward", ep_reward, self.learn_step_cnt)
def write_summary_scalar(self, tag, value, iteration):
self.summary_writer.add_summary(tf.Summary(value=[tf.Summary.Value(tag=tag, simple_value=value)]), iteration)
env = gym.make('Switch2-v0')
alg = QMix(env, env.observation_space[0].shape[0], env.action_space[0].n)
# alg = QMix(env, env.observation_space.shape[0], env.action_space.n)
alg.train()
|
tensorflow.Summary.Value
| 8,792 |
import tensorflow as tf
gh_w = gh_w.reshape(-1, 1) / np.sqrt(np.pi)
shape = tf.shape(Fmu)
Fmu, Fvar = [tf.reshape(e, (-1, 1)) for e in (Fmu, Fvar)]
X = gh_x * tf.sqrt(2.0 * Fvar) + Fmu
logp = phi(X)
return tf.reshape(tf.matmul(logp, gh_w), shape)
import tensorflow as tf
|
tensorflow.matmul
| 8,793 |
from tensorflow.python.framework import ops
self.graph = None
self.feed_tensors = None
self.fetch_tensors = None
def process(self, inputs):
# Create a session for every worker only once. The session is not
# pickleable, so it can't be created at the DoFn constructor.
if not self.session:
self.graph = ops.Graph()
with self.graph.as_default():
self.session = tf.Session()
metagraph_def = loader.load(
self.session, {self.meta_tag}, self.model_dir)
signature_def = metagraph_def.signature_def[self.meta_signature]
# inputs
|
tensorflow.python.framework.ops.Graph
| 8,794 |
import tensorflow as tf
return
with tf.Graph().as_default():
if FLAGS.eval:
self._eval_cnn()
else:
self._benchmark_cnn()
def _eval_cnn(self):
"""Evaluate the model from a checkpoint using validation dataset."""
(enqueue_ops, fetches) = self._build_model()
saver = tf.train.Saver(tf.global_variables())
summary_writer = tf.summary.FileWriter(FLAGS.eval_dir,
tf.get_default_graph())
target = ''
with tf.Session(target=target, config=create_config_proto()) as sess:
for i in xrange(len(enqueue_ops)):
sess.run(enqueue_ops[:(i+1)])
if FLAGS.train_dir is None:
raise ValueError('Trained model directory not specified')
global_step = load_checkpoint(saver, sess, FLAGS.train_dir)
start_time = time.time()
count_top_1 = 0.0
count_top_5 = 0.0
total_eval_count = self.num_batches * self.batch_size
|
tensorflow.get_default_graph
| 8,795 |
import tensorflow as tf
interpreter.allocate_tensors()
except ValueError:
assert False
input_index = (interpreter.get_input_details()[0]["index"])
interpreter.set_tensor(input_index, test_inputs)
interpreter.invoke()
output_index = (interpreter.get_output_details()[0]["index"])
result = interpreter.get_tensor(output_index)
# Reset all variables so it will not pollute other inferences.
interpreter.reset_all_variables()
return result
def testStaticRnnMultiRnnCell(self):
sess = tf.compat.v1.Session(config=CONFIG)
x, prediction, output_class = self.buildModel(
self.buildLstmLayer(), is_dynamic_rnn=False)
self.trainModel(x, prediction, output_class, sess)
saver = tf.train.Saver()
x, prediction, output_class, new_sess = self.saveAndRestoreModel(
self.buildLstmLayer(), sess, saver, is_dynamic_rnn=False)
test_inputs, expected_output = self.getInferenceResult(
x, output_class, new_sess)
# Test Toco-converted model.
|
tensorflow.compat.v1.Session
| 8,796 |
from tensorflow.python.framework import ops
cov,
math_ops.mul(math_ops.sqrt(var_predictions), math_ops.sqrt(var_labels)),
'pearson_r')
with ops.control_dependencies(
[update_cov, update_var_predictions, update_var_labels]):
update_op = _safe_div(update_cov, math_ops.mul(
math_ops.sqrt(update_var_predictions),
math_ops.sqrt(update_var_labels)), 'update_op')
if metrics_collections:
ops.add_to_collections(metrics_collections, pearson_r)
if updates_collections:
ops.add_to_collections(updates_collections, update_op)
return pearson_r, update_op
# TODO(nsilberman): add a 'normalized' flag so that the user can request
# normalization if the inputs are not normalized.
def streaming_mean_cosine_distance(predictions, labels, dim, weights=None,
metrics_collections=None,
updates_collections=None,
name=None):
"""Computes the cosine distance between the labels and predictions.
|
tensorflow.python.framework.ops.add_to_collections
| 8,797 |
import tensorflow as tf
next_sentence_log_probs = tf.reshape(
next_sentence_log_probs, [-1, next_sentence_log_probs.shape[-1]])
next_sentence_predictions = tf.argmax(
next_sentence_log_probs, axis=-1, output_type=tf.int32)
next_sentence_labels = tf.reshape(next_sentence_labels, [-1])
next_sentence_accuracy = tf.metrics.accuracy(
labels=next_sentence_labels, predictions=next_sentence_predictions)
next_sentence_mean_loss = tf.metrics.mean(
values=next_sentence_example_loss)
return {
"masked_lm_accuracy": masked_lm_accuracy,
"masked_lm_loss": masked_lm_mean_loss,
"next_sentence_accuracy": next_sentence_accuracy,
"next_sentence_loss": next_sentence_mean_loss,
|
tensorflow.metrics.mean
| 8,798 |
import tensorflow as tf
# (1, height, width, A * 4)
# (1, height, width, A * 4)
rpn_labels, rpn_bbox_targets, rpn_bbox_inside_weights, rpn_bbox_outside_weights = tf.py_func(
anchor_target_layer,
[rpn_cls_score, self._gt_boxes, self._im_info, self._feat_stride, self._anchors, self._num_anchors],
[tf.float32, tf.float32, tf.float32, tf.float32])
#self._gt_boxes = tf.placeholder(tf.float32, shape=[None, 5]) #gt_boxes缩放之后的坐标以及所属类别的标号
rpn_labels.set_shape([1, 1, None, None])
rpn_bbox_targets.set_shape([1, None, None, self._num_anchors * 4])
rpn_bbox_inside_weights.set_shape([1, None, None, self._num_anchors * 4])
rpn_bbox_outside_weights.set_shape([1, None, None, self._num_anchors * 4])
rpn_labels = tf.to_int32(rpn_labels, name="to_int32")
self._anchor_targets['rpn_labels'] = rpn_labels
self._anchor_targets['rpn_bbox_targets'] = rpn_bbox_targets
self._anchor_targets['rpn_bbox_inside_weights'] = rpn_bbox_inside_weights
self._anchor_targets['rpn_bbox_outside_weights'] = rpn_bbox_outside_weights
self._score_summaries.update(self._anchor_targets)
return rpn_labels
def _proposal_target_layer(self, rois, roi_scores, name):
with tf.variable_scope(name):
# 这里的index是对于cfg.FLAGS.batch_size=256 而言
|
tensorflow.to_int32
| 8,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.