seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
import tensorflow as tf
num_params = 0
# utils.logger.log('Model parameters:')
for var in tf_trainable_vars:
# utils.logger.log(str(var))
num_params += np.prod([dim.value for dim in var.get_shape()])
utils.logger.log('Model has {} parameters'.format(num_params))
return num_params
def _add_vars_assign_op(self, vars):
var_phs = {
tf_var.name: tf.placeholder(dtype=tf_var.dtype, shape=tf_var.shape)
for tf_var in vars
}
vars_assign_op = tf.group([
tf.assign(tf_var, ph)
for (tf_var, ph) in zip(vars, var_phs.values())
], name='vars_assign_op')
return (var_phs, vars_assign_op)
####################################
| tensorflow.placeholder | 6,300 |
import tensorflow as tf
tf.logging.info("**** Trainable Variables ****")
for var in tvars:
init_string = ""
if var.name in initialized_variable_names:
init_string = ", *INIT_FROM_CKPT*"
tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
init_string)
output_spec = None
if mode == tf.estimator.ModeKeys.TRAIN:
| tensorflow.logging.info | 6,301 |
import tensorflow as tf
x_t_flat = tf.reshape(x_t, (1, -1))
y_t_flat = tf.reshape(y_t, (1, -1))
d_t_flat = tf.reshape(d_t, (1, -1))
| tensorflow.reshape | 6,302 |
import tensorflow as tf
querry_size = query.get_shape().as_list()[-1]
queries = tf.tile(query, [1, tf.shape(facts)[1]])
queries = tf.reshape(queries, tf.shape(facts))
din_all = tf.concat([queries, facts, queries-facts, queries*facts], axis=-1)
d_layer_1_all = tf.layers.dense(din_all, 80, activation=tf.nn.sigmoid, name='f1_att' + stag)
d_layer_2_all = tf.layers.dense(d_layer_1_all, 40, activation=tf.nn.sigmoid, name='f2_att' + stag)
d_layer_3_all = tf.layers.dense(d_layer_2_all, 1, activation=None, name='f3_att' + stag)
d_layer_3_all = tf.reshape(d_layer_3_all, [-1, 1, tf.shape(facts)[1]])
scores = d_layer_3_all
# Mask
# key_masks = tf.sequence_mask(facts_length, tf.shape(facts)[1]) # [B, T]
key_masks = tf.expand_dims(mask, 1) # [B, 1, T]
paddings = tf.ones_like(scores) * (-2 ** 32 + 1)
scores = tf.where(key_masks, scores, paddings) # [B, 1, T]
# Scale
# scores = scores / (facts.get_shape().as_list()[-1] ** 0.5)
# Activation
if softmax_stag:
scores = tf.nn.softmax(scores) # [B, 1, T]
| tensorflow.expand_dims | 6,303 |
import tensorflow as tf
opt_denoise = self.optimizer_func(self.hparams.learning_rate)
opt_ranker = self.optimizer_func(self.ranker_learning_rate)
denoise_updates = opt_denoise.apply_gradients(zip(denoise_gradients, denoise_params),
global_step=self.global_step)
ranker_updates = opt_ranker.apply_gradients(zip(ranking_model_gradients, ranking_model_params))
self.updates = tf.group(denoise_updates, ranker_updates)
def DenoisingNet(self, list_size, forward_only=False, scope=None):
with tf.variable_scope(scope or "denoising_model"):
# If we are in testing, do not compute propensity
if forward_only:
return tf.ones_like(self.output)#, tf.ones_like(self.output)
input_vec_size = list_size*4
def propensity_network(input_data, index):
reuse = None if index < 1 else True
propensity_initializer = tf.constant_initializer(0.001) if self.hparams.constant_propensity_initialization else None
with tf.variable_scope("propensity_network", initializer=propensity_initializer,
reuse=reuse):
output_data = input_data
current_size = input_vec_size
output_sizes = [
int((list_size+1)/2) + 1,
int((list_size+1)/4) + 1,
| tensorflow.ones_like | 6,304 |
from tensorflow.python.ops import array_ops
'concatenate along must have statically known size')
# We move `axis` to the front of the internal array so assign ops can be
# applied to contiguous slices
init_size = 0 if max_size is None else max_size
init_shape = [init_size] + fixed_shape
array = _create_local(
'array', shape=init_shape, validate_shape=False, dtype=values.dtype)
size = _create_local('size', shape=[], dtype=dtypes.int32)
perm = [0 if n == axis else n + 1 if n < axis else n for n in range(ndim)]
valid_array = array[:size]
valid_array.set_shape([None] + fixed_shape)
value = array_ops.transpose(valid_array, perm, name='concat')
values_size = array_ops.shape(values)[axis]
if max_size is None:
batch_size = values_size
else:
batch_size = math_ops.minimum(values_size, max_size - size)
perm = [axis] + [n for n in range(ndim) if n != axis]
batch_values = array_ops.transpose(values, perm)[:batch_size]
def reallocate():
next_size = _next_array_size(new_size)
| tensorflow.python.ops.array_ops.transpose | 6,305 |
import tensorflow as tf
lr_dec_every=self.lr_dec_every,
lr_dec_rate=self.lr_dec_rate,
optim_algo=self.optim_algo,
sync_replicas=self.sync_replicas,
num_aggregate=self.num_aggregate,
num_replicas=self.num_replicas)
self.skip_rate = tf.constant(0.0, dtype=tf.float32)
| tensorflow.constant | 6,306 |
import tensorflow as tf
self.batch_size = 1000
# LSTM structure
self.n_inputs = len(X_train[0][0]) # Features count is of 9: three 3D sensors features over time
self.n_hidden = N_HIDDEN_CONFIG # nb of neurons inside the neural network
self.n_classes = 6 # Final output classes
self.W = {
'hidden': tf.Variable(tf.random_normal([self.n_inputs, self.n_hidden])), # [9, 32]
'output': tf.Variable(tf.random_normal([self.n_hidden, self.n_classes])) # [32, 6]
}
self.biases = {
'hidden': tf.Variable(tf.random_normal([self.n_hidden], mean=1.0)), # [32]
'output': tf.Variable(tf.random_normal([self.n_classes])) # [6]
}
| tensorflow.random_normal | 6,307 |
from tensorflow.python.ops import control_flow_ops
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.python.ops.control_flow_ops.group | 6,308 |
import tensorflow as tf
# Set up training loss and learning rate.
global_step = tf.train.get_or_create_global_step()
| tensorflow.train.get_or_create_global_step | 6,309 |
import tensorflow as tf
with tf.variable_scope("Context_to_Query_Attention_Layer"):
# C = tf.tile(tf.expand_dims(c,2),[1,1,self.q_maxlen,1])
# Q = tf.tile(tf.expand_dims(q,1),[1,self.c_maxlen,1,1])
# S = trilinear([C, Q, C*Q], input_keep_prob = 1.0 - self.dropout)
S = optimized_trilinear_for_attention([c, q], self.c_maxlen, self.q_maxlen, 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_, q)
self.q2c = tf.matmul(tf.matmul(S_, S_T), c)
attention_outputs = [c, self.c2q, c * self.c2q, c * self.q2c]
with tf.variable_scope("Model_Encoder_Layer"):
inputs = tf.concat(attention_outputs, axis = -1)
self.enc = [conv(inputs, d, name = "input_projection")]
for i in range(3):
if i % 2 == 0: # dropout every 2 blocks
self.enc[i] = tf.nn.dropout(self.enc[i], 1.0 - self.dropout)
self.enc.append(
residual_block(self.enc[i],
num_blocks = 7,
num_conv_layers = 2,
kernel_size = 5,
mask = self.c_mask,
num_filters = d,
num_heads = nh,
seq_len = self.c_len,
scope = "Model_Encoder",
| tensorflow.concat | 6,310 |
import tensorflow as tf
'Optimizer vars: %s.' % ', '.join(var for var in optimizer_vars))
tf.logging.info('Will train: %s.' % vars_to_load)
tf.train.init_from_checkpoint(params['resnet_checkpoint'], vars_to_load)
if not vars_to_load:
| tensorflow.train.init_from_checkpoint | 6,311 |
import tensorflow as tf
self.training_op = tf.compat.v1.train.AdamOptimizer(self.learning_rate).minimize(self.loss)
# Perf metrics
with tf.name_scope("accuracy"):
prediction = tf.equal(tf.argmax(self.fc2, 1), tf.argmax(self.y, 1))
self.accuracy = tf.reduce_mean(tf.cast(prediction, tf.float32))
| tensorflow.argmax | 6,312 |
import tensorflow as tf
if direction is None:
direct_mask = tf.not_equal(head_idxs, dep_idxs) # [bs, slh, sld]
else:
if direction == 'forward':
direct_mask = tf.greater(head_idxs, dep_idxs) # [bs, slh, sld]
else:
direct_mask = tf.less(head_idxs, dep_idxs) # [bs, slh, sld]
# [bs, slh, slh]
rep_mask_tile = tf.logical_and(tf.expand_dims(rep_dep_mask, 1), tf.expand_dims(rep_head_mask, 2))
attn_mask = tf.logical_and(direct_mask, rep_mask_tile) # [bs, slh, sld]
# tensor tile
rep_map_tile = tf.tile(tf.expand_dims(rep_dep_tensor, 1), [1, sl_head, 1, 1]) # bs,slh,sld,vec
with tf.variable_scope('attention'): # bs,sl,sl,vec
f_bias = tf.get_variable('f_bias', [ivec], tf.float32, tf.constant_initializer(0.))
dependent = linear(rep_dep_tensor_dp, ivec, False, scope='linear_dependent') # bs,sld,vec
dependent_etd = tf.expand_dims(dependent, 1) # bs,1,sld,vec
head = linear(rep_head_tensor_dp, ivec, False, scope='linear_head') # bs,slh,vec
head_etd = tf.expand_dims(head, 2) # bs,slh,1,vec
logits = scaled_tanh(dependent_etd + head_etd + f_bias, 5.0) # bs,slh,sld,vec
logits_masked = exp_mask_for_high_rank(logits, attn_mask) # bs,slh,sld,vec
attn_score = tf.nn.softmax(logits_masked, 2) # bs,slh,sld,vec
attn_score = mask_for_high_rank(attn_score, attn_mask)
attn_result = tf.reduce_sum(attn_score * rep_map_tile, 2) # bs,slh,vec -> head_org_idx
return attn_result
| tensorflow.variable_scope | 6,313 |
import tensorflow as tf
segment_ids.append(0)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
label_id = label_map[example.label]
if ex_index < 5:
tf.logging.info("*** Example ***")
tf.logging.info("guid: %s" % (example.guid))
tf.logging.info("tokens: %s" % " ".join(
[tokenization.printable_text(x) for x in tokens]))
tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
tf.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
tf.logging.info("label: %s (id = %d)" % (example.label, label_id))
feature = InputFeatures(
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
label_id=label_id)
return feature
def file_based_convert_examples_to_features(
examples, label_list, max_seq_length, tokenizer, output_file):
"""Convert a set of `InputExample`s to a TFRecord file."""
writer = tf.python_io.TFRecordWriter(output_file)
| tensorflow.logging.info | 6,314 |
import tensorflow as tf
tf.estimator.ModeKeys.EVAL,
eval_metrics=(eval_metrics_fn, logits),
loss=loss)
else:
return tf.contrib.tpu.TPUEstimatorSpec(
tf.estimator.ModeKeys.EVAL,
eval_metrics=(eval_metrics_fn, [logits, labels]),
loss=loss)
else:
eval_metrics_fns = metrics.create_evaluation_metrics([problem], hparams)
eval_metrics = {}
for metric_name, metric_fn in six.iteritems(eval_metrics_fns):
eval_metrics[metric_name] = metric_fn(logits, features)
return tf.estimator.EstimatorSpec(
tf.estimator.ModeKeys.EVAL,
predictions={"predictions": logits},
eval_metric_ops=eval_metrics,
loss=loss)
def estimator_spec_predict(self, features):
"""Construct EstimatorSpec for PREDICT mode."""
decode_hparams = self._decode_hparams
infer_out = self.infer(
features,
beam_size=decode_hparams.beam_size,
top_beams=(decode_hparams.beam_size
if decode_hparams.return_beams else 1),
| tensorflow.estimator.EstimatorSpec | 6,315 |
from tensorflow.python.framework import ops
# The dimensions are compatible, so output is the same size in that
# dimension.
return_dims.append(dim_x.merge_with(dim_y))
else:
raise ValueError("Incompatible shapes for broadcasting: %s and %s"
% (shape_x, shape_y))
return [tensor_shape.TensorShape(return_dims)]
@ops.RegisterShape("AddN")
def _AddNShape(op):
merged_shape = tensor_shape.unknown_shape()
for input_ in op.inputs:
merged_shape = merged_shape.merge_with(input_.get_shape())
return [merged_shape]
@ops.RegisterShape("Select")
| tensorflow.python.framework.ops.RegisterShape | 6,316 |
import tensorflow as tf
return output_
if decoder.use_dropout: # FIXME: why no pervasive dropout here?
initial_state = tf.nn.dropout(initial_state, keep_prob=decoder.initial_state_keep_prob)
with tf.variable_scope(scope_name):
activation_fn = None if decoder.initial_state == 'linear' else tf.nn.tanh
if decoder.initial_state == 'trained':
initial_state = get_variable(shape=[cell_state_size], name='initial_state')
initial_state = tf.tile(tf.expand_dims(initial_state, axis=0), [batch_size, 1])
elif decoder.initial_state == 'zero':
initial_state = tf.zeros(shape=[batch_size, cell_state_size])
elif decoder.layer_norm:
initial_state = dense(initial_state, cell_state_size, use_bias=False, name='initial_state_projection')
initial_state = tf.contrib.layers.layer_norm(initial_state, activation_fn=activation_fn,
scope='initial_state_layer_norm')
else:
initial_state = dense(initial_state, cell_state_size, use_bias=True, name='initial_state_projection',
activation=activation_fn)
if decoder.cell_type.lower() == 'lstm' and decoder.use_lstm_full_state:
initial_output = initial_state
| tensorflow.zeros | 6,317 |
import tensorflow as tf
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],
axis=1)
context_size = initial_context.shape[1].value
| tensorflow.expand_dims | 6,318 |
import tensorflow as tf
def create_global_steps(self, n_points_train_set):
self.n_batches_per_epoch = np.ceil(n_points_train_set/self.batch_size["train"])
self.global_step = tf.train.get_or_create_global_step()
self.global_epoch = tf.cast(tf.floor(tf.cast(self.global_step, tf.float32) /
self.n_batches_per_epoch),
tf.int64, "global_epoch")
| tensorflow.cast | 6,319 |
import tensorflow as tf
offset = get_variable("offset", shape=[channels], dtype=tf.float32, initializer=tf.constant_initializer(0.0))
scale = get_variable("scale", shape=[channels], dtype=tf.float32, initializer=tf.constant_initializer(1.0), regularizer=tf.nn.l2_loss)
mean, variance = tf.nn.moments(inp, axes=[0, 1, 2], shift=moving_mean)
mean_op = moving_mean.assign(decay * moving_mean + (1 - decay) * mean)
var_op = moving_variance.assign(decay * moving_variance + (1 - decay) * variance)
assert(phase in ['train', 'test'])
if phase == 'train':
with tf.control_dependencies([mean_op, var_op]):
return tf.nn.batch_normalization(inp, mean, variance, offset, scale, 0.01, name='norm')
else:
return tf.nn.batch_normalization(inp, moving_mean, moving_variance, offset, scale, 0.01, name='norm')
def pool(inp, name, kind, size, stride, padding='SAME'):
assert kind in ['max', 'avg']
| tensorflow.control_dependencies | 6,320 |
import tensorflow as tf
start_y = tf.random.uniform(shape=(1,), minval=0, maxval=im_height, dtype=tf.int32)
mask = tf.pad(mask, [[cutout_size + start_y[0], im_height - start_y[0]],
[cutout_size + start_x[0], im_width - start_x[0]]])
mask = mask[cutout_size: cutout_size + im_height,
cutout_size: cutout_size + im_width]
mask = tf.tile(tf.reshape(mask, (im_height, im_width, 1)), (1, 1, 3))
image = tf.where(tf.equal(mask, 0), x=image, y=tf.zeros_like(image))
return image
def _add_drop_path(self, X, keep_prob):
with tf.variable_scope('drop_path'):
batch_size = tf.shape(X)[0]
noise_shape = (batch_size, 1, 1, 1)
random_tensor = keep_prob + tf.random_uniform(noise_shape, dtype=tf.float32)
binary_tensor = tf.floor(random_tensor)
X = (X / keep_prob) * binary_tensor
return X
def _do_conv(self, X, w, h, in_ch, out_ch, filter_size=1, no_relu=False, no_reg=False, is_train=False):
W = self._make_var('W', (filter_size, filter_size, in_ch, out_ch), no_reg=no_reg)
if not no_relu:
X = tf.nn.relu(X)
X = tf.nn.conv2d(X, W, (1, 1, 1, 1), padding='SAME')
X = self._add_batch_norm(X, out_ch, is_train=is_train)
X = tf.reshape(X, (-1, w, h, out_ch)) # Sanity shape check
return X
def _do_separable_conv(self, X, w, h, ch, filter_size=3, stride=1, ch_mul=1,
| tensorflow.floor | 6,321 |
import tensorflow as tf
x = (x + 1.0) * (width_f) / 2.0
y = (y + 1.0) * (height_f) / 2.0
z = (z + 1.0) * (depth_f) / 2.0
x0 = tf.to_int32(tf.floor(x))
x1 = x0 + 1
y0 = tf.to_int32(tf.floor(y))
y1 = y0 + 1
z0 = tf.to_int32(tf.floor(z))
z1 = z0 + 1
x0_clip = tf.clip_by_value(x0, zero, max_x)
x1_clip = tf.clip_by_value(x1, zero, max_x)
y0_clip = tf.clip_by_value(y0, zero, max_y)
y1_clip = tf.clip_by_value(y1, zero, max_y)
z0_clip = tf.clip_by_value(z0, zero, max_z)
| tensorflow.floor | 6,322 |
import tensorflow as tf
image = tf.slice(image, [offset_height, offset_width, 0], [size, size, -1])
return image
def lighting(image, std, eigval, eigvec):
v = tf.random_normal(shape=[3], stddev=std) * eigval
inc = tf.matmul(eigvec, tf.reshape(v, [3, 1]))
image = tf.cast(tf.cast(image, tf.float32) + tf.reshape(inc, [3]), image.dtype)
return image
def validation_mapper(byte):
image = tf.image.decode_jpeg(
tf.reshape(byte, shape=[]), 3, **JPEG_OPT)
image = resize_shortest_edge(image, tf.shape(image), 256)
image = center_crop(image, 224)
image = tf.reverse(image, axis=[2]) # to BGR
return image
def training_mapper(byte):
jpeg_shape = tf.image.extract_jpeg_shape(byte) # hwc
bbox_begin, bbox_size, distort_bbox = tf.image.sample_distorted_bounding_box(
jpeg_shape,
bounding_boxes=tf.zeros(shape=[0, 0, 4]),
| tensorflow.reshape | 6,323 |
import tensorflow as tf
self.grads.append(self.grads_and_vars[i][0]);
self.vars.append(self.grads_and_vars[i][1]);
self.grads=self.grads[-1*NUM_VARS:];
self.vars=self.vars[-1*NUM_VARS:];
self.train_op = self.optimizer.apply_gradients(
self.grads_and_vars, global_step=tf.contrib.framework.get_global_step())
def predict(self, state, sess=None):
sess = sess or tf.get_default_session()
state=featurize_state(state);
return sess.run(self.action, { self.state: [state] })[0]
def update(self, state, target, action, sess=None):
sess = sess or tf.get_default_session()
for st_idx in range(len(state)):
state[st_idx]=featurize_state(state[st_idx]);
feed_dict = { self.state: state, self.target: target, self.a_his: action }
_, loss = sess.run([self.train_op, self.loss], feed_dict)
return loss
class ValueEstimator_MountainCarContinuous():
def __init__(self, learning_rate=0.1, par_idx=0,scope="value_estimator"):
w_init = tf.random_normal_initializer(0.,.1);
with tf.variable_scope(scope+"_"+str(par_idx)):
# state and target
self.state = tf.placeholder(tf.float32, [None,400], "state")
| tensorflow.get_default_session | 6,324 |
import tensorflow as tf
for network_parameters in ap.network_wrappers.values():
network_parameters.framework = args.framework
return graph_manager
def _save_tf_model(self):
ckpt_dir = '/opt/ml/output/data/checkpoint'
model_dir = '/opt/ml/model'
import tensorflow as tf # importing tensorflow here so that MXNet docker image is compatible with this file.
# Re-Initialize from the checkpoint so that you will have the latest models up.
tf.train.init_from_checkpoint(ckpt_dir,
{'main_level/agent/online/network_0/': 'main_level/agent/online/network_0'})
tf.train.init_from_checkpoint(ckpt_dir,
{'main_level/agent/online/network_1/': 'main_level/agent/online/network_1'})
# Create a new session with a new tf graph.
sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
sess.run(tf.global_variables_initializer()) # initialize the checkpoint.
# This is the node that will accept the input.
| tensorflow.train.init_from_checkpoint | 6,325 |
import tensorflow as tf
initializer=modeling.create_initializer(bert_config.initializer_range))
output_bias = tf.get_variable(
"output_bias", shape=[2], initializer=tf.zeros_initializer())
logits = tf.matmul(input_tensor, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
log_probs = tf.nn.log_softmax(logits, axis=-1)
labels = tf.reshape(labels, [-1])
one_hot_labels = tf.one_hot(labels, depth=2, 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, log_probs)
| tensorflow.nn.log_softmax | 6,326 |
import tensorflow as tf
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)
def ortho_init(scale=1.0):
def _ortho_init(shape, dtype, partition_info=None):
#lasagne ortho init for tf
shape = tuple(shape)
if len(shape) == 2:
flat_shape = shape
| tensorflow.log | 6,327 |
import tensorflow as tf
return filename
with tf.gfile.GFile(lang1_fname, mode="w") as lang1_resfile:
| tensorflow.gfile.GFile | 6,328 |
import tensorflow as tf
self._loss = None
if mode_gen in ('ce_train', 'loss', ):
xent = CE_loss(vocab_scores, answer_batch, loss_weights) # [batch_size]
if mode_gen == 'loss': xent *= self.placeholders.reward # multiply with rewards
self._loss = tf.reduce_mean(xent)
# Calculate coverage loss from the attention distributions
if options.use_coverage:
with tf.variable_scope('coverage_loss'):
self._coverage_loss = _coverage_loss(attn_dists, loss_weights)
self._loss = self._loss + options.cov_loss_wt * self._coverage_loss
# accuracy is calculated only under 'ce_train', where true answer is given
if mode_gen == 'ce_train':
accuracy = _mask_and_accuracy(vocab_scores, answer_batch, loss_weights)
| tensorflow.variable_scope | 6,329 |
import tensorflow as tf
# q network evaluation
q_t = q_func(obs_t_input.get(), num_actions, scope="q_func", reuse=True) # reuse parameters from act
q_func_vars = U.scope_vars(U.absolute_scope_name("q_func"))
# target q network evalution
q_tp1 = q_func(obs_tp1_input.get(), num_actions, scope="target_q_func")
target_q_func_vars = U.scope_vars(U.absolute_scope_name("target_q_func"))
# q scores for actions which we know were selected in the given state.
q_t_selected = tf.reduce_sum(q_t * tf.one_hot(act_t_ph, num_actions), 1)
# compute estimate of best possible value starting from state at t + 1
if double_q:
q_tp1_using_online_net = q_func(obs_tp1_input.get(), num_actions, scope="q_func", reuse=True)
q_tp1_best_using_online_net = tf.arg_max(q_tp1_using_online_net, 1)
q_tp1_best = tf.reduce_sum(q_tp1 * tf.one_hot(q_tp1_best_using_online_net, num_actions), 1)
else:
q_tp1_best = tf.reduce_max(q_tp1, 1)
q_tp1_best_masked = (1.0 - done_mask_ph) * q_tp1_best
# compute RHS of bellman equation
q_t_selected_target = rew_t_ph + gamma * q_tp1_best_masked
# compute the error (potentially clipped)
td_error = q_t_selected - tf.stop_gradient(q_t_selected_target)
errors = U.huber_loss(td_error)
weighted_error = tf.reduce_mean(importance_weights_ph * errors)
| tensorflow.arg_max | 6,330 |
import tensorflow as tf
with tf.variable_scope(scope, default_name="bert"):
with tf.variable_scope("embeddings"):
| tensorflow.variable_scope | 6,331 |
import tensorflow as tf
(tf.Tensor) A single value tensor containing the loss.
"""
loss = None
with tf.name_scope(name, "softmax_loss",[output]):
label_dis = labels / tf.reduce_sum(labels, 1, keep_dims=True)
loss = tf.nn.softmax_cross_entropy_with_logits(logits=output, labels=label_dis) * tf.reduce_sum(labels, 1)
return tf.reduce_sum(loss) / tf.reduce_sum(labels)
def get_normalized_weights(self, propensity):
"""Computes listwise softmax loss with propensity weighting.
Args:
propensity: (tf.Tensor) A tensor of the same shape as `output` containing the weight of each element.
| tensorflow.reduce_sum | 6,332 |
import tensorflow as tf
'maxls': 50,
'ftol' : 1.0 * np.finfo(float).eps})
self.optimizer_Adam = tf.train.AdamOptimizer()
self.train_op_Adam = self.optimizer_Adam.minimize(self.loss)
init = tf.global_variables_initializer()
self.sess.run(init)
def initialize_NN(self, layers):
weights = []
biases = []
num_layers = len(layers)
for l in range(0,num_layers-1):
W = self.xavier_init(size=[layers[l], layers[l+1]])
b = tf.Variable(tf.zeros([1,layers[l+1]], dtype=tf.float32), dtype=tf.float32)
weights.append(W)
biases.append(b)
return weights, biases
def xavier_init(self, size):
in_dim = size[0]
out_dim = size[1]
xavier_stddev = np.sqrt(2/(in_dim + out_dim))
return tf.Variable(tf.truncated_normal([in_dim, out_dim], stddev=xavier_stddev), dtype=tf.float32)
def neural_net(self, X, weights, biases):
num_layers = len(weights) + 1
H = 2.0*(X - self.lb)/(self.ub - self.lb) - 1.0
| tensorflow.zeros | 6,333 |
import tensorflow as tf
from model_io import model_io
from task_module import classifier
import tensorflow as tf
from metric import tf_metrics
from optimizer import distributed_optimizer as optimizer
from model_io import model_io
from distillation import knowledge_distillation as distill
def correlation(x, y):
x = x - tf.reduce_mean(x, axis=-1, keepdims=True)
y = y - tf.reduce_mean(y, axis=-1, keepdims=True)
x = tf.nn.l2_normalize(x, -1)
y = tf.nn.l2_normalize(y, -1)
return -tf.reduce_sum(x*y, axis=-1) # higher the better
def kd(x, y):
x_prob = tf.nn.softmax(x)
print(x_prob.get_shape(), y.get_shape(), tf.reduce_sum(x_prob * y, axis=-1).get_shape())
return -tf.reduce_sum(x_prob * y, axis=-1) # higher the better
def mse(x, y):
x = x - tf.reduce_mean(x, axis=-1, keepdims=True)
y = y - tf.reduce_mean(y, axis=-1, keepdims=True)
return tf.reduce_sum((x-y)**2, axis=-1) # lower the better
def kd_distance(x, y, dist_type):
if dist_type == "person":
return correlation(x,y)
| tensorflow.reduce_sum | 6,334 |
import tensorflow as tf
eval_input_fn = None
'''
# Add hooks
train_hooks = [
tf.train.StopAtStepHook(last_step=params.train_steps),
tf.train.NanTensorHook(loss), # Monitors the loss tensor and stops training if loss is NaN
tf.train.LoggingTensorHook(
{
"step": global_step,
"loss": loss,
| tensorflow.train.NanTensorHook | 6,335 |
import tensorflow as tf
"""Trains model on train_data using optimizer."""
tf.train.get_or_create_global_step()
def model_loss(labels, chars, sequence_length):
predictions = model((chars, sequence_length), training=True)
loss_value = loss(labels, predictions)
tf.contrib.summary.scalar("loss", loss_value)
return loss_value
for (batch, (labels, chars, sequence_length)) in enumerate(
tfe.Iterator(train_data)):
with tf.contrib.summary.record_summaries_every_n_global_steps(log_interval):
batch_model_loss = functools.partial(model_loss, labels, chars,
| tensorflow.contrib.summary.scalar | 6,336 |
from tensorflow.python.framework import ops
if updates_collections:
ops.add_to_collections(updates_collections, update_op)
| tensorflow.python.framework.ops.add_to_collections | 6,337 |
from tensorflow.python.client import device_lib
class RevNetBenchmark(tf.test.Benchmark):
"""Eager and graph benchmarks for RevNet."""
def _train_batch_sizes(self):
"""Shamelessly copied from `resnet50_test.py`.
Note: This is targeted towards ImageNet. CIFAR-10 should allow more
aggressive batch sizes.
Returns:
A tuple of possible batch sizes
"""
for device in device_lib.list_local_devices():
if tf.DeviceSpec.from_string(device.name).device_type == "GPU":
if "K20" in device.physical_device_desc:
return (16,)
if "P100" in device.physical_device_desc:
return (16, 32, 64)
if tf.DeviceSpec.from_string(device.name).device_type == "TPU":
return (32,)
return (16, 32)
def _force_device_sync(self):
"""Shamelessly copied from `resnet50_test.py`."""
| tensorflow.python.client.device_lib.list_local_devices | 6,338 |
import tensorflow as tf
features: an map of string to `Tensor`
decode_length: an integer. How many additional timesteps to decode.
beam_size: number of beams.
top_beams: an integer. How many of the beams to return.
alpha: Float that controls the length penalty. larger the alpha, stronger
the preference for slonger translations.
Returns:
samples: an integer `Tensor`. Top samples from the beam search
"""
batch_size = common_layers.shape_list(features["inputs"])[0]
def symbols_to_logits_fn(ids):
"""Go from ids to logits."""
ids = tf.expand_dims(tf.expand_dims(ids, axis=2), axis=3)
ids = tf.pad(ids[:, 1:], [[0, 0], [0, 1], [0, 0], [0, 0]])
if "partial_targets" in features:
pt = features["partial_targets"]
pt_length = common_layers.shape_list(pt)[1]
pt = tf.tile(pt, [1, beam_size])
pt = tf.reshape(pt, [batch_size * beam_size, pt_length, 1, 1])
ids = tf.concat([pt, ids], axis=1)
features["targets"] = ids
self._coverage = None
logits, _ = self(features) # pylint: disable=not-callable
# now self._coverage is a coverage tensor for the first datashard.
# it has shape [batch_size] and contains floats between 0 and
# source_length.
if self._problem_hparams:
| tensorflow.pad | 6,339 |
from tensorflow.python.util import deprecation
from tensorflow.python.training import saver as saver_lib
from tensorflow.python.training import summary_io
from tensorflow.python.util import deprecation
# TODO(ptucker): Split each monitor class into a separate file.
# TODO(ptucker): Fail if epoch or step does not monotonically increase?
class BaseMonitor(object):
"""Base class for Monitors.
Defines basic interfaces of Monitors.
Monitors can either be run on all workers or, more commonly, restricted
to run exclusively on the elected chief worker.
"""
@deprecation.deprecated(
"2016-12-05",
"Monitors are deprecated. Please use tf.train.SessionRunHook.")
def __init__(self):
self._begun = False
self._current_epoch = None
self._current_step = None
self._max_steps = None
self._estimator = None
@property
def run_on_all_workers(self):
return False
def set_estimator(self, estimator):
| tensorflow.python.util.deprecation.deprecated | 6,340 |
import tensorflow as tf
self.validateKolmogorovSmirnov([10**5], 0.0, 0.1, 0.05, 0.10)
class ParameterizedTruncatedNormalGpuTest(ParameterizedTruncatedNormalTest):
_use_gpu = True
# Benchmarking code
def parameterized_vs_naive(shape, num_iters, use_gpu=False):
np.random.seed(1618) # Make it reproducible.
# No CSE/CF.
optimizer_options = tf.OptimizerOptions(opt_level=tf.OptimizerOptions.L0)
config = tf.ConfigProto(
graph_options=tf.GraphOptions(optimizer_options=optimizer_options))
with tf.Session(config=config) as sess:
with tf.device("/cpu:0" if not use_gpu else None):
param_op = tf.group(random_ops.parameterized_truncated_normal(shape))
naive_op = tf.group(random_ops.truncated_normal(shape))
# Burn-in to avoid session setup costs in the timing.
sess.run(param_op)
sess.run(param_op)
param_dt = timeit.timeit(lambda: sess.run(param_op), number=num_iters)
sess.run(naive_op)
sess.run(naive_op)
naive_dt = timeit.timeit(lambda: sess.run(naive_op), number=num_iters)
| tensorflow.GraphOptions | 6,341 |
import tensorflow as tf
self.assertEqual(logits_.shape,
(batch_size, max_time))
# case 4
hparams = {
"pretrained_model_name": None,
"regr_strategy": "all_time",
"max_seq_len": max_time
}
inputs = tf.placeholder(tf.int32, shape=[batch_size, 6])
regressor = XLNetRegressor(hparams=hparams)
logits = regressor(inputs)
with self.test_session() as sess:
sess.run(tf.global_variables_initializer())
logits_ = sess.run(
logits,
feed_dict={inputs: np.random.randint(30521,
| tensorflow.placeholder | 6,342 |
import tensorflow as tf
x = np.clip(x, 0, 1)
# convert to RGB array
x *= 255
if K.image_dim_ordering() == 'th':
x = x.transpose((1, 2, 0))
x = np.clip(x, 0, 255).astype('uint8')
return x
def _compute_gradients(tensor, var_list):
grads = tf.gradients(tensor, var_list)
return [grad if grad is not None else tf.zeros_like(var) for var, grad in zip(var_list, grads)]
def grad_cam(input_model, image, category_index, layer_name):
nb_classes = 1000
target_layer = lambda x: target_category_loss(x, category_index, nb_classes)
x = Lambda(target_layer, output_shape = target_category_loss_output_shape)(input_model.output)
model = Model(inputs=input_model.input, outputs=x)
#model.summary()
loss = K.sum(model.output)
| tensorflow.gradients | 6,343 |
import tensorflow as tf
def mean_pooling_for_unselected_head(
unhead_org_idx, sl_unhead, rep_unhead_mask,
dep_org_idx, sl_dep, rep_dep_mask,
rep_dep_tensor, direction
):
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]
| tensorflow.not_equal | 6,344 |
import tensorflow as tf
candidate_mask = tf.logical_and(candidate_ends < num_words, tf.equal(candidate_start_sentence_indices, candidate_end_sentence_indices)) # [num_words, max_span_width]
flattened_candidate_mask = tf.reshape(candidate_mask, [-1]) # [num_words * max_span_width]
candidate_starts = tf.boolean_mask(tf.reshape(candidate_starts, [-1]), flattened_candidate_mask) # [num_candidates]
candidate_ends = tf.boolean_mask(tf.reshape(candidate_ends, [-1]), flattened_candidate_mask) # [num_candidates]
candidate_sentence_indices = tf.boolean_mask(tf.reshape(candidate_start_sentence_indices, [-1]), flattened_candidate_mask) # [num_candidates]
candidate_cluster_ids = self.get_candidate_labels(candidate_starts, candidate_ends, gold_starts, gold_ends, cluster_ids) # [num_candidates]
candidate_span_emb = self.get_span_emb(flattened_head_emb, context_outputs, candidate_starts, candidate_ends) # [num_candidates, emb]
candidate_mention_scores = self.get_mention_scores(candidate_span_emb) # [k, 1]
candidate_mention_scores = tf.squeeze(candidate_mention_scores, 1) # [k]
k = tf.to_int32(tf.floor(tf.to_float(tf.shape(context_outputs)[0]) * self.config["top_span_ratio"]))
top_span_indices = coref_ops.extract_spans(tf.expand_dims(candidate_mention_scores, 0),
tf.expand_dims(candidate_starts, 0),
tf.expand_dims(candidate_ends, 0),
tf.expand_dims(k, 0),
util.shape(context_outputs, 0),
True) # [1, k]
top_span_indices.set_shape([1, None])
top_span_indices = tf.squeeze(top_span_indices, 0) # [k]
top_span_starts = tf.gather(candidate_starts, top_span_indices) # [k]
top_span_ends = tf.gather(candidate_ends, top_span_indices) # [k]
top_span_emb = tf.gather(candidate_span_emb, top_span_indices) # [k, emb]
top_span_cluster_ids = tf.gather(candidate_cluster_ids, top_span_indices) # [k]
top_span_mention_scores = tf.gather(candidate_mention_scores, top_span_indices) # [k]
top_span_sentence_indices = tf.gather(candidate_sentence_indices, top_span_indices) # [k]
top_span_speaker_ids = tf.gather(speaker_ids, top_span_starts) # [k]
| tensorflow.expand_dims | 6,345 |
from tensorflow.python.ops import array_ops
b_list = [b[i] for i in range(numTensors)]
b_grads = b_module.bspmm(a_indices, a_values, a_shape, grad, adjoint_a=True, adjoint_b=False)
bg_row=tf.shape(b_grads[0])[0]
bg_col=tf.shape(b_grads[0])[1]
b_grads = tf.reshape(b_grads, (numTensors * bg_row, bg_col))
if adj_b:
b_grads = [array_ops.transpose(b_g) for b_g in b_grads]
for t in range(numTensors):
rows = a_indices[t][:, 0]
cols = a_indices[t][:, 1]
parts_a = array_ops.gather(grad[t], rows if not adj_a else cols)
parts_b = array_ops.gather(b_list[t] if not adj_b else array_ops.transpose(b_list[t]), cols if not adj_a else rows)
a_values_grads.append(math_ops.reduce_sum(parts_a * parts_b, reduction_indices=1))
| tensorflow.python.ops.array_ops.transpose | 6,346 |
import tensorflow as tf
# for each key I get the collection of summary nodes
# I set up a filewriter for each summary node
self.summary_nodes = {sk: tf.get_collection(sk) for sk in self.summary_keys}
for sk in self.summary_keys:
| tensorflow.get_collection | 6,347 |
import tensorflow as tf
"""Example sequence-to-sequence model that uses GRU cells."""
def GRUSeq2Seq(enc_inp, dec_inp):
cell = tf.nn.rnn_cell.MultiRNNCell([tf.nn.rnn_cell.GRUCell(24)] * 2,
state_is_tuple=True)
return tf.nn.seq2seq.embedding_attention_seq2seq(
enc_inp, dec_inp, cell, num_encoder_symbols=classes,
num_decoder_symbols=classes, embedding_size=24,
output_projection=(w, b))
targets = [dec_inp[i+1] for i in range(len(dec_inp) - 1)] + [0]
def SampledLoss(labels, inputs):
labels = tf.reshape(labels, [-1, 1])
return tf.nn.sampled_softmax_loss(w_t, b, inputs, labels, 8, classes)
return tf.nn.seq2seq.model_with_buckets(
enc_inp, dec_inp, targets, weights, buckets, GRUSeq2Seq,
softmax_loss_function=SampledLoss)
# Now we construct the copy model.
batch_size = 8
inp = [tf.placeholder(tf.int32, shape=[None]) for _ in range(8)]
out = [tf.placeholder(tf.int32, shape=[None]) for _ in range(8)]
| tensorflow.reshape | 6,348 |
import tensorflow as tf
logits=logits, weights=inst_weights, onehot_labels=one_hot_labels)
return loss
src_loss = get_loss(src_logits, inst_weights, src_one_hot_labels)
dst_loss = get_loss(dst_logits, 1., finetune_one_hot_labels)
l2_loss = []
for v in tf.trainable_variables():
if 'batch_normalization' not in v.name and 'rl_controller' not in v.name:
l2_loss.append(tf.nn.l2_loss(v))
l2_loss = FLAGS.dst_weight_decay * tf.add_n(l2_loss)
enable_pretrain = tf.cast(
| tensorflow.trainable_variables | 6,349 |
import tensorflow as tf
def _batch_padding(self, dataset: tf.data.Dataset, pad_id=0, **kwargs) -> tf.data.Dataset:
pad_id = tf.constant(pad_id, dtype=tf.int32)
# fmt: off
padded_shapes = kwargs.get("padded_shapes", ([None, ], [None, ], [None, ], [None, ]))
padding_values = kwargs.get("padding_values", (pad_id, pad_id, pad_id, pad_id))
# fmt: on
dataset = utils.batching_and_padding(dataset, padded_shapes, padding_values, **kwargs)
return dataset
def _bucket_padding(self, dataset: tf.data.Dataset, pad_id=0, **kwargs) -> tf.data.Dataset:
pad_id = tf.constant(pad_id, dtype=tf.int32)
# fmt: off
padded_shapes = kwargs.get("padded_shapes", ([None, ], [None, ], [None, ], [None, ]))
padding_values = kwargs.get("padding_values", (pad_id, pad_id, pad_id, pad_id))
# fmt: on
dataset = utils.bucketing_and_padding(
dataset,
bucket_fn=lambda a, b, c, y: tf.size(a),
padded_shapes=padded_shapes,
padding_values=padding_values,
**kwargs,
| tensorflow.constant | 6,350 |
import tensorflow as tf
v = tf.Variable(np.int64(-1), name="v")
save = tf.train.Saver({"v": v})
| tensorflow.train.Saver | 6,351 |
import tensorflow as tf
input_images = tf.reshape(x_input, [-1, 28, 28, 1])
generated_images = tf.reshape(decoder_output, [-1, 28, 28, 1])
# Tensorboard visualization
tf.summary.scalar(name='Autoencoder Loss', tensor=autoencoder_loss)
tf.summary.scalar(name='Discriminator gauss Loss', tensor=dc_g_loss)
tf.summary.scalar(name='Discriminator categorical Loss', tensor=dc_c_loss)
tf.summary.scalar(name='Generator Loss', tensor=generator_loss)
tf.summary.scalar(name='Supervised Encoder Loss', tensor=supervised_encoder_loss)
tf.summary.histogram(name='Encoder Gauss Distribution', values=encoder_output_latent)
tf.summary.histogram(name='Real Gauss Distribution', values=real_distribution)
tf.summary.histogram(name='Encoder Categorical Distribution', values=encoder_output_label)
tf.summary.histogram(name='Real Categorical Distribution', values=categorial_distribution)
tf.summary.image(name='Input Images', tensor=input_images, max_outputs=10)
tf.summary.image(name='Generated Images', tensor=generated_images, max_outputs=10)
summary_op = tf.summary.merge_all()
# Saving the model
saver = tf.train.Saver()
step = 0
with tf.Session() as sess:
if train_model:
tensorboard_path, saved_model_path, log_path = form_results()
sess.run(init)
writer = tf.summary.FileWriter(logdir=tensorboard_path, graph=sess.graph)
x_l, y_l = mnist.test.next_batch(n_labeled)
| tensorflow.summary.image | 6,352 |
import tensorflow as tf
with self.assertRaisesWithPredicateMatch(
IOError, lambda e: "does not exist"):
tf.train.import_meta_graph(filename)
def testSliceVariable(self):
test_dir = self._TestDir("slice_saver")
filename = os.path.join(test_dir, "metafile")
with self.test_session():
v1 = tf.Variable([20.0], name="v1")
v2 = tf.Variable([20.0], name="v2")
v2._set_save_slice_info(tf.Variable.SaveSliceInfo("v1", [1], [0], [1]))
# The names are different and will work.
slice_saver = tf.train.Saver({"first": v1, "second": v2})
tf.initialize_all_variables().run()
# Exports to meta_graph
| tensorflow.Variable | 6,353 |
import tensorflow as tf
eval_metrics=(eval_metrics_fn, logits),
loss=loss)
else:
return tf.contrib.tpu.TPUEstimatorSpec(
tf.estimator.ModeKeys.EVAL,
eval_metrics=(eval_metrics_fn, [logits, labels]),
| tensorflow.contrib.tpu.TPUEstimatorSpec | 6,354 |
import tensorflow as tf
else:
cols = width
hparams = tf.contrib.training.HParams(
hidden_size=2,
| tensorflow.contrib.training.HParams | 6,355 |
import tensorflow as tf
for time_step in range(self.num_steps):
if time_step > 0: tf.get_variable_scope().reuse_variables()
(cell_output, state) = cell(inputs[:, time_step, :], state)
outputs.append(cell_output)
output = tf.reshape(tf.concat(outputs, 1), [-1, config.hidden_size])
return output, state
def assign_lr(self, session, lr_value):
| tensorflow.concat | 6,356 |
import tensorflow as tf
cells.append(cell)
if len(cells) == 1:
return cells[0]
else:
return CellWrapper(MultiRNNCell(cells))
def look(time, state, input_, prev_weights=None, pos=None, context=None):
prev_weights_ = [prev_weights if i == align_encoder_id else None for i in range(len(encoders))]
pos_ = None
if decoder.pred_edits:
pos_ = [pos if i == align_encoder_id else None for i in range(len(encoders))]
if decoder.attn_prev_word:
state = tf.concat([state, input_], axis=1)
if decoder.attn_prev_attn and context is not None:
state = tf.concat([state, context], axis=1)
if decoder.hidden_state_scaling:
attention_states_ = [states * decoder.hidden_state_scaling for states in attention_states]
else:
attention_states_ = attention_states
parameters = dict(hidden_states=attention_states_, encoder_input_length=encoder_input_length,
encoders=encoders, aggregation_method=decoder.aggregation_method)
context, new_weights = multi_attention(state, time=time, pos=pos_, prev_weights=prev_weights_, **parameters)
| tensorflow.concat | 6,357 |
from tensorflow.python.framework import ops
A `Tensor` of the same type as `a`.
"""
with ops.op_scope([a, b], name, "MatMul") as name:
a = ops.convert_to_tensor(a, name="a")
| tensorflow.python.framework.ops.op_scope | 6,358 |
import tensorflow as tf
return (
tf.identity(self._moving_mean),
tf.identity(self._moving_variance),
tf.identity(self._moving_second_moment),
| tensorflow.identity | 6,359 |
import tensorflow as tf
# print(avg_loss)
# exit()
return avg_loss
def compute_contra_loss(pred1, pred2, tgt1, tgt2, hard_ratio=1.0):
geq = tf.cast((tgt1 - tgt2) > 0, tf.bool)
tgt_larg = tf.where(geq, tgt1, tgt2)
tgt_small = tf.where(geq, tgt2, tgt1)
pred_larg = tf.where(geq, pred1, pred2)
pred_small = tf.where(geq, pred2, pred1)
loss = tf.maximum(0., (tgt_larg - tgt_small) - (pred_larg - pred_small))
if hard_ratio < 1.0:
hard_num = tf.cast(tools.shape(pred1)[0] * hard_ratio, tf.int32)
loss = tf.reshape(loss, [-1])
hard_loss, _ = tf.math.top_k(loss, k=hard_num)
return hard_loss
return loss
| tensorflow.where | 6,360 |
import tensorflow as tf
scaffold_fn = tpu_scaffold
else:
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
tf.logging.info("**** Trainable Variables ****")
for var in tvars:
init_string = ""
if var.name in initialized_variable_names:
init_string = ", *INIT_FROM_CKPT*"
tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
init_string)
output_spec = None
if mode == tf.estimator.ModeKeys.TRAIN:
train_op = optimization.create_optimizer(
total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
| tensorflow.logging.info | 6,361 |
import tensorflow as tf
"""
normalizer_fn = slim.batch_norm
normalizer_fn_args = {
'is_training': is_training,
'zero_debias_moving_mean': True,
'fused': fused_batch_norm,
}
_validate_image_inputs(inputs)
inp_shape = inputs.get_shape().as_list()[1]
end_points = {}
with tf.compat.v1.variable_scope(scope, values=[inputs], reuse=reuse) as scope:
with slim.arg_scope([normalizer_fn], **normalizer_fn_args):
with slim.arg_scope([slim.conv2d],
stride=2,
kernel_size=4,
activation_fn=tf.nn.leaky_relu):
net = inputs
for i in xrange(int(log(inp_shape, 2))):
scope = 'conv%i' % (i + 1)
current_depth = depth * 2**i
normalizer_fn_ = None if i == 0 else normalizer_fn
net = slim.conv2d(
net, current_depth, normalizer_fn=normalizer_fn_, scope=scope)
| tensorflow.compat.v1.variable_scope | 6,362 |
import tensorflow as tf
tf.split(1, max_sequence_len, embeddings)]
# Need to prepare a mask to zero out the padding symbols.
# Make a batch_size x max_sequence_len matrix where each
# row contains the length repeated max_sequence_len times.
lengths_transposed = tf.expand_dims(tf.to_int32(self.seq_lens), 1)
lengths_tiled = tf.tile(lengths_transposed, [1, max_sequence_len])
# Make a matrix where each row contains [0, 1, ..., max_sequence_len]
r = tf.range(0, max_sequence_len, 1)
range_row = tf.expand_dims(r, 0)
range_tiled = tf.tile(range_row, [batch_size, 1])
# Use the logical operations to create a mask
indicator = tf.less(range_tiled, lengths_tiled)
sz = [batch_size, max_sequence_len]
self._mask = tf.select(indicator, tf.ones(sz), tf.zeros(sz))
def _DoPredictions(self, in_size, mats, class_weights=None):
| tensorflow.range | 6,363 |
import tensorflow as tf
# intermediate projection to embedding size (before projecting to vocabulary size)
# this is useful to reduce the number of parameters, and
# to use the output embeddings for output projection (tie_embeddings parameter)
output_ = dense(output_, decoder.embedding_size, use_bias=False, name='softmax0')
if decoder.tie_embeddings and (decoder.pred_embed_proj or decoder.pred_deep_layer):
bias = get_variable('softmax1/bias', shape=[decoder.vocab_size])
output_ = tf.matmul(output_, tf.transpose(embedding)) + bias
else:
output_ = dense(output_, decoder.vocab_size, use_bias=True, name='softmax1')
return output_
if decoder.use_dropout: # FIXME: why no pervasive dropout here?
initial_state = tf.nn.dropout(initial_state, keep_prob=decoder.initial_state_keep_prob)
| tensorflow.transpose | 6,364 |
import tensorflow as tf
iteration_op = tfe.define_output(model_owner.player_name, aggregated_model_grads, model_owner.update_model)
with tfe.Session(target=session_target) as sess:
sess.run(tf.global_variables_initializer(), tag='init')
for i in range(model_owner.ITERATIONS):
| tensorflow.global_variables_initializer | 6,365 |
import tensorflow as tf
def update(self, state, target, a_his, sess=None):
sess = sess or tf.get_default_session()
feed_dict = { self.state: state, self.target: target, self.a_his: a_his }
_, loss = sess.run([self.train_op, self.loss], feed_dict)
return loss
class ValueEstimator_Pendulum():
def __init__(self, learning_rate=0.1, par_idx=0,scope="value_estimator"):
w_init = tf.random_normal_initializer(0.,.1);
with tf.variable_scope(scope+"_"+str(par_idx)):
# state and target
self.state = tf.placeholder(tf.float32, [None,num_state], "state")
self.target = tf.placeholder(tf.float32, [None,1], name="target")
# layers
l_c = tf.layers.dense(self.state, 100, tf.nn.relu6, kernel_initializer=w_init, name='lc')
| tensorflow.random_normal_initializer | 6,366 |
from tensorflow.contrib.data import Iterator
temp_val_data['X'][i * 2 + 1, :, :, :] = self.val_data['X'][i, :, sh[2] // 2:, :]
temp_val_data['Y'][i * 2, :, :] = self.val_data['Y'][i, :, :sh[2] // 2]
temp_val_data['Y'][i * 2 + 1, :, :] = self.val_data['Y'][i, :, sh[2] // 2:]
self.val_data = temp_val_data
def init_tfdata(self, batch_size, main_dir, resize_shape, mode='train'):
self.data_session = tf.Session()
print("Creating the iterator for training data")
with tf.device('/cpu:0'):
segdl = SegDataLoader(main_dir, batch_size, (resize_shape[0], resize_shape[1]), resize_shape,
# * 2), resize_shape,
'data/cityscapes_tfdata/train.txt')
iterator = Iterator.from_structure(segdl.data_tr.output_types, segdl.data_tr.output_shapes)
next_batch = iterator.get_next()
self.init_op = iterator.make_initializer(segdl.data_tr)
self.data_session.run(self.init_op)
print("Loading Validation data in memoryfor faster training..")
self.val_data = {'X': np.load(self.args.data_dir + "X_val.npy"),
'Y': np.load(self.args.data_dir + "Y_val.npy")}
# self.crop()
# import cv2
# cv2.imshow('crop1', self.val_data['X'][0,:,:,:])
# cv2.imshow('crop2', self.val_data['X'][1,:,:,:])
| tensorflow.contrib.data.Iterator.from_structure | 6,367 |
import tensorflow as tf
def encode(self, x, encode_params):
"""See base class."""
del encode_params # Unused.
signs = tf.sign(x)
abs_vals = tf.abs(x)
ints = tf.floor(abs_vals)
floats = abs_vals - ints
return {
self.ENCODED_SIGNS_KEY: signs,
self.ENCODED_INTS_KEY: ints,
self.ENCODED_FLOATS_KEY: floats
| tensorflow.floor | 6,368 |
from tensorflow.python.ops import array_ops
"""_TargetColumn for regression."""
def __init__(self, loss_fn, label_name, weight_column_name, target_dimension):
super(_RegressionTargetColumn, self).__init__(
loss_fn=loss_fn,
num_label_columns=target_dimension,
label_name=label_name,
weight_column_name=weight_column_name)
def logits_to_predictions(self, logits, proba=False):
if self.num_label_columns == 1:
return array_ops.squeeze(logits, squeeze_dims=[1])
return logits
def get_eval_ops(self, features, logits, targets, metrics=None):
loss = self.loss(logits, targets, features)
result = {"loss": metrics_lib.streaming_mean(loss)}
if metrics:
predictions = self.logits_to_predictions(logits, proba=False)
result.update(_run_metrics(predictions, targets, metrics,
self.get_weight_tensor(features)))
return result
| tensorflow.python.ops.array_ops.squeeze | 6,369 |
import tensorflow as tf
"""
mu, var = self.build_prior_mean_var(test_points, num_latent, True)
jitter = tfhacks.eye(tf.shape(mu)[0], var.dtype) * 1e-06
L = tf.batch_cholesky(tf.transpose(var, (2, 0, 1)) + jitter)
| tensorflow.shape | 6,370 |
import tensorflow as tf
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_dcl, optimizer, global_step, tower_grads, total_loss_dict, num_gpu, graph)
if __name__ == '__main__':
| tensorflow.get_variable_scope | 6,371 |
import tensorflow as tf
# samples_world = grid.generate(
# (-5.0, -5.0, -5.0),
# (5.0, 5.0, 5.0),
# [self.resolution, self.resolution, self.resolution])
samples_world = tf.reshape(samples_world, [-1, 3])
ious = []
status = False
if status:
_, axs = plt.subplots(labeled_translations.shape[0], 5)
fig_obj_count = 0
for class_id in range(self.max_num_classes):
# Do the same for the ground truth and predictions
sdf_values = tf.zeros_like(samples_world)[:, 0:1]
for mtype, (classes, sdfs, poses) in enumerate([
(labeled_classes, labeled_sdfs, labeled_poses),
(predicted_classes, predicted_sdfs, predicted_poses)]):
for i in range(classes.shape[0]):
if class_id == classes[i]:
sdf = tf.expand_dims(sdfs[i], -1)
sdf = sdf * -1.0 # inside positive, outside zero
samples_object = centernet_utils.transform_pointcloud(
tf.reshape(samples_world, [1, 1, -1, 3]),
tf.reshape(poses[2][i], [1, 1, 3]),
tf.reshape(poses[0][i], [1, 1, 3, 3]),
tf.reshape(poses[1][i], [1, 1, 3]), inverse=True) * 2.0
| tensorflow.zeros_like | 6,372 |
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)
| tensorflow.layers.dense | 6,373 |
import tensorflow as tf
for var, perturbed_var in zip(all_vars, all_perturbed_vars):
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:
# Do not perturb, just assign.
| tensorflow.shape | 6,374 |
import tensorflow as tf
h0 = tf.nn.dropout(tf.reshape(z_, [-1, s_h3, s_w3, nf3]), keep_prob)
import IPython
IPython.embed()
h1 = lrelu(deconv2d(tf.concat([h0, skip_h3], 3),
[self.batch_size, s_h2, s_w2, nf2], name='d_h1', d_h=ns3, d_w=ns3))
h2 = lrelu(deconv2d(tf.concat([h1, skip_h2], 3),
[self.batch_size, s_h1, s_w1, nf1], name='d_h2', d_h=ns2, d_w=ns2))
h3 = lrelu(deconv2d(tf.concat([h2, skip_h1], 3),
[self.batch_size, s_h0, s_w0, nf0], name='d_h3', d_h=ns1, d_w=ns1))
print(h3.get_shape())
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:
| tensorflow.concat | 6,375 |
import tensorflow as tf
# source_length.
if self._problem_hparams:
modality = self._problem_hparams.target_modality
if modality.top_is_pointwise:
return tf.squeeze(logits, axis=[1, 2, 3])
# -1 due to the pad above.
current_output_position = common_layers.shape_list(ids)[1] - 1
logits = logits[:, current_output_position, :, :]
| tensorflow.squeeze | 6,376 |
import tensorflow as tf
def avg_pool(self, bottom, kernal_size = 2, stride = 2, name = "avg"):
return tf.nn.avg_pool(bottom, ksize=[1, kernal_size, kernal_size, 1], strides=[1, stride, stride, 1], padding='VALID', name=name)
def max_pool(self, bottom, kernal_size = 2, stride = 2, name = "max"):
return tf.nn.max_pool(bottom, ksize=[1, kernal_size, kernal_size, 1], strides=[1, stride, stride, 1], padding='SAME', name=name)
def conv_layer(self, bottom, kernal_size, in_channels, out_channels, stride, name):
with tf.variable_scope(name):
filt, conv_biases = self.get_conv_var(kernal_size, in_channels, out_channels, name)
conv = tf.nn.conv2d(bottom, filt, [1,stride,stride,1], padding='SAME')
bias = tf.nn.bias_add(conv, conv_biases)
tf.summary.histogram('weight', filt)
tf.summary.histogram('bias', conv_biases)
return bias
| tensorflow.variable_scope | 6,377 |
import tensorflow as tf
[0, 1]], dtype=tf.float32)
mask1 = tf.constant([[1, 1],
| tensorflow.constant | 6,378 |
import tensorflow as tf
# fixed folder
saved_model_dir = "tf_cnn_model/1/"
target_dir = "tflite_cnn_model"
def convert_tflite():
if not os.path.exists(target_dir):
os.makedirs(target_dir)
converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
#converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_LATENCY]
tflite_model = converter.convert()
with open(f"{target_dir}/tflite_model.tflite", "wb") as f:
f.write(tflite_model)
def validation():
| tensorflow.lite.TFLiteConverter.from_saved_model | 6,379 |
from tensorflow.contrib.tensorboard.plugins import projector
self.embedding_test_ph = tf.placeholder(tf.float32, embedding_shape, name='embedding')
self.embedding_test = tf.Variable(tf.random_normal(embedding_shape), name='test_embedding', trainable=False)
self.embedding_assign = self.embedding_test.assign(self.embedding_test_ph)
self.embedding_saver = tf.train.Saver(var_list=[self.embedding_test])
config = projector.ProjectorConfig()
embedding = config.embeddings.add()
embedding.tensor_name = self.embedding_test.name
embedding.sprite.image_path = './sprite.png'
embedding.sprite.single_image_dim.extend([80, 80])
| tensorflow.contrib.tensorboard.plugins.projector.ProjectorConfig | 6,380 |
import tensorflow as tf
raise ValueError('depth=%g is a not a valid setting!' % depth)
# input tensors
self.input_x = tf.placeholder(tf.int32, [None, sequence_max_length], name="input_x")
self.input_tags = tf.placeholder(tf.int32, [None, sequence_max_length], name="input_tags")
self.input_deps = tf.placeholder(tf.int32, [None, sequence_max_length], name="input_dependency")
self.input_head = tf.placeholder(tf.int32, [None, sequence_max_length], name="input_head")
self.input_y = tf.placeholder(tf.float32, [None, num_classes], name="input_y")
self.is_training = tf.placeholder(tf.bool)
initializer = tf.contrib.layers.variance_scaling_initializer()
# Embedding Lookup 16
with tf.device('/cpu:0'), tf.name_scope("embedding"):
if use_he_uniform:
self.embedding_W = tf.get_variable(name='lookup_W', shape=[num_quantized_chars, embedding_size],
initializer=tf.contrib.layers.variance_scaling_initializer())
else:
self.embedding_W = tf.Variable(tf.random_uniform([num_quantized_chars, embedding_size], -1.0, 1.0),name="embedding_W")
self.embedded_characters = tf.nn.embedding_lookup(self.embedding_W, self.input_x)
embedded_text_expand = tf.expand_dims(self.embedded_characters, -1)
with tf.device('/cpu:0'), tf.name_scope("embedding_tags"):
W_tags = tf.get_variable("embed_W_tags", [tags_vocab_size, embedding_size], initializer=initializer)
embedded_tags = tf.nn.embedding_lookup(W_tags, self.input_tags)
embedded_tags_expanded = tf.expand_dims(embedded_tags, -1)
| tensorflow.device | 6,381 |
import tensorflow as tf
network = resnet_model.imagenet_resnet_v2(
resnet_size=18, num_classes=class_num, mode='se', data_format=None)
inputs= network(inputs=inputs, is_training=training)
feat = tf.nn.l2_normalize(inputs, 1, 1e-10, name='feat')
inputs = tf.layers.dense(inputs=inputs, units=class_num)
# inputs = tf.layers.dense(inputs=feat, units=class_num)
inputs = tf.identity(inputs, 'final_dense')
return inputs, feat
# image_size = 32, img_channels = 3, class_num = 10 in cifar10
x = tf.placeholder(tf.float32, shape=[None, image_size, image_size, img_channels])
label = tf.placeholder(tf.float32, shape=[None,])
one_hot_labels = tf.one_hot(indices=tf.cast(label, tf.int32), depth=class_num)
training_flag = tf.placeholder(tf.bool)
learning_rate = tf.placeholder(tf.float32, name='learning_rate')
logits, feat = resnet_model_fn(x, training=training_flag)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_labels, logits=logits))
Focal_loss = tf.reduce_mean(focal_loss(one_hot_labels, logits, alpha=0.5))
l2_loss = weight_decay * tf.add_n([tf.nn.l2_loss(v) for v in tf.trainable_variables()])
Center_loss, Centers = center_loss(feat, tf.cast(label, dtype=tf.int32), 0.95, class_num)
| tensorflow.placeholder | 6,382 |
import tensorflow as tf
return out
def intprod(x):
return int(np.prod(x))
def numel(x):
return intprod(var_shape(x))
def flatgrad(loss, var_list, clip_norm=None):
grads = tf.gradients(loss, var_list)
if clip_norm is not None:
grads = [tf.clip_by_norm(grad, clip_norm=clip_norm) for grad in grads]
return tf.concat(axis=0, values=[
tf.reshape(grad if grad is not None else tf.zeros_like(v), [numel(v)])
for (v, grad) in zip(var_list, grads)
])
class SetFromFlat(object):
def __init__(self, var_list, dtype=tf.float32):
assigns = []
shapes = list(map(var_shape, var_list))
total_size = np.sum([intprod(shape) for shape in shapes])
self.theta = theta = tf.placeholder(dtype, [total_size])
| tensorflow.clip_by_norm | 6,383 |
import tensorflow as tf
def evaluate_legendre_polynomial(degree_l: TensorLike,
order_m: TensorLike,
x: TensorLike) -> TensorLike:
degree_l = tf.convert_to_tensor(value=degree_l)
order_m = tf.convert_to_tensor(value=order_m)
x = tf.convert_to_tensor(value=x)
| tensorflow.convert_to_tensor | 6,384 |
import tensorflow as tf
"""
SHAPE = 256
BATCH = 1
TEST_BATCH = 32
NF = 64 # channel size
def INReLU(x, name=None):
x = InstanceNorm('inorm', x)
return tf.nn.relu(x, name=name)
def INLReLU(x, name=None):
x = InstanceNorm('inorm', x)
return LeakyReLU(x, name=name)
class Model(GANModelDesc):
def _get_inputs(self):
| tensorflow.nn.relu | 6,385 |
import tensorflow as tf
self.W_out_train = params.get('W_out_train', True)
self.b_rec_train = params.get('b_rec_train', True)
self.b_out_train = params.get('b_out_train', True)
self.init_state_train = params.get('init_state_train', True)
# Tensorflow initializations
self.x = tf.placeholder("float", [N_batch, N_steps, N_in])
self.y = tf.placeholder("float", [N_batch, N_steps, N_out])
self.output_mask = tf.placeholder("float", [N_batch, N_steps, N_out])
# trainable variables
with tf.variable_scope("model"):
# ------------------------------------------------
# Random initialization Load weights from weights path
# for Initial state, Weight matrices, and bias weights
# ------------------------------------------------
if self.load_weights_path is None:
# random initializations
init_state_initializer = tf.random_normal_initializer(mean=0.1, stddev=0.01)
W_in_initializer = tf.constant_initializer(
0.1 * np.random.uniform(-1, 1, size=(self.N_rec, self.N_in)))
| tensorflow.variable_scope | 6,386 |
import tensorflow as tf
import layers as L
import vat
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('device', '/gpu:0', "device")
tf.app.flags.DEFINE_string('dataset', 'cifar10', "{cifar10, svhn}")
tf.app.flags.DEFINE_string('log_dir', "", "log_dir")
tf.app.flags.DEFINE_integer('seed', 1, "initial random seed")
tf.app.flags.DEFINE_bool('validation', False, "")
tf.app.flags.DEFINE_integer('batch_size', 32, "the number of examples in a batch")
| tensorflow.app.flags.DEFINE_string | 6,387 |
import tensorflow as tf
with tf.variable_scope("evaluation"):
accuracy_1 = tf.reduce_mean(tf.cast(tf.equal(
tf.argmax(output_1, axis=-1),
tf.argmax(y_1, axis=-1)), tf.float32), name="accuracy_1")
accuracy_2 = tf.reduce_mean(tf.cast(tf.equal(
tf.argmax(output_2, axis=-1),
tf.argmax(y_2, axis=-1)), tf.float32), name="accuracy_2")
accuracy = tf.divide(accuracy_1 + accuracy_2, 2.0, name="accuracy")
with tf.variable_scope("train"):
global_step = tf.get_variable("global_step", shape=(), dtype=tf.int32, trainable=False)
train_op = tf.train.AdamOptimizer(learning_rate=lr).minimize(loss_total, global_step=global_step)
with tf.variable_scope("summary"):
summary_loss_total = tf.summary.scalar("loss_total", loss_total)
summary_accuracy_test = tf.summary.scalar("accuracy_test", accuracy)
summary_accuracy_train = tf.summary.scalar("accuracy_train", accuracy)
# standardization
train_X_reshaped = train_X.reshape([train_X.shape[0], -1])
train_X_means = np.mean(train_X_reshaped, axis=0, keepdims=True)
train_X_stds = np.std(train_X_reshaped, axis=0, keepdims=True)
def standardization(x):
x_reshaped = x.reshape([x.shape[0], -1])
result = (x_reshaped - train_X_means) / (train_X_stds + 1e-9)
return result.reshape(x.shape)
| tensorflow.summary.scalar | 6,388 |
import tensorflow as tf
reader=tf.TFRecordReader()
_,serialized_example=reader.read(filename_queue)
features=tf.parse_single_example(serialized_example,
features={
'label':tf.FixedLenFeature([], tf.int64),
'img_raw' : tf.FixedLenFeature([], tf.string),
})
image=tf.decode_raw(features['img_raw'],tf.uint8)
label=tf.cast(features['label'],tf.int32)
image=tf.reshape(image,[4096,1])
return image,label
def get_batch(image,label,batch_size,crop_size):
#print(image.shape)
#print(label.shape)
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])
class trainwork(object):
def __init__(self):
with tf.variable_scope('scop'):
| tensorflow.train.shuffle_batch | 6,389 |
import tensorflow as tf
fc3_1 = contrib.layers.fully_connected(dropout2_1, 32, scope="fc3_1")
fc3_2 = contrib.layers.fully_connected(dropout2_2, 32, scope="fc3_2")
if cross_stitch_enabled:
with tf.variable_scope("cross_stitch_3"):
stitch3_1, stitch3_2 = apply_cross_stitch(fc3_1, fc3_2)
else:
stitch3_1, stitch3_2 = fc3_1, fc3_2
| tensorflow.variable_scope | 6,390 |
import tensorflow as tf
self.report_benchmark(
name="eager_train_%s%s_%d" %
("gpu" if tf.test.is_gpu_available() else "cpu",
"_defun" if defun else "", sample_size),
iters=hparams.n_iters,
extras={"examples_per_sec": examples_per_sec},
wall_time=wall_time)
del dynamics
if __name__ == "__main__":
tf.enable_eager_execution()
tf.test.main()
| tensorflow.test.main | 6,391 |
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)
if task_name != "sts-b":
probabilities = tf.nn.softmax(logits, axis=-1)
predictions = tf.argmax(probabilities, axis=-1, output_type=tf.int32)
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)
else:
probabilities = logits
logits = tf.squeeze(logits, [-1])
predictions = logits
per_example_loss = tf.square(logits - labels)
loss = tf.reduce_mean(per_example_loss)
return (loss, per_example_loss, probabilities, logits, predictions)
def model_fn_builder(config, num_labels, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps, use_tpu,
| tensorflow.one_hot | 6,392 |
import tensorflow as tf
# Step-wise contrastive loss
horizon_pred, horizon_tgt = horizon_sumV2(pred, tgt, horizon)
# pred1, pred2 = tf.split(horizon_pred, 2, axis=0)
# tgt1, tgt2 = tf.split(horizon_tgt, 2, axis=0)
even = [2 * i for i in range(25)]
odd = [2 * i + 1 for i in range(25)]
pred1 = tf.gather(horizon_pred, even)
pred2 = tf.gather(horizon_pred, odd)
tgt1 = tf.gather(horizon_tgt, even)
tgt2 = tf.gather(horizon_tgt, odd)
geq = tf.cast((tgt1 - tgt2) > 0, tf.bool)
tgt_larg = tf.where(geq, tgt1, tgt2)
tgt_small = tf.where(geq, tgt2, tgt1)
pred_larg = tf.where(geq, pred1, pred2)
pred_small = tf.where(geq, pred2, pred1)
loss = tf.maximum(0.0, ((tgt_larg - tgt_small) - (pred_larg - pred_small)))
loss = tf.reduce_mean(loss)
return loss
def apply_optimizers(objectives, trainer, config):
# Make sure all losses are computed and apply loss scales.
processed = []
values = [ob.value for ob in objectives]
| tensorflow.where | 6,393 |
import tensorflow as tf
mus, log_sigmas = params[:,:,:,0::2], params[:,:,:,1::2]
x2, ldj = log_gaussianize(z2, mus, log_sigmas, inverse=tf.constant(True))
x2 = tf.where(z2 > self.epsilon, x2, z2)
ldj = tf.where(z2 > self.epsilon, ldj, tf.zeros_like(ldj))
return x2, tf.math.reduce_sum(ldj, axis=[1,2,3])
def half_gaussianize(x, log_sigmas, inverse=tf.constant(False)):
if inverse:
z = tf.math.exp(log_sigmas)*x
ldj = tf.math.reduce_sum(log_sigmas, axis=[1,2,3])
else:
z = x*tf.math.exp(-log_sigmas)
ldj = -tf.math.reduce_sum(log_sigmas, axis=[1,2,3])
return z, ldj
class HalfGaussianize(Parameterize):
| tensorflow.math.exp | 6,394 |
import tensorflow as tf
expected_labels_0_n = tf.constant([[-1, 2, 3],
[0, 4, 1]], dtype=tf.int32)
self.assertAllEqual(labels_0_n.numpy(), expected_labels_0_n.numpy())
def test_map_labels_to_0_to_n2(self):
labels = tf.constant([[-1, 1, 2],
[1, 1, 2]], dtype=tf.int32)
labels_0_n = isu.map_labels_to_0_to_n(labels)
expected_labels_0_n = tf.constant([[-1, 0, 1],
[0, 0, 1]], dtype=tf.int32)
| tensorflow.constant | 6,395 |
import tensorflow as tf
self.c_grads, _ = tf.clip_by_global_norm(self.c_grads, 20.0)
opt = tf.train.AdamOptimizer(self.LR)
self.update_a_op = opt.apply_gradients(zip(self.a_grads, self.pi_params))
self.update_c_op = opt.apply_gradients(zip(self.c_grads, self.vf_params))
self.sess.run(tf.global_variables_initializer())
# Tensorboard
if summary_dir is not None:
self.writer = tf.summary.FileWriter(summary_dir)
tf.summary.scalar('Loss/Policy', loss_pg)
tf.summary.scalar('Loss/Value', loss_vf)
tf.summary.scalar('Loss/Entropy', - 0.01 * tf.reduce_mean(pi.entropy()))
tf.summary.scalar('Var/Policy Mode', tf.reduce_mean(pi.mode()))
tf.summary.scalar('Var/Policy Sigma', tf.reduce_mean(pi.stddev()))
tf.summary.scalar('Var/Value', tf.reduce_mean(self.vf))
self.summarise = tf.summary.merge(tf.get_collection(tf.GraphKeys.SUMMARIES))
| tensorflow.summary.FileWriter | 6,396 |
from tensorflow.python.ops import math_ops
values = math_ops.to_float(values)
if weights is not None:
weights = math_ops.to_float(weights)
values = math_ops.mul(values, weights)
value_tensor = array_ops.identity(count)
update_op = state_ops.assign_add(count, math_ops.reduce_sum(values))
if metrics_collections:
ops.add_to_collections(metrics_collections, value_tensor)
if updates_collections:
ops.add_to_collections(updates_collections, update_op)
| tensorflow.python.ops.math_ops.reduce_sum | 6,397 |
import tensorflow as tf
h = tf.zeros([config.num_layers, self.batch_size, config.hidden_size],
tf.float32)
self._initial_state = (tf.contrib.rnn.LSTMStateTuple(h=h, c=c),)
outputs, h, c = self._cell(inputs, h, c, self._rnn_params, is_training)
outputs = tf.transpose(outputs, [1, 0, 2])
outputs = tf.reshape(outputs, [-1, config.hidden_size])
return outputs, (tf.contrib.rnn.LSTMStateTuple(h=h, c=c),)
def _get_lstm_cell(self, config, is_training):
if config.rnn_mode == BASIC:
| tensorflow.reshape | 6,398 |
import tensorflow as tf
make_tensors_fn=lambda:
{'x': tf.compat.v1.placeholder(tf.string, (None,))},
| tensorflow.compat.v1.placeholder | 6,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.