seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
import tensorflow as tf
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)
with tf.device('/cpu:0'), tf.name_scope("embedding_deps"):
W_deps = tf.get_variable("embed_W_deps", [deps_vocab_size, embedding_size], initializer=initializer)
embedded_deps = tf.nn.embedding_lookup(W_deps, self.input_deps)
embedded_deps_expanded = tf.expand_dims(embedded_deps, -1)
with tf.device('/cpu:0'), tf.name_scope("embedding_head"):
W_head = tf.get_variable("embed_W_head", [num_quantized_chars, embedding_size], initializer=initializer)
embedded_head = tf.nn.embedding_lookup(W_head, self.input_head)
embedded_head_expanded = tf.expand_dims(embedded_head, -1)
cnn_inputs = tf.concat(
[embedded_text_expand, embedded_tags_expanded, embedded_deps_expanded, embedded_head_expanded], -1)
print("-" * 20)
print("Embedded Lookup:", cnn_inputs.get_shape())
|
tensorflow.expand_dims
| 8,600 |
from tensorflow.python.ops import array_ops
values = array_ops.stack(tensors)
with ops.device(device):
return array_ops.unstack(values)
else:
with ops.device(tensors[0].device):
sizes = array_ops.stack(
[array_ops.shape(tensor)[0] for tensor in tensors])
values = array_ops.concat(tensors, axis=0)
with ops.device(device):
sizes = array_ops.unstack(sizes)
return list(array_ops.split(values, sizes, axis=0))
def _scheduled_stamp_resource_op_runner(batch, stamp):
"""Runs a batch operation on a stamped resource."""
if not batch:
return
arg_keys = set(batch[0].args.keys())
grouped_args = collections.OrderedDict()
resource_handles = []
|
tensorflow.python.ops.array_ops.split
| 8,601 |
import tensorflow as tf
"""
agent_qs_reshaped = tf.reshape(agent_qs, [-1, 1, n_agents])
# n_h_mixer * n_agents because result will be reshaped into matrix
hyper_w_1 = get_variable('hyper_w_1', [state_dim, n_h_mixer*n_agents])
hyper_w_final = get_variable('hyper_w_final', [state_dim, n_h_mixer])
hyper_b_1 = tf.get_variable('hyper_b_1', [state_dim, n_h_mixer])
hyper_b_final_l1 = tf.layers.dense(inputs=state, units=n_h_mixer, activation=tf.nn.relu,
use_bias=False, name='hyper_b_final_l1')
hyper_b_final = tf.layers.dense(inputs=hyper_b_final_l1, units=1, activation=None,
use_bias=False, name='hyper_b_final')
# First layer
w1 = tf.abs(tf.matmul(state, hyper_w_1))
b1 = tf.matmul(state, hyper_b_1)
w1_reshaped = tf.reshape(w1, [-1, n_agents, n_h_mixer]) # reshape into batch of matrices
|
tensorflow.layers.dense
| 8,602 |
import tensorflow as tf
parameters = dict(encoders=encoders[:1], decoder=decoder, encoder_inputs=encoder_inputs[:1],
other_inputs=other_inputs, training=training)
attention_states, encoder_state, encoder_input_length[:1] = multi_encoder(
encoder_input_length=encoder_input_length[:1], **parameters)
if chaining_stop_gradient:
attns = tf.stop_gradient(attns)
states = tf.stop_gradient(states)
decoder_outputs = tf.stop_gradient(decoder_outputs)
if chaining_strategy == 'concat_attns':
attention_states[0] = tf.concat([attention_states[0], attns], axis=2)
elif chaining_strategy == 'concat_states':
attention_states[0] = tf.concat([attention_states[0], states], axis=2)
elif chaining_strategy == 'sum_attns':
attention_states[0] += attns
elif chaining_strategy in ('map_attns', 'map_states', 'map_outputs'):
if chaining_strategy == 'map_attns':
|
tensorflow.stop_gradient
| 8,603 |
import tensorflow as tf
src = batch_of_data["feature"]
if self._trg_lang_tag_position in ["src", "source"]:
src = tf.concat([tf.expand_dims(batch_of_data["trg_lang"], axis=1), src], axis=1)
if self._with_src_lang_tag:
src = tf.concat([tf.expand_dims(batch_of_data["src_lang"], axis=1), src], axis=1)
input_dict = {"src": src,
"src_length": deduce_text_length(src, self._multilingual_dp.meta["pad_id"],
|
tensorflow.expand_dims
| 8,604 |
import tensorflow as tf
nf3 = 8
ns0 = 1
ns1 = 2
ns2 = 1
ns3 = 2
# with tf.variable_scope("conv_context") as scope:
def encode(img):
img_h0 = lrelu(conv2d(img, nf0, d_h=ns0, d_w=ns0, name='h0_conv'))
img_h1 = lrelu(conv2d(img_h0, nf1, d_h=ns1, d_w=ns1, name='h1_conv'))
img_h2 = lrelu(conv2d(img_h1, nf2, d_h=ns2, d_w=ns2, name='h2_conv'))
img_h3 = lrelu(conv2d(img_h2, nf3, d_h=ns3, d_w=ns3, name='h3_conv'))
print(img_h3.get_shape())
img_h4 = lrelu(linear(tf.nn.dropout(tf.reshape(img_h3, [self.batch_size, -1]), keep_prob), featsize, 'h4_lin'))
img_z = lrelu(linear(tf.nn.dropout(img_h4, keep_prob), featsize, 'hz_lin'))
return img_h0, img_h1, img_h2, img_h3, img_h4, img_z
with tf.variable_scope("conv") as scope:
srcimg_h0, srcimg_h1, srcimg_h2, srcimg_h3, srcimg_h4, srcimg_z = encode(srcimg)
scope.reuse_variables()
tgtimg_h0, tgtimg_h1, tgtimg_h2, tgtimg_h3, tgtimg_h4, tgtimg_z = encode(tgtimg)
tgtctx_h0, tgtctx_h1, tgtctx_h2, tgtctx_h3, tgtctx_h4, tgtctx_z = encode(tgtctx)
with tf.variable_scope("translate") as scope:
trans_h0 = lrelu(linear(tf.nn.dropout(tf.concat([srcimg_z, tgtctx_z], 1), keep_prob), featsize, 'trans_h0'))
trans_z = linear(tf.nn.dropout(trans_h0, keep_prob), featsize, 'trans_z')
|
tensorflow.reshape
| 8,605 |
import tensorflow as tf
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)
max_src_len = tf.shape(reconstructed_weights)[1]
batch_size = tf.shape(reconstructed_weights)[0]
attn_loss = tf.matmul(reconstructed_weights, attention_weights) - tf.eye(max_src_len)
src_mask = tf.sequence_mask(encoder_input_length[0], maxlen=max_src_len, dtype=tf.float32)
src_mask = tf.einsum('ij,ik->ijk', src_mask, src_mask)
attn_loss *= tf.to_float(src_mask) # don't take padding words into account
attn_loss = tf.norm(attn_loss) / tf.to_float(batch_size)
xent_loss += reconstruction_attn_weight * attn_loss
attention_weights = [attention_weights, reconstructed_weights]
losses = [xent_loss, None, None]
return losses, [outputs], encoder_state, attention_states, attention_weights, samples, beam_fun, initial_data
def chained_encoder_decoder(encoders, decoders, encoder_inputs, targets, feed_previous,
chaining_strategy=None, align_encoder_id=0, chaining_non_linearity=False,
chaining_loss_ratio=1.0, chaining_stop_gradient=False, training=True, **kwargs):
decoder = decoders[0]
targets = targets[0] # single decoder
|
tensorflow.norm
| 8,606 |
import tensorflow as tf
#
# If the input is a 2D tensor of shape [batch_size, seq_length], we
# reshape to [batch_size, seq_length, 1].
if input_ids.shape.ndims == 2:
input_ids = tf.expand_dims(input_ids, axis=[-1])
embedding_table = tf.get_variable(
name=word_embedding_name,
shape=[vocab_size, embedding_size],
initializer=create_initializer(initializer_range))
if use_one_hot_embeddings:
flat_input_ids = tf.reshape(input_ids, [-1])
one_hot_input_ids = tf.one_hot(flat_input_ids, depth=vocab_size)
output = tf.matmul(one_hot_input_ids, embedding_table)
else:
output = tf.nn.embedding_lookup(embedding_table, input_ids)
input_shape = get_shape_list(input_ids)
output = tf.reshape(output,
input_shape[0:-1] + [input_shape[-1] * embedding_size])
return (output, embedding_table)
|
tensorflow.reshape
| 8,607 |
import tensorflow as tf
else:
op = tf.constant(1.0)
save_op.append(op)
sok_results = list()
with tf.Session() as sess:
sess.run(sok_init_op)
sess.run([init_op, iterator_init])
sess.run(restore_op)
sess.graph.finalize()
|
tensorflow.Session
| 8,608 |
import tensorflow as tf
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1: # tensorflow version < 0.12
writer = tf.train.SummaryWriter('logs/', sess.graph)
|
tensorflow.train.SummaryWriter
| 8,609 |
import tensorflow as tf
# randrom horizon
def contra_traj_lossV3(pred, tgt, horizon=12):
# 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
|
tensorflow.gather
| 8,610 |
import tensorflow.contrib.slim as slim
with tf.variable_scope(tf.get_variable_scope()):
for i in range(num_gpu):
with tf.device('/gpu:%d' % i):
with tf.name_scope('tower_%d' % i):
with slim.arg_scope(
[slim.model_variable, slim.variable],
device='/device:CPU:0'):
with slim.arg_scope([slim.conv2d, slim.conv2d_in_plane,
slim.conv2d_transpose, slim.separable_conv2d,
|
tensorflow.contrib.slim.arg_scope
| 8,611 |
import tensorflow as tf
# 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:
|
tensorflow.contrib.layers.variance_scaling_initializer
| 8,612 |
import tensorflow as tf
# Each line of the dataset is comma-separated and formatted as
# color_name, r, g, b
# so `items` is a list [color_name, r, g, b].
items = tf.string_split([line], ",").values
rgb = tf.string_to_number(items[1:], out_type=tf.float32) / 255.
# Represent the color name as a one-hot encoded character sequence.
|
tensorflow.string_split
| 8,613 |
import tensorflow as tf
else:
value = initial_value
if self.trainable:
var = tf.get_variable(name = var_name, initializer=value, trainable=True)
# tf.Variable(value, name=var_name)
else:
var = tf.constant(value, dtype=tf.float32, name=var_name)
|
tensorflow.get_variable
| 8,614 |
import tensorflow as tf
elif isinstance(boundaries, int) or (isinstance(boundaries, tf.Tensor) and
boundaries.get_shape().ndims == 0):
min_value, max_value = _min_and_max(x, True)
boundaries = tf.linspace(
tf.cast(min_value, tf.float32), tf.cast(max_value, tf.float32),
tf.cast(boundaries, tf.int64))
# Shift the boundaries slightly to account for floating point errors,
# and due to the fact that the rightmost boundary is essentially ignored.
boundaries = tf.expand_dims(tf.cast(boundaries, tf.float32), 0) - 0.0001
bucket_indices = tf_utils.assign_buckets(
tf.cast(x, tf.float32), remove_leftmost_boundary(boundaries))
bucket_vocab, counts = count_per_key(tf.strings.as_string(bucket_indices))
counts = tf_utils.reorder_histogram(bucket_vocab, counts,
tf.size(boundaries) - 1)
return counts, boundaries
|
tensorflow.cast
| 8,615 |
import tensorflow as tf
img *= 255.0/img.max()
file_name = 'heatmap_{}_{}.jpg'.format(save_image_with_heatmap.counter, ind)
imsave(os.path.join(config.DEBUG_DIR, file_name), img.astype(np.uint8))
return save_image_with_heatmap.counter
def get_keypoint(image, targets, predictions, heatmap_size, height, width, category, clip_at_zero=True, data_format='channels_last', name=None):
predictions = tf.reshape(predictions, [1, -1, heatmap_size*heatmap_size])
pred_max = tf.reduce_max(predictions, axis=-1)
pred_indices = tf.argmax(predictions, axis=-1)
pred_x, pred_y = tf.cast(tf.floormod(pred_indices, heatmap_size), tf.float32), tf.cast(tf.floordiv(pred_indices, heatmap_size), tf.float32)
width, height = tf.cast(width, tf.float32), tf.cast(height, tf.float32)
pred_x, pred_y = pred_x * width / tf.cast(heatmap_size, tf.float32), pred_y * height / tf.cast(heatmap_size, tf.float32)
if clip_at_zero:
pred_x, pred_y = pred_x * tf.cast(pred_max>0, tf.float32), pred_y * tf.cast(pred_max>0, tf.float32)
pred_x = pred_x * tf.cast(pred_max>0, tf.float32) + tf.cast(pred_max<=0, tf.float32) * (width / 2.)
pred_y = pred_y * tf.cast(pred_max>0, tf.float32) + tf.cast(pred_max<=0, tf.float32) * (height / 2.)
if config.PRED_DEBUG:
pred_indices_ = tf.squeeze(pred_indices)
image_ = tf.squeeze(image) * 255.
pred_heatmap = tf.one_hot(pred_indices_, heatmap_size*heatmap_size, on_value=1., off_value=0., axis=-1, dtype=tf.float32)
|
tensorflow.cast
| 8,616 |
import tensorflow as tf
# Only make the ops if we know that `is_training=True`, or the value of
# `is_training` is unknown.
is_training_const = utils.constant_value(is_training)
if is_training_const is None or is_training_const:
update_mean_op, update_variance_op = utils.smart_cond(
is_training,
build_update_ops,
build_no_ops,
)
# Every new connection creates a new op which adds its contribution
# to the running average when ran.
tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_mean_op)
tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_variance_op)
def _build_update_ops_second_moment(self, mean, second_moment, is_training):
"""Builds the moving average update ops when using the moving second moment.
Args:
mean: The mean value to update with.
second_moment: The second_moment value to update with.
is_training: Boolean Tensor to indicate if we're currently in
training mode.
"""
def build_update_ops():
"""Builds the exponential moving average update ops."""
|
tensorflow.add_to_collection
| 8,617 |
import tensorflow as tf
tf.Summary.Value(tag="Tacotron_eval_model/eval_stats/eval_loss", simple_value=loss),
]
if linear_loss is not None:
values.append(tf.Summary.Value(tag="Tacotron_eval_model/eval_stats/eval_linear_loss",
simple_value=linear_loss))
test_summary = tf.Summary(value=values)
|
tensorflow.Summary.Value
| 8,618 |
import tensorflow as tf
for layer in range(self.config["contextualization_layers"]):
with tf.variable_scope("layer_{}".format(layer)):
with tf.variable_scope("fw_cell"):
cell_fw = util.CustomLSTMCell(self.config["contextualization_size"], num_sentences, self.lstm_dropout)
with tf.variable_scope("bw_cell"):
cell_bw = util.CustomLSTMCell(self.config["contextualization_size"], num_sentences, self.lstm_dropout)
state_fw = tf.contrib.rnn.LSTMStateTuple(tf.tile(cell_fw.initial_state.c, [num_sentences, 1]), tf.tile(cell_fw.initial_state.h, [num_sentences, 1]))
state_bw = tf.contrib.rnn.LSTMStateTuple(tf.tile(cell_bw.initial_state.c, [num_sentences, 1]), tf.tile(cell_bw.initial_state.h, [num_sentences, 1]))
(fw_outputs, bw_outputs), _ = tf.nn.bidirectional_dynamic_rnn(
cell_fw=cell_fw,
cell_bw=cell_bw,
inputs=current_inputs,
|
tensorflow.tile
| 8,619 |
import tensorflow as tf
def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
"""The `model_fn` for TPUEstimator."""
tf.logging.info("*** Features ***")
for name in sorted(features.keys()):
tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
input_ids = features["input_ids"]
input_mask = features["input_mask"]
segment_ids = features["segment_ids"]
|
tensorflow.logging.info
| 8,620 |
import tensorflow as tf
clone_loss = _gather_clone_loss(clone, len(clones),
regularization_losses)
if clone_loss is not None:
clones_losses.append(clone_loss)
# Only use regularization_losses for the first clone
regularization_losses = None
if clones_losses:
total_loss = tf.add_n(clones_losses, name='total_loss')
# Add the summaries from the first clone. These contain the summaries
# created by model_fn and either optimize_clones() or _gather_clone_loss().
summaries |= set(tf.get_collection(tf.GraphKeys.SUMMARIES,
first_clone.scope))
if total_loss is not None:
# Add total_loss to summary.
summaries.add(tf.summary.scalar('total_loss', total_loss))
if summaries:
# Merge all summaries together.
summary_op = tf.merge_summary(list(summaries), name='summary_op')
else:
|
tensorflow.get_collection
| 8,621 |
import tensorflow as tf
def batch_norm(x, train, name, decay=0.99, epsilon=1e-5):
shape = x.get_shape().as_list()
with tf.variable_scope(name):
beta = tf.get_variable('beta', [shape[-1]], initializer=tf.constant_initializer(0.))
gamma = tf.get_variable('gamma', [shape[-1]], initializer=tf.random_normal_initializer(1., 0.02))
pop_mean = tf.get_variable('pop_mean', [shape[-1]], initializer=tf.constant_initializer(0.), trainable=False)
pop_var = tf.get_variable('pop_var', [shape[-1]], initializer=tf.constant_initializer(1.), trainable=False)
if pop_mean not in tf.moving_average_variables():
tf.add_to_collection(tf.GraphKeys.MOVING_AVERAGE_VARIABLES, pop_mean)
tf.add_to_collection(tf.GraphKeys.MOVING_AVERAGE_VARIABLES, pop_var)
def func1():
# execute at training time
batch_mean, batch_var = tf.nn.moments(x, range(len(shape) - 1))
update_mean = tf.assign_sub(pop_mean, (1 - decay)*(pop_mean - batch_mean))
update_var = tf.assign_sub(pop_var, (1 - decay)*(pop_var - batch_var))
with tf.control_dependencies([update_mean, update_var]):
return tf.nn.batch_normalization(x, batch_mean, batch_var, beta, gamma, epsilon)
|
tensorflow.add_to_collection
| 8,622 |
import tensorflow as tf
for aux_logits in aux_logits_list:
log_probs = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=aux_logits, labels=classes)
|
tensorflow.nn.sparse_softmax_cross_entropy_with_logits
| 8,623 |
import tensorflow as tf
h1 = tf.transpose(h1, perm=[1, 0, 2])
h1 = tf.reshape(h1, shape=h1_shape)
|
tensorflow.reshape
| 8,624 |
from tensorflow.python.framework import ops
distribution(s). `rate` must be positive.
validate_args: Python `Boolean`, default `False`. When `True` distribution
parameters are checked for validity despite possibly degrading runtime
performance. When `False` invalid inputs may silently render incorrect
outputs.
allow_nan_stats: Python `Boolean`, default `True`. When `True`, statistics
(e.g., mean, mode, variance) use the value "`NaN`" to indicate the
result is undefined. When `False`, an exception is raised if one or
more of the statistic's batch members are undefined.
name: `String` name prefixed to Ops created by this class.
"""
parameters = locals()
with ops.name_scope(name, values=[rate]) as ns:
with ops.control_dependencies([check_ops.assert_positive(rate)] if
validate_args else []):
self._rate = array_ops.identity(rate, name="rate")
super(Poisson, self).__init__(
dtype=self._rate.dtype,
is_continuous=False,
reparameterization_type=distribution.NOT_REPARAMETERIZED,
validate_args=validate_args,
allow_nan_stats=allow_nan_stats,
parameters=parameters,
graph_parents=[self._rate],
|
tensorflow.python.framework.ops.name_scope
| 8,625 |
import tensorflow as tf
alpha_fixed_block_id = [
sess.run(
networks._generator_alpha(2, tf.constant(progress, tf.float32)))
for progress in [0, 0.2, 1, 1.2, 2, 2.2, 3]
|
tensorflow.constant
| 8,626 |
import tensorflow as tf
return normed
def conv(input, scope, filter_dims, stride_dims, padding='SAME',
non_linear_fn=tf.nn.relu, dilation=[1, 1, 1, 1], bias=True):
input_dims = input.get_shape().as_list()
assert (len(input_dims) == 4) # batch_size, height, width, num_channels_in
assert (len(filter_dims) == 3) # height, width and num_channels out
assert (len(stride_dims) == 2) # stride height and width
num_channels_in = input_dims[-1]
filter_h, filter_w, num_channels_out = filter_dims
stride_h, stride_w = stride_dims
with tf.variable_scope(scope):
conv_weight = tf.Variable(
tf.truncated_normal([filter_h, filter_w, num_channels_in, num_channels_out], stddev=0.1, dtype=tf.float32))
conv_bias = tf.Variable(tf.zeros([num_channels_out], dtype=tf.float32))
map = tf.nn.conv2d(input, conv_weight, strides=[1, stride_h, stride_w, 1], padding=padding, dilations=dilation)
if bias is True:
map = tf.nn.bias_add(map, conv_bias)
if non_linear_fn is not None:
activation = non_linear_fn(map)
else:
activation = map
# print(activation.get_shape().as_list())
|
tensorflow.variable_scope
| 8,627 |
import tensorflow as tf
if encoder.attn_window_size > 0:
sigma = encoder.attn_window_size / 2
numerator = -tf.pow((idx - pos), tf.convert_to_tensor(2, dtype=tf.float32))
div = tf.truediv(numerator, 2 * sigma ** 2)
weights *= tf.exp(div) # result of the truncated normal distribution
# normalize to keep a probability distribution
|
tensorflow.truediv
| 8,628 |
import tensorflow as tf
scaffold_fn = tpu_scaffold
else:
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
|
tensorflow.train.init_from_checkpoint
| 8,629 |
import tensorflow as tf
# Set up functionality to re-compute `param_noise_scale`. This perturbs yet another copy
# of the network and measures the effect of that perturbation in action space. If the perturbation
# is too big, reduce scale of perturbation, otherwise increase.
with tf.variable_scope("adaptive_model", reuse=False):
adaptive_policy = q_func(sess, ob_space, ac_space, 1, 1, None, obs_phs=obs_phs)
perturb_for_adaption = perturb_vars(original_scope="model", perturbed_scope="adaptive_model/model")
kl_loss = tf.reduce_sum(
tf.nn.softmax(policy.q_values) *
(tf.log(tf.nn.softmax(policy.q_values)) - tf.log(tf.nn.softmax(adaptive_policy.q_values))),
axis=-1)
mean_kl = tf.reduce_mean(kl_loss)
def update_scale():
"""
|
tensorflow.nn.softmax
| 8,630 |
from tensorflow.python.framework import ops
self._tensors = []
graph = ops.get_default_graph()
|
tensorflow.python.framework.ops.get_default_graph
| 8,631 |
import tensorflow as tf
log("Checkpoint path: {}".format(checkpoint_fpath))
log("Loading training data from: {}".format(metadat_fpath))
log("Using model: Tacotron")
log(hparams_debug_string())
# Start by setting a seed for repeatability
tf.set_random_seed(hparams.tacotron_random_seed)
# Set up data feeder
coord = tf.train.Coordinator()
with tf.variable_scope("datafeeder") as scope:
feeder = Feeder(coord, metadat_fpath, hparams)
# Set up model:
global_step = tf.Variable(0, name="global_step", trainable=False)
model, stats = model_train_mode(args, feeder, hparams, global_step)
eval_model = model_test_mode(args, feeder, hparams, global_step)
# Embeddings metadata
char_embedding_meta = os.path.join(meta_folder, "CharacterEmbeddings.tsv")
if not os.path.isfile(char_embedding_meta):
with open(char_embedding_meta, "w", encoding="utf-8") as f:
for symbol in symbols:
if symbol == " ":
symbol = "\\s" # For visual purposes, swap space with \s
f.write("{}\n".format(symbol))
char_embedding_meta = char_embedding_meta.replace(log_dir, "..")
|
tensorflow.Variable
| 8,632 |
import tensorflow as tf
# to all be the same size along the batch dimension.
for elem_shape in elem_shapes:
if (not elem_shape or not elem_shape[0]
or elem_shape[0] != elem_shapes[0][0]):
return tf.map_fn(fn, elems, dtype, parallel_iterations, back_prop)
arg_tuples = zip(*[tf.unstack(elem) for elem in elems])
outputs = [fn(arg_tuple) for arg_tuple in arg_tuples]
else:
if not isinstance(elems, tf.Tensor):
raise ValueError('`elems` must be a Tensor or list of Tensors.')
elems_shape = elems.shape.as_list()
if not elems_shape or not elems_shape[0]:
return tf.map_fn(fn, elems, dtype, parallel_iterations, back_prop)
outputs = [fn(arg) for arg in tf.unstack(elems)]
# Stack `outputs`, which is a list of Tensors or list of lists of Tensors
if all([isinstance(output, tf.Tensor) for output in outputs]):
return tf.stack(outputs)
else:
if all([isinstance(output, list) for output in outputs]):
if all([all(
[isinstance(entry, tf.Tensor) for entry in output_list])
for output_list in outputs]):
return [tf.stack(output_tuple) for output_tuple in zip(*outputs)]
raise ValueError('`fn` should return a Tensor or a list of Tensors.')
|
tensorflow.unstack
| 8,633 |
import tensorflow as tf
:return:
"""
return tf.layers.batch_normalization(inputs=inputdata, training=is_training, name=name, scale=scale)
@staticmethod
def layergn(inputdata, name, group_size=32, esp=1e-5):
"""
:param inputdata:
:param name:
:param group_size:
:param esp:
:return:
"""
with tf.variable_scope(name):
inputdata = tf.transpose(inputdata, [0, 3, 1, 2])
n, c, h, w = inputdata.get_shape().as_list()
group_size = min(group_size, c)
inputdata = tf.reshape(inputdata, [-1, group_size, c // group_size, h, w])
mean, var = tf.nn.moments(inputdata, [2, 3, 4], keep_dims=True)
inputdata = (inputdata - mean) / tf.sqrt(var + esp)
# 每个通道的gamma和beta
gamma = tf.Variable(tf.constant(1.0, shape=[c]), dtype=tf.float32, name='gamma')
beta = tf.Variable(tf.constant(0.0, shape=[c]), dtype=tf.float32, name='beta')
gamma = tf.reshape(gamma, [1, c, 1, 1])
beta = tf.reshape(beta, [1, c, 1, 1])
# 根据论文进行转换 [n, c, h, w, c] 到 [n, h, w, c]
|
tensorflow.variable_scope
| 8,634 |
import tensorflow as tf
"""The actual input function."""
batch_size = params["batch_size"]
name_to_features = {
"input_ids":
tf.FixedLenFeature([max_seq_length], tf.int64),
"input_mask":
tf.FixedLenFeature([max_seq_length], tf.int64),
"segment_ids":
tf.FixedLenFeature([max_seq_length], tf.int64),
"masked_lm_positions":
tf.FixedLenFeature([max_predictions_per_seq], tf.int64),
"masked_lm_ids":
tf.FixedLenFeature([max_predictions_per_seq], tf.int64),
"masked_lm_weights":
tf.FixedLenFeature([max_predictions_per_seq], tf.float32),
"next_sentence_labels":
tf.FixedLenFeature([1], tf.int64),
}
# For training, we want a lot of parallel reading and shuffling.
# For eval, we want no shuffling and parallel reading doesn't matter.
if is_training:
d = tf.data.Dataset.from_tensor_slices(tf.constant(input_files))
d = d.repeat()
d = d.shuffle(buffer_size=len(input_files))
|
tensorflow.FixedLenFeature
| 8,635 |
import tensorflow as tf
saver = tf.train.Saver(tf.global_variables())
sv = tf.train.Supervisor(
is_chief=True,
|
tensorflow.train.Supervisor
| 8,636 |
import tensorflow as tf
if decoder.conditional_rnn:
with tf.variable_scope('conditional_2'):
output, state = update(state, context)
elif not decoder.generate_first:
output, state = update(state, input_, context, ids)
logits = generate(output, input_, context)
pos = tf.expand_dims(pos, axis=1)
state = tf.concat([state, context, pos, new_weights], axis=1)
return state, logits
def _time_step(time, input_, input_symbol, pos, state, output, outputs, states, weights, attns, prev_weights,
samples, context):
if decoder.conditional_rnn:
with tf.variable_scope('conditional_1'):
output, state = update(state, input_)
|
tensorflow.expand_dims
| 8,637 |
import tensorflow as tf
feed_dict={
testnum: test_num,
trainnum: train_num,
learnrate:lr
}
for i in range(loop_count):
loss_np, _, label_np, image_np, inf_np = sess.run(
[loss, opti, batch_label, batch_image, inf],feed_dict=feed_dict)
if i > 0 and i % report_step == 0:
accuracy_np = sess.run([accuracy],feed_dict=feed_dict)
print(i, accuracy_np, loss_np)
if i > 0 and i % save_step == 0:
tf.train.Saver().save(sess, path)
tf.train.Saver().save(sess, path)
coord.request_stop()
coord.join(threads)
def test_and_valid(test_loop=1,valid_loop=1,test_num=64,valid_num=64):
feed_dict={
testnum: test_num,
validnum: valid_num
}
with tf.Session(config=config) as sess:
sess.run(init)
coord = tf.train.Coordinator()
|
tensorflow.train.Saver
| 8,638 |
import tensorflow as tf
if use_tilt:
tilt = emission_dist(
size=data_size,
hidden_layer_sizes=fcnet_hidden_sizes,
initializers=initializers,
name="tilt")
else:
tilt = None
rnn_cell = tf.nn.rnn_cell.LSTMCell(rnn_hidden_size,
initializer=initializers["w"])
rev_rnn_cell = tf.nn.rnn_cell.LSTMCell(rnn_hidden_size,
initializer=initializers["w"])
return TrainableVRNN(
rnn_cell, data_encoder, latent_encoder, transition,
emission, proposal_type, proposal=proposal, rev_rnn_cell=rev_rnn_cell,
tilt=tilt, random_seed=random_seed)
|
tensorflow.nn.rnn_cell.LSTMCell
| 8,639 |
import tensorflow as tf
# 2.0 is used to make sure every target has a prior assigned
best_target_per_prior = tf.tensor_scatter_nd_update(best_target_per_prior, tf.expand_dims(best_prior_per_target_index, 1), tf.ones_like(best_prior_per_target_index, dtype=tf.float32)*2.0)
# size: num_priors
labels = tf.gather(gt_labels, best_target_per_prior_index)
labels = tf.where(tf.less(best_target_per_prior, iou_threshold), tf.constant(0, dtype='int64'), labels)
# labels[best_target_per_prior < iou_threshold] = 0 # the backgournd id
boxes = tf.gather(gt_boxes, best_target_per_prior_index)
return boxes, labels
|
tensorflow.less
| 8,640 |
import tensorflow as tf
Args:
* vars_list: list of variables
Returns:
* prune_ratio: overall pruning ratio of the given list of variables
"""
nb_params_nnz = tf.add_n([tf.count_nonzero(var) for var in vars_list])
nb_params_all = tf.add_n([tf.size(var) for var in vars_list])
prune_ratio = 1.0 - tf.cast(nb_params_nnz, tf.float32) / tf.cast(nb_params_all, tf.float32)
return prune_ratio
|
tensorflow.count_nonzero
| 8,641 |
import tensorflow as tf
return out
def valid_inference(self,images):
images=tf.cast(images,tf.float32)/255.0
l1 = tf.matmul(images, self.w1)+self.b1
l1=tf.nn.relu(l1)
out = tf.matmul(l1, self.w2)+self.b2
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
def optimer(self,loss,lr=0.001):
train_step=tf.train.GradientDescentOptimizer(lr).minimize(loss)
return train_step
path=r'C:\JC\test\train_model.ckpt'
|
tensorflow.nn.softmax
| 8,642 |
import tensorflow as tf
lstm_cell = rnn.BasicLSTMCell(LSTM_SIZE, forget_bias = 1.0)
outputs, _ = rnn.static_rnn(lstm_cell, x, dtype = tf.float32)
# Slice to keep only the last cell of the RNN
outputs = outputs[-1]
#print('last outputs={}'.format(outputs))
# Output is result of linear activation of last layer of RNN
weight = tf.Variable(tf.random_normal([LSTM_SIZE, N_OUTPUTS]))
bias = tf.Variable(tf.random_normal([N_OUTPUTS]))
predictions = tf.matmul(outputs, weight) + bias
# 2. Loss function, training/eval ops
if mode == tf.estimator.ModeKeys.TRAIN or mode == tf.estimator.ModeKeys.EVAL:
loss = tf.losses.mean_squared_error(labels, predictions)
train_op = tf.contrib.layers.optimize_loss(
loss = loss,
global_step = tf.train.get_global_step(),
learning_rate = 0.01,
optimizer = "SGD")
eval_metric_ops = {
"rmse": tf.metrics.root_mean_squared_error(labels, predictions)
}
else:
loss = None
train_op = None
eval_metric_ops = None
|
tensorflow.losses.mean_squared_error
| 8,643 |
import tensorflow as tf
zt = q_zt.sample(seed=self.random_seed)
p_xt_given_zt, latent_encoded = self.emission(zt, rnn_out)
log_p_xt_given_zt = tf.reduce_sum(p_xt_given_zt.log_prob(targets), axis=-1)
log_p_zt = tf.reduce_sum(p_zt.log_prob(zt), axis=-1)
log_q_zt = tf.reduce_sum(q_zt.log_prob(zt), axis=-1)
weights = log_p_zt + log_p_xt_given_zt - log_q_zt
if self._tilt:
prev_log_r = tf.cond(
tf.greater(t, 0),
lambda: self.tilt(state.rnn_out, state.latent_encoded, targets),
lambda: 0.) # On the first step, prev_log_r = 0.
log_r = tf.cond(
tf.less(t + 1, self.max_seq_len),
lambda: self.tilt(rnn_out, latent_encoded, self.targets_ta.read(t+1)),
lambda: 0.)
# On the last step, log_r = 0.
|
tensorflow.greater
| 8,644 |
import tensorflow as tf
observations = features["inputs_raw"]
observations = tf.cast(observations, tf.float32)
flat_observations = tf.layers.flatten(observations)
with tf.variable_scope("policy"):
x = flat_observations
for size in self.hparams.policy_layers:
|
tensorflow.variable_scope
| 8,645 |
import tensorflow as tf
a = attn(x, 'attn', nx, n_head, train=train, scale=scale)
n = norm(x+a, 'ln_1')
m = mlp(n, 'mlp', nx*4, train=train)
h = norm(n+m, 'ln_2')
return h
def embed(X, we):
#X [-1,,2]
we = convert_gradient_to_tensor(we)
e = tf.gather(we, X)
h = tf.reduce_sum(e, 2)
return h
def clf(x, ny, w_init=tf.random_normal_initializer(stddev=0.02), b_init=tf.constant_initializer(0), train=False):
with tf.variable_scope('clf'):
nx = shape_list(x)[-1]
w = tf.get_variable("w", [nx, ny], initializer=w_init)
b = tf.get_variable("b", [ny], initializer=b_init)
return tf.matmul(x, w)+b
def model(X, M, Y, train=False, reuse=False):
with tf.variable_scope('model', reuse=reuse):
we = tf.get_variable("we", [n_vocab+n_special+n_ctx, n_embd], initializer=tf.random_normal_initializer(stddev=0.02))
we = dropout(we, embd_pdrop, train)
#X:[n_batch_train, 2, n_ctx, 2] -> [n_batch_train*2,n_ctx,2]
X = tf.reshape(X, [-1, n_ctx, 2])
M = tf.reshape(M, [-1, n_ctx])
|
tensorflow.variable_scope
| 8,646 |
import tensorflow as tf
# Weighted sum
if mode == 'SUM':
output = tf.matmul(scores, facts) # [B, 1, H]
# output = tf.reshape(output, [-1, tf.shape(facts)[-1]])
else:
scores = tf.reshape(scores, [-1, tf.shape(facts)[1]])
output = facts * tf.expand_dims(scores, -1)
output = tf.reshape(output, tf.shape(facts))
if return_alphas:
return output, scores
return output
def self_attention(facts, ATTENTION_SIZE, mask, stag='null'):
|
tensorflow.expand_dims
| 8,647 |
import tensorflow as tf
model_fn = model_fn_builder(
bert_config=bert_config,
num_labels=len(label_list)+1,
init_checkpoint=FLAGS.init_checkpoint,
learning_rate=FLAGS.learning_rate,
num_train_steps=num_train_steps,
num_warmup_steps=num_warmup_steps,
use_tpu=FLAGS.use_tpu,
use_one_hot_embeddings=FLAGS.use_tpu)
estimator = tf.contrib.tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=model_fn,
config=run_config,
train_batch_size=FLAGS.train_batch_size,
eval_batch_size=FLAGS.eval_batch_size)
if FLAGS.do_train:
train_file = os.path.join(FLAGS.output_dir, "train.tf_record")
|
tensorflow.contrib.tpu.TPUEstimator
| 8,648 |
import tensorflow as tf
# Multi-GPU setting
sharded_losses = parallel.parallel_model(
model.get_training_func(initializer),
features,
params.device_list
)
loss = tf.add_n(sharded_losses) / len(sharded_losses)
# Create global step
global_step = tf.train.get_or_create_global_step()
# Print parameters
|
tensorflow.add_n
| 8,649 |
import tensorflow as tf
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]
}
config = Config(X_train, X_test)
# print("Some useful info to get an insight on dataset's shape and normalisation:")
# print("features shape, labels shape, each features mean, each features standard deviation")
# print(X_test.shape, y_test.shape,
# np.mean(X_test), np.std(X_test))
|
tensorflow.random_normal
| 8,650 |
import tensorflow as tf
cost = tf.reduce_sum(cost * weights, axis=1)
if average_across_timesteps:
total_size = tf.reduce_sum(weights, axis=1)
total_size += 1e-12 # just to avoid division by 0 for all-0 weights
cost /= total_size
cost = tf.reduce_sum(cost)
if average_across_batch:
cost /= tf.to_float(batch_size)
return cost
|
tensorflow.reduce_sum
| 8,651 |
import tensorflow as tf
beta1=beta1).minimize(generator_loss, var_list=en_var)
supervised_encoder_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate,
beta1=beta1).minimize(supervised_encoder_loss,
var_list=en_var)
init = tf.global_variables_initializer()
# Reshape immages to display them
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
|
tensorflow.summary.scalar
| 8,652 |
import tensorflow as tf
def session(self, sess):
if sess is not None:
self.sess = sess
else:
config_proto = tf.ConfigProto()
config_proto.gpu_options.allow_growth = True
self.sess = tf.Session(config=config_proto)
def initialize(self):
self.sess.run(tf.global_variables_initializer())
def save(self, path):
self.saver.save(self.sess, path)
def restore(self, path):
self.saver.restore(self.sess, path)
def close(self):
self.sess.close()
|
tensorflow.global_variables_initializer
| 8,653 |
from tensorflow.contrib.rnn.python.ops.core_rnn_cell import _Linear
kernel_initializer=self._kernel_initializer)
value = math_ops.sigmoid(self._gate_linear([inputs, state]))
r, u = array_ops.split(value=value, num_or_size_splits=2, axis=1)
r_state = r * state
if self._candidate_linear is None:
with vs.variable_scope("candidate"):
self._candidate_linear = _Linear(
[inputs, r_state],
self._num_units,
True,
bias_initializer=self._bias_initializer,
kernel_initializer=self._kernel_initializer)
c = self._activation(self._candidate_linear([inputs, r_state]))
u = (1.0 - att_score) * u
|
tensorflow.contrib.rnn.python.ops.core_rnn_cell._Linear
| 8,654 |
import tensorflow as tf
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))
def decode(self, serialized_example):
"""Decode the serialized example.
Args:
serialized_example: a single serialized tf.Example string.
Returns:
decoded_tensors: a dictionary of tensors with the following fields:
- image: a uint8 tensor of shape [None, None, 3].
- source_id: a string scalar tensor.
|
tensorflow.shape
| 8,655 |
import tensorflow as tf
return output
def dense_layer(self, data, num_tags):
logits = tf.layers.dense(data, num_tags)
return logits
def load_tag_data(self):
# data = np.loadtxt(self.params['tags'], dtype=np.unicode, encoding=None)
data = self.params["tags_data"]
mapping_strings = tf.Variable(data)
return mapping_strings
def load_word_data(self):
data = np.loadtxt(self.params["words"], dtype=np.unicode, encoding=None)
mapping_strings = tf.Variable(data.reshape((-1,)))
return mapping_strings
def tag2id(self, labels, name=None):
|
tensorflow.Variable
| 8,656 |
import tensorflow as tf
input_transformation_fn(tensor_dict=tensor_dict))
self.assertAllClose(transformed_inputs[fields.InputDataFields.image],
np_image / 255.)
self.assertAllClose(transformed_inputs[fields.InputDataFields.
true_image_shape],
[4, 4, 3])
def test_applies_data_augmentation_fn_to_tensor_dict(self):
np_image = np.random.randint(256, size=(4, 4, 3))
tensor_dict = {
fields.InputDataFields.image:
tf.constant(np_image),
fields.InputDataFields.groundtruth_classes:
tf.constant(np.array([3, 1], np.int32))
}
def add_one_data_augmentation_fn(tensor_dict):
return {key: value + 1 for key, value in tensor_dict.items()}
num_classes = 4
input_transformation_fn = functools.partial(
inputs.transform_input_data,
|
tensorflow.constant
| 8,657 |
import tensorflow as tf
train_file = os.path.join(FLAGS.output_dir, "train.tf_record")
file_based_convert_examples_to_features(
train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file)
tf.logging.info("***** Running training *****")
tf.logging.info(" Num examples = %d", len(train_examples))
tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
tf.logging.info(" Num steps = %d", num_train_steps)
train_input_fn = file_based_input_fn_builder(
input_file=train_file,
seq_length=FLAGS.max_seq_length,
|
tensorflow.logging.info
| 8,658 |
import tensorflow as tf
tf.app.flags.DEFINE_boolean('load_state', True, 'Load state if possible ')
tf.app.flags.DEFINE_boolean('kill_depth', False, 'Ignore depth information')
tf.app.flags.DEFINE_boolean('dev', False, 'Indicate development mode')
tf.app.flags.DEFINE_integer('batch_size', 128, 'Batch size')
tf.app.flags.DEFINE_float('learning_rate', 0.0001, 'Create visualization of ')
tf.app.flags.DEFINE_float('blur', 5.0, 'Max sigma value for Gaussian blur applied to training set')
tf.app.flags.DEFINE_boolean('new_blur', False, 'Use data augmentation as blur info')
tf.app.flags.DEFINE_integer('blur_decrease', 10000, 'Decrease image blur every X steps')
FLAGS = tf.app.flags.FLAGS
slim = tf.contrib.slim
|
tensorflow.app.flags.DEFINE_boolean
| 8,659 |
import tensorflow as tf
test_labels=tf.one_hot(test_label_batch,classnum)
test_pre = tf.reshape(test_inf, [testnum, classnum])
correct_prediction=tf.equal(tf.argmax(test_inf,1),tf.argmax(test_labels,1))
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
test_pre = tf.argmax(test_pre, 1)
test_true = tf.argmax(test_labels, 1)
valid_image_batch,valid_label_batch=get_valid_batch(valid_image,valid_label,validnum)
valid_inf=work.valid_inference(valid_image_batch)
valid_labels=tf.one_hot(valid_label_batch,classnum)
#train_step=tf.train.GradientDescentOptimizer(0.001).minimize(cross_entropy)
valid_pre = tf.reshape(valid_inf, [validnum, classnum])
valid_correct_prediction=tf.equal(tf.argmax(valid_inf,1),tf.argmax(valid_labels,1))
valid_accuracy=tf.reduce_mean(tf.cast(valid_correct_prediction,tf.float32))
valid_pre = tf.argmax(valid_pre, 1)
valid_true = tf.argmax(valid_labels, 1)
target_names = ['class sg', 'class bm', 'class wd', 'class wt', 'class wj', 'class wo', 'class ym', 'class shq', 'class shj',
|
tensorflow.one_hot
| 8,660 |
import tensorflow as tf
## End new version
if self._normalize_cols:
logits_vec = logits_vec - tf.math.reduce_logsumexp(
logits_vec, axis=0)[None]
relabel_indices = tf.random.categorical(logits=logits_vec, num_samples=1)
|
tensorflow.math.reduce_logsumexp
| 8,661 |
import tensorflow as tf
def __init__(self, p=2):
self._dim = None
self._p = p
def _compute(self, x, y):
self._dim = x._rank()
kernel = np.zeros((tf.size(x), tf.size(y)))
for l in tf.range(start=0, limit=tf.size(x), delta=1, dtype=None, name='l_range'):
for m in tf.range(start=0, limit=tf.size(y), delta=1, dtype=None, name='m_range'):
vx = tf.contrib.lookup.MutableHashTable(key_dtype=tf.string,
value_dtype=tf.int64,
|
tensorflow.size
| 8,662 |
import tensorflow as tf
'num_cpu_threads', 0,
'The number of cpu cores used to train.')
tf.app.flags.DEFINE_float(
'gpu_memory_fraction', 1., 'GPU memory fraction to use.')
# scaffold related configuration
tf.app.flags.DEFINE_string(
'data_dir', '../PASCAL/VOC_TF/VOC0712TF/',
'The directory where the dataset input data is stored.')
tf.app.flags.DEFINE_string(
'dataset_name', 'pascalvoc_0712', 'The name of the dataset to load.')
tf.app.flags.DEFINE_integer(
'num_classes', 21, 'Number of classes to use in the dataset.')
tf.app.flags.DEFINE_string(
'dataset_split_name', 'train', 'The name of the train/test split.')
tf.app.flags.DEFINE_string(
'model_dir', './logs_v3/',
|
tensorflow.app.flags.DEFINE_string
| 8,663 |
import tensorflow as tf
model_names = tf.global_variables() # Fallback when slim is not used
model_names = set([v.name.split(':')[0] for v in model_names])
checkpoint_names = set(saved_shapes.keys())
found_names = model_names & checkpoint_names
missing_names = model_names - checkpoint_names
shape_conflicts = set()
restored = []
with tf.variable_scope('', reuse=True):
for name in found_names:
# print(tf.global_variables())
# print(name, name in model_names, name in checkpoint_names)
var = tf.get_variable(name)
var_shape = var.get_shape().as_list()
if var_shape == saved_shapes[name]:
restored.append(var)
else:
shape_conflicts.add(name)
found_names -= shape_conflicts
return (restored, sorted(found_names),
sorted(missing_names), sorted(shape_conflicts))
def load(self, checkpoint_path, flexible_restore=True):
|
tensorflow.get_variable
| 8,664 |
import tensorflow as tf
noise_shape = [shape[0], 1]
scale = keep_prob
if mode == "recurrent" and len(args.get_shape().as_list()) == 3:
noise_shape = [shape[0], 1, shape[-1]]
args = tf.cond(is_train, lambda: tf.nn.dropout(
args, keep_prob, noise_shape=noise_shape) * scale, lambda: args)
return args
def softmax_mask(val, mask):
return -INF * (1 - tf.cast(mask, tf.float32)) + val
def pointer(inputs, state, hidden, mask, scope="pointer"):
with tf.variable_scope(scope):
u = tf.concat([tf.tile(tf.expand_dims(state, axis=1), [1, tf.shape(inputs)[1], 1]), inputs], axis=2) #[N,PL,2d]
s0 = tf.nn.tanh(dense(u, hidden, use_bias=False, scope="s0"))
s = dense(s0, 1, use_bias=False, scope="s")
s1 = softmax_mask(tf.squeeze(s, [2]), mask)#[N,PL]
a = tf.expand_dims(tf.nn.softmax(s1), axis=2)#[N,PL,1]
res = tf.reduce_sum(a * inputs, axis=1)
return res, s1 # attention_sum probability
def summ(memory, hidden, mask, keep_prob=1.0, is_train=None, scope="summ"):
with tf.variable_scope(scope):
d_memory = dropout(memory, keep_prob=keep_prob, is_train=is_train)
s0 = tf.nn.tanh(dense(d_memory, hidden, scope="s0"))
s = dense(s0, 1, use_bias=False, scope="s")
s1 = softmax_mask(tf.squeeze(s, [2]), mask)
|
tensorflow.shape
| 8,665 |
import tensorflow as tf
):
if E_init_args is None:
E_init_args = {}
super(EmbeddingInputlayer, self).__init__(prev_layer=None, name=name)
logging.info("EmbeddingInputlayer %s: (%d, %d)" % (self.name, vocabulary_size, embedding_size))
self.inputs = inputs
with tf.variable_scope(name):
embeddings = tf.get_variable(
name='embeddings', shape=(vocabulary_size, embedding_size), initializer=E_init, dtype=LayersConfig.tf_dtype, **E_init_args)
embed = tf.nn.embedding_lookup(embeddings, self.inputs)
self.outputs = embed
self.all_layers = [self.outputs]
self.all_params = [embeddings]
|
tensorflow.variable_scope
| 8,666 |
import tensorflow as tf
return_dict = {}
# invalid position mask such as query and special symbols (PAD, SEP, CLS)
p_mask = features["p_mask"]
# logit of the start position
with tf.variable_scope("start_logits"):
start_logits = tf.layers.dense(
output,
1,
kernel_initializer=initializer)
start_logits = tf.transpose(tf.squeeze(start_logits, -1), [1, 0])
start_logits_masked = start_logits * (1 - p_mask) - 1e30 * p_mask
start_log_probs = tf.nn.log_softmax(start_logits_masked, -1)
|
tensorflow.layers.dense
| 8,667 |
import tensorflow as tf
shape=[2, bert_config.hidden_size],
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)
|
tensorflow.matmul
| 8,668 |
import tensorflow as tf
else:
eval_metrics = {}
predictions = {"predictions": logits}
for metric_name, metric_fn in six.iteritems(eval_metrics_fns):
eval_metrics[metric_name] = metric_fn(logits, features,
features["targets"])
return tf.estimator.EstimatorSpec(
tf.estimator.ModeKeys.EVAL,
predictions=predictions,
eval_metric_ops=eval_metrics,
evaluation_hooks=[restore_hook],
loss=loss)
|
tensorflow.estimator.EstimatorSpec
| 8,669 |
import tensorflow as tf
# expects [batch_size, ...] Tensors, thus reshape to introduce a batch
# dimension. These Tensors are implicitly concatenated to
# [params['batch_size']].
global_step_t = tf.reshape(global_step, [1])
total_loss_t = tf.reshape(total_loss, [1])
total_rpn_loss_t = tf.reshape(total_rpn_loss, [1])
rpn_score_loss_t = tf.reshape(rpn_score_loss, [1])
rpn_box_loss_t = tf.reshape(rpn_box_loss, [1])
total_fast_rcnn_loss_t = tf.reshape(total_fast_rcnn_loss, [1])
fast_rcnn_class_loss_t = tf.reshape(fast_rcnn_class_loss, [1])
fast_rcnn_box_loss_t = tf.reshape(fast_rcnn_box_loss, [1])
mask_loss_t = tf.reshape(mask_loss, [1])
learning_rate_t = tf.reshape(learning_rate, [1])
host_call = (host_call_fn,
[global_step_t, total_loss_t, total_rpn_loss_t,
rpn_score_loss_t, rpn_box_loss_t, total_fast_rcnn_loss_t,
fast_rcnn_class_loss_t, fast_rcnn_box_loss_t,
mask_loss_t, learning_rate_t])
else:
train_op = None
|
tensorflow.reshape
| 8,670 |
import tensorflow as tf
def characters(filename, batch_size, sequence_size):
"""Returns a dataset of characters from the given file."""
def _to_chars(line):
"""string scalar -> Dataset of characters (string scalars)."""
chars, = tf.py_func(_split_string, [line + "\n"], [tf.string])
chars.set_shape([None])
return tf.data.Dataset.from_tensor_slices(chars)
return (tf.data.TextLineDataset([filename])
|
tensorflow.py_func
| 8,671 |
import tensorflow as tf
"Mean squared error loss"
loss=tf.reduce_mean(tf.square(tf.reshape(predictions,[-1])-tf.reshape(yy,[-1])))
"Adding regularization"
if lambda_l2_reg > 0 :
cell_l2 = tf.reduce_sum([tf.nn.l2_loss(tf_var) for tf_var in tf.trainable_variables() if not ("noreg" in tf_var.name or "Bias" in tf_var.name)])
Predict_l2 = tf.nn.l2_loss(W) #+ tf.nn.l2_loss(b)
total_loss = tf.reduce_sum(loss + lambda_l2_reg* tf.reduce_sum(cell_l2+Predict_l2) )
else:
total_loss = loss
"Define the train_step"
train_step = tf.train.AdamOptimizer(learning_rate).minimize(total_loss)
return dict(x=x,
y=y,
batch_size=batch_size,
input_prob=input_prob,
state_prob=state_prob,
output_prob=output_prob,
init_state=init_state,
final_state=final_state,
|
tensorflow.train.AdamOptimizer
| 8,672 |
import tensorflow as tf
sess.run([tf.global_variables_initializer()])
res = sess.run(dec)
self.assertEqual(3, len(res))
self.assertEqual((2, 2), res[0].shape)
# Test that previous-feeding model ignores inputs after the first.
dec_inp2 = [tf.constant(0, tf.int32, shape=[2]) for _ in range(3)]
with tf.variable_scope("other"):
d3, _ = tf.nn.seq2seq.embedding_attention_seq2seq(
enc_inp, dec_inp2, cell, num_encoder_symbols=2,
num_decoder_symbols=5, embedding_size=2,
feed_previous=tf.constant(True))
|
tensorflow.constant
| 8,673 |
import tensorflow as tf
# at last assign attributes for remainder of the model
self.embedding = embedding
def _build_word_embeddings(self):
projection_dim = self.options['lstm']['projection_dim']
# the word embeddings
with tf.device("/cpu:0"):
self.embedding_weights = tf.get_variable(
"embedding", [self._n_tokens_vocab, projection_dim],
dtype=DTYPE,
)
self.embedding = tf.nn.embedding_lookup(self.embedding_weights,
self.ids_placeholder)
|
tensorflow.device
| 8,674 |
import tensorflow as tf
A tf.Variable, filled with drawn samples.
"""
shape = tuple(map(int, shape))
if seed is None:
# ensure that randomness is conditioned by the Numpy RNG
seed = np.random.randint(10e8)
value = tf.random_uniform_initializer(
low, high, dtype=dtype, seed=seed)(shape)
return tf.Variable(value, dtype=dtype, name=name)
def random_normal_variable(shape,
mean,
scale,
dtype=tf.float32,
name=None,
|
tensorflow.Variable
| 8,675 |
import tensorflow as tf
b = tf.Variable(tf.random_normal(shape=[1,1]))
# Initialize placeholders
x_data = tf.placeholder(shape=[sentence_size], dtype=tf.int32)
y_target = tf.placeholder(shape=[1, 1], dtype=tf.float32)
# Text-Vocab Embedding
x_embed = tf.nn.embedding_lookup(identity_mat, x_data)
x_col_sums = tf.reduce_sum(x_embed, 0)
# Declare model operations
x_col_sums_2D = tf.expand_dims(x_col_sums, 0)
model_output = tf.add(tf.matmul(x_col_sums_2D, A), b)
# Declare loss function (Cross Entropy loss)
loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=model_output, labels=y_target))
|
tensorflow.reduce_sum
| 8,676 |
import tensorflow as tf
target_placeholder = tf.placeholder(tf.int32, shape=(None, None, 1), name='audio_targets')
target_type = tf.int32
self._placeholders = [
input_placeholder,
target_placeholder,
tf.placeholder(tf.int32, shape=(None, ), name='input_lengths'),
]
queue_types = [tf.float32, target_type, tf.int32]
if self.local_condition:
|
tensorflow.placeholder
| 8,677 |
import tensorflow as tf
assert padding in ["SAME", "VALID", "REFLECT", "PARTIAL"], 'valid paddings: "SAME", "VALID", "REFLECT", "PARTIAL"'
if type(size) == int: size = [size, size]
if init_stddev <= 0.0:
init = tf.contrib.layers.variance_scaling_initializer(dtype=tf.float32)
else:
init = tf.truncated_normal_initializer(stddev=init_stddev)
if padding == "PARTIAL":
with tf.variable_scope('mask'):
_, h, w, _ = input.get_shape().as_list()
slide_window = size[0] * size[1]
mask = tf.ones(shape=[1, h, w, 1])
update_mask = tf.layers.conv2d(mask, filters=1, dilation_rate=(dilation, dilation), name='mask' + id,
kernel_size=size, kernel_initializer=tf.constant_initializer(1.0),
strides=stride, padding="SAME", use_bias=False, trainable=False)
mask_ratio = slide_window / (update_mask + 1e-8)
update_mask = tf.clip_by_value(update_mask, 0.0, 1.0)
mask_ratio = mask_ratio * update_mask
with tf.variable_scope('parconv'):
x = tf.layers.conv2d(input, filters=channels, name='conv' + id, kernel_size=size, kernel_initializer=init,
strides=stride, padding="SAME", use_bias=False)
x = x * mask_ratio
if use_bias:
|
tensorflow.ones
| 8,678 |
import tensorflow as tf
def get_input_function():
"""A function to get test inputs. Returns an image with one box."""
image = tf.random_uniform([32, 32, 3], dtype=tf.float32)
key = tf.constant('image_000000')
class_label = tf.random_uniform(
[1], minval=0, maxval=NUMBER_OF_CLASSES, dtype=tf.int32)
|
tensorflow.random_uniform
| 8,679 |
import tensorflow as tf
def _build_data_pipeline(self):
def normalize(image, label):
image = tf.cast(image, tf.float32) / 255.0
return image, label
dataset = tf.data.TFRecordDataset(["./data/train.tfrecord"])
dataset = dataset.map(decode)
dataset = dataset.map(normalize)
dataset = dataset.batch(50)
dataset = dataset.take(1) # keep validating on the same items
dataset = dataset.repeat()
|
tensorflow.data.TFRecordDataset
| 8,680 |
import tensorflow as tf
# If you want to use the token-level output, use model.get_sequence_output()
# instead.
output_layer = model.get_pooled_output()
hidden_size = output_layer.shape[-1].value
output_weights = tf.get_variable(
"output_weights", [num_labels, hidden_size],
initializer=tf.truncated_normal_initializer(stddev=0.02))
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
|
tensorflow.truncated_normal_initializer
| 8,681 |
import tensorflow as tf
return _initializer
'''
G(x) = 1 {-(1/2)*[(x-u)/sigma]^2}
------------------- e
sigma*(2*pi)^(1/2)
'''
def gaussian_pdf(mean, loc_std, sample):
Z = 1.0 / (loc_std * tf.sqrt(2.0 * np.pi))
a = - tf.square(sample - mean) / (2.0 * tf.square(loc_std))
return Z * tf.exp(a)
class ACNet:
def __init__(self, scope, GRID_SIZE, a_size, trainer,TRAINING, GLOBAL_NET_SCOPE):
with tf.variable_scope(str(scope)+'/qvalues'):
#The input size may require more work to fit the interface.
self.inputs = tf.placeholder(shape=[None,GRID_SIZE,GRID_SIZE, num_channels], dtype=tf.float32) # input state
# self.goal_pos = tf.placeholder(shape=[None,2],dtype=tf.float32)
|
tensorflow.square
| 8,682 |
import tensorflow as tf
image_difference = fake_images - real_images
print_obj(func_name, "image_difference", image_difference)
# Get random samples from this mixed image distribution.
mixed_images = random_uniform_num * image_difference
mixed_images += real_images
print_obj(func_name, "mixed_images", mixed_images)
# Send to the discriminator to get logits.
mixed_logits = self.get_discriminator_logits(
X=mixed_images, alpha_var=alpha_var, params=params
)
print_obj(func_name, "mixed_logits", mixed_logits)
# Get the mixed loss.
mixed_loss = tf.reduce_sum(
input_tensor=mixed_logits,
name="mixed_loss"
)
print_obj(func_name, "mixed_loss", mixed_loss)
# Get gradient from returned list of length 1.
mixed_gradients = tf.gradients(
ys=mixed_loss,
xs=[mixed_images],
name="gradients"
)[0]
print_obj(func_name, "mixed_gradients", mixed_gradients)
# Get gradient's L2 norm.
|
tensorflow.reduce_sum
| 8,683 |
import tensorflow as tf
(=False) examples.
- *positive_fraction*: desired fraction of positive examples (scalar in [0,1])
in the batch.
Returns:
*sampled_idx_indicator*: boolean tensor of shape [N], True for entries which are sampled.
"""
negative_idx = tf.logical_not(labels)
positive_idx = tf.logical_and(labels, indicator)
negative_idx = tf.logical_and(negative_idx, indicator)
# Sample positive and negative samples separately
if sample_size is None:
max_num_pos = tf.reduce_sum(tf.cast(positive_idx, dtype=tf.int32))
else:
max_num_pos = int(positive_fraction * sample_size)
|
tensorflow.logical_not
| 8,684 |
import tensorflow as tf
perturbation loss
"""
noise = tf.random_normal(shape=tf.shape(embedded))
perturb = _scale_l2(_mask_by_length(noise, length), perturb_norm_length)
|
tensorflow.shape
| 8,685 |
import tensorflow as tf
enc_inp, dec_inp, cell, num_encoder_symbols,
num_decoder_symbols, embedding_size=2, feed_previous=feed_previous)
def EmbeddingAttentionSeq2SeqNoTuple(enc_inp, dec_inp, feed_previous):
cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=False)
return tf.nn.seq2seq.embedding_attention_seq2seq(
enc_inp, dec_inp, cell, num_encoder_symbols,
num_decoder_symbols, embedding_size=2, feed_previous=feed_previous)
for model in (EmbeddingRNNSeq2SeqF, EmbeddingRNNSeq2SeqNoTupleF,
|
tensorflow.nn.seq2seq.embedding_attention_seq2seq
| 8,686 |
import tensorflow as tf
Args:
boxlist1: Nx4 floatbox
boxlist2: Mx4
Returns:
a tensor with shape [N, M] representing pairwise intersections
"""
x_min1, y_min1, x_max1, y_max1 = tf.split(boxlist1, 4, axis=1)
x_min2, y_min2, x_max2, y_max2 = tf.split(boxlist2, 4, axis=1)
all_pairs_min_ymax = tf.minimum(y_max1, tf.transpose(y_max2))
all_pairs_max_ymin = tf.maximum(y_min1, tf.transpose(y_min2))
intersect_heights = tf.maximum(0.0, all_pairs_min_ymax - all_pairs_max_ymin)
all_pairs_min_xmax = tf.minimum(x_max1, tf.transpose(x_max2))
all_pairs_max_xmin = tf.maximum(x_min1, tf.transpose(x_min2))
intersect_widths = tf.maximum(0.0, all_pairs_min_xmax - all_pairs_max_xmin)
return intersect_heights * intersect_widths
@under_name_scope()
def pairwise_iou(boxlist1, boxlist2):
"""Computes pairwise intersection-over-union between box collections.
Args:
boxlist1: Nx4 floatbox
boxlist2: Mx4
Returns:
a tensor with shape [N, M] representing pairwise iou scores.
"""
|
tensorflow.maximum
| 8,687 |
import tensorflow as tf
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
# In this example, we limit mnist data
Xtr, Ytr = mnist.train.next_batch(5000) #5000 for training (nn candidates)
Xte, Yte = mnist.test.next_batch(200) #200 for testing
# tf Graph Input
xtr = tf.placeholder("float", [None, 784])
xte = tf.placeholder("float", [784])
# Nearest Neighbor calculation using L1 Distance
# Calculate L1 Distance
distance = tf.reduce_sum(tf.abs(tf.add(xtr, tf.negative(xte))),
reduction_indices=1)
# Prediction: Get min distance index (Nearest neighbor)
pred = tf.arg_min(distance, 0)
accuracy = 0.
# Initialize the variables (i.e. assign their default value)
init = tf.global_variables_initializer()
# Start training
with tf.compat.v1.Session() as sess:
# Run the initializer
sess.run(init)
# Add the fault injection code here to instrument the graph
# We start injecting the fault right away here unlike earlier
|
tensorflow.arg_min
| 8,688 |
import tensorflow as tf
'num of residual units')
tf.app.flags.DEFINE_string('Optimizer', 'mom',
'The optimizer used to train the model.')
tf.app.flags.DEFINE_bool('RCE_train', False,
'Whether use RCE to train the model.')
tf.app.flags.DEFINE_string('attack_method', 'fgsm',
|
tensorflow.app.flags.DEFINE_bool
| 8,689 |
import tensorflow as tf
"""
with tf.variable_scope(scope, 'precision_at_recall', [logits, labels, label_priors], reuse=reuse):
|
tensorflow.variable_scope
| 8,690 |
import tensorflow as tf
tf.summary.scalar('policy_loss', policy_loss)
tf.summary.scalar('qf1_loss', qf1_loss)
|
tensorflow.summary.scalar
| 8,691 |
import tensorflow as tf
masked_lm_ids = tf.reshape(masked_lm_ids, [-1])
masked_lm_weights = tf.reshape(masked_lm_weights, [-1])
masked_lm_accuracy = tf.metrics.accuracy(
labels=masked_lm_ids,
|
tensorflow.metrics.accuracy
| 8,692 |
import tensorflow as tf
"""Calculates the per-example cross-entropy loss for a sequence of logits and
masks out all losses passed the sequence length.
Args:
logits: Logits of shape `[T, B, vocab_size]`
targets: Target classes of shape `[T, B]`
sequence_length: An int32 tensor of shape `[B]` corresponding
to the length of each input
Returns:
A tensor of shape [T, B] that contains the loss per example, per time step.
"""
with tf.name_scope("cross_entropy_sequence_loss"):
losses = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=targets)
loss_mask = tf.sequence_mask(tf.to_int32(sequence_length), tf.to_int32(tf.shape(targets)[0]))
losses = losses * tf.transpose(tf.to_float(loss_mask), [1, 0])
return losses
def dice_loss(predictions, targets, weights=1., name='dice_loss'):
with tf.name_scope(name):
# predictions = tf.to_float(predictions)
targets = tf.to_float(targets)
|
tensorflow.name_scope
| 8,693 |
import tensorflow as tf
return conv_bn
def convMfm(inpOp, nIn, nOut, kH, kW, dH, dW, padType, name, phase_train=True, use_batch_norm=True, weight_decay=0.0):
net_1 = convLinear(inpOp, nIn, nOut, kH, kW, dH, dW, padType, name+'_1', phase_train, use_batch_norm, weight_decay)
net_2 = convLinear(inpOp, nIn, nOut, kH, kW, dH, dW, padType, name+'_2', phase_train, use_batch_norm, weight_decay)
out = tf.maximum(net_1, net_2)
return out
def affine(inpOp, nIn, nOut, name, weight_decay=0.0):
|
tensorflow.maximum
| 8,694 |
import tensorflow as tf
weights = weights.write(time, new_weights)
states = states.write(time, state)
outputs = outputs.write(time, output_)
if not decoder.conditional_rnn and not decoder.update_first and decoder.generate_first:
output, state = update(state, input_, context, predicted_symbol)
return (time + 1, input_, predicted_symbol, pos, state, output, outputs, states, weights, attns, new_weights,
samples, context)
with tf.variable_scope('decoder_{}'.format(decoder.name)):
_, _, _, new_pos, new_state, _, outputs, states, weights, attns, new_weights, samples, _ = tf.while_loop(
cond=lambda time, *_: time < time_steps,
body=_time_step,
loop_vars=(time, initial_input, initial_symbol, initial_pos, initial_state, initial_output, outputs,
weights, states, attns, initial_weights, samples, initial_context),
parallel_iterations=decoder.parallel_iterations,
swap_memory=decoder.swap_memory)
outputs = outputs.stack()
weights = weights.stack() # batch_size, encoders, output time, input time
states = states.stack()
|
tensorflow.while_loop
| 8,695 |
import tensorflow as tf
# to get q_tot_
q_ = self.sess.run(self.q_next, feed_dict={self.s_: s_})
q_m_ = np.max(q_, axis=1)
q_tot_ = self.sess.run(self.Q_tot_, feed_dict={self.S_: S_, self.q_m_: q_m_})
q_target = np.array(R) + (1 - np.array(done)) * self.gamma * np.squeeze(q_tot_, axis=-1)
# import pdb; pdb.set_trace()
tvars = tf.trainable_variables()
tvars_vals_b = self.sess.run(tvars)
# f = open("before.txt", "a")
# for var, val in zip(tvars, tvars_vals):
# f.write(var,)
# f.close()
# update
_, cost = self.sess.run([self._train_op, self.loss],
|
tensorflow.trainable_variables
| 8,696 |
import tensorflow as tf
outputs = tf.concat(outputs, 2)
self.Z_hat = tf.layers.dense(outputs, 1 + fourier_window_size // 2)
self.loss1 = tf.reduce_mean(tf.abs(self.Y_hat - self.Y))
self.loss2 = tf.reduce_mean(tf.abs(self.Z_hat - self.Z))
self.loss = self.loss1 + self.loss2
self.optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(self.loss)
# In[3]:
tf.reset_default_graph()
sess = tf.InteractiveSession()
size_layers = 128
learning_rate = 1e-3
num_layers = 2
model = Model(num_layers, size_layers, learning_rate)
sess.run(tf.global_variables_initializer())
# In[4]:
|
tensorflow.InteractiveSession
| 8,697 |
import tensorflow as tf
# Target for Q value regression
q_backup = tf.stop_gradient(
self.rewards_ph +
(1 - self.terminals_ph) * self.gamma * self.value_target
)
# Compute Q-Function loss
# TODO: test with huber loss (it would avoid too high values)
qf1_loss = 0.5 * tf.reduce_mean(((q_backup - qf1) ** 2)*self.weight_ph)
qf1_loss_col = tf.reduce_mean(((q_backup - qf1) ** 2),1)
qf2_loss = 0.5 * tf.reduce_mean(((q_backup - qf2) ** 2)*self.weight_ph)
if self.n_step:
q_backup_n = tf.stop_gradient(
self.rewards_ph_n +
(1 - self.terminals_ph_n) *( self.gamma**self.n_step_length ) * self.value_target_n)
qf1_loss_n = 0.5 * tf.reduce_mean(((q_backup_n - qf1) ** 2)*self.weight_ph)
qf1_loss_n_col = tf.reduce_mean(((q_backup_n - qf1) ** 2),1)
qf2_loss_n = 0.5 * tf.reduce_mean(((q_backup_n - qf2) ** 2)*self.weight_ph)
|
tensorflow.reduce_mean
| 8,698 |
import tensorflow as tf
raise ValueError('Illegal dataset name')
tfrecord_writer = tf.python_io.TFRecordWriter(record_filename)
for filename in filenames:
with tf.gfile.Open(filename, 'r') as f:
data = cPickle.load(f)
images = data['data']
num_images = images.shape[0]
images = images.reshape((num_images, 3, 32, 32))
labels = data['labels']
with tf.Graph().as_default():
image_placeholder = tf.placeholder(dtype=tf.uint8)
encoded_image = tf.image.encode_png(image_placeholder)
with tf.Session('') as sess:
for j in range(num_images):
sys.stdout.write('\r>> Reading file [%s] image %d' % (
filename, offset + 1))
sys.stdout.flush()
if ('train' == name) and ( math.floor(offset / images_per_shard) > shard) :
tfrecord_writer.close()
shard = shard + 1
|
tensorflow.Graph
| 8,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.