seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
import tensorflow as tf
def add_forward_pass_and_gradients(
self, host_images, host_labels, nclass, phase_train, device_num,
input_data_type, data_type, input_nchan, use_synthetic_gpu_images,
gpu_copy_stage_ops, gpu_compute_stage_ops, gpu_grad_stage_ops):
"""Add ops for forward-pass and gradient computations."""
if not use_synthetic_gpu_images:
with tf.device(self.cpu_device):
images_shape = host_images.get_shape()
labels_shape = host_labels.get_shape()
gpu_copy_stage = data_flow_ops.StagingArea(
[tf.float32, tf.int32],
shapes=[images_shape, labels_shape])
| tensorflow.device | 13,300 |
import tensorflow as tf
trg_bucket_boundaries.append(minimal_multiple(trg_bucket_boundaries[-1] + 1, 8))
src_bucket_boundaries, trg_bucket_boundaries = dataset_utils.associated_bucket_boundaries(
src_bucket_boundaries, trg_bucket_boundaries)
src_bucket_boundaries = [x - num_extra_srctokens for x in src_bucket_boundaries]
bucket_boundaries = {
"feature": src_bucket_boundaries,
"label": trg_bucket_boundaries
}
bucket_batch_sizes = dataset_utils.adjust_batch_size(
batch_size,
bucket_boundaries=bucket_boundaries if args["batch_by_tokens"] else None,
boundaries_reduce_to_length_fn=lambda x: max(tf.nest.flatten(x)),
num_replicas_in_sync=num_replicas_in_sync)
if isinstance(bucket_batch_sizes, list):
bucket_batch_sizes = [
int(maximum_lower_multiple(x // num_replicas_in_sync, 8) * num_replicas_in_sync)
for x in bucket_batch_sizes]
else:
bucket_batch_sizes = int(maximum_lower_multiple(
bucket_batch_sizes // num_replicas_in_sync, 8) * num_replicas_in_sync)
return dataset_utils.batch_examples_by_token(
dataset,
| tensorflow.nest.flatten | 13,301 |
import tensorflow as tf
return input_fn
def _decode_tfrecord(self, record):
"""Decodes a record to a TensorFlow example."""
example = tf.parse_single_example(record, self._name_to_feature_config)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name, tensor in example.items():
if tensor.dtype == tf.int64:
example[name] = tf.cast(tensor, tf.int32)
else:
example[name] = tensor
return example
| tensorflow.cast | 13,302 |
import tensorflow as tf
y_t = tf.reshape(
tf.tile(tf.linspace(-1.0, 1.0, height), [width * depth]),
[depth, width, height])
y_t = tf.transpose(y_t, [0, 2, 1])
sample_grid = tf.tile(
tf.linspace(float(z_near), float(z_far), depth), [width * height])
z_t = tf.reshape(sample_grid, [height, width, depth])
z_t = tf.transpose(z_t, [2, 0, 1])
z_t = 1 / z_t
d_t = 1 / z_t
x_t /= z_t
y_t /= z_t
x_t_flat = tf.reshape(x_t, (1, -1))
y_t_flat = tf.reshape(y_t, (1, -1))
d_t_flat = tf.reshape(d_t, (1, -1))
ones = tf.ones_like(x_t_flat)
grid = tf.concat([d_t_flat, y_t_flat, x_t_flat, ones], 0)
return grid
def _transform(theta, input_dim, out_size, z_near, z_far):
with tf.variable_scope('_transform'):
num_batch = input_dim.get_shape().as_list()[0]
num_channels = input_dim.get_shape().as_list()[4]
theta = tf.reshape(theta, (-1, 4, 4))
theta = tf.cast(theta, 'float32')
| tensorflow.reshape | 13,303 |
import tensorflow as tf
tgt1, tgt2 = tf.split(tgt, 2, axis=0)
geq = tf.cast((tgt1 - tgt2) > 0, tf.bool)
tgt_larg = tf.where(geq, tgt1, tgt2)
tgt_small = tf.where(geq, tgt2, tgt1)
| tensorflow.where | 13,304 |
import tensorflow as tf
fnegtive_mask = tf.cast(negtive_mask, tf.float32)
n_negtives = tf.reduce_sum(fnegtive_mask)
n_neg_to_select = tf.cast(params['negative_ratio'] * n_positives, tf.int32)
n_neg_to_select = tf.minimum(n_neg_to_select, tf.cast(n_negtives, tf.int32))
# hard negative mining for classification
predictions_for_bg = tf.nn.softmax(cls_pred)[:, 0]
prob_for_negtives = tf.where(negtive_mask,
0. - predictions_for_bg,
# ignore all the positives
0. - tf.ones_like(predictions_for_bg))
topk_prob_for_bg, _ = tf.nn.top_k(prob_for_negtives, k=n_neg_to_select)
selected_neg_mask = prob_for_negtives > topk_prob_for_bg[-1]
| tensorflow.nn.softmax | 13,305 |
import tensorflow as tf
def __init__(self):
self.weights = {}
self.bn_epsilon = 1e-5 # Default used by Caffe
def build(self, weights_path="open_nsfw-weights.npy",
input_type=InputType.TENSOR):
self.weights = np.load(weights_path, encoding="latin1").item()
self.input_tensor = None
if input_type == InputType.TENSOR:
self.input = tf.placeholder(tf.float32,
shape=[None, 224, 224, 3],
name="input")
self.input_tensor = self.input
elif input_type == InputType.BASE64_JPEG:
from image_utils import load_base64_tensor
self.input = tf.placeholder(tf.string, shape=(None,), name="input")
self.input_tensor = load_base64_tensor(self.input)
else:
raise ValueError("invalid input type '{}'".format(input_type))
| tensorflow.placeholder | 13,306 |
import tensorflow as tf
@registry.register_model
class FeedForwardCnnSmallCategoricalPolicyNew(PolicyBase):
"""Small cnn network with categorical output."""
def body(self, features):
observations = features["inputs"]
x = tf.transpose(observations, [0, 2, 3, 1, 4])
x_shape = common_layers.shape_list(x)
x = tf.reshape(x, x_shape[:-2] + [-1])
dropout = getattr(self.hparams, "dropout_ppo", 0.0)
with tf.variable_scope("feed_forward_cnn_small"):
x = tf.cast(x, tf.float32) / 255.0
x = tf.nn.dropout(x, rate=dropout)
x = tf.layers.conv2d(
x, 32, (4, 4), strides=(2, 2), name="conv1",
activation=common_layers.belu, padding="SAME")
x = tf.nn.dropout(x, rate=dropout)
x = tf.layers.conv2d(
x, 64, (4, 4), strides=(2, 2), name="conv2",
activation=common_layers.belu, padding="SAME")
x = tf.nn.dropout(x, rate=dropout)
x = tf.layers.conv2d(
| tensorflow.cast | 13,307 |
import tensorflow.contrib.rnn as rnn
model.add(keras.layers.Dense(1))
model.compile(loss = 'mean_squared_error',
optimizer = 'adam',
metrics = ['mae', 'mape']) # mean absolute [percentage] error
return keras.estimator.model_to_estimator(model, model_dir=output_dir)
# Create the inference model
def simple_rnn(features, labels, mode):
# 0. Reformat input shape to become a sequence
x = tf.split(features[TIMESERIES_COL], N_INPUTS, 1)
# 1. Configure the RNN
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:
| tensorflow.contrib.rnn.static_rnn | 13,308 |
import tensorflow as tf
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')
| tensorflow.random_uniform | 13,309 |
from tensorflow.contrib.tensorboard.plugins import projector
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])
embedding.metadata_path = './metadata.tsv'
projector.visualize_embeddings(self.summary_writer, config)
sess.run(tf.variables_initializer([self.embedding_test], name='init_embeddings'))
# build sprite image
ut.images_to_sprite(self.test_set, path=os.path.join(FLAGS.logdir, 'sprite.png'))
ut.generate_tsv(len(self.test_set), tsv_path)
def _add_loss_summary(self, name, var, collection='train'):
if var is not None:
| tensorflow.contrib.tensorboard.plugins.projector.visualize_embeddings | 13,310 |
import tensorflow as tf
loss = weights * losses_utils.weighted_surrogate_loss(
labels,
logits + biases,
surrogate_type=surrogate_type,
positive_weights=1.0 + lambdas * (1.0 - precision_values),
negative_weights=lambdas * precision_values)
maybe_log2 = tf.log(2.0) if surrogate_type == 'xent' else 1.0
maybe_log2 = tf.cast(maybe_log2, logits.dtype.base_dtype)
lambda_term = lambdas * (1.0 - precision_values) * label_priors * maybe_log2
per_anchor_loss = loss - lambda_term
per_label_loss = delta * tf.reduce_sum(per_anchor_loss, 2)
# Normalize the AUC such that a perfect score function will have AUC 1.0.
# Because precision_range is discretized into num_anchors + 1 intervals
# but only num_anchors terms are included in the Riemann sum, the
| tensorflow.cast | 13,311 |
import tensorflow as tf
"""Turn x_bit representing numbers bitwise (lower-endian) to int tensor.
Args:
x_bit: Tensor containing numbers in a particular base to be
converted to
int.
num_bits: Number of bits in the representation.
base: Base of the representation.
Returns:
Integer representation of this number.
"""
x_l = tf.stop_gradient(tf.to_int32(tf.reshape(x_bit, [-1, num_bits])))
x_labels = []
for i in range(num_bits):
x_labels.append(x_l[:, i] * tf.to_int32(base)**tf.to_int32(i))
res = sum(x_labels)
return tf.to_int32(tf.reshape(res, common_layers.shape_list(x_bit)[:-1]))
def int_to_bit(self, x_int, num_bits, base=2):
"""Turn x_int representing numbers into a bitwise (lower-endian) tensor.
Args:
x_int: Tensor containing integer to be converted into base
notation.
num_bits: Number of bits in the representation.
base: Base of the representation.
Returns:
Corresponding number expressed in base.
| tensorflow.to_int32 | 13,312 |
import tensorflow as tf
masked_lm_log_probs = tf.reshape(
masked_lm_log_probs, [-1, masked_lm_log_probs.shape[-1]]
)
masked_lm_predictions = tf.argmax(
masked_lm_log_probs, axis=-1, output_type=tf.int32
)
masked_lm_example_loss = tf.reshape(masked_lm_example_loss, [-1])
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,
predictions=masked_lm_predictions,
weights=masked_lm_weights,
)
masked_lm_mean_loss = tf.metrics.mean(
values=masked_lm_example_loss, weights=masked_lm_weights
)
| tensorflow.metrics.accuracy | 13,313 |
import tensorflow as tf
)
elif mode == tf.estimator.ModeKeys.EVAL:
def metric_fn(per_example_loss, label_ids, logits, is_real_example):
# predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)
# ones=tf.get_variable('ones',shape=logits.shape,initializer=tf.ones_initializer)
# zeros=tf.get_variable('zeros',shape=logits.shape,initializer=tf.zeros_initializer)
predictions=tf.where(logits>=0,tf.ones(tf.shape(logits)),tf.zeros(tf.shape(logits)))
accuracy = tf.metrics.accuracy(
labels=label_ids, predictions=predictions, weights=is_real_example)
loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example)
return {
"eval_accuracy": accuracy,
"eval_loss": loss,
}
eval_metrics = (metric_fn,
[per_example_loss, label_ids, logits, is_real_example])
output_spec = tf.estimator.EstimatorSpec(
mode=mode,
| tensorflow.metrics.mean | 13,314 |
import tensorflow as tf
if ent_coef_loss is not None:
with tf.control_dependencies([train_values_op]):
| tensorflow.control_dependencies | 13,315 |
import tensorflow as tf
def hparams(self, defaults, unused_model_hparams):
(super(QuestionAndContext2TextProblem, self)
.hparams(defaults, unused_model_hparams))
p = defaults
source_vocab_size = self._encoders["context"].vocab_size
p.input_modality["context"] = (registry.Modalities.SYMBOL,
source_vocab_size)
if self.packed_length:
raise NotImplementedError("QuestionAndContext2Text does not "
"support packed_length")
def example_reading_spec(self):
data_fields, data_items_to_decoders = (super(QuestionAndContext2TextProblem,
self)
.example_reading_spec())
data_fields["context"] = tf.VarLenFeature(tf.int64)
return (data_fields, data_items_to_decoders)
class Text2SelfProblem(Text2TextProblem):
"""Language modeling problems base class.
See Text2TextProblem for subclass interface.
"""
def generate_samples(self, data_dir, tmp_dir, dataset_split):
"""Generate samples of text.
Args:
data_dir: final data directory. Typically only used in this method to copy
| tensorflow.VarLenFeature | 13,316 |
import tensorflow as tf
head_embed_row = tf.expand_dims(head_embed, 1) # embeddings as row vectors
tail_embed_col = tf.expand_dims(tail_embed, 2) # embeddings as column vectors
head_rel_mult = tf.batch_matmul(head_embed_row, rel_embed_square)
# Output needs a squeeze into a 1d vector
| tensorflow.batch_matmul | 13,317 |
import tensorflow as tf
self.observations_ph = self.policy_tf.obs_ph
# Normalized observation for pixels
self.processed_obs_ph = self.policy_tf.processed_obs
self.next_observations_ph = self.target_policy.obs_ph
self.processed_next_obs_ph = self.target_policy.processed_obs
self.action_target = self.target_policy.action_ph
self.terminals_ph = tf.placeholder(tf.float32, shape=(None, 1), name='terminals')
self.rewards_ph = tf.placeholder(tf.float32, shape=(None, 1), name='rewards')
self.is_demo_ph = tf.placeholder(tf.float32, shape=(None, 1), name='is_demonstrations')
self.weight_ph = tf.placeholder(tf.float32, shape=(None, 1), name='importance_weight')
self.actions_ph = tf.placeholder(tf.float32, shape=(None,) + self.action_space.shape,
name='actions')
self.learning_rate_ph = tf.placeholder(tf.float32, [], name="learning_rate_ph")
if self.n_step:
self.next_observations_ph_n = self.target_policy.obs_ph
self.processed_next_obs_ph_n = self.target_policy.processed_obs
self.rewards_ph_n = tf.placeholder(tf.float32, shape=(None, 1), name='n_step_rewards')
self.terminals_ph_n = tf.placeholder(tf.float32, shape=(None, 1), name='n_step_terminals')
| tensorflow.placeholder | 13,318 |
import tensorflow as tf
else:
out = tf.nn.max_pool3d(bottom, ksize=[1,1, FLAGS.pool_kernel, FLAGS.pool_kernel,1], strides=[1,1,FLAGS.pool_stride,FLAGS.pool_stride,1], padding='VALID')
shape = out.get_shape()
print('pool{}'.format(l + 1))
print('\t{} --> {}'.format(bottom.name, out.name))
print('\t{} --> {}'.format(bottom.get_shape(), out.get_shape()))
with tf.variable_scope('scale'):
bottom = out
if FLAGS.pm[l + 1] == FLAGS.pm[l]:
kernel_size = 1 # useless 1x1 pooling
elif int(FLAGS.pm[l + 1]) < int(FLAGS.pm[l]):
num_scales_prev = int(FLAGS.pm[l])
| tensorflow.variable_scope | 13,319 |
import tensorflow as tf
self.g = tf.get_variable('g',[output_dim],
initializer=tf.constant_initializer(float('nan')))
self.b = tf.get_variable('b',[output_dim],
initializer=tf.constant_initializer(float('nan')))
self.epsilon = epsilon
def __call__(self,input_var,name=None,**kwargs) :
if( input_var.shape.ndims > 2 ) :
dims = tf.reduce_prod(tf.shape(input_var)[1:])
input_var = tf.reshape(input_var,[-1,dims])
def _init():
v_norm = tf.nn.l2_normalize(self.v,axis=0)
t = tf.matmul(input_var,v_norm)
mu,var = tf.nn.moments(t,axes=[0])
std = tf.sqrt(var+self.epsilon)
return [tf.assign(self.g,1/std),tf.assign(self.b,-1.*mu/std)]
| tensorflow.reshape | 13,320 |
import tensorflow as tf
self.scope = scope
def __call__(self,input_var,is_training,**xargs) :
with tf.variable_scope(self.scope) :
return tf.layers.batch_normalization(
input_var,
| tensorflow.variable_scope | 13,321 |
import tensorflow as tf
ys = tf.placeholder(tf.float32, [None, 1], name='y_input') # 同上
# add hidden layer
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu,nameScope="layerTest1")
# add output layer
prediction = add_layer(l1, 10, 1, activation_function=None,nameScope="layerTest2")
sess = tf.Session()
# 上面的wtih或者是name都是可选的,可以选择添加,也可以选择不添加,but下面的这一行是一定要写的。
# 这个表明了 在当前的目录下面创建以恶搞logs的文件家,然后把图的信息保存进去
# 这样运行完这段代码之后,就会有一个logs的文件夹被创建
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)
else: # tensorflow version >= 0.12
writer = tf.summary.FileWriter("logs/", sess.graph)
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
init = tf.initialize_all_variables()
else:
init = tf.global_variables_initializer()
sess.run(init) | tensorflow.__version__.split | 13,322 |
import tensorflow as tf
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
meta_graph_def = slice_saver.export_meta_graph(filename)
with tf.Graph().as_default():
# Restores from MetaGraphDef.
new_saver = tf.train.import_meta_graph(filename)
# Generates a new MetaGraphDef.
new_meta_graph_def = new_saver.export_meta_graph()
# It should be the same as the original.
self.assertProtoEquals(meta_graph_def, new_meta_graph_def)
def _testGraphExtensionSave(self):
test_dir = self._TestDir("graph_extension")
filename = os.path.join(test_dir, "metafile")
saver0_ckpt = os.path.join(test_dir, "saver0.ckpt")
with self.test_session(graph=tf.Graph()) as sess:
| tensorflow.Graph | 13,323 |
import tensorflow as tf
with tf.variable_scope(scope):
input_dims = input_data.get_shape().as_list()
if len(input_dims) == 4:
_, input_h, input_w, num_channels = input_dims
in_dim = input_h * input_w * num_channels
flat_input = tf.reshape(input_data, [-1, in_dim])
else:
in_dim = input_dims[-1]
flat_input = input_data
if initial_value is None:
| tensorflow.reshape | 13,324 |
import tensorflow as tf
h_params = np.apply_along_axis(
gaussianization.compute_tukey_hh_params, 0, l_skewness_and_kurtosis)
hh_l_mean, hh_l_scale = gaussianization.tukey_hh_l_mean_and_scale(h_params)
scale = np.true_divide(accumulator.l2, hh_l_scale,
where=valid_scale, out=np.ones_like(accumulator.l2))
loc = accumulator.l1 - scale * hh_l_mean
hl = h_params[0, ...]
hr = h_params[1, ...]
return [self._output_numpy_dtype(x) for x in [loc, scale, hl, hr]]
def output_tensor_infos(self):
# The output is (loc, scale, hl, hr).
return [
analyzer_nodes.TensorInfo(
tf.as_dtype(self._output_numpy_dtype), self._output_shape, None)
] * 4
@property
def accumulator_coder(self):
# TODO(b/170510451): Re-enable caching for this Combiner.
return None
def _combine_accumulators(self, a, b):
"""Combines two accumulators.
Args:
a: A _LMomentsAccumulator.
b: A _LMomentsAccumulator.
| tensorflow.as_dtype | 13,325 |
import tensorflow as tf
self.block3_4 = self.res_block_3_layers(self.block3_3, [256, 256, 1024], "res4d")# 14*14
self.block3_5 = self.res_block_3_layers(self.block3_4, [256, 256, 1024], "res4e")# 14*14
self.block3_6 = self.res_block_3_layers(self.block3_5, [256, 256, 1024], "res4f")# 14*14
#[None 7 7 512]
self.pool4 = self.max_pool(self.block3_6, 2, 2, "pool4")# 14*14
self.block4_1 = self.res_block_3_layers(self.pool4, [512, 512, 2048], "res5a", True)# 7*7
self.block4_2 = self.res_block_3_layers(self.block4_1, [512, 512, 2048], "res5b")# 7*7
self.block4_3 = self.res_block_3_layers(self.block4_2, [512, 512, 2048], "res5c")# 7*7
# upsample layer begins
self.deconv_1 = self.deconv_bn_relu(self.block4_3, name = 'deconv_1',kernel_size = 3, output_channels = 1024,
initializer = tf.contrib.layers.variance_scaling_initializer(), stride=2, bn=True, training=self.is_training)# 14*14
self.deconv_2 = self.deconv_bn_relu(self.deconv_1, name = 'deconv_2',kernel_size = 3, output_channels = 512,
initializer = tf.contrib.layers.variance_scaling_initializer(), stride=2, bn=True, training=self.is_training)# 28*28
self.deconv_3 = self.deconv_bn_relu(self.deconv_2, name = 'deconv_3',kernel_size = 3, output_channels = 256,
initializer = tf.contrib.layers.variance_scaling_initializer(), stride=2, bn=True, training=self.is_training)# 56*56
self.deconv_4 = self.deconv_bn_relu(self.deconv_3, name = 'deconv_4',kernel_size = 3, output_channels = 128,
initializer =tf.contrib.layers.variance_scaling_initializer(), stride=2, bn=True, training=self.is_training)# 112*112
self.deconv_5 = self.deconv_bn_relu(self.deconv_4, name = 'deconv_5',kernel_size = 3, output_channels = 64,
initializer =tf.contrib.layers.variance_scaling_initializer(), stride=2, bn=True, training=self.is_training)# 224*224
# self.final_layer = self.conv_layer(bottom = self.deconv_5, kernal_size = 1, in_channels = 64, out_channels = 3, stride = 1, name = 'final_layer')
self.final_layer = self.conv_bn_relu(bottom = self.deconv_5, name = 'final_layer', kernel_size = 1, output_channels = 3, initializer =tf.contrib.layers.variance_scaling_initializer(), bn = False, training = self.is_training, relu=False)
# self.pool5 = self.avg_pool(self.block4_3, 7, 1, "pool5")
#self.fc0 = self.fc_layer(self.pool5, 2048, 1024, "fc0")
| tensorflow.contrib.layers.variance_scaling_initializer | 13,326 |
import tensorflow as tf
if self.config.fix_pretrained_vector:
dc = self.char_mat.get_shape()[-1]
with tf.variable_scope("Model_Encoder_Layer"):
inputs = tf.concat(self.attention_outputs, axis=-1)
self.enc = [conv(inputs, d, name="input_projection")]
for i in range(3):
| tensorflow.concat | 13,327 |
import tensorflow as tf
def din_fcn_attention(query, facts, attention_size, mask, stag='null', mode='SUM', softmax_stag=1, time_major=False, return_alphas=False, forCnn=False):
if isinstance(facts, tuple):
# In case of Bi-RNN, concatenate the forward and the backward RNN outputs.
facts = tf.concat(facts, 2)
if len(facts.get_shape().as_list()) == 2:
facts = tf.expand_dims(facts, 1)
if time_major:
# (T,B,D) => (B,T,D)
facts = tf.array_ops.transpose(facts, [1, 0, 2])
# Trainable parameters
mask = tf.equal(mask, tf.ones_like(mask))
facts_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer
querry_size = query.get_shape().as_list()[-1]
query = tf.layers.dense(query, facts_size, activation=None, name='f1' + stag)
query = prelu(query)
queries = tf.tile(query, [1, tf.shape(facts)[1]])
queries = tf.reshape(queries, tf.shape(facts))
din_all = tf.concat([queries, facts, queries-facts, queries*facts], axis=-1)
| tensorflow.array_ops.transpose | 13,328 |
from tensorflow.core.protobuf import queue_runner_pb2
tf.initialize_all_variables()
# Creates a saver.
save = tf.train.Saver({"v0": v0})
# Adds a set of collections.
tf.add_to_collection("int_collection", 3)
tf.add_to_collection("float_collection", 3.5)
tf.add_to_collection("string_collection", "hello")
tf.add_to_collection("variable_collection", v0)
# Add QueueRunners.
tf.train.add_queue_runner(qr)
# Adds user_defined proto in three formats: string, bytes and Any.
queue_runner = queue_runner_pb2.QueueRunnerDef(queue_name="test_queue")
tf.add_to_collection("user_defined_string_collection", str(queue_runner))
tf.add_to_collection("user_defined_bytes_collection",
queue_runner.SerializeToString())
any_buf = Any()
any_buf.Pack(queue_runner)
tf.add_to_collection("user_defined_any_collection", any_buf)
# Generates MetaGraphDef.
meta_graph_def = save.export_meta_graph(filename)
self.assertTrue(meta_graph_def.HasField("saver_def"))
| tensorflow.core.protobuf.queue_runner_pb2.QueueRunnerDef | 13,329 |
import tensorflow as tf
for i, k in zip(inputs, kernels)]
conv = tf.concat(outputs, channel_axis)
ret = tf.identity(tf.nn.bias_add(conv, b, data_format=data_format)
if use_bias else conv, name=name)
| tensorflow.nn.bias_add | 13,330 |
import tensorflow as tf
# Create summary writer
self.summary_writer = tf.summary.FileWriter(self.args.summary_dir, self.sess.graph)
| tensorflow.summary.FileWriter | 13,331 |
import tensorflow as tf
# additional configs required for using TPUs
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(args.tpu)
tpu_config = tf.contrib.tpu.TPUConfig(
num_shards=8, # using Cloud TPU v2-8
| tensorflow.contrib.tpu.TPUConfig | 13,332 |
import tensorflow as tf
with argscope([Conv2D, FullyConnected], nl=tf.nn.relu):
with tf.variable_scope('STN1'):
sampled1 = get_stn(image)
with tf.variable_scope('STN2'):
sampled2 = get_stn(image)
# For visualization in tensorboard
with tf.name_scope('visualization'):
padded1 = tf.pad(sampled1, [[0, 0], [HALF_DIFF, HALF_DIFF], [HALF_DIFF, HALF_DIFF], [0, 0]])
padded2 = tf.pad(sampled2, [[0, 0], [HALF_DIFF, HALF_DIFF], [HALF_DIFF, HALF_DIFF], [0, 0]])
img_orig = tf.concat([image[:, :, :, 0], image[:, :, :, 1]], 1) # b x 2h x w
transform1 = tf.concat([padded1[:, :, :, 0], padded1[:, :, :, 1]], 1)
transform2 = tf.concat([padded2[:, :, :, 0], padded2[:, :, :, 1]], 1)
stacked = tf.concat([img_orig, transform1, transform2], 2, 'viz')
tf.summary.image('visualize',
tf.expand_dims(stacked, -1), max_outputs=30)
sampled = tf.concat([sampled1, sampled2], 3, 'sampled_concat')
logits = (LinearWrap(sampled)
.FullyConnected('fc1', out_dim=256, nl=tf.nn.relu)
.FullyConnected('fc2', out_dim=128, nl=tf.nn.relu)
.FullyConnected('fct', out_dim=19, nl=tf.identity)())
tf.nn.softmax(logits, name='prob')
| tensorflow.concat | 13,333 |
import tensorflow as tf
train=False,
validation=FLAGS.validation,
shuffle=True)
def placeholder_like(x, name=None):
return tf.placeholder(shape=x.shape, dtype=tf.float32, name=name)
def random_sphere(shape):
n = tf.random_normal(shape=shape, dtype=tf.float32)
n = tf.reshape(n, shape=(int(shape[0]), -1))
n = tf.nn.l2_normalize(n, dim=1)
n = tf.reshape(n, shape)
return n
def random_sphere_numpy(shape):
n = np.random.normal(size=shape)
proj_shape = tuple([n.shape[0]] + [1 for _ in range(len(shape) - 1)])
return n / np.linalg.norm(n.reshape((n.shape[0], -1)), axis=1).reshape(proj_shape)
print(ul_images.shape)
| tensorflow.nn.l2_normalize | 13,334 |
import tensorflow as tf
c, h = tf.split(axis=1, num_or_size_splits=2, value=s)
for idx, (x, m) in enumerate(zip(xs, ms)):
c = c*(1-m)
h = h*(1-m)
z = tf.matmul(x, wx) + tf.matmul(h, wh) + b
i, f, o, u = tf.split(axis=1, num_or_size_splits=4, value=z)
i = tf.nn.sigmoid(i)
f = tf.nn.sigmoid(f)
o = tf.nn.sigmoid(o)
u = tf.tanh(u)
c = f*c + i*u
h = o*tf.tanh(c)
xs[idx] = h
s = tf.concat(axis=1, values=[c, h])
return xs, s
def _ln(x, g, b, e=1e-5, axes=[1]):
u, s = tf.nn.moments(x, axes=axes, keep_dims=True)
| tensorflow.tanh | 13,335 |
import tensorflow as tf
status2 = False
if status2:
a = 1
values = interpolated
inter = tf.reshape(values, [self.resolution,
self.resolution,
self.resolution])
inter = tf.transpose(tf.reduce_max(inter, axis=a))
im = axs[fig_obj_count, 0].matshow(inter.numpy())
plt.colorbar(im, ax=axs[fig_obj_count, 0])
values = tf.math.sign(tf.nn.relu(interpolated + self.tol))
inter = tf.reshape(values, [self.resolution,
self.resolution,
self.resolution])
inter = tf.transpose(tf.reduce_max(inter, axis=a))
im = axs[fig_obj_count, 1].matshow(inter.numpy())
plt.colorbar(im, ax=axs[fig_obj_count, 1])
values = sdf_values
inter = tf.reshape(values, [self.resolution,
self.resolution,
| tensorflow.nn.relu | 13,336 |
from tensorflow.contrib.framework import deprecated_args
with ops.control_dependencies([true_positives_update_op,
false_positives_update_op]):
update_op = compute_precision('update_op')
if metrics_collections:
ops.add_to_collections(metrics_collections, precision)
if updates_collections:
ops.add_to_collections(updates_collections, update_op)
return precision, update_op
@deprecated_args(IGNORE_MASK_DATE, IGNORE_MASK_INSTRUCTIONS, 'ignore_mask')
def streaming_recall(predictions, labels, ignore_mask=None, weights=None,
metrics_collections=None, updates_collections=None,
name=None):
"""Computes the recall of the predictions with respect to the labels.
The `streaming_recall` function creates two local variables, `true_positives`
and `false_negatives`, that are used to compute the recall. This value is
ultimately returned as `recall`, an idempotent operation that simply divides
`true_positives` by the sum of `true_positives` and `false_negatives`.
For estimation of the metric over a stream of data, the function creates an
`update_op` that updates these variables and returns the `recall`. `update_op`
| tensorflow.contrib.framework.deprecated_args | 13,337 |
import tensorflow as tf
constructing a BidirectionalLanguageModel.
'''
with open(options_file, 'r') as fin:
options = json.load(fin)
max_word_length = options['char_cnn']['max_characters_per_token']
vocab = UnicodeCharsVocabulary(vocab_file, max_word_length)
batcher = Batcher(vocab_file, max_word_length)
ids_placeholder = tf.placeholder('int32',
shape=(None, None, max_word_length)
)
model = BidirectionalLanguageModel(options_file, weight_file)
embedding_op = model(ids_placeholder)['token_embeddings']
n_tokens = vocab.size
embed_dim = int(embedding_op.shape[2])
| tensorflow.placeholder | 13,338 |
import tensorflow as tf
:return [Tensor] [N, H', W', C]. Convolution results.
"""
blk_shape = tf.shape(blk_indices)
blk_indices_ = tf.reshape(blk_indices, [-1, 3])
ksize = tf.shape(w)
| tensorflow.reshape | 13,339 |
import tensorflow as tf
class CovCopyAttenGen:
def __init__(self, placeholders, options, vocab):
self.options = options
self.vocab = vocab
self.cell = tf.contrib.rnn.LSTMCell(
options.gen_hidden_size,
initializer=tf.random_uniform_initializer(-0.1, 0.1, seed=113),
state_is_tuple=True)
self.placeholders = placeholders
with tf.variable_scope("embedding"), tf.device('/cpu:0'):
self.embedding = tf.get_variable('word_embedding', trainable=(options.fix_word_vec==False),
initializer=tf.constant(self.vocab.word_vecs), dtype=tf.float32)
| tensorflow.random_uniform_initializer | 13,340 |
from tensorflow.python.platform import gfile
s3 = save.save(sess, os.path.join(save_dir, "s3"))
self.assertEqual([s2, s3], save.last_checkpoints)
self.assertEqual(0, len(gfile.Glob(s1)))
self.assertFalse(gfile.Exists(save._MetaGraphFilename(s1)))
self.assertEqual(2, len(gfile.Glob(s2)))
| tensorflow.python.platform.gfile.Glob | 13,341 |
import tensorflow as tf
[rpn_cls_prob, rpn_bbox_pred, self._im_info, self._mode,
self._feat_stride, self._anchors, self._num_anchors],
[tf.float32, tf.float32])
rois.set_shape([None, 5])
rpn_scores.set_shape([None, 1])
return rois, rpn_scores
def _crop_pool_layer(self, bottom, rois, name):
with tf.variable_scope(name):
# tf.squeeze()返回一个张量,这个张量是将原始input中所有维度中为1的那些维都删掉的结果
batch_ids = tf.squeeze(tf.slice(rois, [0, 0], [-1, 1], name="batch_id"), [1])
# Get the normalized coordinates of bboxes
bottom_shape = tf.shape(bottom)
height = (tf.to_float(bottom_shape[1]) - 1.) * np.float32(self._feat_stride[0])
width = (tf.to_float(bottom_shape[2]) - 1.) * np.float32(self._feat_stride[0])
# rois除以h,w就得到了rois在特征图上的位置
x1 = tf.slice(rois, [0, 1], [-1, 1], name="x1") / width
y1 = tf.slice(rois, [0, 2], [-1, 1], name="y1") / height
x2 = tf.slice(rois, [0, 3], [-1, 1], name="x2") / width
y2 = tf.slice(rois, [0, 4], [-1, 1], name="y2") / height
# Won't be backpropagated to rois anyway, but to save time
bboxes = tf.stop_gradient(tf.concat([y1, x1, y2, x2], axis=1))
# 'roi_pooling_size', 7
pre_pool_size = cfg.FLAGS.roi_pooling_size * 2
# 把rois对于的特征图上的部分crop出来,然后resize打破14*14的大小
crops = tf.image.crop_and_resize(bottom, bboxes, tf.to_int32(batch_ids), [pre_pool_size, pre_pool_size], name="crops")
return slim.max_pool2d(crops, [2, 2], padding='SAME')
| tensorflow.to_float | 13,342 |
import tensorflow as tf
# # pyram_3x3_4 = self.conv('_atr_3x3_3', net, depth/2, size=3, stride=1, padding="SAME", dilation=rate[2])
# net = tf.concat((pyram_1x1_0, pyram_3x3_1, pyram_3x3_2, pyram_3x3_3), axis=3, name="concat")
# net = self.conv('_1x1_output', net, depth, size=1, stride=1, padding="SAME")
return net
with tf.variable_scope('discriminator') as scope:
if reuse:
scope.reuse_variables()
print('D in:', X.get_shape().as_list())
rate = [2, 3, 4]
X = atrous_convs(X, "d_atrous_0", rate = rate, depth=256, reuse=reuse)
| tensorflow.variable_scope | 13,343 |
import tensorflow as tf
def lnlstm(xs, ms, s, scope, nh, init_scale=1.0):
nbatch, nin = [v.value for v in xs[0].get_shape()]
with tf.variable_scope(scope):
wx = tf.get_variable("wx", [nin, nh*4], initializer=ortho_init(init_scale))
gx = tf.get_variable("gx", [nh*4], initializer=tf.constant_initializer(1.0))
bx = tf.get_variable("bx", [nh*4], initializer=tf.constant_initializer(0.0))
wh = tf.get_variable("wh", [nh, nh*4], initializer=ortho_init(init_scale))
gh = tf.get_variable("gh", [nh*4], initializer=tf.constant_initializer(1.0))
bh = tf.get_variable("bh", [nh*4], initializer=tf.constant_initializer(0.0))
b = tf.get_variable("b", [nh*4], initializer=tf.constant_initializer(0.0))
gc = tf.get_variable("gc", [nh], initializer=tf.constant_initializer(1.0))
bc = tf.get_variable("bc", [nh], initializer=tf.constant_initializer(0.0))
| tensorflow.constant_initializer | 13,344 |
import tensorflow as tf
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(
tf.greater_equal(global_step, FLAGS.first_pretrain_steps), tf.float32)
loss = src_loss * tf.stop_gradient(loss_weights) * enable_pretrain
loss += dst_loss + l2_loss
return tf.identity(loss), src_loss, dst_loss
def train_model_fn(features, labels, mode, params): # pylint: disable=unused-argument
"""Defines the model function."""
target_num_classes = FLAGS.target_num_classes
global_step = tf.train.get_global_step()
src_features, src_labels = features['src'], tf.cast(labels['src'], tf.int64)
finetune_features = features['finetune']
target_features = features['target']
num_classes = FLAGS.src_num_classes
| tensorflow.identity | 13,345 |
import tensorflow as tf
self.EPOCHS = 8
self.EPSILON = 0.2
self.EPS_LEN = 100000
# GPU setup
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False, device_count={'GPU': gpu})
config.gpu_options.allow_growth = True
config.gpu_options.per_process_gpu_memory_fraction = 0.5
# Placeholders
self.sess = tf.Session(config=config)
self.s_dim, self.a_dim = env.observation_space.shape, env.action_space.shape[0]
self.a_bound = (env.action_space.high - env.action_space.low) / 2
self.actions = tf.placeholder(tf.float32, [None, self.a_dim], 'action')
self.state = tf.placeholder(tf.float32, [None, self.s_dim[0]], 'state')
self.advantage = tf.placeholder(tf.float32, [None, 1], 'advantage')
self.rewards = tf.placeholder(tf.float32, [None, 1], 'discounted_r')
# Dateset with experiennce replay
self.dataset = tf.data.Dataset.from_tensor_slices({'state': self.state, 'actions': self.actions,
| tensorflow.Session | 13,346 |
import tensorflow as tf
def testPostProcessImageTrainMode(self, likelihood, num_mixtures, depth):
batch = 1
rows = 8
cols = 24
hparams = tf.contrib.training.HParams(
hidden_size=2,
likelihood=likelihood,
mode=tf.estimator.ModeKeys.TRAIN,
num_mixtures=num_mixtures,
)
inputs = tf.random_uniform([batch, rows, cols, hparams.hidden_size],
minval=-1., maxval=1.)
outputs = common_image_attention.postprocess_image(
inputs, rows, cols, hparams)
self.assertEqual(outputs.shape, (batch, rows, cols, depth))
@parameterized.parameters(
(common_image_attention.DistributionType.DMOL, 5, 50),
(common_image_attention.DistributionType.CAT, None, 256),
)
| tensorflow.random_uniform | 13,347 |
import tensorflow as tf
test_image_batch,test_label_batch=get_test_batch(test_image,test_label,testnum)
test_inf=work.test_inference(test_image_batch)
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)
| tensorflow.argmax | 13,348 |
import tensorflow as tf
pred_annotation, logits = inference(image, keep_probability)
tf.summary.image("input_image", image, max_outputs=2)
| tensorflow.summary.image | 13,349 |
import tensorflow as tf
Returns:
A tf.data.Dataset.
"""
if args is None:
args = self._args
else:
args = deep_merge_dict(self._args, args, local_overwrite=False)
eos = tf.constant(self._multilingual_dp.meta["eos_id"], dtype=tf.int64)
int_zero = tf.zeros([], dtype=tf.int64)
dataset = ds.build(map_func=self.get_data_preprocess_fn(mode, ds.status, args),
map_output_dtypes=self.inputs_signature(mode)[0],
auto_shard=(mode == compat.ModeKeys.TRAIN),
shuffle=(mode == compat.ModeKeys.TRAIN))
if mode == compat.ModeKeys.INFER:
logging.info("Creating test dataset.")
| tensorflow.zeros | 13,350 |
import tensorflow as tf
dtype = initial_learning_rate.dtype
maximal_learning_rate = tf.cast(self.maximal_learning_rate, dtype)
step_size = tf.cast(self.step_size, dtype)
cycle = tf.floor(1 + step / (2 * step_size))
x = tf.abs(step / step_size - 2 * cycle + 1)
| tensorflow.floor | 13,351 |
import tensorflow as tf
return Y
def fwd_gradients_0(self, U, x):
g = tf.gradients(U, x, grad_ys=self.dummy_x0_tf)[0]
return tf.gradients(g, self.dummy_x0_tf)[0]
def fwd_gradients_1(self, U, x):
g = tf.gradients(U, x, grad_ys=self.dummy_x1_tf)[0]
return tf.gradients(g, self.dummy_x1_tf)[0]
def net_U0(self, x):
lambda_1 = self.lambda_1
lambda_2 = tf.exp(self.lambda_2)
U = self.neural_net(x, self.weights, self.biases)
U_x = self.fwd_gradients_0(U, x)
U_xx = self.fwd_gradients_0(U_x, x)
U_xxx = self.fwd_gradients_0(U_xx, x)
F = -lambda_1*U*U_x - lambda_2*U_xxx
U0 = U - self.dt*tf.matmul(F, self.IRK_alpha.T)
return U0
def net_U1(self, x):
lambda_1 = self.lambda_1
lambda_2 = tf.exp(self.lambda_2)
| tensorflow.exp | 13,352 |
import tensorflow as tf
return e / tf.clip_by_value(tf.reduce_sum(e, axis=dim, keep_dims=True), 10e-37, 10e+37)
def sequence_loss(logits, targets, weights, average_across_timesteps=False, average_across_batch=True, rewards=None):
batch_size = tf.shape(targets)[0]
time_steps = tf.shape(targets)[1]
logits_ = tf.reshape(logits, tf.stack([time_steps * batch_size, logits.get_shape()[2].value]))
targets_ = tf.reshape(targets, tf.stack([time_steps * batch_size]))
crossent = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits_, labels=targets_)
crossent = tf.reshape(crossent, tf.stack([batch_size, time_steps]))
if rewards is not None:
crossent *= tf.stop_gradient(rewards)
log_perp = tf.reduce_sum(crossent * 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
| tensorflow.nn.sparse_softmax_cross_entropy_with_logits | 13,353 |
import tensorflow as tf
# nwords = tf.feature_column.input_layer({'words_len': raw_nwords}, params['words_len_feature_columns'])
# nwords = tf.reshape(nwords, [-1])
# nwords = tf.to_int32(nwords)
# words = features['words']
# words = tf.convert_to_tensor(words)
#
# nwords = features['words_len']
# nwords = tf.convert_to_tensor(nwords)
nwords = tf.identity(self.features["words_len"], name="input_words_len")
# get tag info
# with Path(self.params['tags']).open() as f:
indices = [
idx
for idx, tag in enumerate(self.params["tags_data"])
if tag.strip() != "O"
]
num_tags = len(indices) + 1
| tensorflow.identity | 13,354 |
import tensorflow as tf
self.model_W = tf.get_variable("{}_W".format(name), initializer=kernel_initializer([n_in, n_out])) # variational parameters
self.model_b = tf.get_variable("{}_b".format(name), initializer=tf.zeros([n_out]))
| tensorflow.zeros | 13,355 |
import tensorflow as tf
# reconstructions
with tf.name_scope('decodings'):
| tensorflow.name_scope | 13,356 |
import tensorflow as tf
outputs = [
f(tf.constant([[1, 3]]), tf.constant([2])),
f(tf.constant([[1, 3]]), tf.constant([2]))
| tensorflow.constant | 13,357 |
import tensorflow as tf
with self.assertRaisesRegexp(ValueError, "same name: v1"):
tf.train.Saver([v0, v1, v2])
# The names are different and will work.
tf.train.Saver({"vee1": v1, "other": [v2]})
def testBasicsWithListOfVariables(self):
save_path = os.path.join(self.get_temp_dir(), "basics_with_list")
with self.test_session(graph=tf.Graph()) as sess:
# Build a graph with 2 parameter nodes, and Save and
# Restore nodes for them.
v0 = tf.Variable(10.0, name="v0")
v1 = tf.Variable(20.0, name="v1")
save = tf.train.Saver([v0, v1])
tf.initialize_all_variables().run()
# Check that the parameter nodes have been initialized.
self.assertEqual(10.0, v0.eval())
self.assertEqual(20.0, v1.eval())
# Save the initialized values in the file at "save_path"
val = save.save(sess, save_path)
self.assertTrue(isinstance(val, six.string_types))
| tensorflow.Variable | 13,358 |
import tensorflow as tf
outputs = tf.nn.relu(tf.layers.batch_normalization(outputs, training=is_training))
return outputs
class Model:
def __init__(self, num_layers, size_layers, learning_rate=1e-3, dropout=1.0):
self.X = tf.placeholder(tf.int32, (None, None))
self.training = tf.placeholder(tf.bool, None)
lookup_table = tf.get_variable(
"lookup_table",
dtype=tf.float32,
shape=[len(vocab), size_layers],
initializer=tf.truncated_normal_initializer(mean=0.0, stddev=0.01),
)
lookup_table = tf.concat((tf.zeros(shape=[1, size_layers]), lookup_table[1:, :]), 0)
forward = tf.nn.embedding_lookup(lookup_table, self.X)
self.Y = tf.placeholder(tf.float32, (None, None, n_mels * resampled))
self.decoder_inputs = tf.concat((tf.zeros_like(self.Y[:, :1, :]), self.Y[:, :-1, :]), 1)
self.decoder_inputs = self.decoder_inputs[:, :, -n_mels:]
self.Z = tf.placeholder(tf.float32, (None, None, fourier_window_size // 2 + 1))
batch_size = tf.shape(self.X)[0]
seq_lens = tf.count_nonzero(tf.reduce_sum(self.decoder_inputs, -1), 1, dtype=tf.int32) + 1
def cells(reuse=False):
return tf.contrib.rnn.DropoutWrapper(
tf.nn.rnn_cell.LSTMCell(
size_layers, initializer=tf.orthogonal_initializer(), reuse=reuse
| tensorflow.zeros | 13,359 |
import tensorflow as tf
w = x_shape[2] + pad_w0 + pad_w1
pad_h1 += tf.mod(-h + bsize[1], bstrides[1])
| tensorflow.mod | 13,360 |
import tensorflow as tf
output = model.build_server_graph(FLAGS, input_image)
output = (output + 1.) * 127.5
output = tf.reverse(output, [-1])
output = tf.saturate_cast(output, tf.uint8)
# load pretrained model
vars_list = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)
assign_ops = []
for var in vars_list:
vname = var.name
from_name = vname
var_value = tf.contrib.framework.load_variable(checkpoint_dir, from_name)
assign_ops.append(tf.assign(var, var_value))
sess.run(assign_ops)
result = sess.run(output)
tf.reset_default_graph()
return result[0][:, :, ::-1]
| tensorflow.contrib.framework.load_variable | 13,361 |
from tensorflow.python.ops import array_ops
name, 'expand_and_tile', (tensor, multiple, dim)) as scope:
# Sparse.
if isinstance(tensor, ops.SparseTensorValue):
tensor = ops.SparseTensor.from_value(tensor)
if isinstance(tensor, ops.SparseTensor):
if dim < 0:
expand_dims = array_ops.reshape(
array_ops.size(tensor.shape) + dim, [1])
else:
expand_dims = [dim]
expanded_shape = array_ops.concat(
0, (array_ops.slice(tensor.shape, [0], expand_dims), [1],
array_ops.slice(tensor.shape, expand_dims, [-1])),
name='expanded_shape')
expanded = sparse_ops.sparse_reshape(
tensor, shape=expanded_shape, name='expand')
if multiple == 1:
return expanded
return sparse_ops.sparse_concat(
dim - 1 if dim < 0 else dim, [expanded] * multiple, name=scope)
# Dense.
expanded = array_ops.expand_dims(
tensor, dim if (dim >= 0) else (dim - 1), name='expand')
| tensorflow.python.ops.array_ops.slice | 13,362 |
import tensorflow as tf
# Policy Gradient loss, with truncated importance sampling & bias correction
value = strip(value, self.n_envs, self.n_steps, True)
# check_shape([qret, value, rho_i, f_i], [[self.n_envs * self.n_steps]] * 4)
# check_shape([rho, distribution_f, q_value], [[self.n_envs * self.n_steps, self.n_act]] * 2)
# Truncated importance sampling
adv = qret - value
log_f = tf.log(f_i + eps)
# [n_envs * n_steps]
gain_f = log_f * tf.stop_gradient(adv * tf.minimum(self.correction_term, rho_i))
loss_f = -tf.reduce_mean(gain_f)
# Bias correction for the truncation
adv_bc = (q_value - tf.reshape(value, [self.n_envs * self.n_steps, 1])) # [n_envs * n_steps, n_act]
# check_shape([adv_bc, log_f_bc], [[self.n_envs * self.n_steps, self.n_act]] * 2)
if continuous:
gain_bc = tf.stop_gradient(adv_bc *
| tensorflow.minimum | 13,363 |
import tensorflow as tf
self.range_tiled = range_tiled
# Use the logical operations to create a mask
indicator = tf.less(range_tiled, lengths_tiled+1) #i.e. where seq len is less than index
trim = np.ones(indicator.get_shape())
trim[:,0] = 0 #ignore start symbol
indicator = tf.logical_and(indicator, trim.astype(bool))
self.indicator = indicator
sz = [batch_size, max_sequence_len]
self._mask = tf.select(indicator, tf.ones(sz), tf.zeros(sz))
#-------------------------------#
self.weights = tf.constant(weights, dtype=tf.float32, name='class_weights')
hidden_size = model_params['model_hidden_size']
proj_size = model_params['model_proj_size'] # optional, can be None
def GetCell():
"""Creates an LSTM cell with dropout."""
c = tf.nn.rnn_cell.LSTMCell(hidden_size,
use_peepholes=model_params['peepholes'],
num_proj=proj_size)
if dropout_keep_prob is not None:
c = tf.nn.rnn_cell.DropoutWrapper(c, input_keep_prob=dropout_keep_prob)
return c
| tensorflow.constant | 13,364 |
import tensorflow as tf
model_carlini_adv = models_carlini(hps)
#Construct predictions
image = tf.placeholder(tf.float32,shape=[hps.batch_size, image_size, image_size,
num_channel])############MNIST and CIFAR10 are different ar here
adv_image = tf.placeholder(tf.float32,shape=[hps.batch_size, image_size, image_size,
num_channel])############MNIST and CIFAR10 are different ar here
predict = tf.placeholder(tf.float32,shape=[hps.batch_size, 10])
logit_nor,tsne_logit_nor = model_carlini_adv.predict(image,tsne_logits=True)
logit_adv,tsne_logit_adv = model_carlini_adv.predict(adv_image,tsne_logits=True)
predict_nor = tf.nn.softmax(logit_nor)
predict_adv = tf.nn.softmax(logit_adv)
# Calculate entropy
argmax_y_onehot = tf.one_hot(tf.argmax(predict, 1), 10, on_value=0.0, off_value=1.0, axis=-1)
normalized_y_nonmaximal = tf.reduce_sum(predict * argmax_y_onehot, 1)
entropy = tf.reduce_sum(-tf.log(predict) * predict * argmax_y_onehot,1) / normalized_y_nonmaximal + tf.log(normalized_y_nonmaximal)
for k in range(1):
result_dict = loadmat('kernel_para_'+FLAGS.dataset+'/kernel1000_for_attack_' + f1 + '.mat')
result_dict_median = loadmat('kernel_para_'+FLAGS.dataset+'/kernel1000_median_for_attack_' + f1 + '.mat')
# e_mean = result_dict['mean_logits_' + f1] # 10X64
# e_invcovar = result_dict['inv_covar_' + f1] # 64X64X10
e_kernel_train = result_dict['kernel_'+f1+'_for_attack'] #100X64X10
e_median = result_dict_median['median_out'] # 10X1
if FLAGS.attack_method == 'carliniL2':
attack1 = attacks.carliniL2.CarliniL2(sess, model_carlini_adv, batch_size=10, max_iterations=10,targeted=True,
confidence=0, initial_const=1.0,binary_search_steps=9)
attack2 = None
| tensorflow.reduce_sum | 13,365 |
from tensorflow.python.ops import array_ops
'image/class/label':
parsing_ops.FixedLenFeature(
shape=[1],
dtype=dtypes.int64,
default_value=array_ops.zeros(
[1], dtype=dtypes.int64))
}
| tensorflow.python.ops.array_ops.zeros | 13,366 |
import tensorflow as tf
"question")
self.ch = tf.placeholder(tf.int32, [self.config.batch_size * self.max_p_num, self.config.max_p_len,
self.config.max_ch_len], "context_char")
self.qh = tf.placeholder(tf.int32, [self.config.batch_size * self.max_p_num, self.config.max_q_len,
self.config.max_ch_len], "question_char")
self.start_label = tf.placeholder(tf.int32, [self.config.batch_size], "answer_label1")
self.end_label = tf.placeholder(tf.int32, [self.config.batch_size], "answer_label2")
self.position_emb = position_embedding(self.c, 2 * self.config.hidden_size)
self.c_mask = tf.cast(self.c, tf.bool) # index 0 is padding symbol N x self.max_p_num, max_p_len
self.q_mask = tf.cast(self.q, tf.bool)
self.c_len = tf.reduce_sum(tf.cast(self.c_mask, tf.int32), axis=1)
self.q_len = tf.reduce_sum(tf.cast(self.q_mask, tf.int32), axis=1)
self.dropout = tf.placeholder(tf.float32, name="dropout")
self.global_step = tf.Variable(0, name="global_step", trainable=False)
"""
| tensorflow.cast | 13,367 |
from tensorflow.python.framework import ops
"""Calculates the on-disk weight parameters for BiasAdd."""
bias_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[1])
bias_shape.assert_is_fully_defined()
bias_count = np.prod(bias_shape.as_list())
return ops.OpStats("weight_parameters", bias_count)
def xw_plus_b(x, weights, biases, name=None): # pylint: disable=invalid-name
| tensorflow.python.framework.ops.OpStats | 13,368 |
import tensorflow as tf
# Add dropout if training
if is_train:
X = tf.nn.dropout(X, dropout_keep_prob)
# Compute logits from X
| tensorflow.nn.dropout | 13,369 |
import tensorflow as tf
pass
@staticmethod
def make_input_fn(is_training):
"""Construct training input_fn that uses synthetic data."""
def input_fn(params):
"""Generated input_fn for the given epoch."""
batch_size = (params["batch_size"] if is_training else
params["eval_batch_size"])
num_users = params["num_users"]
num_items = params["num_items"]
users = tf.random_uniform([batch_size], dtype=tf.int32, minval=0,
maxval=num_users)
items = tf.random_uniform([batch_size], dtype=tf.int32, minval=0,
maxval=num_items)
if is_training:
valid_point_mask = tf.cast(tf.random_uniform(
[batch_size], dtype=tf.int32, minval=0, maxval=2), tf.bool)
labels = tf.cast(tf.random_uniform(
[batch_size], dtype=tf.int32, minval=0, maxval=2), tf.bool)
data = {
movielens.USER_COLUMN: users,
movielens.ITEM_COLUMN: items,
| tensorflow.random_uniform | 13,370 |
import tensorflow as tf
c_emb = tf.nn.dropout(tf.nn.embedding_lookup(self.word_mat, self.c), 1.0 - self.dropout)
q_emb = tf.nn.dropout(tf.nn.embedding_lookup(self.word_mat, self.q), 1.0 - self.dropout)
c_emb = tf.concat([c_emb, ch_emb], axis=2)
q_emb = tf.concat([q_emb, qh_emb], axis=2)
self.c_emb = highway(c_emb, size=d, scope="highway", dropout=self.dropout, reuse=None)
self.q_emb = highway(q_emb, size=d, scope="highway", dropout=self.dropout, reuse=True)
def _encode(self):
N, PL, QL, CL, d, dc, nh = self._params()
if self.config.fix_pretrained_vector:
dc = self.char_mat.get_shape()[-1]
with tf.variable_scope("Embedding_Encoder_Layer"):
self.c_embed_encoding = residual_block(self.c_emb,
num_blocks=1,
num_conv_layers=2,
kernel_size=7,
mask=self.c_mask,
num_filters=d,
num_heads=nh,
seq_len=self.c_len,
scope="Encoder_Residual_Block",
bias=False,
dropout=self.dropout)
self.q_embed_encoding = residual_block(self.q_emb,
| tensorflow.variable_scope | 13,371 |
import tensorflow as tf
return (model, graph, sess, saver, monitored_values)
def _load_tf_vars(self, params):
m = self._model
utils.logger.log('Loading TF vars...')
tf_vars = tf.global_variables()
values = self._sess.run(tf_vars) # Get current values for vars
# Build feed dict for op for loading vars
# For each var, use current value of param in session if not in params
var_feeddict = {
m.var_phs[tf_var.name]: params[tf_var.name]
| tensorflow.global_variables | 13,372 |
import tensorflow as tf
# Declare loss function (Cross Entropy loss)
loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=model_output, labels=y_target))
| tensorflow.nn.sigmoid_cross_entropy_with_logits | 13,373 |
import tensorflow as tf
tf.app.flags.DEFINE_integer('num_residual_units', 5,
'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',
'The attacking method used')
tf.app.flags.DEFINE_float('eps', 0.01,
'The eps in attacking methods.')
tf.app.flags.DEFINE_string('save_pwd', None,
'')
epoch_jsma = 100
num_classes = 10
if FLAGS.dataset == 'cifar10':
image_size = 32
num_channel = 3
| tensorflow.app.flags.DEFINE_string | 13,374 |
import tensorflow as tf
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':
x = attns
elif chaining_strategy == 'map_outputs':
x = decoder_outputs
| tensorflow.concat | 13,375 |
import tensorflow as tf
def N0(mean, variance):
return 1.0/(tf.sqrt(2.0 * m.pi * variance)) * tf.exp((-(mean**2))/(2*variance))
N = tf.cast(tf.shape(X)[0], tf.float32)
if y is None:
y = silverman_rule_of_thumb(N)
A = tf.subtract(tf.expand_dims(X, 0), tf.expand_dims(X, 1))
return (1.0/(N*N)) * tf.reduce_sum(N0(A, 2*y)) + N0(0.0, 2.0 + 2*y) - (2/N) * tf.reduce_sum(N0(X, 1.0 + 2*y))
def cw_2d(X, y=None):
def __phi(x):
def __phi_f(s):
t = s/7.5
| tensorflow.expand_dims | 13,376 |
import tensorflow as tf
name_to_features = {
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_length], tf.int64),
"segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
"label_ids": tf.FixedLenFeature([], tf.int64),
"is_real_example": tf.FixedLenFeature([], tf.int64),
}
def _decode_record(record, name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
t = tf.to_int32(t)
example[name] = t
return example
| tensorflow.parse_single_example | 13,377 |
import tensorflow as tf
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])
| tensorflow.reshape | 13,378 |
import tensorflow as tf
"label_ids": tf.FixedLenFeature([], tf.int64),
}
serialized_tf_example = tf.placeholder(dtype=tf.string,
shape=[None],
| tensorflow.placeholder | 13,379 |
import tensorflow as tf
loss_pg = - tf.reduce_mean(pi.log_prob(batch['actions']) * batch['advantage']) - 0.01 * tf.reduce_mean(pi.entropy())
loss_vf = 0.5 * tf.reduce_mean(tf.square(batch['rewards'] - self.vf))
self.a_grads = tf.gradients(loss_pg, self.pi_params)
self.c_grads = tf.gradients(loss_vf, self.vf_params)
self.a_grads, _ = tf.clip_by_global_norm(self.a_grads, 20.0)
self.c_grads, _ = tf.clip_by_global_norm(self.c_grads, 20.0)
opt = tf.train.AdamOptimizer(self.LR)
self.update_a_op = opt.apply_gradients(zip(self.a_grads, self.pi_params))
| tensorflow.clip_by_global_norm | 13,380 |
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,
| tensorflow.to_float | 13,381 |
import tensorflow as tf
stats = add_train_stats(model, hparams)
return model, stats
def model_test_mode(args, feeder, hparams, global_step):
with tf.variable_scope("Tacotron_model", reuse=tf.AUTO_REUSE) as scope:
model = create_model("Tacotron", hparams)
model.initialize(feeder.eval_inputs, feeder.eval_input_lengths,
feeder.eval_speaker_embeddings, feeder.eval_mel_targets,
feeder.eval_token_targets, targets_lengths=feeder.eval_targets_lengths,
| tensorflow.variable_scope | 13,382 |
from tensorflow.python.framework import ops
# - For the unweighted case, this is just the number of rows.
# - For the weighted case, it's the sum of the weights broadcast across
# `average_precision` rows.
max_var = contrib_variables.local_variable(
array_ops.zeros([], dtype=dtypes.float64), name=max_scope)
if weights is None:
batch_max = math_ops.to_double(
array_ops.size(average_precision, name='batch_max'))
else:
# TODO(ptucker): More efficient way to broadcast?
broadcast_weights = math_ops.mul(
weights, array_ops.ones_like(average_precision),
name='broadcast_weights')
batch_max = math_ops.reduce_sum(broadcast_weights, name='batch_max')
max_update = state_ops.assign_add(max_var, batch_max, name='update')
with ops.name_scope(None, 'total', (average_precision,)) as total_scope:
total_var = contrib_variables.local_variable(
array_ops.zeros([], dtype=dtypes.float64), name=total_scope)
batch_total = math_ops.reduce_sum(average_precision, name='batch_total')
total_update = state_ops.assign_add(total_var, batch_total, name='update')
# Divide total by max to get mean, for both vars and the update ops.
mean_average_precision = _safe_scalar_div(total_var, max_var, name='mean')
update = _safe_scalar_div(total_update, max_update, name=scope)
if metrics_collections:
ops.add_to_collections(metrics_collections, mean_average_precision)
if updates_collections:
ops.add_to_collections(updates_collections, update)
| tensorflow.python.framework.ops.name_scope | 13,383 |
import tensorflow as tf
label_ids = tf.reshape(label_ids, [-1])
| tensorflow.reshape | 13,384 |
import tensorflow as tf
tf.gfile.DeleteRecursively(FLAGS.checkpoint_path)
tf.gfile.MkDir(FLAGS.checkpoint_path)
input_images = tf.placeholder(tf.float32, shape=[None, None, None, 3], name='input_images')
input_score_maps = tf.placeholder(tf.float32, shape=[None, None, None, 1], name='input_score_maps')
if FLAGS.geometry == 'RBOX':
input_geo_maps = tf.placeholder(tf.float32, shape=[None, None, None, 5], name='input_geo_maps')
else:
input_geo_maps = tf.placeholder(tf.float32, shape=[None, None, None, 8], name='input_geo_maps')
input_training_masks = tf.placeholder(tf.float32, shape=[None, None, None, 1], name='input_training_masks')
global_step = tf.get_variable('global_step', [], initializer=tf.constant_initializer(0), trainable=False)
| tensorflow.placeholder | 13,385 |
import tensorflow as tf
x = tf.reshape(scale_init, [1, 1, 1, num_filters]) * (x - tf.reshape(m_init, [1, 1, 1, num_filters]))
else:
V = maybe_avg(V)
g = maybe_avg(g)
b = maybe_avg(b)
# use weight normalization (Salimans & Kingma, 2016)
W = tf.reshape(g, [1, 1, 1, num_filters]) * tf.nn.l2_normalize(V, [0, 1, 2])
# calculate convolutional layer output
x = tf.nn.bias_add(tf.nn.conv2d(x, W, [1] + list(stride) + [1], pad), b)
return x
| tensorflow.reshape | 13,386 |
import tensorflow as tf
name='T',
bias_initializer=tf.constant_initializer(-1.0))
return H * T + inputs * (1.0 - T)
def conv1d(inputs, kernel_size, channels, activation, is_training, scope):
with tf.variable_scope(scope):
conv1d_output = tf.layers.conv1d(
inputs,
filters=channels,
kernel_size=kernel_size,
activation=activation,
padding='same')
return tf.layers.batch_normalization(conv1d_output, training=is_training)
| tensorflow.layers.conv1d | 13,387 |
import tensorflow as tf
pos = tf.reshape(pos, [-1, 1])
pos = tf.minimum(pos, encoder_input_length - 1)
idx = tf.tile(tf.to_float(tf.range(attn_length)), tf.stack([batch_size]))
idx = tf.reshape(idx, [-1, attn_length])
low = pos - encoder.attn_window_size
high = pos + encoder.attn_window_size
mlow = tf.to_float(idx < low)
mhigh = tf.to_float(idx > high)
m = mlow + mhigh
m += tf.to_float(idx >= encoder_input_length)
mask = tf.to_float(tf.equal(m, 0.0))
e = compute_energy(hidden_states, state, encoder, input_length=encoder_input_length, **kwargs)
weights = softmax(e, mask=mask)
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)
| tensorflow.to_float | 13,388 |
import tensorflow as tf
return weighted_average, weights
def no_attention(state, hidden_states, *args, **kwargs):
batch_size = tf.shape(state)[0]
weighted_average = tf.zeros(shape=tf.stack([batch_size, 0]))
weights = tf.zeros(shape=[batch_size, tf.shape(hidden_states)[1]])
return weighted_average, weights
def average_attention(hidden_states, encoder_input_length, *args, **kwargs):
# attention with fixed weights (average of all hidden states)
lengths = tf.to_float(tf.expand_dims(encoder_input_length, axis=1))
mask = tf.sequence_mask(encoder_input_length, maxlen=tf.shape(hidden_states)[1])
weights = tf.to_float(mask) / lengths
weighted_average = tf.reduce_sum(hidden_states * tf.expand_dims(weights, axis=2), axis=1)
return weighted_average, weights
def last_state_attention(hidden_states, encoder_input_length, *args, **kwargs):
weights = tf.one_hot(encoder_input_length - 1, tf.shape(hidden_states)[1])
weights = tf.to_float(weights)
weighted_average = tf.reduce_sum(hidden_states * tf.expand_dims(weights, axis=2), axis=1)
return weighted_average, weights
| tensorflow.shape | 13,389 |
import tensorflow as tf
with self.test_session(graph=tf.Graph()):
# Imports the text format graph.
tf.train.import_meta_graph(filename)
# Writes wrong contents to the file.
tf.train.write_graph(saver.as_saver_def(), os.path.dirname(filename),
os.path.basename(filename))
with self.test_session(graph=tf.Graph()):
# Import should fail.
with self.assertRaisesWithPredicateMatch(
IOError, lambda e: "Cannot parse file"):
tf.train.import_meta_graph(filename)
# Deletes the file
gfile.Remove(filename)
with self.assertRaisesWithPredicateMatch(
IOError, lambda e: "does not exist"):
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
meta_graph_def = slice_saver.export_meta_graph(filename)
| tensorflow.train.import_meta_graph | 13,390 |
import tensorflow as tf
def test_generator_alpha(self):
with self.test_session(use_gpu=True) as sess:
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]
]
alpha_fixed_progress = [
sess.run(
networks._generator_alpha(block_id, tf.constant(1.2, tf.float32)))
for block_id in range(1, 5)
]
self.assertArrayNear(alpha_fixed_block_id, [0, 0.2, 1, 0.8, 0, 0, 0],
1.0e-6)
self.assertArrayNear(alpha_fixed_progress, [0, 0.8, 0.2, 0], 1.0e-6)
def test_discriminator_alpha(self):
with self.test_session(use_gpu=True) as sess:
| tensorflow.constant | 13,391 |
import tensorflow as tf
num_channels_in = self.top_size
name = 'affine' + str(self.counts['affine'])
self.counts['affine'] += 1
with tf.variable_scope(name):
init_factor = 2. if activation == 'relu' else 1.
kernel = tf.get_variable(
'weights', [num_channels_in, num_out_channels],
self.data_type,
tf.random_normal_initializer(stddev=np.sqrt(init_factor /
(num_channels_in))))
biases = tf.get_variable('biases', [num_out_channels],
self.data_type,
tf.constant_initializer(0.0))
logits = tf.matmul(input_layer, kernel) + biases
if activation == 'relu':
affine1 = tf.nn.relu(logits, name=name)
elif activation == 'linear' or activation is None:
affine1 = logits
else:
raise KeyError('Invalid activation type \'%s\'' % activation)
self.top_layer = affine1
self.top_size = num_out_channels
return affine1
def resnet_bottleneck_v1(self,
depth,
depth_bottleneck,
stride,
input_layer=None,
in_size=None):
| tensorflow.nn.relu | 13,392 |
import tensorflow as tf
x_dim=hparams.x_dim,
minus_loglikelihood_fn=energy_fn,
n_steps=hparams.n_steps,
eps=hparams.eps)
loss, _, _ = l2hmc.compute_loss(dynamics, x)
optimizer = tf.train.AdamOptimizer(learning_rate=hparams.learning_rate)
train_op, loss, _ = graph_step(dynamics, optimizer, x)
# Single thread; fairer comparison against eager
session_conf = tf.ConfigProto(inter_op_parallelism_threads=1)
| tensorflow.train.AdamOptimizer | 13,393 |
import tensorflow as tf
next_relabelled_obs, step_type=(), network_state=())[0].sample()
critic_input = (next_relabelled_obs, sampled_actions_tiled)
q_vals, _ = self._critic(critic_input, training=False)
q_vals_vec = tf.reshape(q_vals, (batch_size, num_tasks))
rewards, dones = self._task_distribution.evaluate(states_tiled,
actions_tiled,
tasks_tiled)
dones = tf.cast(dones, tf.float32)
rewards_vec = tf.reshape(rewards, (batch_size, num_tasks))
dones_vec = tf.reshape(dones, (batch_size, num_tasks))
relabelled_obs = self._task_distribution.combine(states_tiled, tasks_tiled)
action_distribution = self._actor(
relabelled_obs, step_type=(), network_state=())[0]
log_pi = common.log_probability(action_distribution, actions_tiled,
action_spec)
log_pi_vec = tf.reshape(log_pi, (batch_size, num_tasks))
logits_vec = (
| tensorflow.reshape | 13,394 |
import tensorflow as tf
batch_size = tf.shape(a)[0]
return a + b, tf.tile([batch_size], [batch_size])
output = f(tf.constant([[1, 3]]), tf.constant([2]))
tf.train.start_queue_runners()
| tensorflow.constant | 13,395 |
import tensorflow as tf
eval_file = os.path.join(FLAGS.output_dir, "eval.tf_record")
file_based_convert_examples_to_features(
eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file)
tf.logging.info("***** Running evaluation *****")
tf.logging.info(" Num examples = %d (%d actual, %d padding)",
len(eval_examples), num_actual_eval_examples,
len(eval_examples) - num_actual_eval_examples)
tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
| tensorflow.logging.info | 13,396 |
import tensorflow as tf
Res = model_name.ResNet(hps, images, FLAGS.mode, Reuse=False)
Res.build_graph()
saver = tf.train.Saver()
# Open session and restore checkpoint
sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
tf.train.start_queue_runners(sess)
sess.run(tf.global_variables_initializer())
ckpt_state = tf.train.get_checkpoint_state(FLAGS.log_root) # Choose dir according to rt
tf.logging.info('Loading checkpoint %s', ckpt_state.model_checkpoint_path)
| tensorflow.train.start_queue_runners | 13,397 |
from tensorflow.python.ops import math_ops
labels, labels, weights=weights, name='variance_labels')
pearson_r = _safe_div(
cov,
math_ops.mul(math_ops.sqrt(var_predictions), math_ops.sqrt(var_labels)),
'pearson_r')
with ops.control_dependencies(
[update_cov, update_var_predictions, update_var_labels]):
| tensorflow.python.ops.math_ops.sqrt | 13,398 |
import tensorflow as tf
cell_drop=tf.contrib.rnn.DropoutWrapper(lstm,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob)
elif cell_type == 'GRU':
if activation == 'linear':
gru=tf.nn.rnn_cell.GRUCell(state_size, activation = tf.identity)
cell_drop=tf.contrib.rnn.DropoutWrapper(gru,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob)
elif activation == 'relu':
gru=tf.nn.rnn_cell.GRUCell(state_size, activation = tf.nn.relu)
cell_drop=tf.contrib.rnn.DropoutWrapper(gru,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob)
else:
gru=tf.nn.rnn_cell.GRUCell(state_size)
cell_drop=tf.contrib.rnn.DropoutWrapper(gru,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob)
| tensorflow.contrib.rnn.DropoutWrapper | 13,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.