seed
stringlengths 25
1.88k
| seed_api
stringlengths 14
102
| index
int64 0
1.05k
|
---|---|---|
import tensorflow as tf
return crop
def random_apply(fn, image, prob=1.):
b, *_ = image.get_shape().as_list()
chance = tf.less(tf.random_uniform([b], 0, 1.0), prob)
return tf.where(chance, fn(image), tf.identity(image))
def color_distortion(image, s=1.0):
lower, upper, x = (1 - 0.8 * s), (1 + 0.8 * s), image
x = tf.image.random_brightness(x, max_delta=0.8*s)
x = tf.image.random_contrast(x, lower=lower, upper=upper)
x = tf.image.random_saturation(x, lower=lower, upper=upper)
x = tf.image.random_hue(x, max_delta=0.2*s)
x = tf.clip_by_value(x, 0, 1)
return x
def color_drop(image):
image = tf.image.rgb_to_grayscale(image)
image = tf.tile(image, [1, 1, 1, 3])
return image
# pylint: disable=not-callable
@gin.configurable(blacklist=["kwargs"])
class CLGAN(modular_gan.ModularGAN):
| tensorflow.image.random_hue | 500 |
import tensorflow as tf
if FLAGS.use_tpu and FLAGS.tpu_name:
tpu_cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver(
| tensorflow.distribute.cluster_resolver.TPUClusterResolver | 501 |
import tensorflow as tf
return out
@layer
def recurrent_layer(tensor, cell=None, hidden_dims=128, sequence_length=None, decoder_fn=None,
activation=tf.nn.tanh, initializer=tf.orthogonal_initializer(), initial_state=None,
keep_prob=1.0,
return_final_state=False, return_next_cell_input=True, **opts):
if cell is None:
cell = tf.contrib.rnn.BasicRNNCell(hidden_dims, activation=activation)
# cell = tf.contrib.rnn.LSTMCell(hidden_dims, activation=activation)
if keep_prob < 1.0:
keep_prob = _global_keep_prob(keep_prob)
cell = tf.contrib.rnn.DropoutWrapper(cell, keep_prob, keep_prob)
if opts.get("name"):
tf.add_to_collection(opts.get("name"), cell)
| tensorflow.contrib.rnn.BasicRNNCell | 502 |
import tensorflow as tf
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
| tensorflow.log | 503 |
from tensorflow.contrib.distributions.python.ops import distribution_util
x: `Tensor`. Input transposed/reshaped to `B_+E_+S_`.
sample_shape: `Tensor` (1D, `int32`).
"""
with self._name_scope(name, values=[x]):
x = ops.convert_to_tensor(x, name="x")
sample_shape, batch_shape, event_shape = self.get_shape(x)
event_shape = distribution_util.pick_vector(
self._event_ndims_is_0, (1,), event_shape)
batch_shape = distribution_util.pick_vector(
self._batch_ndims_is_0, (1,), batch_shape)
new_shape = array_ops.concat(0, ((-1,), batch_shape, event_shape))
x = array_ops.reshape(x, shape=new_shape)
| tensorflow.contrib.distributions.python.ops.distribution_util.pick_vector | 504 |
from tensorflow.python.framework import random_seed
embed_np = embeds[ids]
embed_tf = ops.embedding_lookup(embeds, ids).eval()
self.assertEqual(embed_np.shape, embed_tf.shape)
self.assertAllClose(embed_np, embed_tf)
def test_categorical_variable(self):
random_seed.set_random_seed(42)
with self.cached_session() as sess:
cat_var_idx = array_ops.placeholder(dtypes.int64, [2, 2])
embeddings = ops.categorical_variable(
cat_var_idx, n_classes=5, embedding_size=10, name="my_cat_var")
sess.run(variables.global_variables_initializer())
| tensorflow.python.framework.random_seed.set_random_seed | 505 |
from tensorflow.core.framework import op_def_pb2
def _to_argdef_list(args):
names = [n for n, t in args]
if len(names) != len(set(names)):
raise ValueError("Expected names to all be unique: %s" % str(names))
return [op_def_pb2.OpDef.ArgDef(type=t.as_datatype_enum, name=n)
for n, t in args]
self._sig.input_arg.extend(_to_argdef_list(inputs))
self._sig.output_arg.extend(_to_argdef_list(outputs))
| tensorflow.core.framework.op_def_pb2.OpDef.ArgDef | 506 |
import tensorflow as tf
tf.saved_model.load(
| tensorflow.saved_model.load | 507 |
import tensorflow as tf
with tf.variable_scope(scope_name):
dec_op, _ = seq2seq(enc_inp, dec_inp, feed_previous=feed_previous)
net_variables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,
scope_name)
optimizer = tf.train.AdamOptimizer(0.03, epsilon=1e-5)
update_op = optimizer.minimize(
tf.nn.seq2seq.sequence_loss(dec_op, targets, weights),
var_list=net_variables)
return dec_op, update_op, net_variables
dec_op_fp_true, update_fp_true, variables_fp_true = ForwardBackward(
enc_inp, dec_inp_fp_true, feed_previous=True)
| tensorflow.nn.seq2seq.sequence_loss | 508 |
import tensorflow as tf
self._deeplift_ref.clear()
ops = []
g = tf.compat.v1.get_default_graph()
for op in g.get_operations():
| tensorflow.compat.v1.get_default_graph | 509 |
import tensorflow as tf
def cnn_bi_lstm_model(x, amp_factor, bil_lstm_win_size, num_classes):
logits = cnn_model(x, amp_factor=amp_factor)
logits = tf.reshape(logits, [-1, bil_lstm_win_size, 256*amp_factor])
forward_cell = tf.nn.rnn_cell.LSTMCell(128)
backward_cell = tf.nn.rnn_cell.LSTMCell(128)
encoder_outputs,_ = tf.nn.bidirectional_dynamic_rnn(
forward_cell,
backward_cell,
logits,
| tensorflow.nn.rnn_cell.LSTMCell | 510 |
import tensorflow as tf
def conv_layer(self, bottom, kernal_size, in_channels, out_channels, stride, name):
with tf.variable_scope(name):
filt, conv_biases = self.get_conv_var(kernal_size, in_channels, out_channels, name)
conv = tf.nn.conv2d(bottom, filt, [1,stride,stride,1], padding='SAME')
bias = tf.nn.bias_add(conv, conv_biases)
tf.summary.histogram('weight', filt)
tf.summary.histogram('bias', conv_biases)
return bias
def conv_bn_relu(self, bottom,name, kernel_size, output_channels, initializer,stride=1, bn=False,training=False,relu=True):
| tensorflow.summary.histogram | 511 |
from tensorflow.python.ops import gen_nn_ops
"""
return gen_nn_ops._top_kv2(input, k=k, sorted=sorted, name=name)
| tensorflow.python.ops.gen_nn_ops._top_kv2 | 512 |
import tensorflow as tf
:param cov_structure: "diag" or "full"
- "diag": cov holds the diagonal elements of the covariance matrix
- "full": cov holds the full covariance matrix (without jitter)
:return: sample from the MVN of shape N x D
"""
eps = tf.random_normal(tf.shape(mean), dtype=settings.float_type) # N x P
if cov_structure == "diag":
sample = mean + tf.sqrt(cov) * eps # N x P
elif cov_structure == "full":
cov = cov + (tf.eye(tf.shape(mean)[1], dtype=settings.float_type) * settings.numerics.jitter_level)[None, ...] # N x P x P
chol = tf.cholesky(cov) # N x P x P
return mean + (tf.matmul(chol, eps[..., None])[..., 0]) # N x P
else:
raise NotImplementedError # pragma: no cover
return sample # N x P
def _expand_independent_outputs(fvar, full_cov, full_output_cov):
"""
Reshapes fvar to the correct shape, specified by `full_cov` and `full_output_cov`.
| tensorflow.cholesky | 513 |
from tensorflow.python.framework import dtypes
**self._extra_kwargs)
_ = defined.name # Fully instantiate the function definition.
if self._grad_func:
# If _grad_func is given, it is another
# _OverloadedFunction. We need to instantiate it with the
# right input types.
output_types = [
dtypes.DType(_.type)
for _ in defined.definition.signature.output_arg
]
# pylint: disable=protected-access
defined._grad_func = self._grad_func.instantiate(input_types +
output_types)
# pylint: enable=protected-access
| tensorflow.python.framework.dtypes.DType | 514 |
import tensorflow as tf
'a',
py_utils.WeightParams(shape=[], init=py_utils.WeightInit.Constant(0)))
var_a = task.theta.a
# Make a NaN gradient.
var_grads = py_utils.NestedMap(a=(var_a, 0. * tf.log(0.)))
has_nan_or_inf, grad_scale, final_var_grads = task.ScaleGradients(var_grads)
with self.session():
tf.global_variables_initializer().run()
self.assertTrue(has_nan_or_inf.eval())
self.assertEqual(0., grad_scale.eval())
# The final gradient must be finite.
self.assertFalse(tf.is_nan(final_var_grads.a[1]).eval())
self.assertTrue(tf.is_finite(final_var_grads.a[1]).eval())
def testScaleGradientsCheckNumerics(self):
"""ScaleGradients when enable_check_numerics=True."""
FLAGS.enable_check_numerics = True
p = self.TestParams()
p.input = base_input_generator.BaseSequenceInputGenerator.Params()
task = p.cls(p)
task.CreateVariable(
'a',
py_utils.WeightParams(shape=[], init=py_utils.WeightInit.Constant(0)))
| tensorflow.is_nan | 515 |
from tensorflow.contrib import metrics as metrics_lib
metrics[_MetricKeys.PRECISION_MEAN % threshold] = _streaming_with_threshold(
metrics_lib.streaming_precision, threshold)
# Recall for positive examples.
metrics[_MetricKeys.RECALL_MEAN % threshold] = _streaming_with_threshold(
metrics_lib.streaming_recall, threshold)
return metrics
# TODO(zakaria): support weights.
def _targets_streaming_mean(unused_predictions, targets):
return metrics_lib.streaming_mean(targets)
def _predictions_streaming_mean(predictions, unused_targets):
return metrics_lib.streaming_mean(predictions)
def _streaming_with_threshold(streaming_metrics_fn, threshold):
def _streaming_metrics(predictions, targets):
return streaming_metrics_fn(predictions=math_ops.to_float(
| tensorflow.contrib.metrics.streaming_mean | 516 |
from tensorflow.python.ops import gen_nn_ops
" {}".format(padding))
return gen_nn_ops.conv2d_backprop_input(input_sizes=output_shape_,
filter=filter,
| tensorflow.python.ops.gen_nn_ops.conv2d_backprop_input | 517 |
from tensorflow.python.eager import test
if __name__ == "__main__":
test.main()
| tensorflow.python.eager.test.main | 518 |
import tensorflow as tf
initializer=tf.constant_initializer(0), trainable=False)
label = tf.reshape(label, [-1])
centers_batch = tf.gather(centers, label)
diff = (1 - alfa) * (centers_batch - features)
centers = tf.scatter_sub(centers, label, diff)
# centers = tf.nn.l2_normalize(centers, 1, 1e-10, name='centers_norm')
loss = tf.reduce_mean(tf.square(features - centers_batch))
return loss, centers
| tensorflow.scatter_sub | 519 |
import tensorflow as tf
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
return tf.train.Scaffold()
| tensorflow.train.Scaffold | 520 |
import tensorflow as tf
train_op = opt.apply_gradients(grads_and_vars, global_step)
# Validation
'''
if params.validation and params.references[0]:
files = [params.validation] + list(params.references)
eval_inputs = files
eval_input_fn = dataset.get_evaluation_input
else:
print("Don't evaluate")
eval_input_fn = None
'''
# Add hooks
train_hooks = [
tf.train.StopAtStepHook(last_step=params.train_steps),
tf.train.NanTensorHook(loss), # Monitors the loss tensor and stops training if loss is NaN
tf.train.LoggingTensorHook(
{
"step": global_step,
"loss": loss,
"chars": tf.shape(features["chars"]),
"source": tf.shape(features["source"]),
#"bert": tf.shape(features["bert"]),
"lr": learning_rate
},
every_n_iter=1
),
tf.train.CheckpointSaverHook(
| tensorflow.train.StopAtStepHook | 521 |
from tensorflow.python.ops import gen_nn_ops
features: A `Tensor` with type `float`, `double`, `int32`, `int64`, `uint8`,
`int16`, or `int8`.
name: A name for the operation (optional).
Returns:
A `Tensor` with the same type as `features`.
"""
with ops.op_scope([features], name, "Relu6") as name:
features = ops.convert_to_tensor(features, name="features")
return gen_nn_ops._relu6(features, name=name)
def softmax_cross_entropy_with_logits(logits, labels, name=None):
"""Computes softmax cross entropy between `logits` and `labels`.
Measures the probability error in discrete classification tasks in which the
classes are mutually exclusive (each entry is in exactly one class). For
example, each CIFAR-10 image is labeled with one and only one label: an image
| tensorflow.python.ops.gen_nn_ops._relu6 | 522 |
from tensorflow.contrib.slim.python.slim.data import tfexample_decoder
items_to_handlers = {
'image': tfexample_decoder.Image(),
'label': tfexample_decoder.Tensor('image/class/label'),
}
| tensorflow.contrib.slim.python.slim.data.tfexample_decoder.Tensor | 523 |
import tensorflow as tf
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)
| tensorflow.layers.flatten | 524 |
from tensorflow.python.ops import array_ops
next_size = _next_array_size(new_size)
next_shape = array_ops.pack([next_size] + fixed_shape)
new_value = array_ops.zeros(next_shape, dtype=values.dtype)
old_value = array.value()
assign_op = state_ops.assign(array, new_value, validate_shape=False)
with ops.control_dependencies([assign_op]):
copy_op = array[:size].assign(old_value[:size])
# return value needs to be the same dtype as no_op() for cond
with ops.control_dependencies([copy_op]):
return control_flow_ops.no_op()
new_size = size + batch_size
array_size = array_ops.shape_internal(array, optimize=False)[0]
maybe_reallocate_op = control_flow_ops.cond(
new_size > array_size, reallocate, control_flow_ops.no_op)
with ops.control_dependencies([maybe_reallocate_op]):
append_values_op = array[size:new_size].assign(batch_values)
with ops.control_dependencies([append_values_op]):
update_op = size.assign(new_size)
if metrics_collections:
ops.add_to_collections(metrics_collections, value)
if updates_collections:
| tensorflow.python.ops.array_ops.shape_internal | 525 |
import tensorflow as tf
loss_class = tf.where(mask_neg,
1 - class_pred[:, 0][..., tf.newaxis], 0)
# 2. hard negative mining
loss_class = tf.reshape(loss_class, [num_batch, num_prior])
loss_class_idx = tf.argsort(loss_class, axis=1, direction='DESCENDING')
loss_class_idx_rank = tf.argsort(loss_class_idx, axis=1)
mask_pos_per_batch = tf.reshape(mask_pos, [num_batch, num_prior])
num_pos_per_batch = tf.reduce_sum(
tf.cast(mask_pos_per_batch, tf.float32), 1, keepdims=True)
| tensorflow.argsort | 526 |
import tensorflow as tf
_MergeCandidates, (tokens, candidates),
parallel_iterations=1,
back_prop=False)[0]
def Encode(self, text):
"""Converts string `text` to integer ids and the encoded string.
Encoding includes prefixing the beginning-of-word token to each word.
Returns:
ids: the encoded integer ids.
tokens: the encoded string.
"""
words = tf.sparse.to_dense(tf.strings.split([text]), default_value='')[0]
num_words = tf.size(words)
ids_ta = tf.TensorArray(tf.int32, 0, dynamic_size=True)
def _WordsToIds(i, words, ids_ta):
encoded_ids = self._EncodeToIds(BOW_STR + words[i])
ids_ta = ids_ta.scatter(
tf.range(ids_ta.size(),
ids_ta.size() + tf.size(encoded_ids)), encoded_ids)
return i + 1, words, ids_ta
_, _, ids_ta = tf.while_loop(
lambda i, *_: i < num_words,
| tensorflow.strings.split | 527 |
import tensorflow as tf
# for each direction, we'll store tensors for each layer
self.lstm_outputs = {'forward': [], 'backward': []}
self.lstm_state_sizes = {'forward': [], 'backward': []}
self.lstm_init_states = {'forward': [], 'backward': []}
self.lstm_final_states = {'forward': [], 'backward': []}
update_ops = []
for direction in ['forward', 'backward']:
if direction == 'forward':
layer_input = self.embedding
else:
layer_input = tf.reverse_sequence(
self.embedding,
sequence_lengths,
seq_axis=1,
batch_axis=0
)
for i in range(n_lstm_layers):
if projection_dim < lstm_dim:
# are projecting down output
lstm_cell = tf.nn.rnn_cell.LSTMCell(
lstm_dim, num_proj=projection_dim,
| tensorflow.reverse_sequence | 528 |
import tensorflow as tf
# 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.
import tensorflow as tf
import tensorflow.contrib.metrics as metrics
import tensorflow.contrib.rnn as rnn
tf.logging.set_verbosity(tf.logging.INFO)
SEQ_LEN = 10
DEFAULTS = [[0.0] for x in range(0, SEQ_LEN)]
BATCH_SIZE = 20
TIMESERIES_INPUT_LAYER = 'rawdata'
TIMESERIES_COL = '{}_input'.format(TIMESERIES_INPUT_LAYER)
# In each sequence, column index 0 to N_INPUTS - 1 are features, and column index N_INPUTS to SEQ_LEN are labels
| tensorflow.logging.set_verbosity | 529 |
import tensorflow as tf
init = tf.truncated_normal_initializer(stddev=init_stddev)
X = tf.layers.conv2d(X, out_channels, kernel_size=filtersize, strides=(stride, stride), padding="valid",
kernel_initializer=init)
if norm == 'I':
X = tf.contrib.layers.instance_norm(X, scope=scope, reuse=reuse, epsilon=0.001)
elif norm == 'B':
X = tf.layers.batch_normalization(X, reuse=reuse, training=True)
elif norm == 'G':
| tensorflow.contrib.layers.instance_norm | 530 |
import tensorflow as tf
# forward pass
if cfg.TEST.HAS_RPN:
feed_dict={net.data: blobs['data'], net.im_info: blobs['im_info'], net.keep_prob: 1.0}
else:
feed_dict={net.data: blobs['data'], net.rois: blobs['rois'], net.keep_prob: 1.0}
run_options = None
run_metadata = None
if cfg.TEST.DEBUG_TIMELINE:
run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
run_metadata = tf.RunMetadata()
#theta_tensor = tf.get_default_graph().get_tensor_by_name('spt_trans_theta')
cls_score, cls_prob, bbox_pred, rois = sess.run([net.get_output('cls_score'),
net.get_output('cls_prob'), net.get_output('bbox_pred'), net.get_output('rois')],
feed_dict=feed_dict,
options=run_options,
run_metadata=run_metadata)
| tensorflow.RunOptions | 531 |
import tensorflow as tf
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(_ln(c, gc, bc))
xs[idx] = h
| tensorflow.tanh | 532 |
from tensorflow.python.ops import array_ops
non_zero_count = math_ops.maximum(count,
array_ops.ones_like(count),
| tensorflow.python.ops.array_ops.ones_like | 533 |
import tensorflow as tf
"""Dataset for iterating over text."""
import collections
import numpy as np
import tensorflow as tf
def _split_string(string):
"""Splits a byte string into an array of character bytes."""
text = tf.compat.as_text(string)
ret = np.empty(len(text), dtype=np.object)
for i, char in enumerate(text):
ret[i] = tf.compat.as_bytes(char)
return ret
def vocabulary(filename, max_size=None, num_oov_buckets=1):
"""Builds vocabulary and ID lookup tables from the given file."""
| tensorflow.compat.as_text | 534 |
import tensorflow as tf
tf.stop_gradient(indicator_matrix), distance_matrix,
tf.fill(tf.shape(distance_matrix), distance_matrix.dtype.max))
hard_distances = tf.math.reduce_min(distance_matrix, axis=-1)
return hard_distances
| tensorflow.math.reduce_min | 535 |
from tensorflow.python.platform import googletest
ig = integrated_gradients.IntegratedGradients(graph, sess, y[0], x)
mask = ig.GetMask(x_value=x_input_val[0], feed_dict={},
x_baseline=x_baseline_val[0], x_steps=1000)
# Verify the result.
self.assertAlmostEqual(expected_val, mask.sum(), places=3)
if __name__ == '__main__':
googletest.main()
| tensorflow.python.platform.googletest.main | 536 |
import tensorflow as tf
return {f: example[f] for f in feature_list if f in example}
def _eager_dataset_iterator(dataset):
for item in dataset:
flat = tf.nest.flatten(item)
flat = [el.numpy() for el in flat]
yield tf.nest.pack_sequence_as(item, flat)
def _train_and_eval_dataset_v1(problem_name, data_dir, train_shuffle_files,
eval_shuffle_files):
"""Return train and evaluation datasets, feature info and supervised keys."""
with tf.device('cpu:0'):
| tensorflow.nest.pack_sequence_as | 537 |
import tensorflow as tf
batch_size=batch_size)
num_dims = shape.size
if tt_rank.size == 1:
tt_rank = tt_rank * np.ones(num_dims - 1)
tt_rank = np.insert(tt_rank, 0, 1)
tt_rank = np.append(tt_rank, 1)
tt_rank = tt_rank.astype(int)
tt_cores = [None] * num_dims
with tf.name_scope(name):
for i in range(num_dims):
curr_core_shape = (batch_size, tt_rank[i], shape[i], tt_rank[i + 1])
tt_cores[i] = tf.random_normal(curr_core_shape, mean=mean, stddev=stddev,
dtype=dtype)
return TensorTrainBatch(tt_cores, shape, tt_rank, batch_size)
def matrix_with_random_cores(shape, tt_rank=2, mean=0., stddev=1.,
dtype=tf.float32,
name='t3f_matrix_with_random_cores'):
"""Generate a TT-matrix of given shape with N(mean, stddev^2) cores.
| tensorflow.random_normal | 538 |
import tensorflow as tf
self.generated_image = tflib.convert_images_to_uint8(self.generator_output, nchw_to_nhwc=True, uint8_cast=False)
self.generated_image_uint8 = tf.saturate_cast(self.generated_image, tf.uint8)
| tensorflow.saturate_cast | 539 |
import tensorflow as tf
update_op = tf.group(*[
param.assign(param - grad * self.LEARNING_RATE)
for param, grad in zip(params, grads)
])
# return update_op
with tf.name_scope('validate'):
x, y = self._build_data_pipeline()
y_hat, loss = self._build_validation_model(x, y)
with tf.control_dependencies([update_op]):
return tf.print('expect', loss, y, y_hat, summarize=50)
class DataOwner:
BATCH_SIZE = 30
def __init__(self, player_name, build_training_model):
self.player_name = player_name
| tensorflow.control_dependencies | 540 |
from tensorflow.contrib.layers.python.layers import feature_column
dnn_feature_columns=(cont_feature,),
dnn_hidden_units=(3, 3),
dnn_optimizer=adagrad.AdagradOptimizer(learning_rate=0.1))
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 benchmarkMultiClass(self):
iris = base.load_iris()
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(
n_classes=3,
linear_feature_columns=(bucketized_feature,),
dnn_feature_columns=(cont_feature,),
dnn_hidden_units=(3, 3))
input_fn = test_data.iris_input_multiclass_fn
| tensorflow.contrib.layers.python.layers.feature_column.real_valued_column | 541 |
from tensorflow.python.framework import ops
ops.RegisterShape("Neg")(common_shapes.unchanged_shape)
ops.RegisterShape("Real")(common_shapes.unchanged_shape)
ops.RegisterShape("Rsqrt")(common_shapes.unchanged_shape)
ops.RegisterShape("Sign")(common_shapes.unchanged_shape)
ops.RegisterShape("Sin")(common_shapes.unchanged_shape)
ops.RegisterShape("Sqrt")(common_shapes.unchanged_shape)
ops.RegisterShape("Square")(common_shapes.unchanged_shape)
ops.RegisterShape("Sigmoid")(common_shapes.unchanged_shape)
ops.RegisterShape("Tanh")(common_shapes.unchanged_shape)
ops.RegisterShape("Cast")(common_shapes.unchanged_shape)
ops.RegisterShape("ComplexAbs")(common_shapes.unchanged_shape)
@ops.RegisterShape("Add")
@ops.RegisterShape("Complex")
@ops.RegisterShape("Div")
@ops.RegisterShape("Equal")
@ops.RegisterShape("Greater")
| tensorflow.python.framework.ops.RegisterShape | 542 |
from tensorflow.contrib.learn.python.learn.estimators import test_data
indices=((0, 0), (0, 1), (60, 0)),
dense_shape=(len(iris.target), 2))
labels = array_ops.reshape(
constant_op.constant(
iris.target, dtype=dtypes.int32), (-1, 1))
return features, labels
iris = test_data.prepare_iris_data_for_logistic_regression()
cont_features = [
feature_column.real_valued_column(str(i)) for i in range(4)
]
linear_features = [
feature_column.bucketized_column(
cont_features[i],
test_data.get_quantile_based_buckets(iris.data[:, i], 10))
for i in range(4)
]
linear_features.append(
feature_column.sparse_column_with_hash_bucket(
'dummy_sparse_column', hash_bucket_size=100))
classifier = dnn_linear_combined.DNNLinearCombinedClassifier(
model_dir=tempfile.mkdtemp(),
linear_feature_columns=linear_features,
dnn_feature_columns=cont_features,
dnn_hidden_units=(3, 3))
metrics = classifier.fit(input_fn=_input_fn, steps=_ITERS).evaluate(
| tensorflow.contrib.learn.python.learn.estimators.test_data.get_quantile_based_buckets | 543 |
import tensorflow as tf
use_skip_connections = self.options['lstm']['use_skip_connections']
if use_skip_connections:
print("USING SKIP CONNECTIONS")
else:
print("NOT USING SKIP CONNECTIONS")
# the sequence lengths from input mask
if self.use_character_inputs:
mask = tf.reduce_any(self.ids_placeholder > 0, axis=2)
else:
mask = self.ids_placeholder > 0
sequence_lengths = tf.reduce_sum(tf.cast(mask, tf.int32), axis=1)
batch_size = tf.shape(sequence_lengths)[0]
# for each direction, we'll store tensors for each layer
self.lstm_outputs = {'forward': [], 'backward': []}
| tensorflow.reduce_any | 544 |
from tensorflow.contrib.learn.python.learn.estimators import run_config
classifier.fit(input_fn=_train_input_fn, steps=15)
classifier.evaluate(input_fn=_eval_input_fn, steps=1)
classifier.export(self._export_dir_base)
def testThatLeafIndexIsInPredictions(self):
learner_config = learner_pb2.LearnerConfig()
learner_config.num_classes = 2
learner_config.constraints.max_tree_depth = 1
model_dir = tempfile.mkdtemp()
config = run_config.RunConfig()
classifier = estimator.GradientBoostedDecisionTreeClassifier(
learner_config=learner_config,
num_trees=1,
examples_per_layer=3,
model_dir=model_dir,
config=config,
feature_columns=[contrib_feature_column.real_valued_column("x")],
output_leaf_index=True)
| tensorflow.contrib.learn.python.learn.estimators.run_config.RunConfig | 545 |
from tensorflow.contrib.layers.python.layers import utils
_add_variable_to_collections(layer.bias, variables_collections, 'biases')
if normalizer_fn is not None:
normalizer_params = normalizer_params or {}
outputs = normalizer_fn(outputs, **normalizer_params)
if activation_fn is not None:
outputs = activation_fn(outputs)
return utils.collect_named_outputs(outputs_collections, sc.name, outputs)
| tensorflow.contrib.layers.python.layers.utils.collect_named_outputs | 546 |
import tensorflow as tf
import random
import tensorflow as tf
FLAGS = flags.FLAGS
# augmentation functions
# augment
def random_crop_and_resize(images, ratio=0.8):
b, h, w, c = images.get_shape().as_list()
ch, cw = map(lambda x: int(x * ratio), (h, w))
crop = tf.random_crop(images, size=[b, ch, cw, 3])
crop = tf.image.resize(crop, [h, w])
return crop
def random_apply(fn, image, prob=1.):
b, *_ = image.get_shape().as_list()
chance = tf.less(tf.random_uniform([b], 0, 1.0), prob)
return tf.where(chance, fn(image), tf.identity(image))
def color_distortion(image, s=1.0):
lower, upper, x = (1 - 0.8 * s), (1 + 0.8 * s), image
x = tf.image.random_brightness(x, max_delta=0.8*s)
| tensorflow.random_crop | 547 |
import tensorflow as tf
with tf.variable_scope('x_entropy'):
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))
| tensorflow.nn.softmax_cross_entropy_with_logits | 548 |
import tensorflow.contrib.graph_editor as ge
checkpoints_other)
debug_print("ops_to_copy = %s", ops_to_copy)
if not ops_to_copy: # we're done!
break
copied_sgv, info = ge.copy_with_input_replacements(ge.sgv(ops_to_copy), {})
for origin_op, op in info._transformed_ops.items():
op._set_device(origin_op.node_def.device)
copied_ops = info._transformed_ops.values()
debug_print("Copied %s to %s", ops_to_copy, copied_ops)
ge.reroute_ts(checkpoints_disconnected_other, checkpoints_other, can_modify=copied_ops)
debug_print("Rewired %s in place of %s restricted to %s",
checkpoints_disconnected_other, checkpoints_other, copied_ops)
# gradient flowing through the checkpointed node
boundary = [info._transformed_ops[r.op]._outputs[0] for r in ts]
substitute_backprops = [d_checkpoints[r] for r in ts]
dv = tf_gradients(boundary,
checkpoints_disconnected_other+xs,
| tensorflow.contrib.graph_editor.reroute_ts | 549 |
import tensorflow as tf
# the true input symbols for the decoder with feed_previous=False.
dec_fp_true = sess.run(dec_op_fp_true)
output_symbols_fp_true = np.argmax(dec_fp_true, axis=2)
dec_inp_fp_false = np.vstack((dec_inp_fp_true[0].eval(),
output_symbols_fp_true[:-1]))
sess.run(update_fp_true)
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(
enc_inp, dec_inp, cell, num_encoder_symbols,
num_decoder_symbols, embedding_size=2, feed_previous=feed_previous)
def EmbeddingTiedRNNSeq2Seq(enc_inp, dec_inp, feed_previous):
cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True)
return tf.nn.seq2seq.embedding_tied_rnn_seq2seq(
enc_inp, dec_inp, cell, num_decoder_symbols, embedding_size=2,
feed_previous=feed_previous)
| tensorflow.nn.seq2seq.embedding_rnn_seq2seq | 550 |
from tensorflow.contrib.eager.python.examples.l2hmc import l2hmc
hparams = get_default_hparams()
tf.enable_resource_variables()
for sample_size in [10, 25, 50, 100, 200]:
hparams.n_samples = sample_size
tf.reset_default_graph()
with tf.Graph().as_default():
energy_fn, _, _ = l2hmc.get_scg_energy_fn()
x = tf.random_normal([hparams.n_samples, hparams.x_dim],
dtype=tf.float32)
dynamics = l2hmc.Dynamics(
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)
with tf.Session(config=session_conf) as sess:
sess.run(tf.global_variables_initializer())
# Warmup to reduce initialization effect when timing
for _ in range(hparams.n_warmup_iters):
_, _ = sess.run([train_op, loss])
| tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.compute_loss | 551 |
import tensorflow as tf
"""Trains model on train_data using optimizer."""
tf.train.get_or_create_global_step()
def model_loss(labels, chars, sequence_length):
predictions = model((chars, sequence_length), training=True)
loss_value = loss(labels, predictions)
tf.contrib.summary.scalar("loss", loss_value)
return loss_value
for (batch, (labels, chars, sequence_length)) in enumerate(
tfe.Iterator(train_data)):
with tf.contrib.summary.record_summaries_every_n_global_steps(log_interval):
batch_model_loss = functools.partial(model_loss, labels, chars,
| tensorflow.contrib.summary.scalar | 552 |
from tensorflow.python.ops import array_ops
labels_sizes = set_ops.set_size(labels)
return math_ops.minimum(labels_sizes, k, name=scope)
# For dense Tensor, calculate scalar count based on last dimension, and
# tile across labels shape.
labels_shape = array_ops.shape(labels)
labels_size = labels_shape[-1]
num_relevant_scalar = math_ops.minimum(labels_size, k)
return array_ops.fill(labels_shape[0:-1], num_relevant_scalar, name=scope)
def expand_and_tile(tensor, multiple, dim=0, name=None):
"""Slice `tensor` shape in 2, then tile along the sliced dimension.
A new dimension is inserted in shape of `tensor` before `dim`, then values are
tiled `multiple` times along the new dimension.
| tensorflow.python.ops.array_ops.fill | 553 |
import tensorflow as tf
from tensor2tensor.data_generators import algorithmic
from tensor2tensor.data_generators import problem as problem_module
from tensor2tensor.data_generators import problem_hparams
from tensor2tensor.layers import modalities
from tensor2tensor.utils import test_utils
import tensorflow as tf
tf.compat.v1.enable_eager_execution()
def assert_tensors_equal(sess, t1, t2, n):
"""Compute tensors `n` times and ensure that they are equal."""
for _ in range(n):
| tensorflow.compat.v1.enable_eager_execution | 554 |
import tensorflow as tf
# Upsampling
up1 = common_deconv2d(dwn5,self.gf*8,stride=1,padding='valid',name='up1') # 16x16 -> 16x16
#print(np.shape(up1))
up2 = common_deconv2d(up1,self.gf*4,name='up2') # 16x16 -> 32x32
up3 = common_deconv2d(up2,self.gf*2,name='up3') # 32x32 -> 64x64
up4 = common_deconv2d(up3,self.gf,name='up4') # 64x64 -> 128x128
out_img = tf.contrib.layers.conv2d_transpose(up4,self.channels,kernel_size=4,stride=2,padding='SAME',activation_fn=tf.nn.tanh) # 128x128 -> 256x256
#print('out_img',(np.shape(out_img)))
return out_img
def build_discriminator(self,image,reuse=False,name='discriminator'):
| tensorflow.contrib.layers.conv2d_transpose | 555 |
import tensorflow as tf
"""
label_smoothing = 0.
def inputs(self):
return [tf.TensorSpec([None, self.image_shape, self.image_shape, 3], self.image_dtype, 'input'),
tf.TensorSpec([None], tf.int32, 'label')]
def build_graph(self, image, label):
image = self.image_preprocess(image)
assert self.data_format in ['NCHW', 'NHWC']
| tensorflow.TensorSpec | 556 |
import tensorflow as tf
# Compute Pearson correlation
pearson = contrib_metrics.streaming_pearson_correlation(
logits, label_ids, weights=is_real_example)
# Compute MSE
# mse = tf.metrics.mean(per_example_loss)
mse = tf.metrics.mean_squared_error(
label_ids, logits, weights=is_real_example)
loss = tf.metrics.mean(
values=per_example_loss,
weights=is_real_example)
| tensorflow.metrics.mean_squared_error | 557 |
import tensorflow as tf
logit_w = tf.get_variable('W', shape=[dnn_output_size, 1], initializer=tf.truncated_normal_initializer(stddev=1.0 / dnn_output_size, dtype=dtype), dtype=dtype)
logit_b = tf.get_variable('b', shape=[1], initializer=tf.constant_initializer(0.0), dtype=dtype)
logits = tf.squeeze(tf.nn.bias_add(tf.matmul(dnn_output, logit_w), logit_b), squeeze_dims=[1])
prediction = tf.nn.sigmoid(logits)
prediction_inspect = tf.reshape(prediction, [batch_size, rnn_nunroll])
prediction_final = tf.squeeze(tf.slice(prediction_inspect, [0, rnn_nunroll - 1], [-1, 1]), squeeze_dims=[1])
| tensorflow.nn.sigmoid | 558 |
import tensorflow as tf
import os
log = infolog.log
def add_embedding_stats(summary_writer, embedding_names, paths_to_meta, checkpoint_path):
# Create tensorboard projector
config = tf.contrib.tensorboard.plugins.projector.ProjectorConfig()
config.model_checkpoint_path = checkpoint_path
for embedding_name, path_to_meta in zip(embedding_names, paths_to_meta):
# Initialize config
embedding = config.embeddings.add()
# Specifiy the embedding variable and the metadata
| tensorflow.contrib.tensorboard.plugins.projector.ProjectorConfig | 559 |
import tensorflow as tf
boxes.append(tf.reshape(box, (x_shape[0], -1, 1, 4)))
objects.append(tf.reshape(obj, (x_shape[0], -1, 1)))
classes.append(tf.reshape(cls, (x_shape[0], -1, num_classes)))
boxes = tf.concat(boxes, axis=1)
objects = tf.concat(objects, axis=1)
classes = tf.concat(classes, axis=1)
scores = objects * classes
boxes, scores, classes, valid = tf.image.combined_non_max_suppression(
boxes=boxes,
scores=scores,
max_output_size_per_class=max_outputs,
max_total_size=max_outputs,
iou_threshold=iou_threshold,
score_threshold=score_threshold,
clip_boxes=False
)
| tensorflow.image.combined_non_max_suppression | 560 |
import tensorflow as tf
import os
os.environ['CUDA_VISIBLE_DEVICES'] = FLAGS.gpu_list
if not tf.gfile.Exists(FLAGS.checkpoint_path):
tf.gfile.MkDir(FLAGS.checkpoint_path)
else:
if not FLAGS.restore:
| tensorflow.gfile.MkDir | 561 |
import tensorflow as tf
if W_p is None:
W_p = self._make_var('W_p', (1, 1, ch_mul * ch, ch))
X = tf.nn.relu(X)
X = tf.nn.separable_conv2d(X, W_d, W_p, strides=(1, stride, stride, 1), padding='SAME')
if not no_batch_norm:
X = self._add_batch_norm(X, ch, is_train=is_train)
| tensorflow.nn.separable_conv2d | 562 |
import tensorflow as tf
X = tf.contrib.layers.instance_norm(X, scope=scope, reuse=reuse)
elif norm == 'B':
X = tf.layers.batch_normalization(X, reuse=reuse, training=is_train, name=name)
elif norm == 'G':
X = tf.contrib.layers.group_norm(X, groups=16, scope=scope, reuse=reuse)
if dropout > 0.0:
X = tf.layers.dropout(X, dropout, training=is_train)
if slope < 1.0:
| tensorflow.contrib.layers.group_norm | 563 |
import tensorflow as tf
'Optimizer to use: momentum or sgd or rmsprop')
tf.flags.DEFINE_float('learning_rate', None,
| tensorflow.flags.DEFINE_float | 564 |
from tensorflow.python.client import graph_util
filter_shape.assert_is_fully_defined()
output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name)
output_shape.assert_is_fully_defined()
filter_height = int(filter_shape[0])
filter_width = int(filter_shape[1])
filter_in_depth = int(filter_shape[2])
filter_out_depth = int(filter_shape[3])
return ops.OpStats("weight_parameters", (filter_height * filter_width *
filter_in_depth * filter_out_depth))
@ops.RegisterStatistics("BiasAdd", "flops")
def _calc_bias_add_flops(graph, node):
"""Calculates the computing needed for BiasAdd."""
input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0])
input_shape.assert_is_fully_defined()
input_count = np.prod(input_shape.as_list())
return ops.OpStats("flops", input_count)
@ops.RegisterStatistics("BiasAdd", "weight_parameters")
def _calc_bias_add_weight_params(graph, node):
"""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)
| tensorflow.python.client.graph_util.tensor_shape_from_node_def_name | 565 |
import tensorflow as tf
self.resolution])
inter = tf.transpose(tf.reduce_max(inter, axis=a))
| tensorflow.reduce_max | 566 |
import tensorflow as tf
return 196.0 * 21.0 / 4096.0
else:
rec = tf.cast(kw * kh, tf.float32)
n_max = 7 + tf.math.ceil(tf.math.log(rec) / tf.math.log(2.))
ns = tf.range(0., n_max)
ns_pow = tf.pow(2., ns)
ks = tf.round(ns_pow / rec)
diffs = tf.math.abs(ks / ns_pow - 1 / rec)
n = tf.argmin(diffs)
k = ks[n]
scale = k / tf.pow(2., tf.cast(n, tf.float32))
scale *= rec
| tensorflow.round | 567 |
import tensorflow as tf
if params['optimizer'] == 'momentum':
optimizer = tf.train.MomentumOptimizer(
learning_rate, momentum=params['momentum'])
elif params['optimizer'] == 'adam':
optimizer = tf.train.AdamOptimizer(learning_rate)
elif params['optimizer'] == 'adadelta':
optimizer = tf.train.AdadeltaOptimizer(learning_rate)
elif params['optimizer'] == 'adagrad':
optimizer = tf.train.AdagradOptimizer(learning_rate)
elif params['optimizer'] == 'rmsprop':
optimizer = tf.train.RMSPropOptimizer(
learning_rate, momentum=params['momentum'])
elif params['optimizer'] == 'lars':
optimizer = tf.contrib.opt.LARSOptimizer(
learning_rate,
momentum=params['momentum'],
weight_decay=params['lars_weight_decay'],
skip_list=['batch_normalization', 'bias'])
else:
raise ValueError('Unsupported optimizer type %s.' % params['optimizer'])
return optimizer
def remove_variables(variables, resnet_depth=50):
"""Removes low-level variables from the input.
| tensorflow.contrib.opt.LARSOptimizer | 568 |
import tensorflow as tf
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)
| tensorflow.nn.moments | 569 |
import tensorflow as tf
import numpy as np
import random
import TensorflowUtils as utils
import read_MITSceneParsingDataParis as scene_parsing
import datetime
import BatchDatsetReader as dataset
from six.moves import xrange
FLAGS = tf.flags.FLAGS
tf.flags.DEFINE_integer("batch_size", "50", "batch size for training")
tf.flags.DEFINE_string("logs_dir", "/scratch1/ram095/nips20/logs_mnist128/", "path to logs directory")
tf.flags.DEFINE_string("data_dir", "/scratch1/ram095/nips20/paris_street", "path to dataset")
tf.flags.DEFINE_float("learning_rate", "1e-4", "Learning rate for Adam Optimizer")
tf.flags.DEFINE_string("model_dir", "Model_zoo/", "Path to vgg model mat")
tf.flags.DEFINE_bool('debug', "False", "Debug mode: True/ False")
tf.flags.DEFINE_string('mode', "train", "Mode train/ test/ visualize")
MODEL_URL = 'http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat'
MAX_ITERATION = int(1e5 + 1)
NUM_OF_CLASSESS = 3
IMAGE_SIZE = 128
def vgg_net(weights, image):
layers = (
'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1',
| tensorflow.flags.DEFINE_bool | 570 |
import tensorflow as tf
phase = conv3d(phase,3,channel_nr, 'SYMMETRIC', 'relu')
concat_layer = tf.keras.layers.concatenate([phase, pc])
concat_layer = conv3d(concat_layer, 1, channel_nr, 'SYMMETRIC', 'relu')
| tensorflow.keras.layers.concatenate | 571 |
import tensorflow as tf
with tf.device(assign_to_gpu(i, "/gpu:0")), tf.variable_scope(tf.get_variable_scope(), reuse=do_reuse):
clf_logits, clf_losses, lm_losses = model(*xs, train=True, reuse=do_reuse)
if lm_coef > 0:
train_loss = tf.reduce_mean(clf_losses) + lm_coef*tf.reduce_mean(lm_losses)
else:
train_loss = tf.reduce_mean(clf_losses)
| tensorflow.reduce_mean | 572 |
import tensorflow as tf
elif (re.sub(r"/ffn_\d+/", "/ffn_1/", six.ensure_str(name))
in init_vars_name and num_of_group > 1):
tvar_name = re.sub(r"/ffn_\d+/", "/ffn_1/", six.ensure_str(name))
elif (re.sub(r"/attention_\d+/", "/attention_1/", six.ensure_str(name))
in init_vars_name and num_of_group > 1):
tvar_name = re.sub(r"/attention_\d+/", "/attention_1/",
six.ensure_str(name))
else:
tf.logging.warn("name %s does not get matched", name)
continue
# tf.logging.info("name %s match to %s", name, tvar_name)
if num_of_group > 0:
group_matched = False
for gid in range(1, num_of_group):
if (("/group_" + str(gid) + "/" in name) or
("/ffn_" + str(gid) + "/" in name) or
| tensorflow.logging.warn | 573 |
from tensorflow.contrib.eager.python import tfe
def loss(labels, predictions):
"""Computes mean squared loss."""
return tf.reduce_mean(tf.squared_difference(predictions, labels))
def test(model, eval_data):
"""Computes the average loss on eval_data, which should be a Dataset."""
avg_loss = tfe.metrics.Mean("loss")
for (labels, chars, sequence_length) in tfe.Iterator(eval_data):
predictions = model((chars, sequence_length), training=False)
avg_loss(loss(labels, predictions))
print("eval/loss: %.6f\n" % avg_loss.result())
with tf.contrib.summary.always_record_summaries():
tf.contrib.summary.scalar("loss", avg_loss.result())
| tensorflow.contrib.eager.python.tfe.metrics.Mean | 574 |
import tensorflow as tf
self.assertEqual((2, 2), res[0][0].h.shape)
self.assertEqual((2, 2), res[0][1].c.shape)
self.assertEqual((2, 2), res[0][1].h.shape)
# pylint: disable=unused-variable,invalid-name
def testDynamicAttentionDecoderStateIsTuple(self):
with self.test_session() as sess:
with tf.variable_scope(
"root", initializer=tf.constant_initializer(0.5)):
cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True)
cell = tf.nn.rnn_cell.MultiRNNCell(cells=[cell] * 2,
state_is_tuple=True)
inp = tf.constant(0.5, shape=[2, 2, 2])
enc_outputs, enc_state = tf.nn.rnn(cell, inp, dtype=tf.float32)
attn_states = tf.concat(1, [tf.reshape(e, [-1, 1, cell.output_size])
for e in enc_outputs])
dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3
dec, mem = tf.nn.seq2seq.attention_decoder(
dec_inp, enc_state,
attn_states, cell, output_size=4)
| tensorflow.nn.rnn_cell.MultiRNNCell | 575 |
from tensorflow.contrib import layers
default_batch_size=1,
exports_to_keep=None):
"""See BaseEstimator.export."""
def default_input_fn(unused_estimator, examples):
return layers.parse_feature_columns_from_examples(examples,
self._feature_columns)
return self._estimator.export(
export_dir=export_dir,
| tensorflow.contrib.layers.parse_feature_columns_from_examples | 576 |
from tensorflow.contrib.rnn import GRUCell
highway_input = tf.layers.dense(highway_input, half_depth)
# 4-layer HighwayNet:
for i in range(4):
highway_input = highwaynet(highway_input, 'highway_%d' % (i + 1), half_depth)
rnn_input = highway_input
# Bidirectional RNN
outputs, states = tf.nn.bidirectional_dynamic_rnn(
GRUCell(half_depth),
GRUCell(half_depth),
rnn_input,
sequence_length=input_lengths,
dtype=tf.float32)
return tf.concat(outputs, axis=2) # Concat forward and backward
def highwaynet(inputs, scope, depth):
with tf.variable_scope(scope):
H = tf.layers.dense(
| tensorflow.contrib.rnn.GRUCell | 577 |
import tensorflow as tf
with self.test_session() as sess:
with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)):
cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True)
cell = tf.nn.rnn_cell.MultiRNNCell(cells=[cell] * 2,
state_is_tuple=True)
inp = [tf.constant(0.5, shape=[2, 2])] * 2
enc_outputs, enc_state = tf.nn.rnn(cell, inp, dtype=tf.float32)
attn_states = tf.concat(1, [tf.reshape(e, [-1, 1, cell.output_size])
for e in enc_outputs])
dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3
dec, mem = tf.nn.seq2seq.attention_decoder(
dec_inp, enc_state,
attn_states, cell, output_size=4)
sess.run([tf.global_variables_initializer()])
res = sess.run(dec)
self.assertEqual(3, len(res))
self.assertEqual((2, 4), res[0].shape)
res = sess.run([mem])
self.assertEqual(2, len(res[0]))
| tensorflow.nn.seq2seq.attention_decoder | 578 |
import tensorflow as tf
gn_grads_, gn_grads_true_, v_grads_, v_grads_true_ = sess.run(
[gn_grads, gn_grads_true, v_grads, v_grads_true])
np.testing.assert_array_equal(gn_grads_, gn_grads_true_)
np.testing.assert_array_equal(v_grads_, v_grads_true_)
def test_get_train_op(self):
"""Tests get_train_op.
"""
var = tf.Variable(0.)
loss = tf.nn.l2_loss(var)
train_op = opt.get_train_op(loss)
self.assertTrue(tf.contrib.framework.is_tensor(train_op))
if __name__ == "__main__":
tf.test.main()
| tensorflow.contrib.framework.is_tensor | 579 |
import tensorflow as tf
if bidirectional:
lstm_cell_bw = tf.contrib.rnn.LSTMBlockFusedCell(num_units=num_units, **kwargs)
lstm_cell_bw = tf.contrib.rnn.TimeReversedFusedRNN(lstm_cell_bw)
outputs_bw, (hidden_bw, output_bw) = lstm_cell_bw(t, dtype=tf.float32, sequence_length=nwords)
outputs = tf.concat([outputs_fw, outputs_bw], axis=-1)
| tensorflow.contrib.rnn.TimeReversedFusedRNN | 580 |
import tensorflow as tf
with tf.Session() as sess:
summary_writer = tf.summary.FileWriter(run_log_dir + '_train', sess.graph, flush_secs=5)
summary_writer_validation = tf.summary.FileWriter(run_log_dir + '_validate', sess.graph, flush_secs=5)
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
# Training and validation
for step in range(FLAGS.max_steps):
# Training: Backpropagation using train set
| tensorflow.local_variables_initializer | 581 |
import tensorflow.contrib.graph_editor as ge
def capture_ops():
"""Decorator to capture ops created in the block.
with capture_ops() as ops:
# create some ops
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):
if not _is_iterable(iterable):
return iterable
return [_to_op(i) for i in iterable]
def _is_iterable(o):
try:
| tensorflow.contrib.graph_editor.select_ops | 582 |
from tensorflow.python.ops import random_ops
def _get_batch_shape(self):
return array_ops.broadcast_static_shape(
self.alpha.get_shape(), self.beta.get_shape())
def _event_shape(self):
return constant_op.constant([], dtype=dtypes.int32)
def _get_event_shape(self):
return tensor_shape.scalar()
def _sample_n(self, n, seed=None):
"""See the documentation for tf.random_gamma for more details."""
return 1. / random_ops.random_gamma([n], self.alpha, beta=self.beta,
dtype=self.dtype, seed=seed)
def _log_prob(self, x):
x = control_flow_ops.with_dependencies([check_ops.assert_positive(x)] if
self.validate_args else [], x)
return (self.alpha * math_ops.log(self.beta) -
math_ops.lgamma(self.alpha) -
(self.alpha + 1.) * math_ops.log(x) - self.beta / x)
def _prob(self, x):
return math_ops.exp(self._log_prob(x))
| tensorflow.python.ops.random_ops.random_gamma | 583 |
import tensorflow as tf
def build_cnet(self, state_in, name, reuse=False, batch_size=64):
reg = tf.contrib.layers.l2_regularizer(1e-3)
with tf.variable_scope(name, reuse=reuse):
layer_c1 = tf.layers.dense(state_in, 512, tf.nn.relu, kernel_regularizer=reg)
layer_c2 = tf.layers.dense(layer_c1, 256, tf.nn.relu, kernel_regularizer=reg)
lstm_c = tf.nn.rnn_cell.LSTMCell(num_units=256)
lstm_c = tf.nn.rnn_cell.DropoutWrapper(lstm_c, output_keep_prob=self.keep_prob)
state_init_c = lstm_c.zero_state(batch_size=batch_size, dtype=tf.float32)
lstm_cin = tf.expand_dims(layer_c2, axis=1)
out_c, state_final_c = tf.nn.dynamic_rnn(cell=lstm_c, inputs=lstm_cin, initial_state=state_init_c)
cell_out_c = tf.reshape(out_c, [-1, 256])
vf = tf.layers.dense(cell_out_c, 1, kernel_regularizer=reg)
| tensorflow.nn.rnn_cell.DropoutWrapper | 584 |
import tensorflow as tf
epoch = step // steps_per_epoch
if use_sgdr is True:
# Apply Stoachastic Gradient Descent with Warm Restarts (SGDR)
lr = tf.train.cosine_decay_restarts(lr, epoch, sgdr_decay_epochs, t_mul=sgdr_t_mul, alpha=sgdr_alpha)
return lr
| tensorflow.train.cosine_decay_restarts | 585 |
import tensorflow as tf
with tf.variable_scope(name):
W = tf.get_variable(name='W', shape=(n_in, n_units), initializer=W_init, dtype=LayersConfig.tf_dtype, **W_init_args)
b = tf.get_variable(name='b', shape=(n_units), initializer=b_init, dtype=LayersConfig.tf_dtype, **b_init_args)
# self.outputs = act(tf.matmul(self.inputs, W) + b)
LayersConfig.set_keep[name] = tf.placeholder(tf.float32)
W_dropcon = tf.nn.dropout(W, LayersConfig.set_keep[name])
self.outputs = act(tf.matmul(self.inputs, W_dropcon) + b)
# self.all_layers = list(layer.all_layers)
# self.all_params = list(layer.all_params)
# self.all_drop = dict(layer.all_drop)
self.all_drop.update({LayersConfig.set_keep[name]: keep})
| tensorflow.nn.dropout | 586 |
from tensorflow.contrib.layers.python.ops import sparse_feature_cross_op
"""Tests the new version of the fingerprint concatenation has no collisions.
"""
# Although the last 10 bits of 359 and 1024+359 are identical.
# As a result, all the crosses shouldn't collide.
t1 = constant_op.constant([[359], [359 + 1024]])
t2 = constant_op.constant([list(range(10)), list(range(10))])
cross = sparse_feature_cross_op.sparse_feature_cross(
[t2, t1],
hashed_output=True,
num_buckets=1024,
hash_key=layers.SPARSE_FEATURE_CROSS_DEFAULT_HASH_KEY)
cross_dense = sparse_ops.sparse_tensor_to_dense(cross)
| tensorflow.contrib.layers.python.ops.sparse_feature_cross_op.sparse_feature_cross | 587 |
import tensorflow as tf
)
mu = 2 * tf.layers.dense(inputs=l1,
units=action_dim, # number of hidden units
activation=tf.nn.tanh,
name='mu',
trainable=trainable
)
sigma = tf.layers.dense(inputs=l1,
units=action_dim, # output units
activation=tf.nn.softplus, # get action probabilities
name='sigma',
trainable=trainable
)
norm_dist = tf.distributions.Normal(loc=mu, scale=sigma)
params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=name)
return norm_dist, params
def choose_action(self, s):
# 決定下一步該怎麼做
# s = s[np.newaxis, :]
s = s.reshape(-1, 84, 84, 3)
a = self.sess.run(self.sample_op, {self.tfs: s})[0]
return np.clip(a, ACTION_BOUND[0], ACTION_BOUND[1])
def get_v(self, s):
if s.ndim < 4:
| tensorflow.distributions.Normal | 588 |
import tensorflow as tf
tf.to_float(tf.range(num_timescales)) * -log_timescale_increment)
scaled_time = (
tf.expand_dims(tf.to_float(position), 2) * tf.expand_dims(
tf.expand_dims(inv_timescales, 0), 0))
signal = tf.concat([tf.sin(scaled_time), tf.cos(scaled_time)], axis=2)
signal = tf.pad(signal, [[0, 0], [0, 0], [0, tf.mod(channels, 2)]])
return signal
| tensorflow.cos | 589 |
from tensorflow.python.saved_model import loader
self.session = tf.Session()
metagraph_def = loader.load(
| tensorflow.python.saved_model.loader.load | 590 |
import tensorflow as tf
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)
def sample_compute(cur_loss, i):
batch1 = tf.gather(batch, tf.random.shuffle(index))
batch2 = tf.gather(batch, tf.random.shuffle(index))
pred1 = tf.slice(batch1, [0, 0], [num_sam, 1])
pred2 = tf.slice(batch2, [0, 0], [num_sam, 1])
tgt1 = tf.slice(batch1, [0, 1], [num_sam, 1])
tgt2 = tf.slice(batch2, [0, 1], [num_sam, 1])
loss = cur_loss + compute_contra_loss(pred1, pred2, tgt1, tgt2)
print(loss)
return (loss, i + 1)
# def sample_compute(i):
# batch1 = tf.gather(batch, tf.random.shuffle(index))
# batch2 = tf.gather(batch, tf.random.shuffle(index))
| tensorflow.random.shuffle | 591 |
from tensorflow.contrib import learn
# Setup vocabulary processor
vocab_processor = learn.preprocessing.VocabularyProcessor(sentence_size, min_frequency=min_word_freq)
| tensorflow.contrib.learn.preprocessing.VocabularyProcessor | 592 |
import tensorflow as tf
# Only make the ops if we know that `is_training=True`, or the value of
# `is_training` is unknown.
is_training_const = utils.constant_value(is_training)
if is_training_const is None or is_training_const:
update_mean_op, update_variance_op = utils.smart_cond(
is_training,
build_update_ops,
build_no_ops,
)
# Every new connection creates a new op which adds its contribution
# to the running average when ran.
tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_mean_op)
tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_variance_op)
def _build_update_ops_second_moment(self, mean, second_moment, is_training):
"""Builds the moving average update ops when using the moving second moment.
Args:
mean: The mean value to update with.
second_moment: The second_moment value to update with.
is_training: Boolean Tensor to indicate if we're currently in
training mode.
"""
def build_update_ops():
"""Builds the exponential moving average update ops."""
| tensorflow.add_to_collection | 593 |
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 | 594 |
from tensorflow.python.client import timeline
pred_boxes = pred_boxes[inv_index, :]
if cfg.TEST.DEBUG_TIMELINE:
trace = timeline.Timeline(step_stats=run_metadata.step_stats)
trace_file = open(str(int(time.time() * 1000)) + '-test-timeline.ctf.json', 'w')
trace_file.write(trace.generate_chrome_trace_format(show_memory=False))
| tensorflow.python.client.timeline.Timeline | 595 |
from tensorflow import keras
dataset = dataset.repeat(num_epochs).batch(batch_size)
iterator = dataset.make_one_shot_iterator()
batch_features, batch_labels = iterator.get_next()
return batch_features, batch_labels
return _input_fn
# Create inference model using Keras
# The model here is a dnn regressor
def make_keras_estimator(output_dir):
from tensorflow import keras
model = keras.models.Sequential()
model.add(keras.layers.Dense(32, input_shape=(N_INPUTS,), name=TIMESERIES_INPUT_LAYER))
model.add(keras.layers.Activation('relu'))
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
| tensorflow.keras.layers.Activation | 596 |
import tensorflow as tf
Haa = param_eta * prec + Waa
# Haa = 0.5 * (Haa + TT.transpose(Haa))
HaaInv = tf.matrix_inverse(Haa)
# The two terms 'term1' and 'term2' which come from normalizers of the
# 1. Original policy distribution
# 2. The distribution after completing the square
sigma = tf.matrix_inverse(prec)
term1 = -0.5 * param_eta * tf.log(tf.matrix_determinant(2 * np.pi * sigma))
if self.beta == 0:
term2 = 0.5 * param_eta * tf.log(tf.matrix_determinant(2 * np.pi * param_eta * HaaInv))
else:
term2 = 0.5 * (param_eta + param_omega) * tf.log(tf.matrix_determinant(2 * np.pi * (param_eta + param_omega) * HaaInv))
dual = param_eta * self.epsilon - param_omega * beta + \
term1 + term2 + tf.reduce_mean(
0.5 * (tf.reduce_sum(tf.matmul(ha, HaaInv) * ha, axis=1) - hss))
| tensorflow.matrix_determinant | 597 |
import tensorflow as tf
dataset, info = tfds.load('oxford_iiit_pet:3.*.*', with_info=True)
def normalize(input_image, input_mask):
input_image = tf.cast(input_image, tf.float32) / 255.0
input_mask -= 1
return input_image, input_mask
def load_image_train(datapoint):
"""Load images for training."""
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
def load_image_test(datapoint):
input_image = tf.image.resize(datapoint['image'], (512, 512))
input_mask = tf.image.resize(datapoint['segmentation_mask'], (128, 128))
input_image, input_mask = normalize(input_image, input_mask)
return input_image, input_mask
| tensorflow.image.flip_left_right | 598 |
from tensorflow.python.ops import nn_ops
with tf.device("/gpu:0"):
conv = nn_ops.conv3d(d1, d2, strides, padding)
| tensorflow.python.ops.nn_ops.conv3d | 599 |