seed stringlengths 25 2.89k | seed_api stringlengths 14 102 | index int64 0 14.8k |
|---|---|---|
import tensorflow as tf
def fc_layer(layer_name, x, out_nodes):
'''
Wrapper for fully connected layers with RELU activation as default
'''
shape = x.get_shape()
if len(shape) == 5: # FC 3D
size = shape[1].value*shape[2].value*shape[3].value*shape[4].value
elif len(shape) == 4:
... | tensorflow.variable_scope | 0 |
import tensorflow as tf
ch_emb = tf.reshape(tf.nn.embedding_lookup(
self.char_mat, self.ch), [N * PL, CL, dc])
qh_emb = tf.reshape(tf.nn.embedding_lookup(
self.char_mat, self.qh), [N * QL, CL, dc])
ch_emb = tf.nn.dropout(ch_emb, 1.0 - 0.5 * self.dropo... | tensorflow.reduce_max | 1 |
import tensorflow as tf
def testGPU(self):
if not tf.test.is_built_with_cuda():
return
save_path = os.path.join(self.get_temp_dir(), "gpu")
with tf.Session("", graph=tf.Graph()) as sess:
with sess.graph.device("/gpu:0"):
v0_1 = tf.Variable(123.45)
save = tf.train.Saver({"v0": v0... | tensorflow.initialize_all_variables | 2 |
import tensorflow as tf
'learning_rate', tf.reduce_mean(learning_rate),
step=global_step)
return tf.contrib.summary.all_summary_ops()
# To log the loss, current learning rate, and epoch for Tensorboard, the
# summary op needs to be run on the host CPU via host_... | tensorflow.reshape | 3 |
import tensorflow as tf
b1 = tf.matmul(state, hyper_b_1)
w1_reshaped = tf.reshape(w1, [-1, n_agents, n_h_mixer]) # reshape into batch of matrices
b1_reshaped = tf.reshape(b1, [-1, 1, n_h_mixer])
# [batch, 1, n_h_mixer]
hidden = tf.nn.elu(tf.matmul(agent_qs_reshaped, w1_reshaped) + b1_reshaped)
... | tensorflow.matmul | 4 |
from tensorflow.contrib.boosted_trees.proto import learner_pb2
num_trees=1,
examples_per_layer=3,
model_dir=model_dir,
config=config,
feature_columns=[core_feature_column.numeric_column("x")],
use_core_libs=True)
model.fit(input_fn=_train_input_fn, steps=15)
mod... | tensorflow.contrib.boosted_trees.proto.learner_pb2.LearnerConfig | 5 |
import tensorflow as tf
"below 1.1.0")
soft_placement = False
if FLAGS.num_gpus > 1:
soft_placement = True
util.auto_parallel(metagraph, m)
with tf.Graph().as_default():
tf.train.import_meta_graph(metagraph)
for model in models.values():
model.import_ops()
... | tensorflow.Graph | 6 |
import tensorflow as tf
transpose=transpose)
if w_project is not None:
x = tf.conv2d(x, w_project, strides, padding='SAME')
# Set shape for BN in the residual function.
| tensorflow.conv2d | 7 |
import tensorflow as tf
if FLAGS.use_tpu:
estimator = tf.contrib.tpu.TPUEstimator(
| tensorflow.contrib.tpu.TPUEstimator | 8 |
from tensorflow.python.ops.rnn_cell_impl import _Linear
[inputs, state],
2 * self._num_units,
True,
bias_initializer=bias_ones,
kernel_initializer=self._kernel_initializer)
value = math_ops.sigmoid(self._gate_linear([inputs, state]))
r, u = array_ops... | tensorflow.python.ops.rnn_cell_impl._Linear | 9 |
from tensorflow.contrib.layers.python.layers import utils
# 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_second_mome... | tensorflow.contrib.layers.python.layers.utils.smart_cond | 10 |
import tensorflow as tf
self._train_op = optimizer.apply_gradients(
zip(grads, tvars),
global_step=tf.train.get_or_create_global_step())
self._new_lr = tf.placeholder(
tf.float32, shape=[], name="new_learning_rate")
self._lr_update = tf.assign(self._lr, self._new_lr)
| tensorflow.placeholder | 11 |
import tensorflow as tf
with self.test_session() as session:
@dynamic_batching.batch_fn
def f(a, b):
return a + b
output0 = f(tf.constant([1]), tf.constant([2]))
output1 = f(tf.constant([[2]]), tf.constant([3]))
tp = pool.ThreadPool(2)
f0 = tp.apply_async(session.run,... | tensorflow.train.Coordinator | 12 |
import tensorflow as tf
if tf.version.VERSION[0]=="2":
gpus = tf.config.experimental.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(gpus[0], True)
tf.config.experimental.set_virtual_device_configuration(gpus[0],
[tf.config.experimental.VirtualDeviceConfigu... | tensorflow.ConfigProto | 13 |
import tensorflow as tf
stochastic_ph = tf.placeholder(tf.bool, (), name="stochastic")
update_eps_ph = tf.placeholder(tf.float32, (), name="update_eps")
update_param_noise_threshold_ph = tf.placeholder(tf.float32, (), name="update_param_noise_threshold")
update_param_noise_scale_ph = tf... | tensorflow.constant_initializer | 14 |
import tensorflow as tf
with tf.variable_scope(name):
filt = self.get_conv_filter(name)
conv = tf.nn.conv2d(bottom, filt, [1, 1, 1, 1], padding='SAME')
conv_biases = self.get_bias(name)
bias = tf.nn.bias_add(conv, conv_biases)
relu = tf.nn.relu(bia... | tensorflow.nn.bias_add | 15 |
import tensorflow as tf
gru_fw = tf.contrib.cudnn_rnn.CudnnGRU(1, num_units)
gru_bw = tf.contrib.cudnn_rnn.CudnnGRU(1, num_units)
init_fw = tf.tile(tf.Variable(
tf.zeros([1, 1, num_units])), [1, batch_size, 1])
init_bw = tf.tile(tf.Variable(
... | tensorflow.ones | 16 |
import tensorflow as tf
x = tf.nn.conv2d(input, filters, strides=[1, stride, stride, 1], padding=padding, name='zero-conv_' + id,
dilations=(1, dilation, dilation, 1))
if use_bias:
bias = tf.get_variable("bias", [channels], initializer=tf.constant_initializer(0.0))
... | tensorflow.nn.bias_add | 17 |
import tensorflow as tf
raise ValueError('Variables to load is empty.')
return tf.train.Scaffold()
| tensorflow.train.Scaffold | 18 |
import tensorflow as tf
def find_hard_distances(distance_matrix, indicator_matrix):
distance_matrix = tf.where(
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)
... | tensorflow.expand_dims | 19 |
import tensorflow as tf
lambda: param_noise_scale.assign(param_noise_scale * 1.01),
lambda: param_noise_scale.assign(param_noise_scale / 1.01),
)
return update_scale_expr
# Functionality to update the threshold for parameter space noise.
... | tensorflow.cond | 20 |
import tensorflow as tf
y += dense(hidden, encoder.attn_size, use_bias=False, name='U_a')
if encoder.position_bias and input_length is not None and time is not None:
src_pos = tf.tile(tf.expand_dims(tf.range(time_steps), axis=0), [batch_size, 1])
trg_pos = tf.tile(tf.reshape(time, [1, 1]), [ba... | tensorflow.expand_dims | 21 |
import tensorflow as tf
filename = _DATA_URL.split('/')[-1]
filepath = os.path.join(dataset_dir, filename)
tf.gfile.Remove(filepath)
| tensorflow.gfile.Remove | 22 |
import tensorflow as tf
elif self.hidden_init == 'zeros':
l1_h2 = tf.zeros(x_shape, dtype=self.dtype)
l2_h2 = tf.zeros(l2_shape, dtype=self.dtype)
l3_h2 = tf.zeros(l3_shape, dtype=self.dtype)
else:
raise RuntimeError
| tensorflow.zeros | 23 |
import tensorflow as tf
def main(argv=None):
start1 = time.time()
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:
tf.gfile.DeleteRecursively(FL... | tensorflow.gfile.DeleteRecursively | 24 |
import tensorflow as tf
"""
mean, var = tf.nn.moments(
x, reduction_axes, shift=None, name=None, keep_dims=False)
if sorted(reduction_axes) == range(ndim(x))[:-1]:
normed = tf.nn.batch_normalization(x, mean, var, beta, gamma, epsilon)
else:
# need broadcasting
target_shape = []
for axis i... | tensorflow.reshape | 25 |
import tensorflow as tf
Arguments:
- *indicator*: a 1-dimensional boolean tensor indicating which elements
are allowed to be sampled and which are not.
- *num_samples*: int32 scalar tensor
Returns:
A boolean tensor with the same shape as input (indicator) tensor
"""
indices = tf... | tensorflow.size | 26 |
import tensorflow as tf
pos_weight = pos_weight,
norm = norm)
# Normalization and preprocessing on adjacency matrix
adj_norm = preprocess_graph(adj)
adj_label = sparse_to_tuple(adj + sp.eye(adj.shape[0]))
# Initiali... | tensorflow.Session | 27 |
import tensorflow as tf
e_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name + '/eval_net')
e_params += tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name + '/mixing_net' + '/eval_hyper')
t_params += tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=se... | tensorflow.summary.FileWriter | 28 |
import tensorflow as tf
self.num_replicas = num_replicas
self.name = name
self._create_params()
arc_seq_1, entropy_1, log_prob_1, c, h = self._build_sampler(use_bias=True)
arc_seq_2, entropy_2, log_prob_2, _, _ = self._build_sampler(prev_c=c, prev_h=h)
self.sample_arc = (arc_seq_1, arc_seq_2)
... | tensorflow.variable_scope | 29 |
import tensorflow as tf
if self.multiplicative_excitation:
if self.lesion_kappa:
setattr(
self,
'kappa_%s' % layer,
tf.constant(0.))
else:
... | tensorflow.constant | 30 |
import tensorflow as tf
def conv3d(layer_name, x, out_channels, kernel_size=[1,3,3], strides=[1,1,1,1,1], data_format='NDHWC', is_pretrain=True):
'''
Convolution 3D op wrapper, use RELU activation after convolution
'''
in_channels = x.get_shape()[-1].value
with tf.variable_scope(layer_name):
... | tensorflow.contrib.layers.xavier_initializer | 31 |
import tensorflow as tf
filter_size[1] - input_.get_shape().as_list()[2], 0
], [-1, -1, -1, -1])
if bias:
biases = variable_on_cpu("biases", [dim_out], tf.constant_initializer(0.))
res = tf.nn.bias_add(res, biases)
if nonlinearity is no... | tensorflow.nn.max_pool | 32 |
import tensorflow as tf
# Make a matrix where each row contains [0, 1, ..., max_sequence_len]
r = tf.range(0, max_sequence_len, 1)
range_row = tf.expand_dims(r, 0)
range_tiled = tf.tile(range_row, [batch_size, 1])
# Use the logical operations to create a mask
| tensorflow.tile | 33 |
import tensorflow as tf
# I.e., 0.1 dropout
output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
logits = tf.matmul(output_layer, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
probabilities = tf.nn.softmax(logits, axis=-1)
log_probs = tf.nn.log_softmax... | tensorflow.reduce_mean | 34 |
import tensorflow as tf
vocab_path = self.vocabulary_file_by_name(vocab_filename)
if not vocab_path:
raise ValueError(
'Could not compute vocabulary size for {}, does not exist'.format(
vocab_filename))
elif vocab_path.endswith('tfrecord.gz'):
dataset = tf.data.TFRecord... | tensorflow.size | 35 |
import tensorflow as tf
def get_assignment_map_from_checkpoint(tvars, init_checkpoint, num_of_group=0):
"""Compute the union of the current variables and checkpoint variables."""
assignment_map = {}
initialized_variable_names = {}
name_to_variable = collections.OrderedDict()
for var in tvars:
name = v... | tensorflow.train.list_variables | 36 |
import tensorflow as tf
x = tf.placeholder(tf.float32, [None, shape[0]])
w = tf.Variable(tf.zeros(shape))
b = tf.Variable(tf.zeros(shape[1]))
self.x = x
self.w = w
self.b = b
y = tf.nn.softmax(tf.matmul(x, w) + b)
y_ = tf.placeholder(tf.float32, [None, sh... | tensorflow.matmul | 37 |
import tensorflow as tf
target_label = sess.run(labels)
adv = attack_carlini.attack(input_data, target_label)
(logits_part_nor, logits_part_adv, labels_part) = sess.run([logits_nor, logits_adv, tf.argmax(labels, 1)],
feed_d... | tensorflow.argmax | 38 |
import tensorflow as tf
stddev=0.02, data_format='NDHWC') :
with tf.variable_scope(name) :
assert(data_format == 'NDHWC')
self.w = tf.get_variable('w', [k_t, k_h, k_w, input_dim, output_dim],
initializer=tf.truncated_normal_initializer(st... | tensorflow.truncated_normal_initializer | 39 |
import tensorflow as tf
loss = None
with tf.name_scope(name, "softmax_loss",[output]):
label_dis = labels / tf.reduce_sum(labels, 1, keep_dims=True)
loss = tf.nn.softmax_cross_entropy_with_logits(logits=output, labels=label_dis) * tf.reduce_sum(labels, 1)
return tf.redu... | tensorflow.reduce_sum | 40 |
import tensorflow as tf
print('===== Decompress =====')
# load model.
model = importlib.import_module(model)
synthesis_transform = model.SynthesisTransform(latent_points)
hyper_encoder = model.HyperEncoder()
hyper_decoder = model.HyperDecoder()
entropy_bottleneck = EntropyBottleneck()
conditiona... | tensorflow.train.latest_checkpoint | 41 |
import tensorflow as tf
const_var = tf.Variable(tf.constant([8, 6, 7, 5, 3, 0, 9]))
const_fill_var = tf.Variable(tf.constant(-1, shape=[row_dim, col_dim]))
sess.run(const_var.initializer)
| tensorflow.constant | 42 |
import tensorflow as tf
def testStrWorksCorrectlyScalar(self):
# Usually we'd write np.float(X) here, but a recent Eager bug would
# erroneously coerce the value to float32 anyway. We therefore use constants
# here, until the bug is resolved in TensorFlow 1.12.
normal = tfd.Normal(loc=tf.constant(0,... | tensorflow.constant | 43 |
import tensorflow as tf
'`rightmost_transposed_ndims` and `perm`.')
if rightmost_transposed_ndims is not None:
rightmost_transposed_ndims = tf.convert_to_tensor(
value=rightmost_transposed_ndims,
dtype=np.int32,
name='rightmost_transposed_ndims... | tensorflow.range | 44 |
import tensorflow as tf
def hgru_ops(self, i0, x, h2, layer, layer_idx):
"""hGRU body."""
var_scope = '%s_hgru_weights' % layer
# Circuit input receives recurrent output h2
c1, g1 = self.circuit_input(
h2=h2,
layer=layer,
var_scope=var_scope,
... | tensorflow.variable_scope | 45 |
import tensorflow as tf
act: (tf.Variable, bool, float, bool, float, bool) -> tf.Variable
function to select and action given observation.
` See the top of the file for details.
"""
if param_noise_filter_func is None:
param_noise_filter_func = default_param_noise_filter
with tf.v... | tensorflow.placeholder | 46 |
import tensorflow as tf
super(TweetSeqModel, self).__init__(batch_size, max_sequence_len,
out_vocab_size, c2v,
dropout_keep_prob)
weights = tf.constant(weights, dtype=tf.float32, name='class_weights')
def GetCell():
""... | tensorflow.nn.rnn_cell.LSTMCell | 47 |
import tensorflow as tf
'image/object/bbox/xmax':
tf.io.VarLenFeature(tf.float32),
'image/object/bbox/ymin':
tf.io.VarLenFeature(tf.float32),
'image/object/bbox/ymax':
tf.io.VarLenFeature(tf.float32),
'image/object/class/label':
tf.io.VarL... | tensorflow.io.VarLenFeature | 48 |
import tensorflow as tf
total_loss = tf.reduce_sum(lm_loss * tgt_mask) / tf.reduce_sum(tgt_mask)
monitor_dict["total_loss"] = total_loss
return total_loss, new_mems, monitor_dict
def get_loss(FLAGS, features, labels, mems, is_training):
"""Pretraining loss with two-stream attention Transformer-XL."""
if ... | tensorflow.tpu.bfloat16_scope | 49 |
import tensorflow as tf
raise Exception("The input dimension must be rank 2")
n_in = int(self.inputs.get_shape()[-1])
self.n_units = n_units
with tf.variable_scope(name):
W = tf.get_variable(name='W', shape=(n_in, n_units), initializer=W_init, dtype=LayersConfig.tf_dtyp... | tensorflow.matmul | 50 |
import tensorflow as tf
elif isinstance(ob_space, Box):
input_shape = (batch_size,) + ob_space.shape
input_x = tf.placeholder(shape=input_shape, dtype=ob_space.dtype, name=name)
processed_x = tf.to_float(input_x)
return input_x, processed_x
else:
| tensorflow.to_float | 51 |
import tensorflow as tf
scope='BoxEncodingPredictor')
if self._use_dropout:
net = slim.dropout(net, keep_prob=self._dropout_keep_prob)
class_predictions_with_background = slim.conv2d(
net, num_predictions_per_location * num_class_slots,
[self._kernel_size, ... | tensorflow.sigmoid | 52 |
import tensorflow as tf
# TODO: move to ops
def _rank(x):
return len(x.get_shape())
def _apply_dropout_mask(tensor_shape, keep_prob=1.0, normalize=True):
random_tensor = keep_prob + tf.random_uniform(tensor_shape, dtype=tf.float32)
binary_mask = tf.floor(random_tensor)
if normalize:
binary_ma... | tensorflow.convert_to_tensor | 53 |
import tensorflow as tf
input_props.append((tf.int32, [None])) # Gold ends.
input_props.append((tf.int32, [None])) # Cluster ids.
self.queue_input_tensors = [tf.placeholder(dtype, shape) for dtype, shape in input_props]
dtypes, shapes = zip(*input_props)
queue = tf.PaddingFIFOQueue(capacity=10, dt... | tensorflow.trainable_variables | 54 |
import tensorflow as tf
def call(self, inputs):
"""Evaluates the QNode on input data using the initialized weights.
Args:
inputs (tensor): data to be processed
Returns:
tensor: output data
"""
if len(tf.shape(inputs)) > 1:
# If the input... | tensorflow.unstack | 55 |
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... | tensorflow.add_to_collection | 56 |
import tensorflow as tf
return_dict["end_top_index"] = end_top_index
# an additional layer to predict answerability
with tf.variable_scope("answer_class"):
# get the representation of CLS
cls_index = tf.one_hot(cls_index, seq_len, axis=-1, dtype=tf.float32)
cls_feature = tf.einsum("lbh,bl->bh", ou... | tensorflow.concat | 57 |
import tensorflow.contrib.graph_editor as ge
d_xs_new = dv[len(checkpoints_other):]
for j in range(len(xs)):
if d_xs_new[j] is not None:
if d_xs[j] is None:
d_xs[j] = _unsparsify(d_xs_new[j])
else:
d_xs[j] += _unsparsif... | tensorflow.contrib.graph_editor.get_forward_walk_ops | 58 |
import tensorflow as tf
def build_trainer(self, child_model):
child_model.build_valid_rl()
self.valid_acc = (tf.to_float(child_model.valid_shuffle_acc) /
tf.to_float(child_model.batch_size))
self.reward = self.valid_acc
if self.entropy_weight is not None:
self.reward += s... | tensorflow.assign_sub | 59 |
import tensorflow as tf
def deconv2d(input_, output_shape,
k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02,
name="deconv2d", with_w=False):
with tf.variable_scope(name):
# filter : [height, width, output_channels, in_channels]
w = tf.get_variable('w', [k_h, k_w, output_shape[-1], input_.get_s... | tensorflow.variable_scope | 60 |
import tensorflow as tf
vz_keys = tf.reshape(tf.Variable([], collections=[], dtype=tf.string), (-1, 1))
x_t = tf.gather(x, l)
x_t_len = tf.strings.length(x_t)
x_t = tf.string_split([x_t], delimiter='').values
z_t = tf.gather(y, m)
... | tensorflow.string_join | 61 |
import tensorflow as tf
# now to upscale to actual image size
deconv_shape1 = image_net["pool4"].get_shape()
W_t1 = utils.weight_variable([4, 4, deconv_shape1[3].value, NUM_OF_CLASSESS], name="W_t1")
b_t1 = utils.bias_variable([deconv_shape1[3].value], name="b_t1")
conv_t1 = ut... | tensorflow.shape | 62 |
from tensorflow.python.framework import ops
name or 'root_mean_squared_error')
root_mean_squared_error = math_ops.sqrt(value_tensor)
with ops.control_dependencies([update_op]):
update_op = math_ops.sqrt(update_op)
| tensorflow.python.framework.ops.control_dependencies | 63 |
import tensorflow as tf
TRAIN_STEPS = 1
CONFIG = tf.ConfigProto(device_count={"GPU": 0})
class UnidirectionalSequenceLstmTest(test_util.TensorFlowTestCase):
def setUp(self):
tf.reset_default_graph()
# Import MNIST dataset
self.mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
# Defin... | tensorflow.reset_default_graph | 64 |
import tensorflow as tf
# Date: 2018/12/22 下午4:06
# 10.3 TensorFlow的并发执行
# 1. 为了能够找到TensorFlow的什么操作正在使用什么设备,我们在计算图会话中传入一个config参数,将log_device_placement设为True。当我们在命令行运行脚本时,会看到指定设备输出
import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
a = tf.constant_initializer([1.0, 2.0, 3.0, ... | tensorflow.constant_initializer | 65 |
import tensorflow as tf
param_eta = tf.placeholder(dtype=tf.float32, shape=[], name="param_eta")
| tensorflow.placeholder | 66 |
import tensorflow as tf
tvars = tf.trainable_variables()
initialized_variable_names = {}
scaffold_fn = None
if init_checkpoint:
(assignment_map, initialized_variable_names
) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)
if us... | tensorflow.train.init_from_checkpoint | 67 |
import tensorflow as tf
# Creates a graph.
v0 = tf.Variable(0.0)
var = tf.Variable(10.0)
tf.add(v0, var)
@function.Defun(x=tf.float32)
def minus_one(x):
return x - 1
minus_one(tf.identity(v0))
save = tf.train.Saver({"v0": v0})
tf.initialize_all_variables()
... | tensorflow.identity | 68 |
import tensorflow as tf
tf.OpError, lambda e: "uninitialized value v0" in e.message):
sess.run(v0)
with self.assertRaisesWithPredicateMatch(
tf.OpError, lambda e: "uninitialized value v1" in e.message):
sess.run(v1)
# Restore the saved values in the parameter nodes.
... | tensorflow.Variable | 69 |
import tensorflow as tf
def to_ids(example):
sentence = tf.reshape(example['tokens'], shape=[1])
words = tf.strings.split(sentence, sep=' ').values
truncated_words = words[:max_seq_len]
| tensorflow.strings.split | 70 |
import tensorflow as tf
tf.summary.scalar('cross_entropy_loss', cross_entropy)
loc_loss = tf.cond(n_positives > 0., lambda: modified_smooth_l1(location_pred, tf.stop_gradient(gtargets), sigma=1.), lambda: tf.zeros_like(location_pred))
#loc_loss = modified_smooth_l1(location_pred, tf.stop_gradient(gtargets... | tensorflow.nn.l2_loss | 71 |
import tensorflow as tf
return model_utils.update_exponential_moving_average(
rl_step_baseline, momentum=rl_baseline_momentum)
rl_baseline = update_rl_baseline()
rl_advantage = rl_reward - rl_baseline
rl_empirical_loss = -tf.stop_gradient(rl_advantage) * log_prob
rl_entropy_loss = -rl_entropy_re... | tensorflow.greater_equal | 72 |
import tensorflow as tf
decided to use the (x_min, y_min, x_max, y_min), forcing use to switch to
TensorFlow's every time we want to use a std function that handles bounding
boxes.
Args:
bboxes: A Tensor of shape (total_bboxes, 4)
Returns:
bboxes: A Tensor of shape (total_bboxes, ... | tensorflow.name_scope | 73 |
import tensorflow as tf
variables_averages_op = variable_averages.apply(tf.trainable_variables())
# batch norm updates
with tf.control_dependencies([variables_averages_op, apply_gradient_op, batch_norm_updates_op]):
train_op = tf.no_op(name='train_op')
saver = tf.train.Saver(tf.global_variable... | tensorflow.ConfigProto | 74 |
import tensorflow as tf
input_images = tf.placeholder(tf.float32, shape=[None, None, None, 3], name='input_images')
| tensorflow.placeholder | 75 |
import tensorflow as tf
(assignment_map, initialized_variable_names
) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)
if use_tpu:
def tpu_scaffold():
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
return tf.train.Scaffold()
s... | tensorflow.train.init_from_checkpoint | 76 |
import tensorflow as tf
if coeff <= 0:
return y
x = np.zeros(y.shape[0], dtype=np.float32)
x[0] = y[0]
for n in range(1, y.shape[0], 1):
x[n] = coeff * x[n - 1] + y[n]
return x
def read_and_decode(filename_queue, canvas_size, preemph=0.):
reader = tf.TFRecordReader()
_, ser... | tensorflow.TFRecordReader | 77 |
import tensorflow as tf
tf.equal(phase, 'train'),
datasets.train.get_next,
datasets.test.get_next)
if not isinstance(data, dict):
data = {'data': data}
if 'length' not in data:
example = data[list(data.keys())[0]]
data['length'] = (
tf.zeros((tf.s... | tensorflow.shape | 78 |
import tensorflow as tf
resnet_size=18, num_classes=class_num, mode='se', data_format=None)
inputs= network(inputs=inputs, is_training=training)
feat = tf.nn.l2_normalize(inputs, 1, 1e-10, name='feat')
inputs = tf.layers.dense(inputs=inputs, units=class_num)
# inputs = tf.layers.dense(input... | tensorflow.placeholder | 79 |
import tensorflow as tf
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# pylint: disable=missing-docstring
from __future__ import absolute_import
from __future__ import division
from __future__... | tensorflow.variable_scope | 80 |
import tensorflow as tf
tf.app.flags.DEFINE_string('eval_data_path', '',
'Filepattern for eval data')
tf.app.flags.DEFINE_string('train_dir', '',
'Directory to keep training outputs.')
tf.app.flags.DEFINE_string('eval_dir', '',
'Dire... | tensorflow.app.flags.DEFINE_bool | 81 |
import tensorflow as tf
l3=tf.matmul(l2, self.w3)+self.b3
l3=tf.nn.relu(l3)
out=tf.matmul(l3, self.w4)+self.b4
return out
def valid_inference(self,images):
images=tf.cast(images,tf.float32)/255.0
l1 = tf.matmul(images, self.w1)+self.b1
l1=tf.nn.r... | tensorflow.matmul | 82 |
import tensorflow as tf
row_norms = tf.sqrt(tf.reduce_sum(tf.square(var_matrix), 1))
scaling = maxnorm / tf.maximum(row_norms, maxnorm)
| tensorflow.maximum | 83 |
from tensorflow.python.framework import ops
"""
with ops.op_scope([value, bias], name, "BiasAddV1") as name:
value = ops.convert_to_tensor(value, name="input")
bias = ops.convert_to_tensor(bias, dtype=value.dtype, name="bias")
return gen_nn_ops._bias_add_v1(value, bias, name=name)
ops.RegisterShape("... | tensorflow.python.framework.ops.RegisterShape | 84 |
from tensorflow.python.ops import math_ops
# Create slots for the global solution.
for v in var_list:
self._zeros_slot(v, "vstar", self._name)
self._zeros_slot(v, "gold", self._name)
def _apply_dense(self, grad, var):
lr_t = math_ops.cast(self._lr_t, var.dtype.base_... | tensorflow.python.ops.math_ops.cast | 85 |
import tensorflow as tf
if modality.top_is_pointwise:
return tf.squeeze(logits, axis=[1, 2, 3])
# -1 due to the pad above.
current_output_position = common_layers.shape_list(ids)[1] - 1
logits = logits[:, current_output_position, :, :]
return tf.squeeze(logits, axis=[1, 2])
... | tensorflow.squeeze | 86 |
import tensorflow as tf
x = tf.transpose(x, perm=[3, 1, 2, 0]) # (batch_size, num_nodes, input_size, order)
x = tf.reshape(x, shape=[batch_size * self._num_nodes, input_size * num_matrices])
weights = tf.get_variable(
'weights', [input_size * num_matrices, output_si... | tensorflow.constant_initializer | 87 |
import tensorflow as tf
print('logit: {}'.format(logits.get_shape()))
# Compute loss
if mode != 'gen':
neg_log_lhoods = tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=targets)
if target_weight_strategy == 'rect':
avg_neg_log_lhood = tf.red... | tensorflow.reduce_sum | 88 |
import tensorflow as tf
for i in range (dim):
dg_i = tf.gradients(flat_grads[i], par) #for each element of grads evaluate the gradients
dg_i_flat = flatten(dg_i) #flatten the resulting hessian onto a 1 d array
| tensorflow.gradients | 89 |
import tensorflow as tf
return choices
samples = multinomial_squeeze(logits, self.hparams.sampling_temp)
return samples, logits, losses
def _shard_features(self, features): # pylint: disable=missing-docstring
sharded_features = dict()
for k, v in six.iteritems(features):
v = tf.co... | tensorflow.expand_dims | 90 |
import tensorflow as tf
random_actions = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=n_actions, dtype=tf.int64)
chose_random = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=1, dtype=tf.float32) < eps
perturbed_stochastic_actions = tf.where(chose_random, random_actions, perturbed... | tensorflow.cond | 91 |
import tensorflow as tf
return tf.clip_by_value(combined_idx, 0, 9)
def get_slow_antecedent_scores(self, top_span_emb, top_antecedents, top_antecedent_emb, top_antecedent_offsets, top_span_speaker_ids, genre_emb):
k = util.shape(top_span_emb, 0)
c = util.shape(top_antecedents, 1)
feature_emb_list =... | tensorflow.get_variable | 92 |
import tensorflow as tf
if data_format_ == 'NHWC':
inputs = tf.transpose(inputs, [0, 2, 3, 1])
ksize = int(6 * sigma + 1.)
x = tf.expand_dims(tf.range(ksize, delta=1, dtype=tf.float32), axis=1)
y = tf.transpose(x, [1, 0])
kernel_matrix = tf.exp(- ((x - ksize/2.) ** 2... | tensorflow.nn.depthwise_conv2d | 93 |
import tensorflow as tf
start_x = tf.random.uniform(shape=(1,), minval=0, maxval=im_width, dtype=tf.int32)
start_y = tf.random.uniform(shape=(1,), minval=0, maxval=im_height, dtype=tf.int32)
mask = tf.pad(mask, [[cutout_size + start_y[0], im_height - start_y[0]],
[cu... | tensorflow.reshape | 94 |
import tensorflow as tf
def regularization(self):
return self.model_lam * (
self.model_prob * tf.reduce_sum(tf.square(self.model_W)) +
tf.reduce_sum(tf.square(self.model_b))
| tensorflow.square | 95 |
import tensorflow.contrib as contrib
dropout3_1 = contrib.layers.dropout(stitch3_1, keep_prob=keep_prob, is_training=is_training,
scope="dropout3_1")
dropout3_2 = contrib.layers.dropout(stitch3_2, keep_prob=keep_prob, is_training=is_training,
... | tensorflow.contrib.layers.dropout | 96 |
import tensorflow as tf
"""Step the batch of environments.
The results of the step can be accessed from the variables defined below.
Args:
action: Tensor holding the batch of actions to apply.
Returns:
Operation.
"""
with tf.name_scope('environment/simulate'):
if action.dty... | tensorflow.name_scope | 97 |
import tensorflow as tf
if not white:
q_mu = tf.matrix_triangular_solve(Luu, q_mu, lower=True)
Luu_tiled = tf.tile(Luu[None, :, :], [num_func, 1, 1]) # remove line once issue 216 is fixed
q_sqrt_r = tf.matrix_triangular_solve(Luu_tiled, q_sqrt_r, lower=True)
Li_eKuf = tf.matrix_trian... | tensorflow.matrix_triangular_solve | 98 |
import tensorflow as tf
d *= noise
z = tf.layers.dense(d, final_filters, name="unbottleneck")
return layer + z, 0.0
| tensorflow.layers.dense | 99 |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 4