seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
import tensorflow as tf
rnn_inputs = tf.nn.bias_add(tf.matmul(feats_all, rnn_proj_w), rnn_proj_b)
rnn_inputs = tf.reshape(rnn_inputs, [batch_size, rnn_nunroll, rnn_size])
| tensorflow.reshape | 13,400 |
import tensorflow as tf
Eval:
{spacer}Positive count: {eval_pos_ct}
{spacer}Batch size: {eval_batch_size} {multiplier}
{spacer}Batch count per epoch: {eval_batch_ct}"""
_TRAIN_FEATURE_MAP = {
movielens.USER_COLUMN: tf.FixedLenFeature([], dtype=tf.string),
movielens.ITEM_COLUMN: tf.FixedLenFeature([], dtype=tf.string),
rconst.MASK_START_INDEX: tf.FixedLenFeature([1], dtype=tf.string),
"labels": tf.FixedLenFeature([], dtype=tf.string),
}
| tensorflow.FixedLenFeature | 13,401 |
import tensorflow as tf
# Input tensors
feats_audio_nunroll = tf.placeholder(dtype, shape=[batch_size, rnn_nunroll + zack_hack, audio_context_len, audio_nbands, audio_nchannels], name='feats_audio')
feats_other_nunroll = tf.placeholder(dtype, shape=[batch_size, rnn_nunroll, nfeats], name='feats_other')
| tensorflow.placeholder | 13,402 |
import tensorflow as tf
input=activation,
input_size=dialogue_state_action_template_size,
output_size=num_actions_arguments * actions_arguments_vocabulary_length,
name='linear_projection_3_predictions_arguments'
)
self.predictions_arguments = softmax_2d(
input=projection,
n_classifiers=num_actions_arguments,
n_classes=actions_arguments_vocabulary_length,
name="softmax_2d_predictions_arguments")
if FLAGS.print_variables:
for v in tf.trainable_variables():
print(v.name)
with tf.name_scope('loss'):
one_hot_labels_action = dense_to_one_hot(actions_template, action_templates_vocabulary_length)
one_hot_labels_arguments = dense_to_one_hot(actions_arguments, actions_arguments_vocabulary_length)
loss_action = tf.reduce_mean(
- one_hot_labels_action * tf.log(tf.clip_by_value(self.predictions_action, 1e-10, 1.0)),
name='loss'
)
loss_arguments = tf.reduce_mean(
- one_hot_labels_arguments * tf.log(tf.clip_by_value(self.predictions_arguments, 1e-10, 1.0)),
name='loss'
)
self.loss = loss_action + loss_arguments
| tensorflow.name_scope | 13,403 |
import tensorflow as tf
def _build_sampler(self, prev_c=None, prev_h=None, use_bias=False):
"""Build the sampler ops and the log_prob ops."""
print ("-" * 80)
print ("Build controller sampler")
anchors = tf.TensorArray(
tf.float32, size=self.num_cells + 2, clear_after_read=False)
anchors_w_1 = tf.TensorArray(
tf.float32, size=self.num_cells + 2, clear_after_read=False)
arc_seq = tf.TensorArray(tf.int32, size=self.num_cells * 4)
if prev_c is None:
assert prev_h is None, "prev_c and prev_h must both be None"
prev_c = [tf.zeros([1, self.lstm_size], tf.float32)
for _ in range(self.lstm_num_layers)]
prev_h = [tf.zeros([1, self.lstm_size], tf.float32)
for _ in range(self.lstm_num_layers)]
inputs = self.g_emb
for layer_id in range(2):
next_c, next_h = stack_lstm(inputs, prev_c, prev_h, self.w_lstm)
prev_c, prev_h = next_c, next_h
anchors = anchors.write(layer_id, tf.zeros_like(next_h[-1]))
anchors_w_1 = anchors_w_1.write(
layer_id, tf.matmul(next_h[-1], self.w_attn_1))
| tensorflow.zeros | 13,404 |
import tensorflow as tf
assert self.mean is not None
assert self.mean_sq is not None
out = tf.nn.relu(self._normalize(x, self.mean, self.mean_sq, "reference"))
self.reference_output = out
def __call__(self, x, update=False):
with tf.variable_scope(self.name) as scope:
if not update:
new_coeff = 1. / (self.batch_size + 1.)
old_coeff = 1. - new_coeff
new_mean = tf.reduce_mean(x, [1, 2], keep_dims=True)
new_mean_sq = tf.reduce_mean(tf.square(x), [1, 2], keep_dims=True)
| tensorflow.variable_scope | 13,405 |
import tensorflow as tf
output, state = self._build_rnn_graph(inputs, config, is_training)
softmax_w = tf.get_variable(
"softmax_w", [size, vocab_size], dtype=data_type())
softmax_b = tf.get_variable("softmax_b", [vocab_size], dtype=data_type())
logits = tf.nn.xw_plus_b(output, softmax_w, softmax_b)
# Reshape logits to be a 3-D tensor for sequence loss
logits = tf.reshape(logits, [self.batch_size, self.num_steps, vocab_size])
# Use the contrib sequence loss and average over the batches
| tensorflow.nn.xw_plus_b | 13,406 |
from tensorflow.python.ops import math_ops
`recall`.
Raises:
ValueError: If `ignore_mask` is not `None` and its shape doesn't match
`predictions`, or if `weights` is not `None` and its shape doesn't match
`predictions`, or if either `metrics_collections` or `updates_collections`
are not a list or tuple.
"""
default_name = _at_k_name('recall', k, class_id=class_id)
with ops.name_scope(name, default_name, (predictions, labels)) as scope:
_, top_k_idx = nn.top_k(predictions, k)
top_k_idx = math_ops.to_int64(top_k_idx)
weights = _mask_weights(ignore_mask, weights)
tp, tp_update = _streaming_sparse_true_positive_at_k(
predictions_idx=top_k_idx, labels=labels, k=k, class_id=class_id,
weights=weights)
fn, fn_update = _streaming_sparse_false_negative_at_k(
predictions_idx=top_k_idx, labels=labels, k=k, class_id=class_id,
weights=weights)
metric = math_ops.div(tp, math_ops.add(tp, fn), name=scope)
update = math_ops.div(
| tensorflow.python.ops.math_ops.to_int64 | 13,407 |
import tensorflow as tf
len(predict_examples), num_actual_predict_examples,
len(predict_examples) - num_actual_predict_examples)
tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size)
| tensorflow.logging.info | 13,408 |
import tensorflow as tf
# break # 结束本回合
# global_step = SESS.run(self.global_AC.global_step)
if __name__ == '__main__':
SESS = tf.Session()
with tf.device('/cpu:0'):
OPT = tf.train.AdamOptimizer(1e-4) # 后续主要是使用该optimizer中的apply—gradients操作
# OPT_C = tf.train.RMSPropOptimizer(LR_C, name='RMSPropC') # 定义critic训练过程
GLOBAL_AC = ACnet(scope=GLOBAL_NET_SCOPE) # 创建中央大脑GLOBALE_AC,只创建结构(A和C的参数)
workers = []
for i in range(N_workers): # N—workers等于cpu数量
i_name = 'W_%i' % i # worker name
workers.append(Worker(name=i_name, globalAC=GLOBAL_AC)) # 创建独立的worker
| tensorflow.device | 13,409 |
import tensorflow as tf
"""
with tf.name_scope(name):
predictions.get_shape().assert_is_compatible_with(labels.get_shape())
predictions = tf.to_float(predictions)
labels = tf.to_float(labels)
losses = -tf.multiply(labels, tf.log(predictions + eps)) - tf.multiply(
(1 - labels), tf.log(1 - predictions + eps))
return tf.losses.compute_weighted_loss(losses, weights)
| tensorflow.log | 13,410 |
import tensorflow as tf
else:
conv_bn = cnv
biases = tf.get_variable("biases", [nOut], initializer=tf.constant_initializer(), dtype=inpOp.dtype)
bias = tf.nn.bias_add(conv_bn, biases)
conv1 = tf.nn.relu(bias)
return conv1
def convLinear(inpOp, nIn, nOut, kH, kW, dH, dW, padType, name, phase_train=True, use_batch_norm=True, weight_decay=0.0):
with tf.variable_scope(name):
l2_regularizer = lambda t: l2_loss(t, weight=weight_decay)
kernel = tf.get_variable("weights", [kH, kW, nIn, nOut],
initializer=tf.truncated_normal_initializer(stddev=1e-1),
regularizer=l2_regularizer, dtype=inpOp.dtype)
cnv = tf.nn.conv2d(inpOp, kernel, [1, dH, dW, 1], padding=padType)
if use_batch_norm:
| tensorflow.variable_scope | 13,411 |
import tensorflow as tf
shape [-1, num_blocks, block_dim].
means: Embedding means of shape.
Returns:
Tensor with nearest element in mean encoded in one-hot notation.
"""
x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keep_dims=True)
means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keep_dims=True)
scalar_prod = tf.matmul(
tf.transpose(x, perm=[1, 0, 2]), tf.transpose(means, perm=[0, 2, 1]))
scalar_prod = tf.transpose(scalar_prod, perm=[1, 0, 2])
dist = x_norm_sq + tf.transpose(
means_norm_sq, perm=[2, 0, 1]) - 2 * scalar_prod
| tensorflow.square | 13,412 |
import tensorflow as tf
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
epsilon_decay = tf.train.polynomial_decay(self.EPSILON, self.global_step, self.EPS_LEN, 0.1, power=0)
ratio = tf.maximum(pi.prob(batch['actions']), 1e-6) / tf.maximum(pi_old.prob(batch['actions']), 1e-6)
ratio = tf.clip_by_value(ratio, 0, 10)
surr1 = batch['advantage'] * ratio
surr2 = batch['advantage'] * tf.clip_by_value(ratio, 1 - epsilon_decay, 1 + epsilon_decay)
loss_pg = - 2.0 * tf.reduce_mean(tf.minimum(surr1, surr2))
loss_vf = 0.5 * tf.reduce_mean(tf.square(batch['rewards'] - self.vf))
loss_entropy = - 0.01 * tf.reduce_mean(pi.entropy())
loss = loss_pg + loss_vf + loss_entropy
opt = tf.train.AdamOptimizer(self.LR)
self.train_op = opt.minimize(loss, global_step=self.global_step, var_list=pi_params + vf_params)
self.pi_new_params = [oldp.assign(p) for p, oldp in zip(pi_params, pi_old_params)]
self.vf_new_params = [oldp.assign(p) for p, oldp in zip(vf_params, vf_old_params)]
self.sess.run(tf.global_variables_initializer())
| tensorflow.minimum | 13,413 |
import tensorflow as tf
self._zeros_slot(v, "g", self._name)
def _apply_dense(self, grad, var):
lr_t = math_ops.cast(self._lr_t, var.dtype.base_dtype)
beta1_t = math_ops.cast(self._beta1_t, var.dtype.base_dtype)
beta2_t = math_ops.cast(self._beta2_t, var.dtype.base_dtype)
if var.dtype.base_dtype == tf.float16:
eps = 1e-7 # Can't use 1e-8 due to underflow -- not sure if it makes a big difference.
else:
eps = 1e-8
v = self.get_slot(var, "v")
v_t = v.assign(beta2_t * v + (1. - beta2_t) * tf.square(grad))
m = self.get_slot(var, "m")
m_t = m.assign(beta1_t * m + (1. - beta1_t) * grad)
v_t_hat = tf.div(v_t, 1. - beta2_t)
m_t_hat = tf.div(m_t, 1. - beta1_t)
g_t = tf.div(m_t_hat, tf.sqrt(v_t_hat) + eps)
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, m_t, v_t, g_t])
def _apply_sparse(self, grad, var):
raise NotImplementedError("Sparse gradient updates are not supported.")
class RegularizeGradientDescentOptimizer(optimizer.Optimizer):
| tensorflow.div | 13,414 |
import tensorflow as tf
#add_layer 函数里面所有的with都是为了tensorboard添加上去的
def add_layer(inputs, in_size, out_size, activation_function=None,nameScope="layer"):
# add one more layer and return the output of this layer
with tf.name_scope(nameScope):
with tf.name_scope('weights'):
Weights = tf.Variable(tf.random_normal([in_size, out_size]), name='W')
with tf.name_scope('biases'):
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b')
with tf.name_scope('Wx_plus_b'):
Wx_plus_b = tf.add(tf.matmul(inputs, Weights), biases)
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b, )
return outputs
# 这个就是在tensorboard上可视化的时候的区别:
# 使用with tf.name_scope('inputs')可以将xs和ys包含进来
# 形成一个大的图层,图层的名字就是with tf.name_scope()方法里的参数。
| tensorflow.name_scope | 13,415 |
import tensorflow as tf
self.assertAllEqual(
padded_tensor_dict[fields.InputDataFields.groundtruth_boxes]
.shape.as_list(), [3, 4])
self.assertAllEqual(
padded_tensor_dict[fields.InputDataFields.groundtruth_classes]
.shape.as_list(), [3, 3])
def test_clip_boxes_and_classes(self):
input_tensor_dict = {
fields.InputDataFields.groundtruth_boxes:
tf.placeholder(tf.float32, [None, 4]),
fields.InputDataFields.groundtruth_classes:
tf.placeholder(tf.int32, [None, 3]),
fields.InputDataFields.num_groundtruth_boxes:
tf.placeholder(tf.int32, [])
}
padded_tensor_dict = inputs.pad_input_data_to_static_shapes(
tensor_dict=input_tensor_dict,
max_num_boxes=3,
num_classes=3,
spatial_image_shape=[5, 6])
self.assertAllEqual(
padded_tensor_dict[fields.InputDataFields.groundtruth_boxes]
| tensorflow.placeholder | 13,416 |
import tensorflow as tf
h4 = deconv2d(tf.concat([h3, skip_h0], 3),
[self.batch_size, s_h, s_w, self.c_dim], name='d_h4', d_h=ns0, d_w=ns0)
return h4
with tf.variable_scope("deconv") as scope:
output_h4 = decode(trans_z, tgtctx_h3, tgtctx_h2, tgtctx_h1, tgtctx_h0)
scope.reuse_variables()
| tensorflow.variable_scope | 13,417 |
import tensorflow as tf
f_i = distribution_f.prob(self.action_ph)
f_i_ = distribution_f.prob(action_)
f_polyak_i = f_polyak.prob(self.action_ph)
phi_i = strip(train_model.proba_distribution.mean, self.n_envs, self.n_steps)
q_value = strip(train_model.value_fn, self.n_envs, self.n_steps)
q_i = q_value[:, 0]
rho_i = tf.reshape(f_i, [-1, 1]) / (self.mu_ph + eps)
rho_i_ = tf.reshape(f_i_, [-1, 1]) / (self.mu_ph + eps)
qret = q_retrace(self.reward_ph, self.done_ph, q_i, value, tf.pow(rho_i, 1 / self.n_act),
self.n_envs, self.n_steps, self.gamma)
else:
# strip off last step
# f is a distribution, chosen to be Gaussian distributions
# with fixed diagonal covariance and mean \phi(x)
# in the paper
distribution_f, f_polyak, q_value = \
| tensorflow.reshape | 13,418 |
import tensorflow as tf
self.EPSILON = 0.2
self.EPS_LEN = 100000
# GPU setup
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False, device_count={'GPU': gpu})
config.gpu_options.allow_growth = True
config.gpu_options.per_process_gpu_memory_fraction = 0.5
# Placeholders
self.sess = tf.Session(config=config)
self.s_dim, self.a_dim = env.observation_space.shape, env.action_space.shape[0]
self.a_bound = (env.action_space.high - env.action_space.low) / 2
self.actions = tf.placeholder(tf.float32, [None, self.a_dim], 'action')
self.state = tf.placeholder(tf.float32, [None, self.s_dim[0]], 'state')
self.advantage = tf.placeholder(tf.float32, [None, 1], 'advantage')
self.rewards = tf.placeholder(tf.float32, [None, 1], 'rewards')
self.keep_prob = tf.placeholder(tf.float32, name='dropout_keep_prob')
| tensorflow.Session | 13,419 |
import tensorflow as tf
last_layer = rnn_output
last_layer_size = rnn_output_size
for i, layer_size in enumerate(dnn_sizes):
layer_name = 'dnn_{}'.format(i)
with tf.variable_scope(layer_name):
dnn_w = tf.get_variable('W', shape=[last_layer_size, layer_size], initializer=dnn_init, dtype=dtype)
dnn_b = tf.get_variable('b', shape=[layer_size], initializer=tf.constant_initializer(0.0), dtype=dtype)
projected = tf.nn.bias_add(tf.matmul(last_layer, dnn_w), dnn_b)
# TODO: argument nonlinearity, change bias to 0.1 if relu
if dnn_nonlin == 'tanh':
last_layer = tf.nn.tanh(projected)
elif dnn_nonlin == 'sigmoid':
last_layer = tf.nn.sigmoid(projected)
elif dnn_nonlin == 'relu':
last_layer = tf.nn.relu(projected)
else:
raise NotImplementedError()
if mode == 'train' and dnn_keep_prob < 1.0:
last_layer = tf.nn.dropout(last_layer, dnn_keep_prob)
last_layer_size = layer_size
print('{}: {}'.format(layer_name, last_layer.get_shape()))
export_feat_tensors[layer_name] = last_layer
dnn_output = last_layer
dnn_output_size = last_layer_size
# Logistic regression
| tensorflow.nn.relu | 13,420 |
import tensorflow as tf
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
| tensorflow.logging.set_verbosity | 13,421 |
import tensorflow as tf
self._deeplift_ref.clear()
ops = []
g = tf.compat.v1.get_default_graph()
for op in g.get_operations():
| tensorflow.compat.v1.get_default_graph | 13,422 |
import tensorflow as tf
def input_fn(params):
"""The actual input function."""
batch_size = params["batch_size"]
num_examples = len(features)
# This is for demo purposes and does NOT scale to large data sets. We do
# not use Dataset.from_generator() because that uses tf.py_func which is
# not TPU compatible. The right way to load data is with TFRecordReader.
d = tf.data.Dataset.from_tensor_slices({
"input_ids":
tf.constant(
all_input_ids, shape=[num_examples, seq_length],
dtype=tf.int32),
"input_mask":
tf.constant(
all_input_mask,
shape=[num_examples, seq_length],
dtype=tf.int32),
"segment_ids":
tf.constant(
all_segment_ids,
shape=[num_examples, seq_length],
dtype=tf.int32),
"label_ids":
tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32),
})
if is_training:
d = d.repeat()
| tensorflow.constant | 13,423 |
import tensorflow as tf
self._add_forward_graph()
self._add_yolo_interpret_graph()
#self._add_yolo_loss_graph()
#self._add_train_graph()
#self._add_viz_graph()
def _add_forward_graph(self):
"""Build the VGG-16 model."""
if self.mc.LOAD_PRETRAINED_MODEL:
assert tf.gfile.Exists(self.mc.PRETRAINED_MODEL_PATH), \
'Cannot find pretrained model at the given path:' \
' {}'.format(self.mc.PRETRAINED_MODEL_PATH)
self.caffemodel_weight = joblib.load(self.mc.PRETRAINED_MODEL_PATH)
with tf.variable_scope('darknet19') as scope:
conv1 = self._conv_layer(
'conv1', self.image_input, filters=32, size=3, stride=1, bn=self.BN, act='lrelu', freeze=True)
pool1 = self._pooling_layer(
'pool1', conv1, size=2, stride=2)
conv2 = self._conv_layer(
'conv2', pool1, filters=64, size=3, stride=1, bn=self.BN, act='lrelu', freeze=True)
pool2 = self._pooling_layer(
'pool2', conv2, size=2, stride=2)
conv3 = self._conv_layer(
'conv3', pool2, filters=128, size=3, stride=1, bn=self.BN, act='lrelu')
conv4 = self._conv_layer(
'conv4', conv3, filters=64, size=1, stride=1, bn=self.BN, act='lrelu')
conv5 = self._conv_layer(
'conv5', conv4, filters=128, size=3, stride=1, bn=self.BN, act='lrelu')
| tensorflow.variable_scope | 13,424 |
import tensorflow.contrib.eager as tfe
hypo = tf.random_uniform(
(sequence_length, batch_size), maxval=vocab_size, dtype=tf.int64)
hypo_trans = tf.constant(np.array(
[[3, 3, 2, 3, 3, 3, 2, 2, 2, 3, 3, 3,
2, 3, 3, 2, 2, 3, 3, 3, 2, 2, 2, 2,
3, 2, 2]] * batch_size, dtype=np.int64).T)
if tfe.num_gpus():
labels = labels.gpu()
prem = prem.gpu()
prem_trans = prem_trans.gpu()
hypo = hypo.gpu()
hypo_trans = hypo_trans.gpu()
| tensorflow.contrib.eager.num_gpus | 13,425 |
import tensorflow as tf
elmo_module = hub.Module("https://tfhub.dev/google/elmo/2")
lm_embeddings = elmo_module(
inputs={"tokens": tokens, "sequence_len": text_len},
signature="tokens", as_dict=True)
word_emb = lm_embeddings["word_emb"] # [num_sentences, max_sentence_length, 512]
lm_emb = tf.stack([tf.concat([word_emb, word_emb], -1),
lm_embeddings["lstm_outputs1"],
lm_embeddings["lstm_outputs2"]], -1) # [num_sentences, max_sentence_length, 1024, 3]
lm_emb_size = util.shape(lm_emb, 2)
lm_num_layers = util.shape(lm_emb, 3)
with tf.variable_scope("lm_aggregation"):
self.lm_weights = tf.nn.softmax(tf.get_variable("lm_scores", [lm_num_layers], initializer=tf.constant_initializer(0.0)))
self.lm_scaling = tf.get_variable("lm_scaling", [], initializer=tf.constant_initializer(1.0))
flattened_lm_emb = tf.reshape(lm_emb, [num_sentences * max_sentence_length * lm_emb_size, lm_num_layers])
flattened_aggregated_lm_emb = tf.matmul(flattened_lm_emb, tf.expand_dims(self.lm_weights, 1)) # [num_sentences * max_sentence_length * emb, 1]
aggregated_lm_emb = tf.reshape(flattened_aggregated_lm_emb, [num_sentences, max_sentence_length, lm_emb_size])
aggregated_lm_emb *= self.lm_scaling
context_emb_list.append(aggregated_lm_emb)
context_emb = tf.concat(context_emb_list, 2) # [num_sentences, max_sentence_length, emb]
head_emb = tf.concat(head_emb_list, 2) # [num_sentences, max_sentence_length, emb]
context_emb = tf.nn.dropout(context_emb, self.lexical_dropout) # [num_sentences, max_sentence_length, emb]
head_emb = tf.nn.dropout(head_emb, self.lexical_dropout) # [num_sentences, max_sentence_length, emb]
text_len_mask = tf.sequence_mask(text_len, maxlen=max_sentence_length) # [num_sentence, max_sentence_length]
context_outputs = self.lstm_contextualize(context_emb, text_len, text_len_mask) # [num_words, emb]
num_words = util.shape(context_outputs, 0)
| tensorflow.expand_dims | 13,426 |
import tensorflow as tf
images,labels=tf.train.shuffle_batch([image,label],
batch_size=batch_size,num_threads=10,capacity=10000,min_after_dequeue=200)
return tf.reshape(images,[batch_size,4096]),tf.reshape(labels,[batch_size])
def get_test_batch(image,label,batch_size):
images,labels=tf.train.batch([image,label],batch_size=batch_size)
return tf.reshape(images,[batch_size,4096]),tf.reshape(labels,[batch_size])
def get_valid_batch(image,label,batch_size):
images,labels=tf.train.batch([image,label],batch_size=batch_size)
return tf.reshape(images,[batch_size,4096]),tf.reshape(labels,[batch_size])
| tensorflow.reshape | 13,427 |
import tensorflow as tf
std = std[::-1]
image_mean = tf.constant(mean, dtype=tf.float32) * 255.
image_std = tf.constant(std, dtype=tf.float32) * 255.
image = (image - image_mean) / image_std
return image
@staticmethod
def compute_loss_and_error(logits, label, label_smoothing=0.):
if label_smoothing != 0.:
nclass = logits.shape[-1]
label = tf.one_hot(label, nclass) if label.shape.ndims == 1 else label
if label.shape.ndims == 1:
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=label)
else:
loss = tf.losses.softmax_cross_entropy(
label, logits, label_smoothing=label_smoothing,
reduction=tf.losses.Reduction.NONE)
loss = tf.reduce_mean(loss, name='xentropy-loss')
def prediction_incorrect(logits, label, topk=1, name='incorrect_vector'):
with tf.name_scope('prediction_incorrect'):
x = tf.logical_not(tf.nn.in_top_k(logits, label, topk))
return tf.cast(x, tf.float32, name=name)
wrong = prediction_incorrect(logits, label, 1, name='wrong-top1')
add_moving_summary(tf.reduce_mean(wrong, name='train-error-top1'))
wrong = prediction_incorrect(logits, label, 5, name='wrong-top5')
add_moving_summary(tf.reduce_mean(wrong, name='train-error-top5'))
| tensorflow.losses.softmax_cross_entropy | 13,428 |
import tensorflow as tf
if full_cov:
# TODO(VD): ``full_cov`` True would return a ``fvar`` of shape N x N x D x D,
# encoding the covariance between input datapoints as well.
# This is not implemented as this feature is only used for plotting purposes.
raise NotImplementedError
pXnew = Gaussian(Xnew_mu, Xnew_var)
num_data = tf.shape(Xnew_mu)[0] # number of new inputs (N)
num_ind = tf.shape(q_mu)[0] # number of inducing points (M)
num_func = tf.shape(q_mu)[1] # output dimension (D)
q_sqrt_r = tf.matrix_band_part(q_sqrt, -1, 0) # D x M x M
eKuf = tf.transpose(expectation(pXnew, (kern, feat))) # M x N (psi1)
if Luu is None:
| tensorflow.shape | 13,429 |
import tensorflow as tf
return auc
def attention(query, facts, attention_size, mask, stag='null', mode='LIST', 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.
facts = tf.concat(facts, 2)
if time_major:
# (T,B,D) => (B,T,D)
facts = tf.array_ops.transpose(facts, [1, 0, 2])
mask = tf.equal(mask, tf.ones_like(mask))
hidden_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer
input_size = query.get_shape().as_list()[-1]
# Trainable parameters
w1 = tf.Variable(tf.random_normal([hidden_size, attention_size], stddev=0.1))
w2 = tf.Variable(tf.random_normal([input_size, attention_size], stddev=0.1))
| tensorflow.array_ops.transpose | 13,430 |
import tensorflow as tf
# squeeze and 2d resize
squeeze_b_z = tf.reshape(reoriented, [-1, y_size_new, x_size, c_size], name='reshape_bz')
| tensorflow.reshape | 13,431 |
from tensorflow.python.platform import gfile
"""
with gfile.Open(filename, 'wb') as f:
f.write(pickle.dumps(self))
@classmethod
def restore(cls, filename):
"""Restores vocabulary processor from given file.
Args:
filename: Path to file to load from.
Returns:
VocabularyProcessor object.
"""
with gfile.Open(filename, 'rb') as f:
return pickle.loads(f.read()) | tensorflow.python.platform.gfile.Open | 13,432 |
import tensorflow as tf
if self.config["coarse_to_fine"]:
top_antecedents, top_antecedents_mask, top_fast_antecedent_scores, top_antecedent_offsets = self.coarse_to_fine_pruning(top_span_emb, top_span_mention_scores, c)
else:
top_antecedents, top_antecedents_mask, top_fast_antecedent_scores, top_antecedent_offsets = self.distance_pruning(top_span_emb, top_span_mention_scores, c)
dummy_scores = tf.zeros([k, 1]) # [k, 1]
for i in range(self.config["coref_depth"]):
with tf.variable_scope("coref_layer", reuse=(i > 0)):
top_antecedent_emb = tf.gather(top_span_emb, top_antecedents) # [k, c, emb]
top_antecedent_scores = top_fast_antecedent_scores + self.get_slow_antecedent_scores(top_span_emb, top_antecedents, top_antecedent_emb, top_antecedent_offsets, top_span_speaker_ids, genre_emb) # [k, c]
top_antecedent_weights = tf.nn.softmax(tf.concat([dummy_scores, top_antecedent_scores], 1)) # [k, c + 1]
top_antecedent_emb = tf.concat([tf.expand_dims(top_span_emb, 1), top_antecedent_emb], 1) # [k, c + 1, emb]
attended_span_emb = tf.reduce_sum(tf.expand_dims(top_antecedent_weights, 2) * top_antecedent_emb, 1) # [k, emb]
with tf.variable_scope("f"):
f = tf.sigmoid(util.projection(tf.concat([top_span_emb, attended_span_emb], 1), util.shape(top_span_emb, -1))) # [k, emb]
top_span_emb = f * attended_span_emb + (1 - f) * top_span_emb # [k, emb]
top_antecedent_scores = tf.concat([dummy_scores, top_antecedent_scores], 1) # [k, c + 1]
top_antecedent_cluster_ids = tf.gather(top_span_cluster_ids, top_antecedents) # [k, c]
top_antecedent_cluster_ids += tf.to_int32(tf.log(tf.to_float(top_antecedents_mask))) # [k, c]
same_cluster_indicator = tf.equal(top_antecedent_cluster_ids, tf.expand_dims(top_span_cluster_ids, 1)) # [k, c]
non_dummy_indicator = tf.expand_dims(top_span_cluster_ids > 0, 1) # [k, 1]
| tensorflow.expand_dims | 13,433 |
import tensorflow as tf
mask = tf.equal(mask, tf.ones_like(mask))
key_masks = tf.expand_dims(mask, 1) # [B, 1, T]
paddings = tf.ones_like(scores) * (-2 ** 32 + 1)
scores = tf.where(key_masks, scores, paddings) # [B, 1, T]
# Activation
if softmax_stag:
scores = tf.nn.softmax(scores) # [B, 1, T]
# Weighted sum
if mode == 'SUM':
output = tf.matmul(scores, facts) # [B, 1, H]
# output = tf.reshape(output, [-1, tf.shape(facts)[-1]])
else:
scores = tf.reshape(scores, [-1, tf.shape(facts)[1]])
output = facts * tf.expand_dims(scores, -1)
output = tf.reshape(output, tf.shape(facts))
if return_alphas:
return output, scores
return output
class VecAttGRUCell(RNNCell):
"""Gated Recurrent Unit cell (cf. http://arxiv.org/abs/1406.1078).
Args:
num_units: int, The number of units in the GRU cell.
| tensorflow.shape | 13,434 |
import tensorflow as tf
tf.select(cdf_delta > 1e-5, tf.log(tf.maximum(cdf_delta, 1e-12)),
log_pdf_mid - np.log(127.5))))
log_probs = tf.reduce_sum(log_probs, 3) + \
log_prob_from_logits(logit_probs)
if sum_all:
return -tf.reduce_sum(log_sum_exp(log_probs))
else:
return -tf.reduce_sum(log_sum_exp(log_probs), [1, 2])
def mse_loss(pred, labels):
try:
batch_size = tf.cast(pred.shape[0], tf.float32)
except Exception as e:
print('Pred is a tf tensor %s' % str(e.message))
batch_size = tf.cast(tf.shape(pred)[0], tf.float32)
loss_val = tf.sqrt(2 * tf.nn.l2_loss(pred - labels)) / batch_size
return loss_val
def pullaway_loss(embeddings, name='pullaway_loss'):
"""Pull Away loss calculation.
Args:
embeddings: The embeddings to be orthogonalized for varied faces.
| tensorflow.cast | 13,435 |
import tensorflow as tf
if encoder.attend_inputs:
encoder_outputs.append(encoder_inputs_)
elif encoder.attend_both:
encoder_outputs.append(tf.concat([encoder_inputs_, encoder_outputs_], axis=2))
else:
encoder_outputs.append(encoder_outputs_)
encoder_states.append(encoder_state_)
new_encoder_input_length.append(encoder_input_length_)
encoder_state = tf.concat(encoder_states, 1)
return encoder_outputs, encoder_state, new_encoder_input_length
def compute_energy(hidden, state, encoder, time=None, input_length=None, prev_weights=None, **kwargs):
batch_size = tf.shape(hidden)[0]
time_steps = tf.shape(hidden)[1]
if encoder.attn_keep_prob is not None:
state_noise_shape = [1, tf.shape(state)[1]] if encoder.pervasive_dropout else None
| tensorflow.concat | 13,436 |
import tensorflow as tf
out=tf.matmul(l3, self.w4)+self.b4
return out
def softmax_loss(self,predicts,labels):
predicts=tf.nn.softmax(predicts)
labels=tf.one_hot(labels,classnum)
loss=-tf.reduce_sum(labels*tf.log(predicts))
return loss
| tensorflow.nn.softmax | 13,437 |
import tensorflow as tf
Shape [batch_size, embeddings_dim]
Return: pull away term loss
"""
with tf.name_scope(name):
norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))
normalized_embeddings = embeddings / norm
similarity = tf.matmul(normalized_embeddings, normalized_embeddings, transpose_b=True)
batch_size = tf.cast(tf.shape(embeddings)[0], tf.float32)
pt_loss = (tf.reduce_sum(similarity) - batch_size) / \
(batch_size * (batch_size - 1))
return pt_loss
| tensorflow.matmul | 13,438 |
import tensorflow as tf
# Calculate the context vector from attn_dist and encoder_states
# shape (batch_size, attn_size).
context_vector = tf.reduce_sum(tf.expand_dims(attn_dist, axis=-1) * encoder_states, axis=1) # [batch_size, encoder_dim]
return context_vector, attn_dist, coverage
def embedding_lookup(self, inputs):
'''
inputs: list of [batch_size], int32
'''
if type(inputs) is list:
return [tf.nn.embedding_lookup(self.embedding, x) for x in inputs]
else:
return tf.nn.embedding_lookup(self.embedding, inputs)
def one_step_decoder(self, state_t_1, context_t_1, coverage_t_1, word_t, encoder_states, encoder_features,
passage_word_idx, passage_mask, v, w_c, vocab):
'''
state_t_1: Tuple of [batch_size, gen_hidden_size]
context_t_1: [batch_size, encoder_dim]
coverage_t_1: [batch_size, passage_len]
word_t: [batch_size, word_dim]
| tensorflow.nn.embedding_lookup | 13,439 |
import tensorflow as tf
self.assertEqual(10.0, v0_2.eval())
self.assertEqual(20.0, v1_2.eval())
def _SaveAndLoad(self, var_name, var_value, other_value, save_path):
with self.test_session() as sess:
var = tf.Variable(var_value, name=var_name)
save = tf.train.Saver({var_name: var})
var.initializer.run()
val = save.save(sess, save_path)
self.assertEqual(save_path, val)
with self.test_session() as sess:
var = tf.Variable(other_value, name=var_name)
save = tf.train.Saver({var_name: var})
save.restore(sess, save_path)
self.assertAllClose(var_value, var.eval())
def testCacheRereadsFile(self):
save_path = os.path.join(self.get_temp_dir(), "cache_rereads")
# Save and reload one Variable named "var0".
self._SaveAndLoad("var0", 0.0, 1.0, save_path)
# Save and reload one Variable named "var1" in the same file.
# The cached readers should know to re-read the file.
| tensorflow.Variable | 13,440 |
import tensorflow as tf
'b_transform', [highway_dim],
initializer=tf.constant_initializer(0.0),
dtype=DTYPE)
embedding = high(embedding, W_carry, b_carry,
W_transform, b_transform)
# finally project down if needed
if use_proj:
embedding = tf.matmul(embedding, W_proj_cnn) + b_proj_cnn
# reshape back to (batch_size, tokens, dim)
if use_highway or use_proj:
shp = tf.concat([batch_size_n_tokens, [projection_dim]], axis=0)
embedding = tf.reshape(embedding, shp)
# at last assign attributes for remainder of the model
self.embedding = embedding
| tensorflow.matmul | 13,441 |
import tensorflow as tf
'mse': 'mse_loss',
'ne': 'ne_mertric',
}
logging_hook = tf.train.LoggingTensorHook(tensors=tensors_to_log, every_n_iter=FLAGS.log_every_n_steps, formatter=lambda dicts: '{}:'.format(model_scope) + (', '.join(['%s=%.6f' % (k, v) for k, v in dicts.items()])))
# FIXME: augment error:tensorflow.python.framework.errors_impl.InvalidArgumentError: indices[0] = 0 is not in [0, 0)
tf.logging.info('Starting a training cycle.')
fashionAI.train(input_fn=lambda : input_pipeline(True, model_scope, epochs_per_eval), hooks=[logging_hook], max_steps=(steps_per_epoch*train_epochs))
tf.logging.info('Starting to evaluate.')
eval_results = fashionAI.evaluate(input_fn=lambda : input_pipeline(False, model_scope, 1))
tf.logging.info(eval_results)
tf.logging.info('Finished model {}.'.format(model_scope))
| tensorflow.logging.info | 13,442 |
import tensorflow as tf
[self.batch_size, s_h4, s_w4, self.gf_dim*2], name='d_h2'))
truthoutput_h3 = lrelu(deconv2d(tf.concat([truthoutput_h2, tgtctx_h1], 3),
[self.batch_size, s_h2, s_w2, self.gf_dim*1], name='d_h3'))
truthoutput_h4 = deconv2d(tf.concat([truthoutput_h3, tgtctx_h0], 3),
[self.batch_size, s_h, s_w, self.c_dim], name='d_h4')
self.simloss = tf.reduce_mean((trans_z - tgtimg_z) ** 2) * 1e3
mean, var = tf.nn.moments(tgtimg_z, axes=[0])
print(var.get_shape())
# self.simloss /= tf.reduce_mean(var)
print(tgtimg_z.get_shape())
self.out = output_h4# + contextimg#tf.nn.tanh(h4)
self.out2 = truthoutput_h4
self.recon1 = tf.nn.l2_loss(tgtimg - self.out)
| tensorflow.nn.moments | 13,443 |
import tensorflow as tf
trainable_vars = tf.trainable_variables()
if self.config.clip_weight:
# clip_weight
tvars = tf.trainable_variables()
grads = tf.gradients(self.loss, tvars)
grads, _ = tf.clip_by_global_norm(grads, clip_norm=self.config.max_norm_grad)
grad_var_pairs = zip(grads, tvars)
self.train_op = self.optimizer.apply_gradients(grad_var_pairs, name='apply_grad')
else:
self.train_op = self.optimizer.minimize(self.loss)
def _attention(self, output, name='attn', reuse=None):
with tf.variable_scope(name, reuse=reuse):
W = tf.get_variable(name="attn_W",
shape=[2 * self.config.hidden_size, 2 * self.config.hidden_size],
initializer=tf.contrib.layers.xavier_initializer(),
# initializer=tf.truncated_normal_initializer(),
# initializer=tf.keras.initializers.lecun_normal(),
dtype=tf.float32)
V = tf.get_variable(name="attn_V", shape=[2 * self.config.hidden_size, 1],
initializer=tf.contrib.layers.xavier_initializer(),
# initializer=tf.truncated_normal_initializer(),
# initializer=tf.keras.initializers.lecun_normal(),
dtype=tf.float32)
U = tf.get_variable(name="attn_U",
shape=[2 * self.config.hidden_size, 2 * self.config.hidden_size],
initializer=tf.contrib.layers.xavier_initializer(),
# initializer=tf.truncated_normal_initializer(),
# initializer=tf.keras.initializers.lecun_normal(),
dtype=tf.float32)
| tensorflow.contrib.layers.xavier_initializer | 13,444 |
import tensorflow as tf
(entropy_test_nor_help,labels_nor_help,confidence_test_nor_help) = sess.run(
[entropy,tf.argmax(predict,axis=1),tf.reduce_max(predict, axis=1)],feed_dict={predict:predict_NOR}
)
# Local entropy and confidence for adv_img
(entropy_test_adv_help, labels_adv_help, confidence_test_adv_help) = sess.run(
[entropy, tf.argmax(predict, axis=1), tf.reduce_max(predict, axis=1)], feed_dict={predict: predict_ADV}
)
if FLAGS.attack_method == 'carliniL2_specific' or FLAGS.attack_method == 'carliniL2_highden':
print('Log-density-ratio in attacking function of nor/adv is %f'%np.sum(log_density_ratio))
m_tsne_logits_adv = (copy.copy(logits_part_adv)).reshape((1, 64))
| tensorflow.argmax | 13,445 |
import tensorflow as tf
# placeholder for current reward
rew_t_ph = tf.placeholder(tf.float32, [None])
# placeholder for next observation (or state)
obs_tp1_ph = tf.placeholder(tf.uint8, [None] + list(input_shape))
# placeholder for end of episode mask
# this value is 1 if the next state corresponds to the end of an episode,
# in which case there is no Q-value at the next state; at the end of an
# episode, only the current state reward contributes to the target, not the
# next state Q-value (i.e. target is just rew_t_ph, not rew_t_ph + gamma * q_tp1)
done_mask_ph = tf.placeholder(tf.float32, [None])
# casting to float on GPU ensures lower data transfer times.
obs_t_float = tf.cast(obs_t_ph, tf.float32) / 255.0
obs_tp1_float = tf.cast(obs_tp1_ph, tf.float32) / 255.0
# Here, you should fill in your own code to compute the Bellman error. This requires
# evaluating the current and next Q-values and constructing the corresponding error.
# TensorFlow will differentiate this error for you, you just need to pass it to the
| tensorflow.placeholder | 13,446 |
import tensorflow as tf
import json
from keras.layers import merge
from keras.layers.core import Lambda
from keras.models import Model
import tensorflow as tf
def make_parallel(model, gpu_count):
def get_slice(data, idx, parts):
shape = tf.shape(data)
size = tf.concat(0, [shape[:1] // parts, shape[1:]])
stride = tf.concat(0, [shape[:1] // parts, shape[1:] * 0])
start = stride * idx
return tf.slice(data, start, size)
outputs_all = []
for i in range(len(model.outputs)):
outputs_all.append([])
# Place a copy of the model on each GPU, each getting a slice of the batch
for i in range(gpu_count):
with tf.device('/gpu:%d' % i):
with tf.name_scope('tower_%d' % i) as scope:
| tensorflow.concat | 13,447 |
import tensorflow as tf
print('------valid_confusion_matrix-----')
cm = confusion_matrix(y_true=valid_true_total, y_pred=valid_pre_total)
print(cm)
print('------valid_confusion_matrix-----')
coord.request_stop()
coord.join(threads)
def predict_time(loop=100):
feed_dict={
testnum:1
}
with tf.Session(config=config) as sess:
sess.run(init)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
tf.train.Saver().restore(sess,path)
total=0.0
for i in range(loop):
a = datetime.now()
accuracy_np = sess.run([accuracy],feed_dict=feed_dict)
b = datetime.now()
c = (b - a).microseconds
total+=c
| tensorflow.Session | 13,448 |
import tensorflow as tf
function to select and action given observation.
` See the top of the file for details.
"""
with tf.variable_scope(scope, reuse=reuse):
observations_ph = U.ensure_tf_input(make_obs_ph("observation"))
stochastic_ph = tf.placeholder(tf.bool, (), name="stochastic")
update_eps_ph = tf.placeholder(tf.float32, (), name="update_eps")
eps = tf.get_variable("eps", (), initializer=tf.constant_initializer(0))
q_values = q_func(observations_ph.get(), num_actions, scope="q_func")
deterministic_actions = tf.argmax(q_values, axis=1)
batch_size = tf.shape(observations_ph.get())[0]
random_actions = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=num_actions, dtype=tf.int64)
chose_random = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=1, dtype=tf.float32) < eps
| tensorflow.constant_initializer | 13,449 |
import tensorflow as tf
'saw rank: {}.'.format(
rightmost_transposed_ndims.shape.ndims))
elif validate_args:
assertions += [tf.compat.v1.assert_rank(rightmost_transposed_ndims, 0)]
rightmost_transposed_ndims_ = tf.get_static_value(
| tensorflow.compat.v1.assert_rank | 13,450 |
import tensorflow as tf
acc_train = [] #store train accuracy for each epoch
acc_test = [] #store test accuracy for each epoch
if actL == 'sigmoid': #accuracy score for binary class classification
Yp = tf.greater(an , 0.5)
accuracy = tf.reduce_mean(tf.cast(tf.equal(Yp, tf.equal(Y,1.0)), "float"))
elif actL == 'esp' or actL == 'relu': #r2 score
| tensorflow.greater | 13,451 |
import tensorflow as tf
params.vocabulary["char"],
control_symbols
)
}
return params
def get_initializer(params):
if params.initializer == "xavier":
return tf.contrib.layers.xavier_initializer()
elif params.initializer == "uniform":
max_val = params.initializer_gain
return tf.random_uniform_initializer(-max_val, max_val)
elif params.initializer == "normal":
return tf.random_normal_initializer(0.0, params.initializer_gain)
elif params.initializer == "normal_unit_scaling":
return tf.variance_scaling_initializer(params.initializer_gain,
mode="fan_avg",
distribution="normal")
| tensorflow.contrib.layers.xavier_initializer | 13,452 |
import tensorflow as tf
def common_conv2d(layer_input,filters,f_size=4,stride=2,padding='SAME',norm=True,name='common_conv2d'):
"""Layers used during downsampling"""
with tf.variable_scope(name):
if reuse:
tf.get_variable_scope().reuse_variables()
else:
assert tf.get_variable_scope().reuse is False
d = tf.contrib.layers.conv2d(layer_input,filters,kernel_size=f_size,stride=stride,padding=padding)
if norm:
d = tf.contrib.layers.batch_norm(d)
d = lrelu(d,alpha=0.2)
return d
#def common_deconv2d(layer_input,skip_input, filters,f_size=4,stride=2,dropout_rate=0,name='common_deconv2d'):
def common_deconv2d(layer_input,filters,f_size=4,stride=2,padding='SAME',dropout_rate=0,name='common_deconv2d'):
| tensorflow.contrib.layers.conv2d | 13,453 |
import tensorflow as tf
"""
grads_and_vars = []
clones_losses = []
num_clones = len(clones)
if regularization_losses is None:
regularization_losses = tf.get_collection(
tf.GraphKeys.REGULARIZATION_LOSSES)
for clone in clones:
with tf.name_scope(clone.scope):
clone_loss, clone_grad = _optimize_clone(
optimizer, clone, num_clones, regularization_losses, **kwargs)
if clone_loss is not None:
clones_losses.append(clone_loss)
grads_and_vars.append(clone_grad)
# Only use regularization_losses for the first clone
regularization_losses = None
| tensorflow.name_scope | 13,454 |
import tensorflow as tf
# Convert inputs to tensors and standardize dtypes.
labels, logits, weights, original_shape = _prepare_labels_logits_weights(labels, logits, weights)
# Create tensors of pairwise differences for logits and labels, and
# pairwise products of weights. These have shape
# [batch_size, batch_size, num_labels].
logits_difference = tf.expand_dims(logits, 0) - tf.expand_dims(logits, 1)
labels_difference = tf.expand_dims(labels, 0) - tf.expand_dims(labels, 1)
weights_product = tf.expand_dims(weights, 0) * tf.expand_dims(weights, 1)
signed_logits_difference = labels_difference * logits_difference
raw_loss = losses_utils.weighted_surrogate_loss(
labels=tf.ones_like(signed_logits_difference),
logits=signed_logits_difference,
surrogate_type=surrogate_type)
weighted_loss = weights_product * raw_loss
| tensorflow.expand_dims | 13,455 |
import tensorflow as tf
import tensorflow as tf
from learners.abstract_learner import AbstractLearner
from learners.distillation_helper import DistillationHelper
from learners.weight_sparsification.pr_optimizer import PROptimizer
from learners.weight_sparsification.utils import get_maskable_vars
from utils.multi_gpu_wrapper import MultiGpuWrapper as mgw
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('ws_save_path', './models_ws/model.ckpt', 'WS: model\'s save path')
tf.app.flags.DEFINE_float('ws_prune_ratio', 0.75, 'WS: target pruning ratio')
tf.app.flags.DEFINE_string('ws_prune_ratio_prtl', 'optimal',
'WS: pruning ratio protocol (\'uniform\' | \'heurist\' | \'optimal\')')
tf.app.flags.DEFINE_integer('ws_nb_rlouts', 200, 'WS: # of roll-outs for the RL agent')
tf.app.flags.DEFINE_integer('ws_nb_rlouts_min', 50,
'WS: minimal # of roll-outs for the RL agent to start training')
tf.app.flags.DEFINE_string('ws_reward_type', 'single-obj',
'WS: reward type (\'single-obj\' OR \'multi-obj\')')
tf.app.flags.DEFINE_float('ws_lrn_rate_rg', 3e-2, 'WS: learning rate for layerwise regression')
tf.app.flags.DEFINE_integer('ws_nb_iters_rg', 20, 'WS: # of iterations for layerwise regression')
tf.app.flags.DEFINE_float('ws_lrn_rate_ft', 3e-4, 'WS: learning rate for global fine-tuning')
tf.app.flags.DEFINE_integer('ws_nb_iters_ft', 400, 'WS: # of iterations for global fine-tuning')
tf.app.flags.DEFINE_integer('ws_nb_iters_feval', 25, 'WS: # of iterations for fast evaluation')
tf.app.flags.DEFINE_float('ws_prune_ratio_exp', 3.0, 'WS: pruning ratio\'s exponent term')
tf.app.flags.DEFINE_float('ws_iter_ratio_beg', 0.1, 'WS: iteration ratio (at starting time)')
tf.app.flags.DEFINE_float('ws_iter_ratio_end', 0.5, 'WS: iteration ratio (at ending time)')
tf.app.flags.DEFINE_float('ws_mask_update_step', 500, 'WS: step size for updating the pruning mask')
def calc_prune_ratio(vars_list):
| tensorflow.app.flags.DEFINE_integer | 13,456 |
import tensorflow as tf
# Optimisation hyperparameters
tf.app.flags.DEFINE_integer('batch-size', 256, 'Number of examples per mini-batch (default: %(default)d)')
tf.app.flags.DEFINE_float('learning-rate', 1e-4, 'Learning rate (default: %(default)d)')
tf.app.flags.DEFINE_integer('img-width', 32, 'Image width (default: %(default)d)')
tf.app.flags.DEFINE_integer('img-height', 32, 'Image height (default: %(default)d)')
| tensorflow.app.flags.DEFINE_float | 13,457 |
import tensorflow as tf
'member/age': tf.io.FixedLenFeature([], tf.int64),
'member/height': tf.io.VarLenFeature(tf.float32),
'member/prefer_prods': tf.io.VarLenFeature(tf.int64)}
features = tf.io.parse_single_example(example_proto, features)
images = tf.image.decode_png(features['member/encoded'], channels=3)
# 注意png原本有4個channel,但執行到下面的處理會出錯,所以前一行先降成3個channel。
images = tf.image.random_brightness(images, 0.1)
images = tf.image.random_saturation(images, 0.7, 1.3)
images = tf.image.random_contrast(images, 0.6, 1.5)
images = tf.image.random_flip_left_right(images)
return features, images
if __name__ == '__main__':
main()
| tensorflow.image.random_contrast | 13,458 |
import tensorflow as tf
inp = features['inputs']
pad = tf.expand_dims(tf.zeros_like(inp[0]) + pad_symbol, axis=0)
concat = tf.concat([pad, inp, pad, targets], axis=0)
# Note: we're updating existing features dictionary here, so make sure
| tensorflow.concat | 13,459 |
from tensorflow.contrib.eager.python.examples.l2hmc import l2hmc
def test_apply_transition(self):
"""Testing function `Dynamics.apply_transition` in graph and eager mode."""
# Eager mode testing
hparams = get_default_hparams()
energy_fn, _, _ = l2hmc.get_scg_energy_fn()
dynamics = l2hmc.Dynamics(
x_dim=hparams.x_dim,
minus_loglikelihood_fn=energy_fn,
n_steps=hparams.n_steps,
eps=hparams.eps)
| tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.get_scg_energy_fn | 13,460 |
import tensorflow as tf
def _init():
v_norm = tf.nn.l2_normalize(self.v,axis=0)
t = tf.matmul(input_var,v_norm)
mu,var = tf.nn.moments(t,axes=[0])
std = tf.sqrt(var+self.epsilon)
return [tf.assign(self.g,1/std),tf.assign(self.b,-1.*mu/std)]
require_init = tf.reduce_any(tf.is_nan(self.g))
init_ops = tf.cond(require_init,_init,lambda : [self.g,self.b])
with tf.control_dependencies(init_ops):
w = tf.expand_dims(self.g,axis=0) * tf.nn.l2_normalize(self.v,axis=0)
return tf.matmul(input_var,w)+self.b
def get_variables(self):
#TODO: self.v should be l2-normalized or not? / currently not.
return {'v':self.v,'b':self.b,'g':self.g}
class SymPadConv2d(object): #Resize and Convolution(upsacle by 2)
def __init__(self,name,input_dim,output_dim,
k_h=3,k_w=3,stddev=0.02) :
assert k_h%2==1 and k_w%2==1, 'kernel size should be odd numbers to ensure exact size'
with tf.variable_scope(name) :
| tensorflow.nn.l2_normalize | 13,461 |
import tensorflow as tf
'The parent directory where the model will be stored.')
tf.app.flags.DEFINE_integer(
'log_every_n_steps', 10,
'The frequency with which logs are print.')
tf.app.flags.DEFINE_integer(
'save_summary_steps', 100,
'The frequency with which summaries are saved, in seconds.')
tf.app.flags.DEFINE_integer(
'save_checkpoints_secs', 3600,
'The frequency with which the model is saved, in seconds.')
# model related configuration
tf.app.flags.DEFINE_integer(
'train_image_size', 384,
'The size of the input image for the model to use.')
tf.app.flags.DEFINE_integer(
'heatmap_size', 96,
'The size of the output heatmap of the model.')
tf.app.flags.DEFINE_string(
'backbone', 'seresnext50',#or seresnext50 seresnet50
'The backbone network to use for feature pyramid.')
tf.app.flags.DEFINE_float(
'heatmap_sigma', 1.,
'The sigma of Gaussian which generate the target heatmap.')
tf.app.flags.DEFINE_float(
'bbox_border', 25.,
'The nearest distance of the crop border to al keypoints.')
tf.app.flags.DEFINE_integer(
'train_epochs', 50,
| tensorflow.app.flags.DEFINE_integer | 13,462 |
import tensorflow as tf
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)
| tensorflow.train.get_or_create_global_step | 13,463 |
from tensorflow.python.ops import gen_math_ops
Returns:
A `Tensor`.
"""
with ops.op_scope([x], name, "Pow") as name:
return gen_math_ops._pow(x, y, name=name)
def complex(real, imag, name=None):
"""Converts two real numbers to a complex number.
| tensorflow.python.ops.gen_math_ops._pow | 13,464 |
import tensorflow as tf
fetches: Any nested structure compatible with `tf.nest`.
session: Optional. A `tf.Session` object in the context of which the
evaluation is to happen.
Returns:
`fetches` with any `Tensor` objects replaced by numpy values.
"""
if any((tf.is_tensor(t) for t in tf.nest.flatten(fetches))):
if session:
fetches = session.run(fetches)
else:
fetches = self.evaluate(fetches)
return fetches
| tensorflow.is_tensor | 13,465 |
from tensorflow.contrib.tpu.python.tpu import tpu_estimator
with tf.device("cpu:0"), mtf.utils.outside_all_rewrites():
eval_metrics = {}
for metric_name, metric_fn in six.iteritems(eval_metrics_fns):
if metric_name.split("/")[-1] not in t2t_model.TPU_METRIC_BLACKLIST:
eval_metrics[metric_name] = metric_fn(
tf_logits, None, tf.identity(labels))
return eval_metrics
return tpu_estimator.TPUEstimatorSpec(
tf.estimator.ModeKeys.EVAL,
evaluation_hooks=[restore_hook],
loss=loss,
eval_metrics=(metric_fn, [logits, labels]))
else:
eval_metrics = {}
| tensorflow.contrib.tpu.python.tpu.tpu_estimator.TPUEstimatorSpec | 13,466 |
import tensorflow as tf
collections=[tf.GraphKeys.WEIGHTS, tf.GraphKeys.GLOBAL_VARIABLES])
return var
def conv(inp, name, size, out_channels, strides=[1, 1, 1, 1],
dilation=None, padding='SAME', apply_relu=True, alpha=0.0,bias=True,
initializer=tf.contrib.layers.xavier_initializer_conv2d()):
batch_size = inp.get_shape().as_list()[0]
res1 = inp.get_shape().as_list()[1]
res2 = inp.get_shape().as_list()[1]
in_channels = inp.get_shape().as_list()[3]
with tf.variable_scope(name):
W = get_variable("W", shape=[size, size, in_channels, out_channels], dtype=tf.float32,
initializer=initializer, regularizer=tf.nn.l2_loss)
b = get_variable("b", shape=[1, 1, 1, out_channels], dtype=tf.float32,
initializer=tf.zeros_initializer(),trainable=bias)
if dilation:
assert(strides == [1, 1, 1, 1])
out = tf.add(tf.nn.atrous_conv2d(inp, W, rate=dilation, padding=padding), b, name='convolution')
out.set_shape([batch_size, res1, res2, out_channels])
else:
out = tf.add(tf.nn.conv2d(inp, W, strides=strides, padding=padding), b, name='convolution')
| tensorflow.variable_scope | 13,467 |
import tensorflow as tf
if q_sqrt.get_shape().ndims == 2:
LTA = A * tf.expand_dims(tf.transpose(q_sqrt), 2) # R x M x N
elif q_sqrt.get_shape().ndims == 3:
L = tf.matrix_band_part(q_sqrt, -1, 0) # R x M x M
A_tiled = tf.tile(tf.expand_dims(A, 0), tf.stack([num_func, 1, 1]))
LTA = tf.matmul(L, A_tiled, transpose_a=True) # R x M x N
else: # pragma: no cover
raise ValueError("Bad dimension for q_sqrt: %s" %
| tensorflow.expand_dims | 13,468 |
import tensorflow as tf
self.v = tf.layers.dense(
inputs=l1,
units=1, # output units
activation=None,
name='V'
)
# 計算損益
self.advantage = self.tfdc_r - self.v
self.closs = tf.reduce_mean(tf.square(self.advantage))
self.ctrain_op = tf.train.AdamOptimizer(C_LR).minimize(self.closs)
# Actor
# 建立網路
action_op, action_op_params = self._build_anet(
'action_op', trainable=True)
old_action_op, old_action_op_params = self._build_anet(
'old_action_op', trainable=False)
| tensorflow.train.AdamOptimizer | 13,469 |
import tensorflow as tf
gating_startat=gating_startat,
final_endpoint=final_endpoint,
min_depth=min_depth,
depth_multiplier=depth_multiplier,
data_format=data_format,
scope=scope)
with tf.variable_scope('Logits'):
if data_format.startswith('NC'):
net = tf.transpose(net, [0, 2, 3, 4, 1])
kernel_size = i3d_utils.reduced_kernel_size_3d(net, [2, 7, 7])
net = layers.avg_pool3d(
net,
| tensorflow.variable_scope | 13,470 |
import tensorflow as tf
lambda: tf.zeros([bs, sl+1, hn], tf.float32),
lambda: tf.scatter_nd(
tf.stack([range_unhead, unhead_org_idx], -1), pooling_result, [bs, sl+1, hn])
)
self_attn_input = rep_map
context_features = tf.add(scatter_attn[:, :-1], scatter_pooling[:, :-1], 'context_features')
output_mask = rep_mask
else:
self_attn_input = rep_head_tensor
context_features = attn_result
output_mask = rep_head_mask
| tensorflow.add | 13,471 |
from tensorflow.python.framework import ops
return math_ops.div(
math_ops.reduce_sum(loss_vec),
math_ops.to_float(math_ops.reduce_sum(weight_tensor)),
name="loss")
def _get_linear_vars(self):
if self._get_linear_feature_columns():
return ops.get_collection(self._linear_weight_collection)
return []
def _get_linear_training_ops(self, linear_grads, linear_vars):
if self._get_linear_feature_columns():
self._linear_optimizer = self._get_optimizer(
self._linear_optimizer,
| tensorflow.python.framework.ops.get_collection | 13,472 |
import tensorflow as tf
batch_per_thread, hard_code_batch_size=False, validation_file_path=None):
import tensorflow as tf
g = tf.Graph()
with g.as_default():
| tensorflow.Graph | 13,473 |
import tensorflow as tf
encoder_input_length = [tf.to_int32(tf.reduce_sum(weights, axis=1))]
attention_states, encoder_state, encoder_input_length = multi_encoder(
encoder_input_length=encoder_input_length, encoders=encoders, encoder_inputs=encoder_inputs,
training=training)
outputs, attention_weights, states, _, samples, beam_fun, initial_data = attention_decoder(
attention_states=attention_states, initial_state=encoder_state, feed_previous=feed_previous,
decoder_inputs=targets[0][:, :-1], encoder_input_length=encoder_input_length,
decoder=decoders[0], training=training, encoders=encoders
)
target_weights = get_weights(targets[0][:, 1:], utils.EOS_ID, include_first_eos=True)
target_length = [tf.to_int32(tf.reduce_sum(target_weights, axis=1))]
xent_loss = sequence_loss(logits=outputs, targets=targets[0][:, 1:], weights=target_weights)
reconstructed_outputs, reconstructed_weights, _, _, _, _, _ = attention_decoder(
attention_states=[states], initial_state=states[:,-1,:], feed_previous=feed_previous,
decoder_inputs=targets[1][:, :-1], encoder_input_length=target_length,
decoder=decoders[1], training=training, encoders=decoders[:1]
)
target_weights = get_weights(targets[1][:, 1:], utils.EOS_ID, include_first_eos=True)
xent_loss += reconstruction_weight * sequence_loss(logits=reconstructed_outputs, targets=targets[1][:, 1:],
weights=target_weights)
| tensorflow.reduce_sum | 13,474 |
import tensorflow as tf
alphas_all = tf.reduce_sum(alphas, 1) # (N, L)
alpha_reg = self.alpha_c * tf.reduce_sum((16./196 - alphas_all) ** 2)
loss += alpha_reg
return loss / tf.to_float(batch_size)
def build_sampler(self, max_len=20):
features = self.features
| tensorflow.to_float | 13,475 |
import tensorflow as tf
if param_noise_filter_func(perturbed_var):
# Perturb this variable.
op = tf.assign(perturbed_var, var + tf.random_normal(shape=tf.shape(var), mean=0., stddev=param_noise_scale))
else:
| tensorflow.shape | 13,476 |
import tensorflow as tf
z = tf.py_func(lambda x: x * 2, [x], [tf.float32])
for _ in xrange(100):
sess.run([y[0].op, z[0].op])
def testNoInput(self):
with self.test_session():
x, = tf.py_func(lambda: 42.0, [], [tf.float64])
self.assertAllClose(x.eval(), 42.0)
def testCleanup(self):
for _ in xrange(1000):
g = tf.Graph()
| tensorflow.py_func | 13,477 |
import tensorflow as tf
tf.io.decode_png(png_bytes, channels=1, dtype=tf.uint8), axis=-1)
mask = tf.cast(mask, dtype=tf.float32)
mask.set_shape([None, None])
return mask
height = parsed_tensors['image/height']
width = parsed_tensors['image/width']
masks = parsed_tensors['image/object/mask']
return tf.cond(
pred=tf.greater(tf.size(input=masks), 0),
true_fn=lambda: tf.map_fn(_decode_png_mask, masks, dtype=tf.float32),
false_fn=lambda: tf.zeros([0, height, width], dtype=tf.float32))
def _decode_areas(self, parsed_tensors):
xmin = parsed_tensors['image/object/bbox/xmin']
xmax = parsed_tensors['image/object/bbox/xmax']
ymin = parsed_tensors['image/object/bbox/ymin']
ymax = parsed_tensors['image/object/bbox/ymax']
return tf.cond(
tf.greater(tf.shape(parsed_tensors['image/object/area'])[0], 0),
lambda: parsed_tensors['image/object/area'],
lambda: (xmax - xmin) * (ymax - ymin))
| tensorflow.zeros | 13,478 |
import tensorflow as tf
self.end_label = tf.placeholder(tf.int32, [self.config.batch_size], "answer_label2")
self.position_emb = position_embedding(self.c, 2 * self.config.hidden_size)
self.c_mask = tf.cast(self.c, tf.bool) # index 0 is padding symbol N x self.max_p_num, max_p_len
self.q_mask = tf.cast(self.q, tf.bool)
self.c_len = tf.reduce_sum(tf.cast(self.c_mask, tf.int32), axis=1)
self.q_len = tf.reduce_sum(tf.cast(self.q_mask, tf.int32), axis=1)
self.dropout = tf.placeholder(tf.float32, name="dropout")
self.global_step = tf.Variable(0, name="global_step", trainable=False)
"""
| tensorflow.cast | 13,479 |
import tensorflow as tf
sequence_length=self.seq_len,
) ## (batch_size, seq_len, num_hidden)
# rnn_outputs = tf.transpose(rnn_outputs, perm=[1,0,2]) ## (seq_len, batch_size, num_hidden) NOT NEEDED ANY MORE
last_outputs = self.last_relevant(rnn_outputs, self.seq_len) ## (batch_size, num_hidden)
with tf.variable_scope('output', reuse=forward_only):
with tf.variable_scope('softmax'):
W = tf.get_variable('W', [self.num_hidden, self.num_classes],
# initializer=tf.random_uniform_initializer(-0.003, 0.003))
initializer=tf.contrib.layers.xavier_initializer())
# initializer=tf.truncated_normal_initializer(stddev=0.1))
b = tf.get_variable('b', [self.num_classes], initializer=tf.constant_initializer(0.1))
logits = tf.matmul(last_outputs, W) + b
self.embed_inputs = embed_inputs
return logits
def loss(self, logits, forward_only=None):
cost = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=tf.cast(self.y, tf.float32))
mean_cost = tf.reduce_mean(cost)
y_pred = tf.argmax(logits, 1)
correct_pred = tf.equal(y_pred, tf.argmax(self.y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
if forward_only:
| tensorflow.matmul | 13,480 |
import tensorflow as tf
summary = tf.summary.merge_all()
| tensorflow.summary.merge_all | 13,481 |
import tensorflow as tf
_evaluate_legendre_polynomial_branch(degree_l, order_m, x, pmm))
def _spherical_harmonics_normalization(l, m, var_type=tf.float64):
l = tf.cast(l, dtype=var_type)
m = tf.cast(m, dtype=var_type)
numerator = (2.0 * l + 1.0) * factorial(l - tf.abs(m))
denominator = 4.0 * np.pi * factorial(l + tf.abs(m))
return tf.sqrt(numerator / denominator)
def _evaluate_spherical_harmonics_branch(degree,
order,
theta,
phi,
sign_order,
| tensorflow.sqrt | 13,482 |
import tensorflow as tf
batch_size = 100
n_epochs = 1000
learning_rate = 0.001
beta1 = 0.9
results_path = './Results/Semi_Supervised'
n_labels = 10
n_labeled = 1000
# Placeholders for input data and the targets
x_input = tf.placeholder(dtype=tf.float32, shape=[batch_size, input_dim], name='Input')
x_input_l = tf.placeholder(dtype=tf.float32, shape=[batch_size, input_dim], name='Labeled_Input')
y_input = tf.placeholder(dtype=tf.float32, shape=[batch_size, n_labels], name='Labels')
x_target = tf.placeholder(dtype=tf.float32, shape=[batch_size, input_dim], name='Target')
real_distribution = tf.placeholder(dtype=tf.float32, shape=[batch_size, z_dim], name='Real_distribution')
categorial_distribution = tf.placeholder(dtype=tf.float32, shape=[batch_size, n_labels],
name='Categorical_distribution')
manual_decoder_input = tf.placeholder(dtype=tf.float32, shape=[1, z_dim + n_labels], name='Decoder_input')
def form_results():
| tensorflow.placeholder | 13,483 |
import tensorflow as tf
[2, self.pretrained_char_mat.get_shape()[1]],
dtype=tf.float32,
initializer=tf.constant_initializer(
self.vocab.char_embeddings[:2],
dtype=tf.float32),
trainable=True)
self.char_mat = tf.concat([self.char_pad_unk_mat, self.pretrained_char_mat], axis=0)
else:
self.word_mat = tf.get_variable(
'word_embeddings',
shape=[self.vocab.word_size(), self.vocab.word_embed_dim],
initializer=tf.constant_initializer(self.vocab.word_embeddings),
trainable=True
)
self.char_mat = tf.get_variable(
'char_embeddings',
shape=[self.vocab.char_size(), self.vocab.char_embed_dim],
initializer=tf.constant_initializer(self.vocab.char_embeddings),
trainable=True
)
self.ch_len = tf.reshape(tf.reduce_sum(
tf.cast(tf.cast(self.ch, tf.bool), tf.int32), axis=2), [-1])
| tensorflow.constant_initializer | 13,484 |
import tensorflow as tf
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.get_variable_scope | 13,485 |
import tensorflow as tf
output_bias = tf.get_variable(
"output_bias", [num_labels], initializer=tf.zeros_initializer())
with tf.variable_scope("loss"):
if is_training:
# I.e., 0.1 dropout
output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
logits = tf.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)
one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)
per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
loss = tf.reduce_mean(per_example_loss)
return (loss, per_example_loss, logits, probabilities)
def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps, use_tpu,
use_one_hot_embeddings):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
"""The `model_fn` for TPUEstimator."""
tf.logging.info("*** Features ***")
| tensorflow.reduce_sum | 13,486 |
import tensorflow as tf
for sample in range(self.num_samples):
with tf.control_dependencies(control_inputs=deltas):
perturbations = [
tf.random_normal(shape=util.shape(variable)) * learning_rate
for variable in variables
]
perturbation_deltas = [
pert - prev_pert
for pert, prev_pert in zip(perturbations, previous_perturbations)
]
applied = self.apply_step(variables=variables, deltas=perturbation_deltas)
previous_perturbations = perturbations
with tf.control_dependencies(control_inputs=(applied,)):
perturbed_loss = fn_loss(**arguments)
direction = tf.sign(x=(unperturbed_loss - perturbed_loss))
deltas = [
delta + direction * perturbation
for delta, perturbation in zip(deltas, perturbations)
]
else:
# TensorFlow while loop
def body(deltas, previous_perturbations):
with tf.control_dependencies(control_inputs=deltas):
perturbations = [
| tensorflow.control_dependencies | 13,487 |
import tensorflow as tf
with tf.Graph().as_default():
initializer = tf.random_uniform_initializer(-config.init_scale,
config.init_scale)
with tf.name_scope("Train"):
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"):
| tensorflow.variable_scope | 13,488 |
import tensorflow as tf
w = w*tf.rsqrt(tf.cast(n_state, tf.float32))
w = mask_attn_weights(w)
w = tf.nn.softmax(w)
w = dropout(w, attn_pdrop, train)
#w=[-1,head,n_ctx,n_ctx],v=[-1,head,n_ctx,emb]
a = tf.matmul(w, v)
return a
def split_states(x, n):
x_shape = shape_list(x)
m = x_shape[-1]
new_x_shape = x_shape[:-1]+[n, m//n]
return tf.reshape(x, new_x_shape)
def merge_states(x):
x_shape = shape_list(x)
new_x_shape = x_shape[:-2]+[np.prod(x_shape[-2:])]
return tf.reshape(x, new_x_shape)
def split_heads(x, n, k=False):
#[-1,n_ctx,head,head_emb]
if k:
return tf.transpose(split_states(x, n), [0, 2, 3, 1])
else:
return tf.transpose(split_states(x, n), [0, 2, 1, 3])
def merge_heads(x):
| tensorflow.reshape | 13,489 |
from tensorflow.python.framework import ops
@ops.RegisterShape("SparseSegmentSum")
def _SparseSegmentReductionShape(op):
"""Common shape function for sparse segment reduction ops."""
data_shape = op.inputs[0].get_shape()
indices_shape = op.inputs[1].get_shape()
indices_shape.assert_has_rank(1)
segment_ids_shape = op.inputs[2].get_shape()
segment_ids_shape.assert_has_rank(1)
indices_shape.assert_is_compatible_with(segment_ids_shape)
return [tensor_shape.TensorShape([None]).concatenate(data_shape[1:])]
@ops.RegisterShape("SparseSegmentMeanGrad")
def _SparseSegmentMeanGradShape(op):
"""Shape function for the SparseSegmentMeanGrad op."""
input_shape = op.inputs[0].get_shape()
indices_shape = op.inputs[1].get_shape().with_rank(1)
unused_segment_ids_shape = op.inputs[2].get_shape().merge_with(indices_shape)
unused_output_dim0_shape = op.inputs[3].get_shape().merge_with(
tensor_shape.scalar())
output_dim0 = tensor_util.ConstantValue(op.inputs[3])
if output_dim0 is not None:
dim0 = output_dim0[0]
else:
| tensorflow.python.framework.ops.RegisterShape | 13,490 |
import tensorflow as tf
df = PrefetchDataZMQ(df, nr_proc=10)
df.reset_state()
scene_data = df.get_data()
saver = tf.train.Saver(tf.global_variables())
with tf.Session() as sess:
ckpt = tf.train.get_checkpoint_state('./model_pretrain')
if ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path):
print("loading checkpoint...")
saver.restore(sess, ckpt.model_checkpoint_path)
else:
sess.run(tf.global_variables_initializer())
summary_writer = tf.summary.FileWriter('./logs_pretrain', sess.graph)
_x = x[:, :, :, ::-1]
tf.summary.image('x', _x, 4)
summary_op = tf.summary.merge_all()
epoch_learning_rate = init_learning_rate
for epoch in range(1, total_epochs + 1):
if epoch % 10 == 0 :
| tensorflow.global_variables_initializer | 13,491 |
import tensorflow as tf
for input_pattern in FLAGS.input_file.split(","):
input_files.extend(tf.gfile.Glob(input_pattern))
| tensorflow.gfile.Glob | 13,492 |
import tensorflow as tf
left_candidates = tf.cond(tf.equal(best_id, 0), lambda: empty, _MergeLeft)
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.
| tensorflow.concat | 13,493 |
import tensorflow as tf
momentum=FLAGS.rmsprop_momentum,
epsilon=FLAGS.rmsprop_epsilon)
else:
raise ValueError('Optimizer "%s" was not recognized', FLAGS.optimizer)
self.variable_mgr.append_apply_gradients_ops(
gradient_state, opt, clipped_grads, training_ops)
train_op = tf.group(*(training_ops + update_ops + extra_nccl_ops))
with tf.device(self.cpu_device):
if self.task_index == 0 and FLAGS.summary_verbosity > 0:
tf.summary.scalar('learning_rate', learning_rate)
tf.summary.scalar('total_loss', total_loss)
for grad, var in avg_grads:
if grad is not None:
tf.summary.histogram(var.op.name + '/gradients', grad)
for var in tf.trainable_variables():
tf.summary.histogram(var.op.name, var)
| tensorflow.device | 13,494 |
import tensorflow as tf
# Create fake embedding matrix.
embed = tf.random_normal((vocab_size, d_embed))
| tensorflow.random_normal | 13,495 |
import tensorflow as tf
strides[1], bsize[1], ksize[0])
assert (bsize[2] - ksize[1]) % strides[2] == 0, ERR_MSG_DIV.format(
strides[2], bsize[2], ksize[1])
assert strides[0] == strides[3] == 1, ERR_MSG_DIM.format(strides)
bstrides = _calc_block_strides(bsize, ksize, strides)
# Pad mask.
mask_ = tf.expand_dims(mask, 3)
mask_ = _pad_input(mask_, ksize, strides, padding, bsize=bsize, bstrides=bstrides)
mask_ = tf.nn.max_pool(mask_, bsize, bstrides, 'VALID') # Blocks are always valid conv.
mask_ = tf.squeeze(mask_, [3])
indices = tf.where(tf.greater(mask_, tol))
indices = tf.cast(indices, tf.int32)
return indices
def convert_mask_to_block_indices(mask, bsize, ksize, strides, padding, tol):
"""
Converts a binary mask to block sparse indices.
:param mask: [Tensor] [N, H, W]. 1 indicates non-sparse locations. Dtype float32.
| tensorflow.squeeze | 13,496 |
from tensorflow.python.ops import state_ops
(prev_count * batch_count / update_count))
update_comoment = state_ops.assign_add(comoment, delta_comoment)
| tensorflow.python.ops.state_ops.assign_add | 13,497 |
from tensorflow.python.ops import control_flow_ops
else:
update_ops = set(update_ops)
# Make sure update_ops are computed before total_loss.
if update_ops:
with tf.control_dependencies(update_ops):
barrier = tf.no_op(name='update_barrier')
self.d_losses[-1] = control_flow_ops.with_dependencies([barrier], self.d_losses[-1])
self.g_losses[-1] = control_flow_ops.with_dependencies([barrier], self.g_losses[-1])
self.d_loss_real = control_flow_ops.with_dependencies([barrier], self.d_loss_real)
self.d_loss_fake = control_flow_ops.with_dependencies([barrier], self.d_loss_fake)
self.d_loss_class = control_flow_ops.with_dependencies([barrier], self.d_loss_class)
t_vars = self._get_vars_semi_supervised()
if self.clip_by_global_norm:
self.capped_d_grads = self._clip_grad_global_norms(
t_vars['d_vars'], self.d_losses[-1], d_optimizer, gradient_noise_scale=0.0)
self.capped_g_grads = self._clip_grad_global_norms(
t_vars['g_vars'], self.g_losses[-1], g_optimizer, gradient_noise_scale=0.0)
else:
self.capped_d_grads = self._clip_grad_norms(
d_optimizer.compute_gradients(self.d_losses[-1], t_vars['d_vars']))
| tensorflow.python.ops.control_flow_ops.with_dependencies | 13,498 |
import tensorflow as tf
eval_metrics = (metric_fn,
[per_example_loss, label_ids, logits, is_real_example])
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
eval_metrics=eval_metrics,
scaffold_fn=scaffold_fn)
else:
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
predictions={"probabilities": probabilities},
scaffold_fn=scaffold_fn)
return output_spec
return model_fn
| tensorflow.contrib.tpu.TPUEstimatorSpec | 13,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.