seed stringlengths 25 1.88k | seed_api stringlengths 14 102 | index int64 0 1.05k |
|---|---|---|
import tensorflow as tf
encoder_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])
encoder_out, encoder_state = tf.nn.dynamic_rnn(
cell=encoder_cells, inputs=forward, sequence_length=seq_lens, dtype=tf.float32
)
encoder_state = tuple(encoder_state[-1... | tensorflow.contrib.seq2seq.TrainingHelper | 200 |
import tensorflow as tf
while True:
random.shuffle(train_examples)
for example in train_examples:
tensorized_example = self.tensorize_example(example, is_training=True)
feed_dict = dict(zip(self.queue_input_tensors, tensorized_example))
session.run(self.enqueue_op, f... | tensorflow.global_variables | 201 |
from tensorflow.python.ops import array_ops
init_shape = [init_size] + fixed_shape
array = _create_local(
'array', shape=init_shape, validate_shape=False, dtype=values.dtype)
size = _create_local('size', shape=[], dtype=dtypes.int32)
perm = [0 if n == axis else n + 1 if n < axis else n for n i... | tensorflow.python.ops.array_ops.shape | 202 |
import tensorflow as tf
# mean all elements of all pixels in all batch
reduction=tf.losses.Reduction.MEAN))
else:
for pred_ind in list(range(len(pred_outputs))):
mse_loss_list.append(tf.losses.mean_squared_error(targets_list[pred_i... | tensorflow.losses.add_loss | 203 |
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:
loggi... | tensorflow.python.platform.tf_logging.warning | 204 |
import tensorflow as tf
nodes: A list of N + 1 `tf.Tensor` of `int64`, N is the number of
hops. Specify node set of each hop, including the root.
adjcents: A list of N `tf.SparseTensor` of `int64`. Specify adjacent
matrix between hops.
"""
nodes = tf.reshape(nodes, [-1])
nodes_list = ... | tensorflow.sparse.reorder | 205 |
from tensorflow.python.ops import variables as vars_
if not isinstance(opt, optimizer_.Optimizer):
raise ValueError("Unrecognized optimizer: function should return "
"subclass of Optimizer. Got %s." % str(opt))
else:
raise ValueError("Unrecognized optimizer: should be s... | tensorflow.python.ops.variables.trainable_variables | 206 |
import tensorflow as tf
def getinputs(path):
filename_queue=tf.train.string_input_producer([path])
| tensorflow.train.string_input_producer | 207 |
import tensorflow as tf
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)
num_pos_per_batch = tf.maximum... | tensorflow.logical_or | 208 |
import tensorflow as tf
"""
L= len(activation) #number of layers
m = Y.shape[1] #number of training examples
last = activation[L-1]
labels= tf.transpose(Y)
if last == 'sigmoid' or last == 'softmax': #use cross entropy loss function
logits= tf.transpose(betan*zn[1])
cost ... | tensorflow.losses.sigmoid_cross_entropy | 209 |
import tensorflow as tf
# Adds a set of collections.
tf.add_to_collection("int_collection", 3)
tf.add_to_collection("float_collection", 3.5)
tf.add_to_collection("string_collection", "hello")
tf.add_to_collection("variable_collection", v0)
# Add QueueRunners.
tf.train.add_queu... | tensorflow.train.add_queue_runner | 210 |
from tensorflow.contrib.eager.python import tfe
default=0.5,
help="Keep probability for dropout between layers.")
parser.add_argument(
"--learning_rate",
type=float,
default=0.01,
help="Learning rate to be used during training.")
parser.add_argument(
"--no_gpu",
acti... | tensorflow.contrib.eager.python.tfe.run | 211 |
from tensorflow.python.framework import ops
sequence_var = tf.Variable(tf.range(start=6, limit=15, delta=3)) # Generates [6, 9, 12] doesn't include the end
sess.run(linear_var.initializer)
sess.run(sequence_var.initializer)
print(sess.run(linear_var))
print(sess.run(sequence_var))
rnorm_var = tf.random_normal([row_di... | tensorflow.python.framework.ops.reset_default_graph | 212 |
from tensorflow.python.framework import tensor_shape
input_shape = input_shape.merge_with(out_backprop_shape)
vector_dim = input_shape[3]
vector_dim = vector_dim.merge_with(mean_shape[0])
vector_dim = vector_dim.merge_with(var_shape[0])
vector_dim = vector_dim.merge_with(beta_shape[0])
return [input_shape]... | tensorflow.python.framework.tensor_shape.vector | 213 |
import tensorflow as tf
dtype=tf.float32):
"""Returns a input_receiver_fn for raw images during serving."""
def _preprocess_image(encoded_image):
"""Preprocess a single raw image."""
image = tf.image.decode_image(encoded_image, channels=shape[-1])
image.set_sh... | tensorflow.image.decode_image | 214 |
import tensorflow as tf
"""Verbosity level for summary ops. Pass 0 to disable
both summaries and checkpoints.""")
tf.flags.DEFINE_integer('save_summaries_steps', 0,
"""How often to save summaries for trained models.
Pass 0 ... | tensorflow.flags.DEFINE_integer | 215 |
import tensorflow as tf
# Open session and restore checkpoint
sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
tf.train.start_queue_runners(sess)
sess.run(tf.global_variables_initializer())
| tensorflow.train.start_queue_runners | 216 |
from tensorflow.contrib.learn.python.learn.estimators import test_data
iris.data[:, i], dtype=dtypes.float32), (-1, 1))
})
# The following shows how to provide the SparseTensor data for
# a SparseColumn.
features['dummy_sparse_column'] = sparse_tensor.SparseTensor(
... | tensorflow.contrib.learn.python.learn.estimators.test_data.prepare_iris_data_for_logistic_regression | 217 |
import tensorflow as tf
'swish':swish,
'gelu':gelu
}
lr_schedules = {
'warmup_cosine':warmup_cosine,
'warmup_linear':warmup_linear,
'warmup_constant':warmup_constant,
}
def _norm(x, g=None, b=None, e=1e-5, axis=[1]):
u = tf.reduce_mean(x, axis=axis, keep_dims=True)
s = tf.reduce_mean(tf.s... | tensorflow.rsqrt | 218 |
import tensorflow as tf
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1: # tensorflow version < 0.12
writer = tf.train.SummaryWriter('logs/', sess.graph)
| tensorflow.train.SummaryWriter | 219 |
import tensorflow as tf
if mode != 'gen':
targets = tf.reshape(targets_nunroll, shape=[batch_size * rnn_nunroll])
target_weights = tf.reshape(target_weights_nunroll, shape=[batch_size * rnn_nunroll])
# CNN
cnn_output = feats_audio
if do_cnn:
layer_la... | tensorflow.constant_initializer | 220 |
import tensorflow as tf
dataset.training_X, dataset.training_y, dataset.validation_X, dataset.validation_y
if not os.path.exists(weights_dir):
os.mkdir(weights_dir)
if not os.path.exists(weights_dir + '/best_models'):
os.mkdir(weights_dir + '/best_models')
# Create a saver.
saver =... | tensorflow.merge_all_summaries | 221 |
import tensorflow as tf
dual_variable: The underlying variable itself.
"""
# We disable partitioning while constructing dual variables because they will
# be updated with assign, which is not available for partitioned variables.
partitioner = tf.get_variable_scope().partitioner
try:
tf.get_variable_s... | tensorflow.contrib.framework.model_variable | 222 |
import tensorflow as tf
loop_vars=[n, result, two])
return result
def factorial(n: TensorLike) -> TensorLike:
n = tf.convert_to_tensor(value=n)
return tf.exp(tf.math.lgamma(n + 1))
def generate_l_m_permutations(
max_band: int,
name: str = "spherical_harmonics_generate_l_m_permutations") -> Tup... | tensorflow.math.lgamma | 223 |
from tensorflow.python.ops import math_ops
self._lambda_t = ops.convert_to_tensor(self._lambda, name="lambda")
def _apply_dense(self, grad, var):
lr_t = math_ops.cast(self._lr_t, var.dtype.base_dtype)
lambda_t = math_ops.cast(self._lambda_t, var.dtype.base_dtype)
| tensorflow.python.ops.math_ops.cast | 224 |
import tensorflow as tf
filepath = os.path.join(work_directory, filename)
if not tf.gfile.Exists(filepath):
temp_file_name, _ = urllib.request.urlretrieve(source_url)
tf.gfile.Copy(temp_file_name, filepath)
with tf.gfile.GFile(filepath) as f:
size = f.size()
| tensorflow.gfile.Copy | 225 |
from tensorflow.python.ops import sparse_ops
name='expanded_shape')
expanded = sparse_ops.sparse_reshape(
| tensorflow.python.ops.sparse_ops.sparse_reshape | 226 |
from tensorflow.python.ops import init_ops
def output_size(self):
return self._num_units
def __call__(self, inputs, state, att_score):
return self.call(inputs, state, att_score)
def call(self, inputs, state, att_score=None):
"""Gated recurrent unit (GRU) with nunits cells."""
if self._gate_line... | tensorflow.python.ops.init_ops.constant_initializer | 227 |
from tensorflow.python.ops import gradients
"""See base class."""
global_step = variables.get_global_step()
assert global_step
loss = self._loss(
self._logits(features), targets, self._get_weight_tensor(features))
logging_ops.scalar_summary("loss", loss)
linear_vars = self._get_linear_... | tensorflow.python.ops.gradients.gradients | 228 |
import tensorflow as tf
block_conv_input = bottom
input_filter = bottom.get_shape().as_list()[-1]
block_conv_1 = self.conv_layer(bottom, 1, input_filter, channel_list[0], 1, name + "_branch2a")
block_norm_1 = tf.layers.batch_normalization(inputs=block_conv_1, axis = 3, momentum=c... | tensorflow.nn.relu | 229 |
import tensorflow as tf
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()
with self.assertRaisesRegexp(tf.errors.InvalidArgumentError,
... | tensorflow.is_finite | 230 |
import tensorflow as tf
#
# c = tf.constant('haHa')
# print(sess.run(c))
#
# sess.close()
identity_matrix = tf.diag([1.0, 3.0, 1.0])
A = tf.truncated_normal([2, 3])
B = tf.fill([2, 3], 5.0)
C = tf.random_uniform([3, 2], maxval=100)
D = tf.convert_to_tensor(np.array([[1., 2., 3.], [-3., -7., -1.], [0., 5.... | tensorflow.diag | 231 |
import tensorflow as tf
return tuple(restored)
def import_ops(self):
if self._is_training:
self._train_op = tf.get_collection_ref('train_op')[0]
self._lr = tf.get_collection_ref('lr')[0]
self._new_lr = tf.get_collection_ref('new_lr')[0]
self._lr_upd... | tensorflow.get_collection_ref | 232 |
from tensorflow.python.training import training as train
* `gradients` is empty.
"""
loss = ops.convert_to_tensor(loss)
contrib_framework.assert_scalar(loss)
if global_step is None:
global_step = train.get_global_step()
else:
train.assert_global_step(global_step)
with vs.variable_scope(name... | tensorflow.python.training.training.assert_global_step | 233 |
import tensorflow as tf
if monitorSession:
# MonitoredSession
# this will restore all the variables from the latest checkpoint if it exists
self._fix_checkpoint_abs_to_rel(self._checkpoint_dir) # need to ensure checkpoint has relative path saved
chiefsess_creato... | tensorflow.train.ChiefSessionCreator | 234 |
import tensorflow as tf
kk = tf.Variable(0, dtype=tf.int64)
for i in tf.range(start=0, limit=tf.size(vx_keys), delta=1, dtype=None, name='range'):
for j in tf.range(start=0, limit=tf.size(vz_keys), delta=1, dtype=None, name='range'):
to_add =... | tensorflow.math.add | 235 |
import tensorflow as tf
def _get_features_dict(input_dict):
"""Extracts features dict from input dict."""
source_id = _replace_empty_string_with_random_number(
input_dict[fields.InputDataFields.source_id])
hash_from_source_id = tf.string_to_hash_bucket_fast(source_id, HASH_BINS)
features = {
fields.I... | tensorflow.string_to_hash_bucket_fast | 236 |
from tensorflow.python.ops import parsing_ops
image = image_ops.resize_bilinear(image, [height, width])
return array_ops.squeeze(image, [0])
def _create_tfrecord_dataset(tmpdir):
if not gfile.Exists(tmpdir):
gfile.MakeDirs(tmpdir)
data_sources = test_utils.create_tfrecord_files(tmpdir, num_files=1)
k... | tensorflow.python.ops.parsing_ops.FixedLenFeature | 237 |
from tensorflow.python.ops import array_ops
def _move_tensors(tensors, device):
"""Moves a list of tensors to a device by concatenating/splitting them."""
# Reset the device setting to avoid weird interactions with device merging
# logic.
with ops.device(None):
if all(tensor.shape == tensor_shape.sc... | tensorflow.python.ops.array_ops.stack | 238 |
import tensorflow as tf
graph_def = tf.get_default_graph().as_graph_def()
self.default_encoding_stage()
new_graph_def = tf.get_default_graph().as_graph_def()
tf.test.assert_equal_graph_def(graph_def, new_graph_def)
def test_encoding_stage_name(self):
| tensorflow.test.assert_equal_graph_def | 239 |
from tensorflow.python.ops import math_ops
# whether we should use the first or last index in case of ties.
min_val = math_ops.reduce_min(math_ops.abs(sensitivities - sensitivity))
indices_at_minval = math_ops.equal(
math_ops.abs(sensitivities - sensitivity), min_val)
indices_at_minva... | tensorflow.python.ops.math_ops.argmax | 240 |
import tensorflow as tf
row_splits=[0, 4, 4, 7, 8, 8]),
}
with tf.compat.v1.Session(graph=graph) as session:
schema = schema_inference.infer_feature_schema(outputs, graph, session)
| tensorflow.compat.v1.Session | 241 |
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()... | tensorflow.nn.rnn_cell.BasicLSTMCell | 242 |
import tensorflow as tf
with tf.name_scope('get_batch'):
if cfgs.IMAGE_PYRAMID:
shortside_len_list = tf.constant(cfgs.IMG_SHORT_SIDE_LEN)
shortside_len = tf.random_shuffle(shortside_len_list)[0]
| tensorflow.constant | 243 |
import tensorflow as tf
else:
dataset_path = os.path.join(dataset_path, 'dev.json')
# Opening with GFile allows to use remotely stored files, e.g.
# in a gs bucket.
dataset_handle = tf.io.gfile.GFile(dataset_path, 'r')
dataset = json.load(dataset_handle)
def mathqa_yield_examples(generator=None):
| tensorflow.io.gfile.GFile | 244 |
import tensorflow as tf
num_items=self.train_set.num_items, emb_size=self.num_factors,
reg_user=self.regs[0], reg_item=self.regs[1], seed=self.seed)
logits = tf.layers.dense(self.interaction, units=1, name='logits',
... | tensorflow.initializers.lecun_uniform | 245 |
import tensorflow as tf
def _smooth_l1(y_true, y_pred):
# y_true [batch_size, num_anchor, 4+1]
# y_pred [batch_size, num_anchor, 4]
regression = y_pred
regression_target = y_true[:, :, :-1]
anchor_state = y_true[:, :, -1]
# 找到正样本
indices = tf.where(keras.bac... | tensorflow.gather_nd | 246 |
import tensorflow as tf
output = tf.add_n([
w_z0_y0_x0 * i_z0_y0_x0, w_z0_y0_x1 * i_z0_y0_x1,
w_z0_y1_x0 * i_z0_y1_x0, w_z0_y1_x1 * i_z0_y1_x1,
w_z1_y0_x0 * i_z1_y0_x0, w_z1_y0_x1 * i_z1_y0_x1,
w_z1_y1_x0 * i_z1_y1_x0, w_z1_y1_x1 * i_z1_y1_x1
])
return output
... | tensorflow.linspace | 247 |
import tensorflow as tf
res = sess.run([mem])
self.assertEqual(1, len(res))
self.assertEqual((2, 2), res[0].shape)
def testEmbeddingRNNDecoder(self):
with self.test_session() as sess:
with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)):
inp = [tf.consta... | tensorflow.nn.seq2seq.embedding_rnn_decoder | 248 |
import tensorflow as tf
'The number of threads used to create the batches.')
tf.app.flags.DEFINE_integer(
'num_cpu_threads', 0,
'The number of cpu cores used to train.')
tf.app.flags.DEFINE_float(
'gpu_memory_fraction', 1., 'GPU memory fraction to use.')
# scaffold related configuration
tf.app.flags.DE... | tensorflow.app.flags.DEFINE_string | 249 |
from tensorflow.contrib.eager.python.examples.l2hmc import l2hmc
# To be defunnable, the function cannot return an Operation, so the above
# function is used for defun or eager, and this function is used in graph to be
# able to run the gradient updates.
def graph_step(dynamics, optimizer, samples):
loss, grads, s... | tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.loss_and_grads | 250 |
import tensorflow as tf
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(0.4, shape=[2, 2])] * 3
| tensorflow.nn.rnn_cell.GRUCell | 251 |
import tensorflow as tf
self.padding = [ [0,0],[k_h//2,k_h//2],[k_w//2,k_w//2],[0,0] ]
def __call__(self,input_var,name=None,**kwargs):
_,h,w,c = input_var.shape.as_list()
_t = tf.image.resize_nearest_neighbor(input_var, [h*2, w*2])
_t = tf.pad(_t,self.padding, mode='SYMMETRIC')
... | tensorflow.image.resize_nearest_neighbor | 252 |
import tensorflow as tf
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
embedding.tensor_name = embedding_name
embedding.metadata_path = p... | tensorflow.contrib.tensorboard.plugins.projector.visualize_embeddings | 253 |
import tensorflow as tf
in0 = tf.placeholder(tf_input_dtype, tu.shape_to_tf_shape(input_shape),
"INPUT0")
in1 = tf.placeholder(tf_input_dtype, tu.shape_to_tf_shape(input_shape),
"INPUT1")
else:
in0 = tf.placeholder(tf_input_dtype, [
... | tensorflow.strings.to_number | 254 |
from tensorflow.contrib.tpu.python.tpu import tpu_estimator
if use_tpu:
# TPU host call. Important: need to be called before remove_summaries()
if hparams.tpu_enable_host_call:
host_call = t2t_model.create_host_call(hparams.model_dir)
else:
host_call = None
t2t_model.remov... | tensorflow.contrib.tpu.python.tpu.tpu_estimator.TPUEstimatorSpec | 255 |
import tensorflow as tf
# In this notebook we demonstrate Trieste's ability to perform asynchronous Bayesian optimisation, as is suitable for scenarios where the objective function can be run for several points in parallel but where observations might return back at different times. To avoid wasting resources waiting ... | tensorflow.get_logger | 256 |
import tensorflow as tf
Args:
inputs: 5-D tensor BxDxHxWxC
kernel_size: a list of 3 ints
stride: a list of 3 ints
Returns:
Variable tensor
"""
with tf.variable_scope(scope) as sc:
kernel_d, kernel_h, kernel_w = kernel_size
stride_d, stride_h, stride_w = stride
... | tensorflow.nn.avg_pool3d | 257 |
import tensorflow as tf
def test_default_encoding_stage(self):
"""Tests the correctness of `default_encoding_stage`."""
stage = self.default_encoding_stage()
self.assertIsInstance(stage,
(encoding_stage.EncodingStageInterface,
encoding_stage.AdaptiveEn... | tensorflow.get_default_graph | 258 |
from tensorflow.python.ops import math_ops
x = ops.convert_to_tensor(x, name="x")
weights = ops.convert_to_tensor(weights, name="weights")
biases = ops.convert_to_tensor(biases, name="biases")
mm = math_ops.matmul(x, weights)
return bias_add(mm, biases, name=name)
| tensorflow.python.ops.math_ops.matmul | 259 |
import tensorflow as tf
return [L_, tf.transpose(L_)]
tmp = tf.scan(fn, L_flat, initializer=init)
if isinstance(tmp, (list, tuple)):
| tensorflow.scan | 260 |
import tensorflow as tf
}
"""
if not features:
features = {}
inputs_old = None
if "inputs" in features and len(features["inputs"].shape) < 4:
inputs_old = features["inputs"]
features["inputs"] = tf.expand_dims(features["inputs"], 2)
if not self.has_input:
features["par... | tensorflow.to_int64 | 261 |
from tensorflow.contrib.learn.python.learn.preprocessing.text import CategoricalVocabulary
min_frequency: Minimum frequency of words in the vocabulary.
vocabulary: CategoricalVocabulary object.
Attributes:
vocabulary_: CategoricalVocabulary object.
"""
self.min_frequency = min_frequency
... | tensorflow.contrib.learn.python.learn.preprocessing.text.CategoricalVocabulary | 262 |
from tensorflow.contrib import metrics as contrib_metrics
def metric_fn(per_example_loss, label_ids, logits, is_real_example):
"""Compute Pearson correlations for STS-B."""
# Display labels and predictions
concat1 = contrib_metrics.streaming_concat(logits)
concat2 = cont... | tensorflow.contrib.metrics.streaming_concat | 263 |
import tensorflow as tf
def nin(x, num_units, **kwargs):
s = tf.shape(x)
sh = x.get_shape().as_list()
x = tf.reshape(x, [tf.reduce_prod(s[:-1]), sh[-1]])
x = dense(x, num_units, **kwargs)
return tf.reshape(x, [-1] + sh[1:-1] + [num_units])
| tensorflow.reduce_prod | 264 |
import tensorflow as tf
save_pb_at_end = config.get("save_pb", 0)
))
# summary hook
if config["save_summaries"]:
save_steps_summaries = self._get_steps(config["save_summaries_period"], self._time_refe... | tensorflow.train.SummarySaverHook | 265 |
from tensorflow.python.ops import math_ops
keep_prob = ops.convert_to_tensor(
keep_prob, dtype=x.dtype, name="keep_prob")
keep_prob.get_shape().assert_is_compatible_with(tensor_shape.scalar())
noise_shape = noise_shape or array_ops.shape(x)
# uniform [keep_prob, 1.0 + keep_prob)
random_ten... | tensorflow.python.ops.math_ops.inv | 266 |
from tensorflow.contrib import framework as contrib_framework
time.sleep(sleep_secs)
# Device allocation
device_fn = device_fn or self._device_fn
with ops.Graph().as_default() as g, g.device(device_fn):
random_seed.set_random_seed(self._config.tf_random_seed)
global_step = contrib_frame... | tensorflow.contrib.framework.create_global_step | 267 |
from tensorflow.python.ops import variable_scope
# accuracy is calculated only under 'ce_train', where true answer is given
if mode_gen == 'ce_train':
accuracy = _mask_and_accuracy(vocab_scores, answer_batch, loss_weights)
return accuracy, self._loss, sampled_words
else:... | tensorflow.python.ops.variable_scope.get_variable | 268 |
import tensorflow as tf
sequence_lengths = tf.convert_to_tensor(sequence_lengths)
| tensorflow.convert_to_tensor | 269 |
import tensorflow as tf
reduce_sum(tf.square(grad),
reduction_indices=red_ind,
keepdims=True))
normalized_grad = old_div(grad, tf.sqrt(square))
else:
normalized_grad = tf.sign(grad)
nor... | tensorflow.clip_by_value | 270 |
import tensorflow as tf
vf_old, vf_old_params, _, _ = self.build_cnet(batch['state'], 'oldvf')
self.vf, vf_params, self.vf_state_init, self.vf_state_final = self.build_cnet(batch['state'], 'vf')
self.vf_eval, _, self.vf_eval_state_init, self.vf_eval_state_final = self.build_cnet(self.state, 'v... | tensorflow.train.polynomial_decay | 271 |
import tensorflow as tf
import tensorflow as tf
import numpy as np
import math
# weights initializers
he_normal = tf.contrib.keras.initializers.he_normal()
#he_normal = tf.contrib.layers.variance_scaling_initializer()
regularizer = tf.contrib.layers.l2_regularizer(1e-4)
def Convolutional_Block(inputs, short... | tensorflow.contrib.keras.initializers.he_normal | 272 |
import tensorflow as tf
print(hidden)
# Split the series because the rnn cell needs time_steps features, each of shape:
hidden = tf.split(0, config.n_steps/4, hidden) # (0, 128, [128*batch_size, 32])
# New hidden's shape: a list of length "time_step" containing tensors of shape [batch... | tensorflow.nn.rnn | 273 |
from tensorflow.contrib import layers
bias variable for each class. Rest of the model structure learns the
residual after centered bias.
target_dimension: TODO(zakaria): dimension of the target for multilabels.
config: RunConfig object to configure the runtime settings.
Raises:
V... | tensorflow.contrib.layers.regression_target | 274 |
import tensorflow.contrib.slim as slim
method=1)
tf.summary.image('Compare/final_detection_gpu:%d' % i, detections_in_img)
loss_dict = outputs[-1]
total_loss_dict... | tensorflow.contrib.slim.learning.clip_gradient_norms | 275 |
from tensorflow.contrib import layers
raise ValueError("n_classes should be greater than 1. Given: {}".format(
n_classes))
target_column = layers.multi_class_target(
n_classes=n_classes,
| tensorflow.contrib.layers.multi_class_target | 276 |
import tensorflow as tf
def main(unused_argv):
tf.compat.v1.enable_v2_behavior() # The trainer only runs with V2 enabled.
| tensorflow.compat.v1.enable_v2_behavior | 277 |
import tensorflow as tf
self.r: batch.r,
self.local_network.state_in[0]: batch.features[0],
self.local_network.state_in[1]: batch.features[1],
}
fetched = sess.run(fetches, feed_dict=feed_dict)
if should_compute_summary:
self.summary_writer.add_... | tensorflow.Summary.FromString | 278 |
import tensorflow as tf
cutoff_vf_worker = tf.reshape(tf.stop_gradient(self.worker_vf), [-1])
log_p = tf.reduce_sum(self.log_pi * self.ac, [1])
worker_loss = (self.r + self.alpha * self.ri - cutoff_vf_worker) * log_p
worker_loss = -tf.reduce_sum(worker_loss, axis=0)
Am = self.... | tensorflow.reduce_sum | 279 |
import tensorflow as tf
print('\rTrained in %.3fs. Global step %i' % (time() - start, step+1))
return summary
class PPO_HC(PPO):
def build_anet(self, state_in, name, reuse=False):
reg = tf.contrib.layers.l2_regularizer(1e-3)
with tf.variable_scope(name, reuse=reuse):
l... | tensorflow.layers.dense | 280 |
from tensorflow.contrib.slim.python.slim.data import dataset
items_to_handlers = {
'image': tfexample_decoder.Image(),
'label': tfexample_decoder.Tensor('image/class/label'),
}
decoder = tfexample_decoder.TFExampleDecoder(keys_to_features,
items_to_han... | tensorflow.contrib.slim.python.slim.data.dataset.Dataset | 281 |
from tensorflow.contrib.data import Iterator
temp_val_data['X'][i * 2 + 1, :, :, :] = self.val_data['X'][i, :, sh[2] // 2:, :]
temp_val_data['Y'][i * 2, :, :] = self.val_data['Y'][i, :, :sh[2] // 2]
temp_val_data['Y'][i * 2 + 1, :, :] = self.val_data['Y'][i, :, sh[2] // 2:]
... | tensorflow.contrib.data.Iterator.from_structure | 282 |
import tensorflow as tf
search_space = Box([0, 0], [1, 1])
num_initial_points = 3
initial_query_points = search_space.sample(num_initial_points)
initial_observations = objective(initial_query_points.numpy(), sleep=False)
initial_data = Dataset(
query_points=initial_query_points,
observations=tf.constant(initi... | tensorflow.math.reduce_variance | 283 |
import tensorflow as tf
if not forward_only:
lstm_cell = tf.nn.rnn_cell.DropoutWrapper(cell=lstm_cell, output_keep_prob=self.dropout_output)
# lstm_cell = tf.nn.rnn_cell.MultiRNNCell(cells=[lstm_cell] * 4, state_is_tuple=True)
if not forward_only:
embed_inputs = tf.nn.dropout(embed_inputs, keep_pr... | tensorflow.nn.dynamic_rnn | 284 |
import tensorflow as tf
if is_max_pool:
x = tf.nn.max_pool3d(x, ksize=kernel_size, strides=strides, padding='VALID', name=layer_name)
| tensorflow.nn.max_pool3d | 285 |
import tensorflow as tf
estimator=entropy_bottleneck)
status = checkpoint.restore(tf.train.latest_checkpoint(ckpt_dir))
x = tf.convert_to_tensor(x_color, "float32")
x_coori = tf.convert_to_tensor(x_coori, "float32")
def loop_analysis(element):
x = tf.expand_dims... | tensorflow.map_fn | 286 |
import tensorflow as tf
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 i... | tensorflow.image.resize | 287 |
from tensorflow.contrib.opt import ScipyOptimizerInterface
if type(method) is str:
success_msg = "SciPy optimizer completed successfully."
options = {'maxiter': maxiter, 'disp': True}
options.update(kw)
optimizer = ScipyOpt... | tensorflow.contrib.opt.ScipyOptimizerInterface | 288 |
import tensorflow as tf
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_annotatio... | tensorflow.pad | 289 |
import tensorflow as tf
Train RNN graph for multiple series
"""
def train_rnn_multi(raw_data_x, raw_data_y, val_data_x, val_data_y, timeindex_train, timeindex_val, g, num_epochs, num_steps, batch_size, input_prob, output_prob, state_prob, epoch_before_val = 50, max_checks_without_progress=50,epoch_overlap=None, verb... | tensorflow.trainable_variables | 290 |
from tensorflow.python.framework import constant_op
features = {"x": constant_op.constant([[1.], [2.], [2.]])}
label = constant_op.constant([[0], [1], [1]], dtype=dtypes.int32)
return features, label
def _infer_ranking_train_input_fn():
features = {
"f1": constant_op.constant([[3.], [2], [1.]]),
... | tensorflow.python.framework.constant_op.constant | 291 |
import tensorflow as tf
#Q_filter_1 = tf.cast(qf1 > min_q,tf.float32)
#Q_filter_2 = tf.cast(qf2 > min_q,tf.float32)
im_loss1 = tf.square(self.actions_ph - self.deterministic_actions_ph)*Q_filter*self.is_demo_ph
#im_loss2 = tf.square(self.a... | tensorflow.contrib.layers.l1_l2_regularizer | 292 |
import tensorflow as tf
t_flatten = tf.reshape(t, shape=(-1,))
uniques, index = tf.unique(t_flatten)
| tensorflow.unique | 293 |
from tensorflow.python.framework import op_def_registry
def _get_op_def(op):
# pylint: disable=protected-access
if hasattr(op, "_sig"):
return getattr(op, "_sig")
else:
return op_def_registry.get_registered_ops()[op.type]
# pylint: enable=protected-access
def _is_in_placeholders(op, func_arg_placeho... | tensorflow.python.framework.op_def_registry.get_registered_ops | 294 |
import tensorflow as tf
### Metrics
global_step = tf.compat.v1.train.get_or_create_global_step()
orig_indices = tf.range(
self._sample_batch_size, dtype=relabel_indices.dtype)
with tf.name_scope("relabelling"):
# How often are the originally commanded goals most optimal?
opt_indice... | tensorflow.compat.v2.summary.scalar | 295 |
import tensorflow as tf
weights=is_real_example)
return {"pred": concat1, "label_ids": concat2, "pearson": pearson,
"MSE": mse, "eval_loss": loss,}
elif task_name == "cola":
def metric_fn(per_example_loss, label_ids, logits, is_real_example):
"""Comput... | tensorflow.metrics.false_negatives | 296 |
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
r... | tensorflow.image.extract_jpeg_shape | 297 |
import tensorflow as tf
for output in model_options.outputs_to_num_classes
}
for i, image_scale in enumerate(eval_scales):
with tf.variable_scope(tf.get_variable_scope(), reuse=True if i else None):
outputs_to_scales_to_logits = multi_scale_logits(
images,
model_options=model_o... | tensorflow.reverse_v2 | 298 |
import tensorflow as tf
lstm_input = tf.transpose(x, perm=[1, 0, 2])
outputs, _ = tf.lite.experimental.nn.dynamic_rnn(
| tensorflow.lite.experimental.nn.dynamic_rnn | 299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.