seed stringlengths 25 1.88k | seed_api stringlengths 14 102 | index int64 0 1.05k |
|---|---|---|
import tensorflow as tf
correct_prediction_action = tf.equal(
tf.argmax(one_hot_labels_action, 1),
tf.argmax(self.predictions_action, 1)
)
self.accuracy_action = tf.reduce_mean(tf.cast(correct_prediction_action, 'float'))
tf.scalar_summary... | tensorflow.scalar_summary | 1,000 |
import tensorflow as tf
edge_types: A 1-D `Tensor` of int32. Specify edge types to filter outgoing
edges.
Return:
A tuple of `SparseTensor` (neibors, weights).
neighbors: A `SparseTensor` of `int64`.
weights: A `SparseTensor` of `float`.
types: A `SparseTensor` of `int32`
"""
sp_... | tensorflow.SparseTensor | 1,001 |
from tensorflow.python.ops import state_ops
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]):
| tensorflow.python.ops.state_ops.assign | 1,002 |
import tensorflow as tf
# and due to the fact that the rightmost boundary is essentially ignored.
boundaries = tf.expand_dims(tf.cast(boundaries, tf.float32), 0) - 0.0001
bucket_indices = tf_utils.assign_buckets(
tf.cast(x, tf.float32), remove_leftmost_boundary(boundaries))
bucket_vocab, count... | tensorflow.strings.as_string | 1,003 |
import tensorflow as tf
import gpflow
from gpflow.ci_utils import ci_niter
from gpflow import set_trainable
from multiclass_classification import plot_from_samples, colors
gpflow.config.set_default_float(np.float64)
gpflow.config.set_default_jitter(1e-4)
gpflow.config.set_default_summary_fmt("notebook")
# convert to... | tensorflow.random.set_seed | 1,004 |
import tensorflow as tf
from sklearn.metrics import classification_report
slim = tf.contrib.slim
global first
first = True
classnum=12
testnum = tf.placeholder(tf.int32)
trainnum = tf.placeholder(tf.int32)
validnum = tf.placeholder(tf.int32)
learnrate = tf.placeholder(tf.float32)
def getinputs(path):
... | tensorflow.TFRecordReader | 1,005 |
import tensorflow as tf
cell = tf.nn.rnn_cell.MultiRNNCell([tf.nn.rnn_cell.GRUCell(24)] * 2,
state_is_tuple=True)
return tf.nn.seq2seq.embedding_attention_seq2seq(
enc_inp, dec_inp, cell, num_encoder_symbols=classes,
num_decod... | tensorflow.nn.sampled_softmax_loss | 1,006 |
from tensorflow.python.platform import gfile
s3 = save.save(sess, os.path.join(save_dir, "s3"))
self.assertEqual([s2, s3], save.last_checkpoints)
self.assertEqual(0, len(gfile.Glob(s1)))
self.assertFalse(gfile.Exists(save._MetaGraphFilename(s1)))
self.assertEqual(2, len(gfile.Glob(s2)))
| tensorflow.python.platform.gfile.Glob | 1,007 |
from tensorflow.python.framework import ops
"""Calculates the on-disk weight parameters for BiasAdd."""
bias_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[1])
bias_shape.assert_is_fully_defined()
bias_count = np.prod(bias_shape.as_list())
return ops.OpStats("weight_parameters", bias_co... | tensorflow.python.framework.ops.OpStats | 1,008 |
import tensorflow as tf
initializer = tf.contrib.layers.variance_scaling_initializer(), stride=2, bn=True, training=self.is_training)# 14*14
self.deconv_2 = self.deconv_bn_relu(self.deconv_1, name = 'deconv_2',kernel_size = 3, output_channels = 512,
initializer... | tensorflow.contrib.layers.variance_scaling_initializer | 1,009 |
import tensorflow as tf
drop_remainder=predict_drop_remainder)
result = estimator.predict(input_fn=predict_input_fn)
output_predict_file = os.path.join(FLAGS.output_dir, "test_results.tsv")
with tf.gfile.GFile(output_predict_file, "w") as writer:
tf.logging.info("*****... | tensorflow.gfile.GFile | 1,010 |
import tensorflow as tf
if FLAGS.write_to_disk:
image_write_ops = tf.write_file(
'%s/%s'% (FLAGS.eval_dir, 'conditional_gan.png'),
tf.image.encode_png(data_provider.float_image_to_uint8(
reshaped_img[0])))
# For unit testing, use `run_eval_loop=False`.
if not run_eval_loop: retur... | tensorflow.contrib.training.StopAfterNEvalsHook | 1,011 |
from tensorflow.python.ops import check_ops
self.event_ndims):
ndims = tensor_util.constant_value(ndims)
sample_ndims = (ndims - self._batch_ndims_static -
self._event_ndims_static)
if sample_ndims < 0:
raise ValueError(
... | tensorflow.python.ops.check_ops.assert_non_negative | 1,012 |
from tensorflow.contrib.cudnn_rnn.python.ops import cudnn_rnn_ops
config = test_configs[config_name]
num_layers = config["num_layers"]
num_units = config["num_units"]
batch_size = config["batch_size"]
seq_length = config["seq_length"]
with ops.Graph().as_default(), ops.device("/dev... | tensorflow.contrib.cudnn_rnn.python.ops.cudnn_rnn_ops.CudnnLSTM | 1,013 |
import tensorflow as tf
print ("creating protobuf...")
g_1 = tf.get_default_graph()
with tf.Session(graph = g_1) as sess:
saver = tf.train.import_meta_graph('save/model.ckpt.meta', clear_devices=True)
saver.restore(sess, ckpt_name)
graph_def = tf.graph_util.convert_variables_to_constants(sess, sess.graph_d... | tensorflow.graph_util.convert_variables_to_constants | 1,014 |
import tensorflow.contrib.graph_editor as ge
bwd_inputs = [t for op in bwd_ops for t in op.inputs]
# list of tensors in forward graph that is in input to bwd graph
ts_filtered = list(set(bwd_inputs).intersection(ts_all))
debug_print("Using tensors %s", ts_filtered)
... | tensorflow.contrib.graph_editor.get_forward_walk_ops | 1,015 |
from tensorflow.python.ops import logging_ops
Returns:
Numpy array of predicted probabilities.
"""
return self._infer_model(x=x, input_fn=input_fn, batch_size=batch_size)
def _get_train_ops(self, features, targets):
"""See base class."""
global_step = variables.get_global_step()
assert... | tensorflow.python.ops.logging_ops.scalar_summary | 1,016 |
from tensorflow.python.platform import tf_logging as logging
# The code should probably use the step from the checkpoint, because
# that's what is being evaluated.
if self._estimator is None:
raise ValueError("Missing call to set_estimator.")
# Check that we are not running evaluation on the same... | tensorflow.python.platform.tf_logging.debug | 1,017 |
import tensorflow as tf
print("episodes %d" % len(episode_rewards))
print("exploration %f" % exploration.value(t))
print("learning_rate %f" % optimizer_spec.lr_schedule.value(t))
mean_rew_summ = tf.Summary(value=[tf.Summary.Value(tag='mean_rew',simple_value=mean_episode_... | tensorflow.Summary.Value | 1,018 |
import tensorflow as tf
# the combined gradients to all towers (depending on --use_nccl option).
# independent: each GPU has its own copy of the variables, and gradients are
# not shared between towers. This can be used to check performance when no
# data is moved between GPUs.
# distributed_repl... | tensorflow.flags.DEFINE_boolean | 1,019 |
import tensorflow as tf
def validation():
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
images = tf.convert_to_tensor(np.expand_dims(x_test/255.0, -1),dtype=tf.float32)
| tensorflow.keras.datasets.mnist.load_data | 1,020 |
import tensorflow as tf
# Reshape patches.
p = tf.reshape(p, [blk_shape[0], blk_shape[1], blk_shape[2], -1])
# Convolution on patches.
q = tf.nn.conv2d(p, w, strides, 'VALID', use_cudnn_on_gpu=True)
# Paste convolution results.
q_shape = tf.shape(q)
def _strid... | tensorflow.strided_slice | 1,021 |
from tensorflow.core.protobuf import meta_graph_pb2
v0 = tf.Variable(10.0, name="v0")
# Creates a saver.
save = tf.train.Saver({"v0": v0})
# Generates MetaGraphDef.
meta_graph_def = meta_graph_pb2.MetaGraphDef()
# Verifies that collection with unsupported key will not be added.
... | tensorflow.core.protobuf.meta_graph_pb2.MetaGraphDef | 1,022 |
from tensorflow import keras
# 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.laye... | tensorflow.keras.estimator.model_to_estimator | 1,023 |
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/")
| tensorflow.examples.tutorials.mnist.input_data.read_data_sets | 1,024 |
import tensorflow as tf
'num of residual units')
tf.app.flags.DEFINE_string('Optimizer', 'mom',
'The optimizer used to train the model.')
tf.app.flags.DEFINE_bool('RCE_train', False,
'Whether use RCE to train the model.')
tf.app.flags... | tensorflow.app.flags.DEFINE_bool | 1,025 |
from tensorflow.python.ops import script_ops
with g.as_default():
c = tf.constant([1.], tf.float32)
_ = tf.py_func(lambda x: x + 1, [c], [tf.float32])
self.assertTrue(script_ops._py_funcs.size() < 100)
def testError(self):
| tensorflow.python.ops.script_ops._py_funcs.size | 1,026 |
from tensorflow.python.client import session
def testSparseDistributed(self):
worker, unused_ps = self._setupCluster()
for dtype in [dtypes.half, dtypes.float32, dtypes.float64]:
with session.Session(worker.target):
var0, var1, update_op = self._setupSparse(True, dtype)
self._assertSpa... | tensorflow.python.client.session.Session | 1,027 |
import tensorflow as tf
cols[3] / height,
cols[2] / width], axis=1)
# add batch dimension (assume batch_size==1)
#assert image.get_shape()[0] == 1
boxes = tf.expand_dims(boxes, dim=0)
image = tf.image.draw_bounding_boxes(image, boxes) ... | tensorflow.summary.image | 1,028 |
import tensorflow as tf
# Create optimizer
opt = tf.train.AdamOptimizer(learning_rate,
beta1=params.adam_beta1,
beta2=params.adam_beta2,
epsilon=params.adam_epsilon)
if params.update... | tensorflow.contrib.layers.optimize_loss | 1,029 |
from tensorflow.python.framework import ops
input_shape.assert_is_fully_defined()
filter_shape = graph_util.tensor_shape_from_node_def_name(graph,
node.input[1])
filter_shape.assert_is_fully_defined()
output_shape = graph_util.tensor_shape_from_node_d... | tensorflow.python.framework.ops.RegisterStatistics | 1,030 |
import tensorflow as tf
def double_factorial(n: TensorLike) -> TensorLike:
n = tf.convert_to_tensor(value=n)
two = tf.ones_like(n) * 2
result = tf.ones_like(n)
_, result, _ = tf.while_loop(
cond=_double_factorial_loop_condition,
body=_double_factorial_loop_body,
loop_vars=[n, result, two])
| tensorflow.ones_like | 1,031 |
import tensorflow as tf
indices_input = tf.reshape(indices_input, [2, -1])
indices_input = tf.transpose(indices_input)
res = tf.sparse_to_dense(
indices_input, [n_elem, n_indices], 1., 0., name="flat_one_hot")
| tensorflow.sparse_to_dense | 1,032 |
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 | 1,033 |
from tensorflow.python.ops import gen_nn_ops
logits: Unscaled log probabilities.
labels: Each entry `labels[i]` must be an index in `[0, num_classes)`.
name: A name for the operation (optional).
Returns:
A 1-D `Tensor` of length `batch_size` of the same type as `logits` with the
softmax cross en... | tensorflow.python.ops.gen_nn_ops._sparse_softmax_cross_entropy_with_logits | 1,034 |
import tensorflow as tf
Based on: https://github.com/gitlimlab/CycleGAN-Tensorflow/blob/master/ops.py
For tf padding, refer to: https://www.tensorflow.org/api_docs/python/tf/pad
"""
reg_l2 = tf.keras.regularizers.l2(5e-7)
if padding == 'SYMMETRIC' or padding == 'REFLECT':
p = (ker... | tensorflow.keras.regularizers.l2 | 1,035 |
import tensorflow as tf
def load_graph(model_file):
graph = tf.Graph()
graph_def = tf.compat.v1.GraphDef()
import os
file_ext = os.path.splitext(model_file)[1]
with open(model_file, "rb") as f:
if file_ext == '.pbtxt':
text_format.Merge(f.read(), graph_def)
else:
graph_def.ParseFromStri... | tensorflow.import_graph_def | 1,036 |
from tensorflow.contrib.framework import deprecated_arg_values
class ExportMonitor(EveryN):
"""Monitor that exports Estimator every N steps."""
# TODO(philstahlfeld): Investigate switching export.export_estimator
# configuration values to **kwargs so that updates to the export_estimator
# function don't have ... | tensorflow.contrib.framework.deprecated_arg_values | 1,037 |
import tensorflow as tf
# Location predictions.
location_feature_map_depth = (self._num_spatial_bins[0] *
self._num_spatial_bins[1] *
self.num_classes *
self._box_code_size)
location_feature_ma... | tensorflow.squeeze | 1,038 |
import tensorflow as tf
def metric_fn(per_example_loss, label_ids, logits, is_real_example):
predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)
accuracy = tf.metrics.accuracy(
labels=label_ids, predictions=predictions, weights=is_real_example)
loss = tf.metrics.me... | tensorflow.metrics.accuracy | 1,039 |
import tensorflow as tf
features = {
d.input_ids: tf.io.VarLenFeature(tf.int64),
d.token_type_ids: tf.io.VarLenFeature(tf.int64),
d.attention_mask: tf.io.VarLenFeature(tf.int64),
d.labels: tf.io.VarLenFeature(tf.int64),
}
dataset = dataset.map(
... | tensorflow.io.parse_example | 1,040 |
import tensorflow as tf
ref=self.internals_memory[name],
indices=indices,
updates=internals[name]
))
for name in sorted(actions):
assignments.append(tf.scatter_update(
ref=self.actions_memory[nam... | tensorflow.scatter_update | 1,041 |
import tensorflow as tf
replaced_list = var_list
if self._scale != 1.0:
loss = tf.scalar_mul(self._scale, loss)
gradvar = self._optimizer.compute_gradients(loss, replaced_list, *args, **kwargs)
final_gradvar = []
for orig_var, (grad, var) in zip(var_list, gradvar)... | tensorflow.scalar_mul | 1,042 |
import tensorflow as tf
An example with the same label and an augmented version of the image.
"""
image, label = example['image'], example['label']
image = tf.image.random_flip_left_right(image)
image_shape = tf.shape(image)
image = tf.pad(
image, [[random_crop_pad, random_crop_pad],
... | tensorflow.image.random_crop | 1,043 |
import tensorflow as tf
if not full_cov and full_output_cov:
fvar = tf.matrix_diag(fvar) # N x P x P
| tensorflow.matrix_diag | 1,044 |
from tensorflow.contrib.layers.python.layers.layers import _build_variable_getter, _add_variable_to_collections
bias_regularizer=biases_regularizer,
activity_regularizer=None,
use_spectral_norm=use_spectral_norm,
is_training=is_training,
t... | tensorflow.contrib.layers.python.layers.layers._add_variable_to_collections | 1,045 |
import tensorflow as tf
# https://en.wikipedia.org/wiki/Matthews_correlation_coefficient
tp, tp_op = tf.metrics.true_positives(
predictions, label_ids, weights=is_real_example)
tn, tn_op = tf.metrics.true_negatives(
predictions, label_ids, weights=is_real_examp... | tensorflow.metrics.false_positives | 1,046 |
import tensorflow as tf
Subclasses can override this function in order to preprocess, and can
yield any number of strings.
Args:
filepath: a string
Yields:
unicode strings.
"""
f = tf.gfile.Open(filepath)
b = f.read()
yield text_encoder.to_unicode_ignore_errors(b)
def f... | tensorflow.gfile.Open | 1,047 |
import tensorflow as tf
train_y_1 = to_categorical(train_y_1, n_class_1)
test_y_1 = to_categorical(test_y_1, n_class_1)
train_y_2 = to_categorical(train_y_2, n_class_2)
test_y_2 = to_categorical(test_y_2, n_class_2)
return train_X, train_y_1, train_y_2, test_X, test_y_1, test_y_2
def apply_cross_... | tensorflow.initializers.identity | 1,048 |
import tensorflow as tf
with self.test_session() as sess:
with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)):
inp = [tf.constant(0.5, shape=[2, 2])] * 2
_, enc_state = tf.nn.rnn(
tf.nn.rnn_cell.GRUCell(2), inp, dtype=tf.float32)
dec_inp = [tf.constant... | tensorflow.nn.seq2seq.rnn_decoder | 1,049 |
from tensorflow.contrib.distributions.python.ops import distribution_util
new_shape = array_ops.concat(0, ((-1,), batch_shape, event_shape))
x = array_ops.reshape(x, shape=new_shape)
x = distribution_util.rotate_transpose(x, shift=-1)
return x, sample_shape
| tensorflow.contrib.distributions.python.ops.distribution_util.rotate_transpose | 1,050 |
from tensorflow.python.ops import nn
`false_positives` variables appropriately, and whose value matches
`precision`.
Raises:
ValueError: If `ignore_mask` is not `None` and its shape doesn't match
`predictions`, or if `weights` is not `None` and its shape doesn't match
`predictions`, or i... | tensorflow.python.ops.nn.top_k | 1,051 |
import tensorflow as tf
def GetWordPred(o_):
logits = tf.nn.xw_plus_b(o_, pred_mat, pred_bias)
return tf.nn.softmax(logits)
preds = GetWordPred(wvsum)
z = tf.tile(tf.reshape(tf.reduce_sum(preds,1),[-1,1]), [1, out_vocab_size])
self.preds, self.z = preds, z
self.probs = tf.div(preds, z)... | tensorflow.div | 1,052 |
import tensorflow as tf
imsave(os.path.join(config.DEBUG_DIR, file_name), img.astype(np.uint8))
return save_image_with_heatmap.counter
def get_keypoint(image, targets, predictions, heatmap_size, height, width, category, clip_at_zero=True, data_format='channels_last', name=None):
predictions = tf.res... | tensorflow.floordiv | 1,053 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.