seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
import tensorflow as tf
out = tf.sqrt(subsamp_sum)
else:
out = tf.pow(subsamp_sum, 1/pnorm)
| tensorflow.pow | 5,400 |
import tensorflow as tf
fields.InputDataFields.groundtruth_boxes:
tf.constant(
np.array([[0, 0, 1, 1], [.2, .2, 4, 4], [.5, .5, 1, 1]],
np.float32)),
fields.InputDataFields.groundtruth_area:
tf.constant(np.array([.5, .4, .3])),
fields.InputDataFields.groundtruth_classes:
tf.constant(np.array([3, -1, 1], np.int32)),
fields.InputDataFields.groundtruth_keypoints:
tf.constant(
np.array([[[.1, .1]], [[.2, .2]], [[.5, .5]]],
np.float32)),
fields.InputDataFields.groundtruth_keypoint_visibilities:
tf.constant([True, False, True]),
fields.InputDataFields.groundtruth_instance_masks:
tf.constant(np.random.rand(3, 4, 4).astype(np.float32)),
fields.InputDataFields.groundtruth_is_crowd:
tf.constant([False, True, False]),
fields.InputDataFields.groundtruth_difficult:
tf.constant(np.array([0, 0, 1], np.int32))
}
num_classes = 3
input_transformation_fn = functools.partial(
inputs.transform_input_data,
model_preprocess_fn=_fake_model_preprocessor_fn,
| tensorflow.constant | 5,401 |
from tensorflow.contrib.learn.python.learn.estimators import test_data
def _assertCommonMetrics(self, metrics):
estimator_test_utils.assert_in_range(_ITERS, _ITERS + 5, 'global_step',
metrics)
estimator_test_utils.assert_in_range(0.9, 1.0, 'accuracy', metrics)
estimator_test_utils.assert_in_range(0.0, 0.2, 'loss', metrics)
self.report_benchmark(
iters=metrics['global_step'],
extras={k: v
for k, v in metrics.items() if k in _METRIC_KEYS})
def benchmarkMatrixData(self):
iris = test_data.prepare_iris_data_for_logistic_regression()
cont_feature = feature_column.real_valued_column('feature', dimension=4)
bucketized_feature = feature_column.bucketized_column(
cont_feature, test_data.get_quantile_based_buckets(iris.data, 10))
classifier = dnn_linear_combined.DNNLinearCombinedClassifier(
model_dir=tempfile.mkdtemp(),
linear_feature_columns=(bucketized_feature,),
dnn_feature_columns=(cont_feature,),
dnn_hidden_units=(3, 3))
input_fn = test_data.iris_input_logistic_fn
metrics = classifier.fit(input_fn=input_fn, steps=_ITERS).evaluate(
input_fn=input_fn, steps=100)
self._assertSingleClassMetrics(metrics)
def benchmarkTensorData(self):
| tensorflow.contrib.learn.python.learn.estimators.test_data.get_quantile_based_buckets | 5,402 |
import tensorflow as tf
cell_drop = tf.contrib.rnn.DropoutWrapper(cell_basic, variational_recurrent=True, dtype=tf.float32,
input_size=num_input, input_keep_prob=input_prob,
state_keep_prob=state_prob)
else: #tanh by default
cell_basic = tf.contrib.rnn.BasicRNNCell(state_size)
cell_drop = tf.contrib.rnn.DropoutWrapper(cell_basic, variational_recurrent=True, dtype=tf.float32,
input_size=num_input, input_keep_prob=input_prob,
state_keep_prob=state_prob)
return cell_drop
| tensorflow.contrib.rnn.DropoutWrapper | 5,403 |
import tensorflow as tf
with tf.Session(config = config) as sess:
# Read the file containing the pairs used for testing
pairs = lfw.read_pairs(os.path.expanduser(args.lfw_pairs))
# Get the paths for the corresponding images
paths, actual_issame = lfw.get_paths(os.path.expanduser(args.lfw_dir), pairs)
image_paths_placeholder = tf.placeholder(tf.string, shape=(None,1), name='image_paths')
labels_placeholder = tf.placeholder(tf.int32, shape=(None,1), name='labels')
batch_size_placeholder = tf.placeholder(tf.int32, name='batch_size')
control_placeholder = tf.placeholder(tf.int32, shape=(None,1), name='control')
phase_train_placeholder = tf.placeholder(tf.bool, name='phase_train')
nrof_preprocess_threads = 4
image_size = (args.image_size, args.image_size)
eval_input_queue = data_flow_ops.FIFOQueue(capacity=2000000,
dtypes=[tf.string, tf.int32, tf.int32],
shapes=[(1,), (1,), (1,)],
shared_name=None, name=None)
eval_enqueue_op = eval_input_queue.enqueue_many([image_paths_placeholder, labels_placeholder, control_placeholder], name='eval_enqueue_op')
image_batch, label_batch = facenet.create_input_pipeline(eval_input_queue, image_size, nrof_preprocess_threads, batch_size_placeholder)
# Load the model
input_map = {'image_batch': image_batch, 'label_batch': label_batch, 'phase_train': phase_train_placeholder}
| tensorflow.placeholder | 5,404 |
import tensorflow as tf
tf.global_variables_initializer().run()
else:
saver.restore(sess, args.model_path)
for i in range(max_train_step):
batch_x, batch_gt = mnist.train.next_batch(batch_size)
sess.run(train_op, feed_dict={x: batch_x, gt: batch_gt})
if i % 100 == 0:
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(gt, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print('=> accuracy: {}'.format(sess.run(accuracy, feed_dict={x: mnist.test.images, gt: mnist.test.labels})))
saver.save(sess, 'mnist/mnist_{:02d}.ckpt'.format(int(i / 100) + 1))
| tensorflow.argmax | 5,405 |
import tensorflow as tf
"""Inject a VAE-style latent."""
# Latent for stochastic model
input_frames = tf.to_float(features["inputs_raw"])
target_frames = tf.to_float(features["targets_raw"])
full_video = tf.concat([input_frames, target_frames], axis=1)
latent_mean, latent_std = self.construct_latent_tower(
full_video, time_axis=1)
latent = common_video.get_gaussian_tensor(latent_mean, latent_std)
latent = tf.layers.flatten(latent)
latent = tf.expand_dims(latent, axis=1)
latent = tf.expand_dims(latent, axis=1)
latent_mask = tf.layers.dense(latent, filters, name="latent_mask")
zeros_mask = tf.zeros(
common_layers.shape_list(layer)[:-1] + [filters], dtype=tf.float32)
layer = tf.concat([layer, latent_mask + zeros_mask], axis=-1)
extra_loss = self.get_extra_loss(latent_mean, latent_std)
return layer, extra_loss
@registry.register_model
| tensorflow.expand_dims | 5,406 |
import tensorflow as tf
odd = [2 * i + 1 for i in range(25)]
pred1 = tf.gather(pred, even)
pred2 = tf.gather(pred, odd)
tgt1 = tf.gather(tgt, even)
tgt2 = tf.gather(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.maximum(0.0, tf.math.abs(tgt_larg - pred_larg) - tf.math.abs(tgt_small - pred_small))
loss = tf.reduce_mean(loss)
return loss
def contra_step_lossV5(pred, tgt, resample=1):
# p = tf.print('begin loss v5', [resample, pred.shape,tgt.shape])
# with tf.control_dependencies([p]):
pred_flat = tf.reshape(pred, [-1])
tgt_flat = tf.reshape(tgt, [-1])
batch = tf.stack([pred_flat, tgt_flat], 1)
num_sam = tools.shape(batch)[0]
index = tf.range(num_sam)
divider = tf.constant(resample, dtype=tf.float32)
| tensorflow.reduce_mean | 5,407 |
import tensorflow as tf
lr = args.lr
n_epoch = args.n_epoch
n_batch_size = args.n_batch_size
reg_lambda = args.reg_lambda
keep_prob = args.keep_prob
cross_stitch_enabled = args.cross_stitch_enabled
with tf.variable_scope("placeholder"):
X = tf.placeholder(tf.float32, (None, 128), "X")
y_1 = tf.placeholder(tf.float32, (None, n_output_1), "y_1")
y_2 = tf.placeholder(tf.float32, (None, n_output_2), "y_2")
is_training = tf.placeholder(tf.bool, (), "is_training")
with tf.variable_scope("network"):
with contrib.framework.arg_scope(
[contrib.layers.fully_connected],
# he initialization
weights_initializer=contrib.layers.variance_scaling_initializer(),
| tensorflow.placeholder | 5,408 |
import tensorflow as tf
with tf.variable_scope(tf.get_variable_scope()):
encoder_output_label, encoder_output_latent = encoder(x_input)
# Concat class label and the encoder output
decoder_input = tf.concat([encoder_output_label, encoder_output_latent], 1)
decoder_output = decoder(decoder_input)
# Regularization Phase
with tf.variable_scope(tf.get_variable_scope()):
d_g_real = discriminator_gauss(real_distribution)
d_g_fake = discriminator_gauss(encoder_output_latent, reuse=True)
with tf.variable_scope(tf.get_variable_scope()):
d_c_real = discriminator_categorical(categorial_distribution)
d_c_fake = discriminator_categorical(encoder_output_label, reuse=True)
# Semi-Supervised Classification Phase
with tf.variable_scope(tf.get_variable_scope()):
encoder_output_label_, _ = encoder(x_input_l, reuse=True, supervised=True)
# Generate output images
with tf.variable_scope(tf.get_variable_scope()):
decoder_image = decoder(manual_decoder_input, reuse=True)
| tensorflow.get_variable_scope | 5,409 |
import tensorflow as tf
def block(x, scope, train=False, scale=False):
with tf.variable_scope(scope):
#nx = emb_size
| tensorflow.variable_scope | 5,410 |
import tensorflow as tf
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Cyclical Learning Rate Schedule policies for TensorFlow."""
import tensorflow as tf
@tf.keras.utils.register_keras_serializable(package="Addons")
class CyclicalLearningRate(tf.keras.optimizers.schedules.LearningRateSchedule):
"""A LearningRateSchedule that uses cyclical schedule."""
def __init__(
self,
initial_learning_rate,
maximal_learning_rate,
step_size,
scale_fn,
scale_mode="cycle",
name=None,
):
| tensorflow.keras.utils.register_keras_serializable | 5,411 |
import tensorflow as tf
activation=modeling.get_activation(bert_config.hidden_act),
kernel_initializer=modeling.create_initializer(
bert_config.initializer_range))
input_tensor = modeling.layer_norm(input_tensor)
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
output_bias = tf.get_variable(
"output_bias",
shape=[bert_config.vocab_size],
initializer=tf.zeros_initializer())
logits = tf.matmul(input_tensor, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
if clip:
log_probs = tf.log(tf.clip_by_value(tf.nn.softmax(logits, axis=-1), 1e-6, 1.0 - 1e-6))
else:
log_probs = tf.nn.log_softmax(logits, axis=-1)
label_ids = tf.reshape(label_ids, [-1])
label_weights = tf.reshape(label_weights, [-1])
one_hot_labels = tf.one_hot(
| tensorflow.matmul | 5,412 |
import tensorflow as tf
if indices is None:
indices = tf.range(len(self._batch_env))
observ_dtype = self._parse_dtype(self._batch_env.observation_space)
observ = tf.py_func(
self._batch_env.reset, [indices], observ_dtype, name='reset')
observ = tf.check_numerics(observ, 'observ')
| tensorflow.py_func | 5,413 |
import tensorflow as tf
t_vars = tf.trainable_variables()
logging.info(" [*] printing trainable variables")
else:
try: # TF1.0+
t_vars = tf.global_variables()
except Exception: # TF0.12
t_vars = tf.all_variables()
logging.info(" [*] printing global variables")
| tensorflow.global_variables | 5,414 |
from tensorflow.python.ops import math_ops
update_op: An operation that accumulates the error from a batch of data.
Raises:
ValueError: If `weights` is not `None` and its shape doesn't match `values`,
or if either `metrics_collections` or `updates_collections` are not a list
or tuple.
"""
check_ops.assert_type(values, dtypes.bool)
count = _create_local('count', shape=[])
values = math_ops.to_float(values)
if weights is not None:
weights = math_ops.to_float(weights)
values = math_ops.mul(values, weights)
value_tensor = array_ops.identity(count)
update_op = state_ops.assign_add(count, math_ops.reduce_sum(values))
if metrics_collections:
ops.add_to_collections(metrics_collections, value_tensor)
| tensorflow.python.ops.math_ops.to_float | 5,415 |
import tensorflow as tf
weight: the weight of the loss.
scope: optional name scope for summary tags.
Returns:
a scalar tensor representing the correlation loss value.
"""
with tf.variable_scope(name):
batch_size = tf.shape(source_samples)[0]
samples = tf.concat(values=[source_samples, target_samples], axis=0)
samples = flatten(samples)
domain_selection_mask = tf.concat(
values=[tf.zeros((batch_size, 1)), tf.ones((batch_size, 1))], axis=0)
| tensorflow.shape | 5,416 |
import tensorflow as tf
labels,
mode,
config=None,
params=None,
decode_hparams=None):
hparams = copy.deepcopy(hparams)
use_tpu = params and params.get("use_tpu", False)
hparams.use_tpu = use_tpu
# merge decode_hparams into hparams if present
if mode == tf.estimator.ModeKeys.PREDICT and decode_hparams is not None:
for k, v in six.iteritems(decode_hparams.values()):
if hasattr(hparams, k) and getattr(hparams, k) != v:
tf.logging.warning("Overriding hparams.%s with %s from decode_hparams"
% (k, v))
setattr(hparams, k, v)
# Instantiate model
data_parallelism = None
if not use_tpu and config:
data_parallelism = config.data_parallelism
model = cls(
hparams,
mode,
data_parallelism=data_parallelism,
| tensorflow.logging.warning | 5,417 |
from tensorflow.python.platform import test
self.assertListEqual([height, width, 3], list(image.shape))
self.assertListEqual([1], list(label.shape))
def testConflictingRecordKeyItem(self):
dataset_dir = tempfile.mkdtemp(prefix=os.path.join(self.get_temp_dir(),
'tfrecord_dataset'))
with self.cached_session():
with self.assertRaises(ValueError):
dataset_data_provider.DatasetDataProvider(
_create_tfrecord_dataset(dataset_dir), record_key='image')
if __name__ == '__main__':
test.main()
| tensorflow.python.platform.test.main | 5,418 |
import tensorflow as tf
with tf.control_dependencies([update]):
self.d_loss_class = tf.identity(self.d_loss_class)
self.d_loss_fake = tf.nn.sigmoid_cross_entropy_with_logits(
logits=self.end_points_D['D_on_G_logits'],
labels=tf.zeros_like(self.end_points_D['D_on_G_logits']))
self.d_loss_class = tf.reduce_mean(self.d_loss_class)
self.d_loss_real = tf.reduce_mean(self.d_loss_real)
self.d_loss_fake = tf.reduce_mean(self.d_loss_fake)
if is_fm_loss:
global_pool_head = self.end_points_D['global_pool']
real_data_features = tf.slice(global_pool_head, [0, 0], [batch_size_train, num_classes])
| tensorflow.reduce_mean | 5,419 |
import tensorflow as tf
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]))
| tensorflow.Variable.SaveSliceInfo | 5,420 |
import tensorflow as tf
key_masks = tf.expand_dims(mask, 1) # [B, 1, T]
paddings = tf.ones_like(scores) * (-2 ** 32 + 1)
if not forCnn:
scores = tf.where(key_masks, scores, paddings) # [B, 1, T]
# Scale
# scores = scores / (facts.get_shape().as_list()[-1] ** 0.5)
# Activation
if softmax_stag:
scores = tf.nn.softmax(scores) # [B, 1, T]
# 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))
| tensorflow.nn.softmax | 5,421 |
import tensorflow as tf
self.conv2 = self._residual_block('conv2_2', self.conv2, 64)
_debug(self.conv2)
with tf.variable_scope('conv3_x'):
self.conv3 = self._residual_block('conv3_1', self.conv2, 128, pool_first=True, strides=2)
_debug(self.conv3)
| tensorflow.variable_scope | 5,422 |
from tensorflow.python.framework import constant_op
var1 = variables.Variable([4.0, 5.0], dtype=dtype)
with self._maybeWithDevice("/job:worker" if is_distributed else None):
grads0 = constant_op.constant([[0.1, 0.1], [0.1, 0.1]], dtype=dtype)
grads1 = constant_op.constant([0.01, 0.01], dtype=dtype)
sgd = gradient_descent.GradientDescentOptimizer(3.0)
clip_opt = variable_clipping_optimizer.VariableClippingOptimizer(
| tensorflow.python.framework.constant_op.constant | 5,423 |
import tensorflow as tf
self._lr = tf.get_collection_ref('lr')[0]
self._new_lr = tf.get_collection_ref('new_lr')[0]
self._lr_update = tf.get_collection_ref('lr_update')[0]
rnn_params = tf.get_collection_ref('rnn_params')
| tensorflow.get_collection_ref | 5,424 |
from tensorflow.python.framework import ops
mu_t = math_ops.cast(self._mu_t, var.dtype.base_dtype)
vstar = self.get_slot(var, "vstar")
gold = self.get_slot(var, "gold") # glod is not sparse
v_diff = state_ops.assign(vstar, mu_t * (var - vstar), use_locking=self._use_locking)
with ops.control_dependencies([v_diff]): # run v_diff operation before scatter_add
scaled_grad = scatter_add(vstar, indices, grad)
var_update = state_ops.assign_sub(var, lr_t * (scaled_grad + gold))
return control_flow_ops.group(*[var_update, ])
| tensorflow.python.framework.ops.control_dependencies | 5,425 |
import tensorflow as tf
else:
return output, alphas
def din_attention(query, facts, attention_size, mask, stag='null', mode='SUM', softmax_stag=1, time_major=False, return_alphas=False):
if isinstance(facts, tuple):
# In case of Bi-RNN, concatenate the forward and the backward RNN outputs.
facts = tf.concat(facts, 2)
print ("querry_size mismatch")
query = tf.concat(values = [
query,
query,
], axis=1)
| tensorflow.concat | 5,426 |
from tensorflow.python.training import checkpoint_utils
# decrease with training.
summary_file = glob.glob(os.path.join(config.logdir, "events.out.*"))[0]
events = summary_test_util.events_from_file(summary_file)
train_losses = [event.summary.value[0].simple_value for event in events
if event.summary.value
and event.summary.value[0].tag == "train/loss"]
self.assertEqual(config.epochs, len(train_losses))
self.assertLess(train_losses[-1], train_losses[0])
# 5. Verify that checkpoints exist and contains all the expected variables.
self.assertTrue(glob.glob(os.path.join(config.logdir, "ckpt*")))
ckpt_variable_names = [
item[0] for item in checkpoint_utils.list_variables(config.logdir)]
self.assertIn("global_step", ckpt_variable_names)
for v in trainer.variables:
variable_name = v.name[:v.name.index(":")] if ":" in v.name else v.name
self.assertIn(variable_name, ckpt_variable_names)
class EagerSpinnSNLIClassifierBenchmark(test.Benchmark):
def benchmarkEagerSpinnSNLIClassifier(self):
test_device = "gpu:0" if tfe.num_gpus() else "cpu:0"
with tf.device(test_device):
| tensorflow.python.training.checkpoint_utils.list_variables | 5,427 |
import tensorflow as tf
# Use fixed archs if specified, otherwise use placeholders'
(normal_arch, reduction_arch) = self._get_fixed_cell_archs(**knobs)
normal_arch = normal_arch if not use_dynamic_arch else ph.normal_arch
reduction_arch = reduction_arch if not use_dynamic_arch else ph.reduction_arch
# Initialize steps variable
step = self._make_var('step', (), dtype=tf.int32, trainable=False, initializer=tf.initializers.constant(0))
# For train dataset, preprocess & do inference
utils.logger.log('Building model for training...')
(train_X, train_classes, train_dataset_init_op) = \
self._preprocess(ph.train_images, ph.train_classes, is_train=True, **knobs)
| tensorflow.initializers.constant | 5,428 |
import tensorflow as tf
input_image = tf.image.resize(datapoint['image'], (512, 512))
input_mask = tf.image.resize(datapoint['segmentation_mask'], (128, 128))
if tf.random.uniform(()) > 0.5:
input_image = tf.image.flip_left_right(input_image)
input_mask = tf.image.flip_left_right(input_mask)
input_image, input_mask = normalize(input_image, input_mask)
return input_image, input_mask
| tensorflow.image.flip_left_right | 5,429 |
import tensorflow as tf
class InstanceSegmentUtilsTest(tf.test.TestCase):
def get_instance_masks(self):
mask0 = tf.constant([[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
| tensorflow.constant | 5,430 |
import tensorflow as tf
for t in range(self.T):
context, alpha = self._attention_layer(features, features_proj, h, reuse=(t!=0))
alpha_list.append(alpha)
if self.selector:
context, beta = self._selector(context, h, reuse=(t!=0))
with tf.variable_scope('lstm', reuse=(t!=0)):
_, (c, h) = lstm_cell(inputs=tf.concat(axis=1, values=[x[:,t,:], context]), state=[c, h])
logits = self._decode_lstm(x[:,t,:], h, context, dropout=self.dropout, reuse=(t!=0))
loss += tf.reduce_sum(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=captions_out[:, t]) * mask[:, t])
if self.alpha_c > 0:
alphas = tf.transpose(tf.stack(alpha_list), (1, 0, 2)) # (N, T, L)
alphas_all = tf.reduce_sum(alphas, 1) # (N, L)
alpha_reg = self.alpha_c * tf.reduce_sum((16./196 - alphas_all) ** 2)
loss += alpha_reg
return loss / tf.to_float(batch_size)
def build_sampler(self, max_len=20):
features = self.features
| tensorflow.nn.sparse_softmax_cross_entropy_with_logits | 5,431 |
import tensorflow as tf
self._on_training_abort(sess)
def inference(self, max=10^6):
self.fetch_datasets()
self.build_ae_model()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# nut.print_model_info()
# nut.list_checkpoint_vars(self.get_latest_checkpoint().replace(EMB_SUFFIX, ''))
self.saver = tf.train.Saver()
self._restore_model(sess)
# nut.print_model_info()
| tensorflow.global_variables_initializer | 5,432 |
import tensorflow as tf
sess.run(sequence_var.initializer)
print(sess.run(linear_var))
print(sess.run(sequence_var))
rnorm_var = tf.random_normal([row_dim, col_dim], mean=0.0, stddev=1.0)
runif_var = tf.random_uniform([row_dim, col_dim], minval=0, maxval=4)
print(sess.run(rnorm_var))
print(sess.run(runif_var))
ops.reset_default_graph()
sess = tf.Session()
my_var = tf.Variable(tf.zeros([1,20]))
merged = tf.summary.merge_all()
writer = tf.summary.FileWriter("./logs", graph=sess.graph)
initialize_op = tf.global_variables_initializer()
sess.run(initialize_op)
| tensorflow.summary.FileWriter | 5,433 |
import tensorflow as tf
c, num_bits=int(self.hparams.z_size / self.hparams.num_blocks), base=2)
c_hot = tf.one_hot(c_int, depth=self.hparams.block_v_size, axis=-1)
c_hot_flat = tf.reshape(
c_hot, shape=[-1, self.hparams.num_blocks, self.hparams.block_v_size])
h1 = tf.matmul(tf.transpose(c_hot_flat, perm=[1, 0, 2]), self.means)
h1 = tf.transpose(h1, perm=[1, 0, 2])
h1 = tf.reshape(h1, shape=h1_shape)
h1_shape[0] = self.hparams.batch_size
h2 = tf.layers.dense(tf.nn.relu(h1), self.hparams.filter_size, name="vch2")
res = tf.layers.dense(
tf.nn.relu(h2), self.hparams.hidden_size, name="vcfin")
return res
def discrete_bottleneck(self, x):
"""Discretization bottleneck for latent variables.
| tensorflow.nn.relu | 5,434 |
import tensorflow as tf
"teacher_logits_tensor":teacher_logit,
"student_feature_tensor":model.get_pooled_output(),
"teacher_feature_tensor":features["distillation_feature"],
"student_label":tf.ones_like(label_ids, dtype=tf.int32),
"teacher_label":tf.zeros_like(label_ids, dtype=tf.int32),
"logits_ratio":kargs.get("logits_ratio", 0.5),
| tensorflow.ones_like | 5,435 |
import tensorflow as tf
w = variable_with_weight_decay([n_in, output_dim], initializer, l2_strength)
variable_summaries(w)
if isinstance(bias, float):
bias = tf.get_variable("biases", [output_dim], tf.float32, tf.constant_initializer(bias))
variable_summaries(bias)
output = tf.nn.bias_add(tf.matmul(x, w), bias)
return output
def _bn(self, name, x):
with tf.variable_scope(name):
moving_average_decay = 0.9
decay = moving_average_decay
batch_mean, batch_var = tf.nn.moments(x, [0, 1, 2])
mu = tf.get_variable('mu', batch_mean.shape, dtype=tf.float32,
initializer=tf.zeros_initializer(), trainable=False)
tf.add_to_collection(tf.GraphKeys.GLOBAL_VARIABLES, mu)
tf.add_to_collection('mu_sigma_bn', mu)
sigma = tf.get_variable('sigma', batch_var.shape, dtype=tf.float32,
initializer=tf.ones_initializer(), trainable=False)
tf.add_to_collection(tf.GraphKeys.GLOBAL_VARIABLES, sigma)
tf.add_to_collection('mu_sigma_bn', sigma)
beta = tf.get_variable('beta', batch_mean.shape, dtype=tf.float32,
| tensorflow.variable_scope | 5,436 |
import tensorflow as tf
"char_embed", [n_chars, char_embed_dim],
dtype=DTYPE,
initializer=tf.random_uniform_initializer(-1.0, 1.0)
)
| tensorflow.random_uniform_initializer | 5,437 |
from tensorflow.python.client import device_lib
else:
raise ValueError("Invalid model: %s", FLAGS.model)
if FLAGS.rnn_mode:
config.rnn_mode = FLAGS.rnn_mode
if FLAGS.num_gpus != 1 or tf.__version__ < "1.3.0" :
config.rnn_mode = BASIC
return config
def main(_):
if not FLAGS.data_path:
raise ValueError("Must set --data_path to PTB data directory")
gpus = [
x.name for x in device_lib.list_local_devices() if x.device_type == "GPU"
]
if FLAGS.num_gpus > len(gpus):
raise ValueError(
"Your machine has only %d gpus "
"which is less than the requested --num_gpus=%d."
% (len(gpus), FLAGS.num_gpus))
raw_data = reader.ptb_raw_data(FLAGS.data_path)
train_data, valid_data, test_data, _ = raw_data
config = get_config()
eval_config = get_config()
| tensorflow.python.client.device_lib.list_local_devices | 5,438 |
import tensorflow as tf
# Set up our moving statistics. When connecting in parallel, this is shared.
self._moving_mean = tf.get_variable(
"moving_mean",
shape=self._mean_shape,
collections=[tf.GraphKeys.MOVING_AVERAGE_VARIABLES,
tf.GraphKeys.GLOBAL_VARIABLES],
initializer=tf.zeros_initializer(),
trainable=False)
self._moving_variance = tf.get_variable(
"moving_variance",
shape=self._mean_shape,
collections=[tf.GraphKeys.MOVING_AVERAGE_VARIABLES,
tf.GraphKeys.GLOBAL_VARIABLES],
initializer=tf.ones_initializer(),
trainable=False)
def build_batch_stats():
"""Builds the batch statistics calculation ops."""
# We use the moving mean as an estimate of the mean in order to perform
# a more numerically stable calculation of the batch mean.
# Copy for better stability.
shift = tf.add(self._moving_mean, 0)
counts, shifted_sum_x, shifted_sum_x2, _ = tf.nn.sufficient_statistics(
input_batch,
reduction_indices,
keep_dims=True,
| tensorflow.ones_initializer | 5,439 |
import tensorflow as tf
Args:
source_samples: a tensor of shape [num_samples, num_features]
target_samples: a tensor of shape [num_samples, num_features]
weight: a scalar weight for the loss.
scope: optional name scope for summary tags.
Returns:
a scalar tensor representing the correlation loss value.
"""
with tf.name_scope(name):
source_samples -= tf.reduce_mean(source_samples, 0)
target_samples -= tf.reduce_mean(target_samples, 0)
source_samples = tf.nn.l2_normalize(source_samples, 1)
target_samples = tf.nn.l2_normalize(target_samples, 1)
source_cov = tf.matmul(tf.transpose(source_samples), source_samples)
target_cov = tf.matmul(tf.transpose(target_samples), target_samples)
corr_loss = tf.reduce_mean(tf.square(source_cov - target_cov)) * weight
assert_op = tf.Assert(tf.is_finite(corr_loss), [corr_loss])
with tf.control_dependencies([assert_op]):
tag = 'Correlation Loss'
barrier = tf.no_op(tag)
return corr_loss
def maximum_mean_discrepancy(x,
y,
| tensorflow.transpose | 5,440 |
import tensorflow as tf
tgt1, tgt2 = tf.split(tgt, 2, axis=0)
soft_sign = tf.tanh((tgt1 - tgt2) * temp)
loss = tf.maximum(0.0, soft_sign * ((tgt1 - tgt2) - (pred1 - pred2)))
loss = tf.reduce_mean(loss)
return loss
| tensorflow.reduce_mean | 5,441 |
import tensorflow as tf
end_logits = tf.transpose(tf.squeeze(end_logits, -1), [1, 0])
end_logits_masked = end_logits * (1 - p_mask) - 1e30 * p_mask
end_log_probs = tf.nn.log_softmax(end_logits_masked, -1)
else:
# during inference, compute the end logits based on beam search
start_top_log_probs, start_top_index = tf.nn.top_k(
start_log_probs, k=FLAGS.start_n_top)
start_index = tf.one_hot(start_top_index,
depth=seq_len, axis=-1, dtype=tf.float32)
start_features = tf.einsum("lbh,bkl->bkh", output, start_index)
end_input = tf.tile(output[:, :, None],
[1, 1, FLAGS.start_n_top, 1])
start_features = tf.tile(start_features[None],
[seq_len, 1, 1, 1])
end_input = tf.concat([end_input, start_features], axis=-1)
| tensorflow.one_hot | 5,442 |
from tensorflow.python.framework import ops
@ops.RegisterShape("Add")
@ops.RegisterShape("Complex")
@ops.RegisterShape("Div")
@ops.RegisterShape("Equal")
@ops.RegisterShape("Greater")
@ops.RegisterShape("GreaterEqual")
@ops.RegisterShape("Less")
@ops.RegisterShape("LessEqual")
@ops.RegisterShape("LogicalAnd")
@ops.RegisterShape("LogicalOr")
@ops.RegisterShape("Maximum")
@ops.RegisterShape("Minimum")
@ops.RegisterShape("Mod")
@ops.RegisterShape("Mul")
@ops.RegisterShape("NotEqual")
@ops.RegisterShape("Pow")
@ops.RegisterShape("Sub")
def _BroadcastShape(op):
"""Common shape function for binary operators that broadcast their inputs."""
shape_x = op.inputs[0].get_shape()
shape_y = op.inputs[1].get_shape()
if shape_x.ndims is None or shape_y.ndims is None:
| tensorflow.python.framework.ops.RegisterShape | 5,443 |
import tensorflow as tf
class StudentTask(base_model.BaseTask):
@base_layer.initializer
def __init__(self, params):
super(StudentTask, self).__init__(params)
p = self.params
with tf.variable_scope(p.name):
self.CreateVariable('x',
py_utils.WeightParams(
shape=[], init=py_utils.WeightInit.Uniform()))
def ComputePredictions(self, theta, input_batch):
return theta.x
| tensorflow.variable_scope | 5,444 |
import tensorflow as tf
Returns:
the list of cropped images.
"""
outputs = []
for image in image_list:
image_height = tf.shape(image)[0]
image_width = tf.shape(image)[1]
offset_height = (image_height - crop_height) / 2
offset_width = (image_width - crop_width) / 2
| tensorflow.shape | 5,445 |
import tensorflow as tf
predict_file = os.path.join(FLAGS.output_dir, "predict.tf_record")
file_based_convert_examples_to_features(predict_examples, label_list,
FLAGS.max_seq_length, tokenizer,
predict_file)
tf.logging.info("***** Running prediction*****")
tf.logging.info(" Num examples = %d (%d actual, %d padding)",
len(predict_examples), num_actual_predict_examples,
len(predict_examples) - num_actual_predict_examples)
tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size)
predict_drop_remainder = True if FLAGS.use_tpu else False
predict_input_fn = file_based_input_fn_builder(
input_file=predict_file,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=predict_drop_remainder)
result = estimator.predict(input_fn=predict_input_fn)
| tensorflow.logging.info | 5,446 |
import tensorflow as tf
generator_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate,
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)
| tensorflow.reshape | 5,447 |
import tensorflow as tf
# calculating loss
self._loss = None
if mode_gen in ('ce_train', 'loss', ):
xent = CE_loss(vocab_scores, answer_batch, loss_weights) # [batch_size]
if mode_gen == 'loss': xent *= self.placeholders.reward # multiply with rewards
self._loss = tf.reduce_mean(xent)
# Calculate coverage loss from the attention distributions
if options.use_coverage:
with tf.variable_scope('coverage_loss'):
self._coverage_loss = _coverage_loss(attn_dists, loss_weights)
| tensorflow.reduce_mean | 5,448 |
from tensorflow.contrib import layers
def default_input_fn(unused_estimator, examples):
return layers.parse_feature_columns_from_examples(examples,
self._feature_columns)
| tensorflow.contrib.layers.parse_feature_columns_from_examples | 5,449 |
import tensorflow as tf
def fc(x, scope, nh, *, init_scale=1.0, init_bias=0.0):
with tf.variable_scope(scope):
| tensorflow.variable_scope | 5,450 |
import tensorflow as tf
self.a = a
self.q = self._build_net(S, self.a, 'eval_net', trainable=True)
# Input (s_, a_), output q_ for q_target
self.q_ = self._build_net(S_, a_, 'target_net', trainable=False) # target_q is based on a_ from Actor's target_net
self.e_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Critic/eval_net')
self.t_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Critic/target_net')
with tf.variable_scope('target_q'):
self.target_q = R + self.gamma * self.q_
with tf.variable_scope('abs_TD'):
self.abs_td = tf.abs(self.target_q - self.q)
| tensorflow.get_collection | 5,451 |
import tensorflow as tf
sess.run(update_fp_false,
{holder: inp for holder, inp in zip(dec_inp_holder_fp_false,
dec_inp_fp_false)})
for v_true, v_false in matched_variables:
self.assertAllClose(v_true.eval(), v_false.eval())
def EmbeddingRNNSeq2SeqF(enc_inp, dec_inp, feed_previous):
cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True)
return tf.nn.seq2seq.embedding_rnn_seq2seq(
enc_inp, dec_inp, cell, num_encoder_symbols,
num_decoder_symbols, embedding_size=2, feed_previous=feed_previous)
def EmbeddingRNNSeq2SeqNoTupleF(enc_inp, dec_inp, feed_previous):
cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=False)
return tf.nn.seq2seq.embedding_rnn_seq2seq(
| tensorflow.nn.rnn_cell.BasicLSTMCell | 5,452 |
import tensorflow as tf
def cw_1d(X, y=None):
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)
| tensorflow.exp | 5,453 |
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('train_dir', '/tmp/cifar10_train',
"""Directory where to write event logs """
"""and checkpoint.""")
tf.app.flags.DEFINE_integer('max_steps', 1000000,
"""Number of batches to run.""")
tf.app.flags.DEFINE_integer('num_gpus', 1,
"""How many GPUs to use.""")
tf.app.flags.DEFINE_boolean('log_device_placement', False,
"""Whether to log device placement.""")
def tower_loss(scope):
"""Calculate the total loss on a single tower running the CIFAR model.
| tensorflow.app.flags.DEFINE_integer | 5,454 |
import tensorflow as tf
Tensor with nearest element in mean encoded in one-hot notation.
"""
x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keep_dims=True)
means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keep_dims=True)
scalar_prod = tf.matmul(
tf.transpose(x, perm=[1, 0, 2]), tf.transpose(means, perm=[0, 2, 1]))
scalar_prod = tf.transpose(scalar_prod, perm=[1, 0, 2])
dist = x_norm_sq + tf.transpose(
means_norm_sq, perm=[2, 0, 1]) - 2 * scalar_prod
if self.hparams.soft_em:
nearest_idx = tf.stack(
| tensorflow.transpose | 5,455 |
import tensorflow as tf
length = tf.reduce_sum(used, axis=1)
length = tf.cast(length, tf.int64)
return length
@staticmethod
def last_relevant(outputs, length):
# Borrowed from: https://gist.github.com/rockt/f4f9df5674f3da6a32786bcf9fbb6a88
batch_size, max_length, hidden_size = tf.unstack(tf.shape(outputs))
index = tf.range(0, batch_size) * max_length + (tf.cast(length, tf.int32) - 1)
flat = tf.reshape(outputs, [-1, hidden_size])
relevant = tf.gather(flat, index)
return relevant
| tensorflow.shape | 5,456 |
import tensorflow as tf
return {'w':self.w,'b':self.b}
class WeightNormTransposedConv2d(object):
def __init__(self,name,input_dim,out_dim,
k_h=4,k_w=4,d_h=2,d_w=2,stddev=0.02,data_format='NHWC',epsilon=1e-9) :
with tf.variable_scope(name) :
assert data_format == 'NHWC'
self.v = tf.get_variable('v', [k_h, k_w, out_dim, input_dim],
initializer=tf.truncated_normal_initializer(stddev=stddev))
self.g = tf.get_variable('g',[out_dim],
initializer=tf.constant_initializer(float('nan')))
self.b = tf.get_variable('b',[out_dim],
initializer=tf.constant_initializer(float('nan')))
self.strides = [1, d_h, d_w, 1]
| tensorflow.truncated_normal_initializer | 5,457 |
import tensorflow as tf
predictions = ssd.get_predictions(
score_threshold=params['score_threshold'],
iou_threshold=params['iou_threshold'],
max_boxes_per_class=params['max_boxes_per_class']
)
if mode == tf.estimator.ModeKeys.PREDICT:
# because images are resized before
# feeding them to the network
box_scaler = features['box_scaler']
predictions['boxes'] /= box_scaler
export_outputs = tf.estimator.export.PredictOutput({
name: tf.identity(tensor, name)
for name, tensor in predictions.items()
})
return tf.estimator.EstimatorSpec(
mode, predictions=predictions,
export_outputs={'outputs': export_outputs}
)
# add l2 regularization
with tf.name_scope('weight_decay'):
add_weight_decay(params['weight_decay'])
regularization_loss = tf.losses.get_regularization_loss()
# create localization and classification losses
| tensorflow.identity | 5,458 |
import tensorflow as tf
if self.config["model_heads"]:
span_indices = tf.expand_dims(tf.range(self.config["max_span_width"]), 0) + tf.expand_dims(span_starts, 1) # [k, max_span_width]
span_indices = tf.minimum(util.shape(context_outputs, 0) - 1, span_indices) # [k, max_span_width]
span_text_emb = tf.gather(head_emb, span_indices) # [k, max_span_width, emb]
with tf.variable_scope("head_scores"):
self.head_scores = util.projection(context_outputs, 1) # [num_words, 1]
span_head_scores = tf.gather(self.head_scores, span_indices) # [k, max_span_width, 1]
span_mask = tf.expand_dims(tf.sequence_mask(span_width, self.config["max_span_width"], dtype=tf.float32), 2) # [k, max_span_width, 1]
span_head_scores += tf.log(span_mask) # [k, max_span_width, 1]
| tensorflow.variable_scope | 5,459 |
import tensorflow as tf
#output = tf.reduce_sum(facts * tf.expand_dims(alphas, -1), 1)
output = facts * tf.expand_dims(alphas, -1)
output = tf.reshape(output, tf.shape(facts))
# output = output / (facts.get_shape().as_list()[-1] ** 0.5)
| tensorflow.shape | 5,460 |
from tensorflow.python.framework import tensor_util
segment_ids_shape.assert_has_rank(1)
indices_shape.assert_is_compatible_with(segment_ids_shape)
return [tensor_shape.TensorShape([None]).concatenate(data_shape[1:])]
@ops.RegisterShape("SparseSegmentMeanGrad")
def _SparseSegmentMeanGradShape(op):
"""Shape function for the SparseSegmentMeanGrad op."""
input_shape = op.inputs[0].get_shape()
indices_shape = op.inputs[1].get_shape().with_rank(1)
unused_segment_ids_shape = op.inputs[2].get_shape().merge_with(indices_shape)
unused_output_dim0_shape = op.inputs[3].get_shape().merge_with(
tensor_shape.scalar())
output_dim0 = tensor_util.ConstantValue(op.inputs[3])
if output_dim0 is not None:
dim0 = output_dim0[0]
else:
dim0 = None
return [tensor_shape.TensorShape([dim0]).concatenate(input_shape[1:])]
@ops.RegisterShape("UnsortedSegmentSum")
def _UnsortedSegmentSumShape(op):
"""Shape function for UnsortedSegmentSum."""
data_shape = op.inputs[0].get_shape()
segment_ids_shape = op.inputs[1].get_shape()
| tensorflow.python.framework.tensor_util.ConstantValue | 5,461 |
import tensorflow as tf
params.output,
"%s.json" % args.model,
collect_params(params, model_cls.get_parameters())
)
# Build Graph
with tf.Graph().as_default():
if not params.record:
# Build input queue
if params.use_bert and params.bert_emb_path:
features = dataset.get_training_input_with_bert(params.input + [params.bert_emb_path], params)
else:
| tensorflow.Graph | 5,462 |
from tensorflow.python.framework import ops
with ops.name_scope(name, values=(
(values or []) + [self.batch_ndims, self.event_ndims])) as scope:
yield scope
def _is_all_constant_helper(self, *args):
"""Helper which returns True if all inputs are constant_value."""
return all(tensor_util.constant_value(x) is not None for x in args)
def _assert_non_negative_int32_scalar(self, x):
"""Helper which ensures that input is a non-negative, int32, scalar."""
x = ops.convert_to_tensor(x, name="x")
if x.dtype.base_dtype != dtypes.int32.base_dtype:
raise TypeError("%s.dtype=%s is not %s" % (x.name, x.dtype, dtypes.int32))
x_value_static = tensor_util.constant_value(x)
if x.get_shape().ndims is not None and x_value_static is not None:
if x.get_shape().ndims != 0:
raise ValueError("%s.ndims=%d is not 0 (scalar)" %
(x.name, x.get_shape().ndims))
if x_value_static < 0:
raise ValueError("%s.value=%d cannot be negative" %
| tensorflow.python.framework.ops.convert_to_tensor | 5,463 |
import tensorflow as tf
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)
| tensorflow.summary.scalar | 5,464 |
import tensorflow as tf
tf.reset_default_graph()
self.graph = tf.Graph()
for c in self.graph.collections:
self.graph.clear_collection(c)
self.graph_manager = self.graph.as_default()
self.graph_manager.__enter__()
self.sess = tf.Session(graph=self.graph)
self.sess_manager = self.sess.as_default()
self.sess_manager.__enter__()
self.sess.__enter__()
logger.add_output(NullOutput())
deterministic.set_seed(1)
| tensorflow.Session | 5,465 |
from tensorflow.contrib.eager.python import tfe
data_dir = os.path.join(FLAGS.dir, "data")
train_data = load_dataset(
data_dir=data_dir, url=SOURCE_TRAIN_URL, batch_size=FLAGS.batch_size)
eval_data = load_dataset(
data_dir=data_dir, url=SOURCE_TEST_URL, batch_size=FLAGS.batch_size)
model = RNNColorbot(
rnn_cell_sizes=FLAGS.rnn_cell_sizes,
label_dimension=3,
keep_prob=FLAGS.keep_probability)
optimizer = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate)
if FLAGS.no_gpu or tfe.num_gpus() <= 0:
print(tfe.num_gpus())
device = "/cpu:0"
else:
device = "/gpu:0"
print("Using device %s." % device)
log_dir = os.path.join(FLAGS.dir, "summaries")
tf.gfile.MakeDirs(log_dir)
train_summary_writer = tf.contrib.summary.create_file_writer(
os.path.join(log_dir, "train"), flush_millis=10000)
test_summary_writer = tf.contrib.summary.create_file_writer(
| tensorflow.contrib.eager.python.tfe.num_gpus | 5,466 |
from tensorflow.contrib.rnn.python.ops import core_rnn
with ops.Graph().as_default(), ops.device("/device:GPU:0"):
inputs = seq_length * [
array_ops.zeros([batch_size, num_units], dtypes.float32)
]
cell = lambda: lstm_ops.LSTMBlockCell(num_units=num_units) # pylint: disable=cell-var-from-loop
multi_cell = rnn_cell.MultiRNNCell(
[cell() for _ in range(num_layers)])
outputs, final_state = core_rnn.static_rnn(
multi_cell, inputs, dtype=dtypes.float32)
trainable_variables = ops.get_collection(
ops.GraphKeys.TRAINABLE_VARIABLES)
gradients = gradients_impl.gradients([outputs, final_state],
trainable_variables)
training_op = control_flow_ops.group(*gradients)
self._BenchmarkOp(training_op, "tf_rnn_lstm_block_cell %s %s" %
| tensorflow.contrib.rnn.python.ops.core_rnn.static_rnn | 5,467 |
import tensorflow as tf
tf.summary.image('geo_map_0', geo_maps[:, :, :, 0:1])
tf.summary.image('geo_map_0_pred', f_geometry[:, :, :, 0:1])
tf.summary.image('training_masks', training_masks)
tf.summary.scalar('model_loss', model_loss)
| tensorflow.summary.image | 5,468 |
import tensorflow as tf
tf.summary.histogram('weight', filt)
tf.summary.histogram('bias', conv_biases)
return bias
def conv_bn_relu(self, bottom,name, kernel_size, output_channels, initializer,stride=1, bn=False,training=False,relu=True):
input_channels = bottom.get_shape().as_list()[-1]
with tf.variable_scope(name) as scope:
kernel = self.variable('weights', [kernel_size, kernel_size, input_channels, output_channels], initializer, regularizer=tf.contrib.layers.l2_regularizer(0.0005))
conv = tf.nn.conv2d(bottom, kernel, [1, stride, stride, 1], padding='SAME')
biases = self.variable('biases', [output_channels], tf.constant_initializer(0.0))
conv_layer = tf.nn.bias_add(conv, biases)
if bn:
conv_layer = self.batch_norm_layer('batch_norm_layer',conv_layer,training)
if relu:
conv_layer = tf.nn.relu(conv_layer, name=scope.name)
print('Conv layer {0} -> {1}'.format(bottom.get_shape().as_list(),conv_layer.get_shape().as_list()))
| tensorflow.contrib.layers.l2_regularizer | 5,469 |
import tensorflow as tf
result = self.dflux / self.dtime
if clip_magnitude is not None:
result = tf.clip_by_value(
result, clip_value_min=-clip_magnitude, clip_value_max=clip_magnitude
| tensorflow.clip_by_value | 5,470 |
import tensorflow as tf
update_mean = moving_averages.assign_moving_average(moving_mean, mean, decay)
update_variance = moving_averages.assign_moving_average(moving_variance, variance, decay)
with tf.control_dependencies([update_mean, update_variance]):
X = tf.identity(X)
else:
# For prediction, do batch norm with computed moving mean & variance from training
# Don't update moving averages if predicting
(X, _, _) = tf.nn.fused_batch_norm(X, scale, offset, mean=moving_mean, variance=moving_variance,
epsilon=epsilon, is_training=False)
else:
(X, _, _) = tf.nn.fused_batch_norm(X, scale, offset, epsilon=epsilon, is_training=True)
return X
def _mark_for_monitoring(self, name, value):
tf.add_to_collection(TF_COLLECTION_MONITORED, tf.identity(value, name))
def _add_monitoring_of_values(self):
monitored_values = tf.get_collection(TF_COLLECTION_MONITORED)
monitored_values = {
| tensorflow.nn.fused_batch_norm | 5,471 |
from tensorflow.python.framework import ops
with ops.op_scope([x], name, "Tanh") as name:
x = ops.convert_to_tensor(x, name="x")
return gen_math_ops._tanh(x, name=name)
ops.RegisterShape("Abs")(common_shapes.unchanged_shape)
ops.RegisterShape("Ceil")(common_shapes.unchanged_shape)
ops.RegisterShape("Conj")(common_shapes.unchanged_shape)
ops.RegisterShape("Cos")(common_shapes.unchanged_shape)
ops.RegisterShape("Exp")(common_shapes.unchanged_shape)
ops.RegisterShape("Floor")(common_shapes.unchanged_shape)
ops.RegisterShape("Imag")(common_shapes.unchanged_shape)
ops.RegisterShape("Inv")(common_shapes.unchanged_shape)
ops.RegisterShape("IsFinite")(common_shapes.unchanged_shape)
ops.RegisterShape("IsInf")(common_shapes.unchanged_shape)
ops.RegisterShape("IsNan")(common_shapes.unchanged_shape)
| tensorflow.python.framework.ops.RegisterShape | 5,472 |
from tensorflow.python.ops import array_ops
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)
| tensorflow.python.ops.array_ops.shape | 5,473 |
import tensorflow as tf
bboxes = tf.concat(
| tensorflow.concat | 5,474 |
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
output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
logits = tf.matmul(output_layer, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
probabilities = tf.nn.softmax(logits, axis=-1)
log_probs = tf.nn.log_softmax(logits, axis=-1)
one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)
per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
loss = tf.reduce_mean(per_example_loss)
| tensorflow.variable_scope | 5,475 |
import tensorflow as tf
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.train.GradientDescentOptimizer | 5,476 |
import tensorflow as tf
print(ops) # => prints ops created.
"""
micros = int(time.time()*10**6)
scope_name = str(micros)
op_list = []
with tf.name_scope(scope_name):
yield op_list
g = tf.get_default_graph()
op_list.extend(ge.select_ops(scope_name+"/.*", graph=g))
def _to_op(tensor_or_op):
if hasattr(tensor_or_op, "op"):
return tensor_or_op.op
return tensor_or_op
def _to_ops(iterable):
| tensorflow.get_default_graph | 5,477 |
import tensorflow as tf
anchor_ratios = [0.25, 0.5, 1.0, 2.0, 4.0]
height, width = 64, 128
anchors = generate(anchor_size,
anchor_stride,
anchor_scales,
anchor_ratios,
height,
width)
init = tf.global_variables_initializer()
with tf.Session(config=tf.ConfigProto(device_count={'GPU': 0})) as sess:
sess.run(init)
anchors_out = sess.run(anchors)
print(anchors_out[-30:])
print(anchors.shape)
print(anchors_out[158623])
| tensorflow.global_variables_initializer | 5,478 |
import tensorflow as tf
name,
shape=[],
dtype=tf.int64,
initializer=tf.initializers.zeros(),
trainable=False,
collections=[tf.GraphKeys.GLOBAL_VARIABLES])
| tensorflow.initializers.zeros | 5,479 |
import tensorflow as tf
final_loss = tf.reduce_mean(loss)
return final_loss, cstr_pct
def contra_traj_lossV4(pred, tgt, horizon=12, resample=1, hard_ratio=1.0):
horizon_pred = horizon_sumV1(pred, horizon)
horizon_tgt = horizon_sumV1(tgt, horizon)
pred_flat = tf.reshape(horizon_pred, [-1])
tgt_flat = tf.reshape(horizon_tgt, [-1])
batch = tf.stack([pred_flat, tgt_flat], 1)
sample_func = sample_pair(batch)
def sample_compute(_):
pairs = sample_func()
| tensorflow.reshape | 5,480 |
import tensorflow as tf
hyper_decoder=hyper_decoder,
estimator=entropy_bottleneck)
status = checkpoint.restore(tf.train.latest_checkpoint(ckpt_dir))
zs = entropy_bottleneck.decompress(z_strings, z_min_v, z_max_v, z_shape, z_shape[-1])
print("Entropy Decoder (Hyper)")
def loop_hyper_deocder(z):
z = tf.expand_dims(z, 0)
loc, scale = hyper_decoder(z)
return tf.squeeze(loc, [0]), tf.squeeze(scale, [0])
locs, scales = tf.map_fn(loop_hyper_deocder, zs, dtype=(tf.float32, tf.float32),
parallel_iterations=1, back_prop=False)
lower_bound = 1e-9# TODO
scales = tf.maximum(scales, lower_bound)
print("Hyper Decoder")
ys = conditional_entropy_model.decompress(y_strings, locs, scales, y_min_v, y_max_v, y_shape)
print("Entropy Decoder")
def loop_synthesis(element):
y = tf.expand_dims(element[0], 0)
x_coori = tf.expand_dims(element[1], 0)
| tensorflow.map_fn | 5,481 |
import tensorflow as tf
loss = tf.reduce_mean(loss)
return loss
def contra_step_lossV4(pred, tgt):
# 50*50
# Step-wise contrastive loss
even = [2 * i for i in range(25)]
odd = [2 * i + 1 for i in range(25)]
pred1 = tf.gather(pred, even)
pred2 = tf.gather(pred, odd)
tgt1 = tf.gather(tgt, even)
tgt2 = tf.gather(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.maximum(0.0, tf.math.abs(tgt_larg - pred_larg) - tf.math.abs(tgt_small - pred_small))
loss = tf.reduce_mean(loss)
return loss
| tensorflow.gather | 5,482 |
from tensorflow.python.framework import op_def_library as _op_def_library
Returns:
A tuple of `Tensor` objects (output1, output2).
output1: A `Tensor` of type `float32`.
output2: A `Tensor` of type `string`.
"""
result = _op_def_lib.apply_op("TestStringOutput", input=input, name=name)
return _TestStringOutputOutput._make(result)
_ops.RegisterShape("TestStringOutput")(None)
def _InitOpDefLibrary():
op_list = _op_def_pb2.OpList()
_text_format.Merge(_InitOpDefLibrary.op_list_ascii, op_list)
_op_def_registry.register_op_list(op_list)
op_def_lib = _op_def_library.OpDefLibrary()
op_def_lib.add_op_list(op_list)
return op_def_lib
_InitOpDefLibrary.op_list_ascii = """op {
name: "GraphDefVersion"
output_arg {
name: "version"
type: DT_INT32
}
is_stateful: true
}
op {
name: "KernelLabel"
| tensorflow.python.framework.op_def_library.OpDefLibrary | 5,483 |
import tensorflow as tf
blk_shape[0], q_shape[1] * strides[1], q_shape[2] * strides[2], 3
], strides)
blk_indices_crop = blk_indices_crop // tf.stack([1, strides[1], strides[2]])
return blk_indices_crop
def _strides_one():
# Calculate otuput indices when strides = 1.
return blk_indices[:, :q_shape[1], :q_shape[2], :]
strides_gt_one = tf.logical_or(tf.greater(strides[1], 1), tf.greater(strides[2], 1))
blk_indices_crop = tf.cond(strides_gt_one, _strides_gt_one, _strides_one)
y = tf.scatter_nd(blk_indices_crop, q, out_shape)
return y
return tf.cond(
tf.equal(tf.size(blk_indices_), 0), lambda: tf.zeros(out_shape, dtype=x.dtype),
_conv_nonzero)
# returns an int64 start timer handle that should be passed to cuda_timer_end_op
| tensorflow.cond | 5,484 |
import tensorflow as tf
else:
return tf.concat(sharded_logits, 0), losses
| tensorflow.concat | 5,485 |
import tensorflow as tf
def f(layer_input):
return tf.keras.layers.concatenate(list(layer_input), axis=-1)
return tf.keras.layers.Lambda(f)
@gin.configurable
def extract_observation_layer():
return tf.keras.layers.Lambda(lambda obs: obs['observation'])
@gin.configurable
def monitor_freq(freq=100, vid_dir='./videos'):
return functools.partial(Monitor, video_callable=lambda x: (x%freq) == 0,
directory=vid_dir)
| tensorflow.keras.layers.Lambda | 5,486 |
import tensorflow as tf
tgt_flat = tf.reshape(horizon_tgt, [-1])
batch = tf.stack([pred_flat, tgt_flat], 1)
| tensorflow.stack | 5,487 |
import tensorflow as tf
# mse_loss = tf.multiply(params['mse_weight'] / params['num_stacks'], tf.add_n(bce_loss_list), name='mse_loss')
# tf.summary.scalar('mse', mse_loss)
# tf.losses.add_loss(mse_loss)
# Add weight decay to the loss. We exclude the batch norm variables because
# doing so leads to a small improvement in accuracy.
loss = mse_loss + params['weight_decay'] * tf.add_n([tf.nn.l2_loss(v) for v in tf.trainable_variables() if 'batch_normalization' not in v.name])
total_loss = tf.identity(loss, name='total_loss')
tf.summary.scalar('loss', total_loss)
if mode == tf.estimator.ModeKeys.EVAL:
return tf.estimator.EstimatorSpec(mode=mode, loss=loss, predictions=predictions, eval_metric_ops=metrics)
| tensorflow.nn.l2_loss | 5,488 |
from tensorflow.python.platform import tf_logging as logging
if np.isnan(_extract_output(outputs, self._loss_tensor)):
failure_message = "Model diverged with loss = NaN."
if self._fail_on_nan_loss:
logging.error(failure_message)
raise NanLossDuringTrainingError
else:
logging.warning(failure_message)
# We don't raise an error but we return "should stop" so we stop, but
# without an exception.
return True
| tensorflow.python.platform.tf_logging.warning | 5,489 |
import tensorflow as tf
def main(argv=None):
keep_probability = tf.placeholder(tf.float32, name="keep_probabilty")
image = tf.placeholder(tf.float32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 3], name="input_image")
annotation = tf.placeholder(tf.float32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 3], name="annotation")
z = tf.placeholder(tf.float32, shape=[None, 4, 4, 128], name="z")
# pred_annotation, logits = inference(image, keep_probability,z)
# tf.summary.image("input_image", image, max_outputs=2)
# tf.summary.image("ground_truth", tf.cast(annotation, tf.uint8), max_outputs=2)
# tf.summary.image("pred_annotation", tf.cast(pred_annotation, tf.uint8), max_outputs=2)
| tensorflow.placeholder | 5,490 |
from tensorflow.python.ops import check_ops
`mask` if `weights` is `None`, and otherwise `weights`.
Raises:
ValueError: If `weights` and `mask` are not `None` and have mismatched
shapes.
"""
if mask is not None:
check_ops.assert_type(mask, dtypes.bool)
if weights is None:
weights = array_ops.ones_like(mask, dtype=dtypes.float32)
weights = math_ops.cast(math_ops.logical_not(mask), weights.dtype) * weights
return weights
| tensorflow.python.ops.check_ops.assert_type | 5,491 |
import tensorflow as tf
with tf.Session("", graph=tf.Graph()) as sess:
with sess.graph.device("/gpu:0"):
v0_1 = tf.Variable(123.45)
save = tf.train.Saver({"v0": v0_1})
tf.initialize_all_variables().run()
save.save(sess, save_path)
with tf.Session("", graph=tf.Graph()) as sess:
with sess.graph.device("/gpu:0"):
v0_2 = tf.Variable(543.21)
save = tf.train.Saver({"v0": v0_2})
tf.initialize_all_variables().run()
self.assertAllClose(543.21, v0_2.eval())
save.restore(sess, save_path)
| tensorflow.Graph | 5,492 |
import tensorflow as tf
with tf.variable_scope("loss"):
if is_training:
output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
output_layer = tf.reshape(output_layer, [-1, hidden_size])
logits = tf.matmul(output_layer, output_weight, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
logits = tf.reshape(logits, [-1, FLAGS.max_seq_length, 11])
log_probs = tf.nn.log_softmax(logits, axis=-1)
# labels = tf.cast(labels,dtype=tf.float32)
one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)
per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
loss = tf.reduce_sum(per_example_loss)
return (loss, per_example_loss, logits)
def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps, use_tpu,
use_one_hot_embeddings):
def model_fn(features, labels, mode, params):
tf.logging.info("*** Features ***")
for name in sorted(features.keys()):
| tensorflow.reduce_sum | 5,493 |
import tensorflow as tf
min_iou_thresh=0.5,
is_class_agnostic=False)
nms_masks_expected2 = tf.stack([mask2, mask0, mask5, mask4])
nms_scores_expected2 = tf.constant([0.95, 1.0, 0.8, 0.7], dtype=tf.float32)
nms_classes_expected2 = tf.constant([0, 1, 2, 2], dtype=tf.int32)
self.assertAllEqual(nms_masks1.numpy(), nms_masks_expected1.numpy())
self.assertAllClose(nms_scores1.numpy(), nms_scores_expected1.numpy())
self.assertAllEqual(nms_classes1.numpy(), nms_classes_expected1.numpy())
| tensorflow.constant | 5,494 |
import tensorflow as tf
with tf.variable_scope("stats") as scope:
for i in range(hparams.tacotron_num_gpus):
tf.summary.histogram("mel_outputs %d" % i, model.tower_mel_outputs[i])
tf.summary.histogram("mel_targets %d" % i, model.tower_mel_targets[i])
tf.summary.scalar("before_loss", model.before_loss)
tf.summary.scalar("after_loss", model.after_loss)
if hparams.predict_linear:
tf.summary.scalar("linear_loss", model.linear_loss)
for i in range(hparams.tacotron_num_gpus):
tf.summary.histogram("mel_outputs %d" % i, model.tower_linear_outputs[i])
tf.summary.histogram("mel_targets %d" % i, model.tower_linear_targets[i])
tf.summary.scalar("regularization_loss", model.regularization_loss)
tf.summary.scalar("stop_token_loss", model.stop_token_loss)
tf.summary.scalar("loss", model.loss)
tf.summary.scalar("learning_rate", model.learning_rate) # Control learning rate decay speed
if hparams.tacotron_teacher_forcing_mode == "scheduled":
tf.summary.scalar("teacher_forcing_ratio", model.ratio) # Control teacher forcing
# ratio decay when mode = "scheduled"
| tensorflow.summary.histogram | 5,495 |
import tensorflow as tf
def validation_mapper(byte):
image = tf.image.decode_jpeg(
tf.reshape(byte, shape=[]), 3, **JPEG_OPT)
image = resize_shortest_edge(image, tf.shape(image), 256)
image = center_crop(image, 224)
image = tf.reverse(image, axis=[2]) # to BGR
return image
def training_mapper(byte):
jpeg_shape = tf.image.extract_jpeg_shape(byte) # hwc
bbox_begin, bbox_size, distort_bbox = tf.image.sample_distorted_bounding_box(
| tensorflow.reverse | 5,496 |
import tensorflow as tf
'WS: pruning ratio protocol (\'uniform\' | \'heurist\' | \'optimal\')')
tf.app.flags.DEFINE_integer('ws_nb_rlouts', 200, 'WS: # of roll-outs for the RL agent')
tf.app.flags.DEFINE_integer('ws_nb_rlouts_min', 50,
'WS: minimal # of roll-outs for the RL agent to start training')
tf.app.flags.DEFINE_string('ws_reward_type', 'single-obj',
'WS: reward type (\'single-obj\' OR \'multi-obj\')')
tf.app.flags.DEFINE_float('ws_lrn_rate_rg', 3e-2, 'WS: learning rate for layerwise regression')
tf.app.flags.DEFINE_integer('ws_nb_iters_rg', 20, 'WS: # of iterations for layerwise regression')
tf.app.flags.DEFINE_float('ws_lrn_rate_ft', 3e-4, 'WS: learning rate for global fine-tuning')
tf.app.flags.DEFINE_integer('ws_nb_iters_ft', 400, 'WS: # of iterations for global fine-tuning')
tf.app.flags.DEFINE_integer('ws_nb_iters_feval', 25, 'WS: # of iterations for fast evaluation')
tf.app.flags.DEFINE_float('ws_prune_ratio_exp', 3.0, 'WS: pruning ratio\'s exponent term')
tf.app.flags.DEFINE_float('ws_iter_ratio_beg', 0.1, 'WS: iteration ratio (at starting time)')
tf.app.flags.DEFINE_float('ws_iter_ratio_end', 0.5, 'WS: iteration ratio (at ending time)')
tf.app.flags.DEFINE_float('ws_mask_update_step', 500, 'WS: step size for updating the pruning mask')
def calc_prune_ratio(vars_list):
"""Calculate the overall pruning ratio for the given list of variables.
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])
| tensorflow.app.flags.DEFINE_float | 5,497 |
from tensorflow.contrib.distributions.python.ops import distribution_util
return control_flow_ops.with_dependencies([
check_ops.assert_less(
array_ops.ones((), self.dtype), self.alpha,
message="mean not defined for components of self.alpha <= 1"),
], mean)
@distribution_util.AppendDocstring(
"""Variance for inverse gamma is defined only for `alpha > 2`. If
`self.allow_nan_stats` is `False`, an exception will be raised rather
than returning `NaN`.""")
def _variance(self):
var = (math_ops.square(self.beta) /
| tensorflow.contrib.distributions.python.ops.distribution_util.AppendDocstring | 5,498 |
import tensorflow as tf
x = tf.placeholder_with_default(input=[1., 3., 5.], shape=[3])
log_prob = pareto.log_prob(x)
self.evaluate(log_prob)
def testParetoLogPdfMultidimensional(self):
batch_size = 6
scale = tf.constant([[2., 4., 5.]] * batch_size)
scale_v = [2., 4., 5.]
concentration = tf.constant([[1.]] * batch_size)
concentration_v = 1.
x = np.array([[6., 7., 9.2, 5., 6., 7.]], dtype=np.float32).T
pareto = tfd.Pareto(concentration, scale)
log_prob = pareto.log_prob(x)
self.assertEqual(log_prob.shape, (6, 3))
| tensorflow.constant | 5,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.