seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
import tensorflow as tf
def conv(x, scope, *, nf, rf, stride, pad='VALID', init_scale=1.0, data_format='NHWC', one_dim_bias=False):
if data_format == 'NHWC':
channel_ax = 3
strides = [1, stride, stride, 1]
bshape = [1, 1, 1, nf]
elif data_format == 'NCHW':
channel_ax = 1
strides = [1, 1, stride, stride]
bshape = [1, nf, 1, 1]
else:
raise NotImplementedError
bias_var_shape = [nf] if one_dim_bias else [1, nf, 1, 1]
nin = x.get_shape()[channel_ax].value
wshape = [rf, rf, nin, nf]
with tf.variable_scope(scope):
w = tf.get_variable("w", wshape, initializer=ortho_init(init_scale))
b = tf.get_variable("b", bias_var_shape, initializer=tf.constant_initializer(0.0))
if not one_dim_bias and data_format == 'NHWC':
b = tf.reshape(b, bshape)
return tf.nn.conv2d(x, w, strides=strides, padding=pad, data_format=data_format) + b
def fc(x, scope, nh, *, init_scale=1.0, init_bias=0.0):
with tf.variable_scope(scope):
nin = x.get_shape()[1].value
w = tf.get_variable("w", [nin, nh], initializer=ortho_init(init_scale))
print("w is "+str(w))
b = tf.get_variable("b", [nh], initializer=tf.constant_initializer(init_bias))
return tf.matmul(x, w)+b
| tensorflow.variable_scope | 6,100 |
import tensorflow as tf
inputs_list = []
for i in range(num_gpu):
start = i * cfgs.BATCH_SIZE
end = (i + 1) * cfgs.BATCH_SIZE
img = img_batch[start:end, :, :, :]
pretrain_zoo = PretrainModelZoo()
if self.cfgs.NET_NAME in pretrain_zoo.pth_zoo or self.cfgs.NET_NAME in pretrain_zoo.mxnet_zoo:
img = img / tf.constant([cfgs.PIXEL_STD])
gtboxes_and_label_h = get_horizen_minAreaRectangle(
tf.reshape(gtboxes_and_label_batch[start:end], [-1, 9]))
gtboxes_and_label_h = tf.reshape(gtboxes_and_label_h, [cfgs.BATCH_SIZE, -1, 5])
gtboxes_and_label_q = tf.reshape(gtboxes_and_label_batch[start:end], [cfgs.BATCH_SIZE, -1, 9])
num_objects = num_objects_batch[start:end]
num_objects = tf.cast(tf.reshape(num_objects, [cfgs.BATCH_SIZE, -1, ]), tf.float32)
img_h = img_h_batch[start:end]
img_w = img_w_batch[start:end]
inputs_list.append([img, gtboxes_and_label_h,
| tensorflow.reshape | 6,101 |
import tensorflow.contrib as contrib
# BN
normalizer_fn=contrib.layers.batch_norm,
normalizer_params={
"is_training": is_training,
"scale": True,
"updates_collections": None
}
):
fc1_1 = contrib.layers.fully_connected(X, 32, scope="fc1_1")
fc1_2 = contrib.layers.fully_connected(X, 32, scope="fc1_2")
if cross_stitch_enabled:
with tf.variable_scope("cross_stitch_1"):
stitch1_1, stitch1_2 = apply_cross_stitch(fc1_1, fc1_2)
else:
stitch1_1, stitch1_2 = fc1_1, fc1_2
| tensorflow.contrib.layers.fully_connected | 6,102 |
import tensorflow as tf
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
return tf.train.Scaffold()
| tensorflow.train.Scaffold | 6,103 |
import tensorflow as tf
def coarse_to_fine_pruning(self, top_span_emb, top_span_mention_scores, c):
k = util.shape(top_span_emb, 0)
top_span_range = tf.range(k) # [k]
antecedent_offsets = tf.expand_dims(top_span_range, 1) - tf.expand_dims(top_span_range, 0) # [k, k]
antecedents_mask = antecedent_offsets >= 1 # [k, k]
fast_antecedent_scores = tf.expand_dims(top_span_mention_scores, 1) + tf.expand_dims(top_span_mention_scores, 0) # [k, k]
fast_antecedent_scores += tf.log(tf.to_float(antecedents_mask)) # [k, k]
fast_antecedent_scores += self.get_fast_antecedent_scores(top_span_emb) # [k, k]
_, top_antecedents = tf.nn.top_k(fast_antecedent_scores, c, sorted=False) # [k, c]
top_antecedents_mask = util.batch_gather(antecedents_mask, top_antecedents) # [k, c]
top_fast_antecedent_scores = util.batch_gather(fast_antecedent_scores, top_antecedents) # [k, c]
top_antecedent_offsets = util.batch_gather(antecedent_offsets, top_antecedents) # [k, c]
| tensorflow.to_float | 6,104 |
import tensorflow as tf
self.W_out_train = params.get('W_out_train', True)
self.b_rec_train = params.get('b_rec_train', True)
self.b_out_train = params.get('b_out_train', True)
self.init_state_train = params.get('init_state_train', True)
# Tensorflow initializations
self.x = tf.placeholder("float", [N_batch, N_steps, N_in])
self.y = tf.placeholder("float", [N_batch, N_steps, N_out])
self.output_mask = tf.placeholder("float", [N_batch, N_steps, N_out])
# trainable variables
with tf.variable_scope("model"):
| tensorflow.placeholder | 6,105 |
import tensorflow as tf
# Tensorboard
if summary_dir is not None:
self.writer = tf.summary.FileWriter(summary_dir)
tf.summary.scalar('Loss/Policy', loss_pg)
| tensorflow.summary.FileWriter | 6,106 |
from tensorflow.python.ops import array_ops
n_classes=2,
label_name=label_name,
weight_column_name=weight_column_name)
def logits_to_predictions(self, logits, proba=False):
if proba:
raise ValueError(
"logits to probabilities is not supported for _BinarySvmTargetColumn")
logits = array_ops.concat(1, [array_ops.zeros_like(logits), logits])
return math_ops.argmax(logits, 1)
# TODO(zakaria): use contrib losses.
def _mean_squared_loss(logits, target):
# To prevent broadcasting inside "-".
if len(target.get_shape()) == 1:
target = array_ops.expand_dims(target, dim=[1])
| tensorflow.python.ops.array_ops.zeros_like | 6,107 |
import tensorflow.contrib.eager as tfe
# limitations under the License.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf # pylint: disable=g-bad-import-order
import tensorflow.contrib.eager as tfe # pylint: disable=g-bad-import-order
from official.mnist import mnist
from official.mnist import mnist_eager
from official.utils.misc import keras_utils
def device():
return "/device:GPU:0" if tfe.num_gpus() else "/device:CPU:0"
def data_format():
return "channels_first" if tfe.num_gpus() else "channels_last"
def random_dataset():
batch_size = 64
images = tf.random_normal([batch_size, 784])
labels = tf.random_uniform([batch_size], minval=0, maxval=10, dtype=tf.int32)
return tf.data.Dataset.from_tensors((images, labels))
def train(defun=False):
| tensorflow.contrib.eager.num_gpus | 6,108 |
import tensorflow as tf
# Compute Matthew's correlation
mcc = tf.div_no_nan(
tp * tn - fp * fn,
tf.pow((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn), 0.5))
# Compute accuracy
accuracy = tf.metrics.accuracy(
labels=label_ids, predictions=predictions,
weights=is_real_example)
loss = tf.metrics.mean(
values=per_example_loss,
weights=is_real_example)
return {"matthew_corr": (mcc, tf.group(tp_op, tn_op, fp_op, fn_op)),
"eval_accuracy": accuracy, "eval_loss": loss,}
eval_metrics = (metric_fn,
[per_example_loss, label_ids, logits, is_real_example])
output_spec = contrib_tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
eval_metrics=eval_metrics,
scaffold_fn=scaffold_fn)
else:
output_spec = contrib_tpu.TPUEstimatorSpec(
mode=mode,
predictions={
"probabilities": probabilities,
| tensorflow.group | 6,109 |
import tensorflow as tf
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, name_scope)
staging_delta_ops = list(self.variable_mgr.staging_delta_ops)
if not update_ops:
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, name_scope)
enqueue_ops.append(tf.group(*gpu_copy_stage_ops))
if self.variable_mgr.supports_staged_vars():
for staging_ops in self.variable_mgr.staging_vars_on_devices:
| tensorflow.get_collection | 6,110 |
import tensorflow as tf
"""
if key.dtype != tf.string:
raise ValueError('key must have type tf.string')
# Quantile ops convert input values to double under the hood. Keep bucket
# boundaries as float for all numeric types.
bucket_dtype = tf.float32
with tf.compat.v1.name_scope(name, 'quantiles_by_key'):
combiner = QuantilesCombiner(
num_buckets,
epsilon,
bucket_dtype.as_numpy_dtype,
has_weights=weights is not None,
| tensorflow.compat.v1.name_scope | 6,111 |
import tensorflow as tf
"""
name = 'batch_norm'
with tf.variable_scope(name):
phase_train = tf.convert_to_tensor(phase_train, dtype=tf.bool)
n_out = int(x.get_shape()[3])
beta = tf.Variable(tf.constant(0.0, shape=[n_out], dtype=x.dtype),
name=name+'/beta', trainable=True, dtype=x.dtype)
gamma = tf.Variable(tf.constant(1.0, shape=[n_out], dtype=x.dtype),
name=name+'/gamma', trainable=True, dtype=x.dtype)
batch_mean, batch_var = tf.nn.moments(x, [0,1,2], name='moments')
ema = tf.train.ExponentialMovingAverage(decay=0.9)
def mean_var_with_update():
ema_apply_op = ema.apply([batch_mean, batch_var])
with tf.control_dependencies([ema_apply_op]):
return tf.identity(batch_mean), tf.identity(batch_var)
mean, var = control_flow_ops.cond(phase_train,
mean_var_with_update,
lambda: (ema.average(batch_mean), ema.average(batch_var)))
normed = tf.nn.batch_normalization(x, mean, var, beta, gamma, 1e-3)
| tensorflow.nn.moments | 6,112 |
import tensorflow as tf
update_ops.extend(optimizer.apply_grad(grad, var))
lowering = mtf.Lowering(graph, {mesh: mesh_impl})
tf_loss = lowering.export_to_tf_tensor(loss)
tf_loss = tf.to_float(tf_loss)
if logits and mode != tf.estimator.ModeKeys.TRAIN:
tf_logits = lowering.export_to_tf_tensor(logits)
if mode == tf.estimator.ModeKeys.TRAIN:
tf_update_ops = [lowering.lowered_operation(op) for op in update_ops]
tf_update_ops.append(tf.assign_add(global_step, 1))
# tf.logging.info("tf_update_ops: {}".format(tf_update_ops))
train_op = tf.group(tf_update_ops)
with mtf.utils.outside_all_rewrites():
# Copy master variables to slices. Must be called first.
restore_hook = mtf.MtfRestoreHook(lowering)
saver = tf.train.Saver(
tf.global_variables(),
sharded=True,
max_to_keep=10,
| tensorflow.assign_add | 6,113 |
import tensorflow as tf
return
# pylint: enable=g-import-not-at-top
with tf.compat.v1.Graph().as_default() as graph:
outputs = {
| tensorflow.compat.v1.Graph | 6,114 |
import tensorflow as tf
input_images = tf.placeholder(tf.float32, shape=[None, None, None, 3], name='input_images')
input_score_maps = tf.placeholder(tf.float32, shape=[None, None, None, 1], name='input_score_maps')
if FLAGS.geometry == 'RBOX':
| tensorflow.placeholder | 6,115 |
from tensorflow.python.saved_model import loader
self.session = tf.Session()
metagraph_def = loader.load(
| tensorflow.python.saved_model.loader.load | 6,116 |
import tensorflow as tf
state[self.ITERATION_STATE_KEY] + tf.constant(1, dtype=tf.int32)
}
def get_params(self, state):
"""See base class."""
params = {
self.ADD_PARAM_KEY: 1 / tf.to_float(state[self.ITERATION_STATE_KEY])
}
return params, params
def encode(self, x, encode_params):
"""See base class."""
| tensorflow.to_float | 6,117 |
import tensorflow as tf
def test_prob_and_grad_gives_finite_results_for_common_events(self):
with self.test_session():
mu = tf.Variable(0.0, name="mu")
sigma = tf.Variable(1.0, name="sigma")
qdist = distributions.QuantizedDistribution(
base_dist_cls=distributions.Normal,
mu=mu,
sigma=sigma)
x = tf.ceil(4 * self._rng.rand(100).astype(np.float32) - 2)
tf.initialize_all_variables().run()
proba = qdist.prob(x)
self._assert_all_finite(proba.eval())
grads = tf.gradients(proba, [mu, sigma])
self._assert_all_finite(grads[0].eval())
self._assert_all_finite(grads[1].eval())
def test_lower_cutoff_must_be_below_upper_cutoff_or_we_raise(self):
with self.test_session():
qdist = distributions.QuantizedDistribution(
base_dist_cls=distributions.Normal,
lower_cutoff=1., # not strictly less than upper_cutoff.
upper_cutoff=1.,
mu=0.,
sigma=1.,
validate_args=True)
self.assertTrue(qdist.validate_args) # Default is True.
| tensorflow.gradients | 6,118 |
import tensorflow as tf
'''
Flattening function:
input: a tensor list
returns: a rank one tensor
'''
s= len(tensor) #number of tensors in the list
for i in range(s):
dl = tensor[i] #take one element of the gradient list (hence the zero)
d1, d2 = dl.get_shape() #Obtain tensor dimensions
fl = tf.reshape(dl,[-1, d1*d2]) #reshape the tensor to a (1, d1*d2) tensor
#concatenate over all the elemets in the list
if i==0: flattened = fl # the first time
else: flattened = tf.concat([flattened, fl], axis=1)
return flattened
#Hessian
def hessian(grads, par):
'''
Evaluates the exact Hessian matrix.
This function uses the same convention of the Autograd package.
| tensorflow.reshape | 6,119 |
import tensorflow as tf
logits = tf.add(logits, output_bias)
probabilities=tf.sigmoid(logits)
# labels=tf.constant(labels,dtype=tf.int32)
per_example_loss=tf.losses.sigmoid_cross_entropy(multi_class_labels=labels, logits=logits,reduction=Reduction.NONE)
per_example_loss=tf.reduce_sum(per_example_loss,axis=-1)
loss = tf.reduce_mean(per_example_loss,name='train_loss')
return (loss, per_example_loss, logits, probabilities)
def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps, use_tpu,
| tensorflow.reduce_mean | 6,120 |
import tensorflow as tf
height = tf.shape(inputs)[1]
width = tf.shape(inputs)[2]
out_height = get_deconv_dim(height, stride_h, kernel_h, padding)
out_width = get_deconv_dim(width, stride_w, kernel_w, padding)
output_shape = tf.stack([batch_size, out_height, out_width, num_output_channels], axis=0)
outputs = tf.nn.conv2d_transpose(inputs, kernel, output_shape,
[1, stride_h, stride_w, 1],
| tensorflow.stack | 6,121 |
import tensorflow as tf
self._tower_loss_semi_supervised(
self.inputs, self.labels, num_classes=num_classes, is_fm_loss=True)
global_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
if update_ops is None:
update_ops = global_update_ops
| tensorflow.get_collection | 6,122 |
from tensorflow.python.framework import ops
"""
with ops.op_scope([features], name, "Relu6") as name:
| tensorflow.python.framework.ops.op_scope | 6,123 |
import tensorflow as tf
self._initial_state = cell.zero_state(config.batch_size, data_type())
state = self._initial_state
# Simplified version of tf.nn.static_rnn().
# This builds an unrolled LSTM for tutorial purposes only.
# In general, use tf.nn.static_rnn() or tf.nn.static_state_saving_rnn().
#
# The alternative version of the code below is:
#
# inputs = tf.unstack(inputs, num=self.num_steps, axis=1)
# outputs, state = tf.nn.static_rnn(cell, inputs,
# initial_state=self._initial_state)
outputs = []
with tf.variable_scope("RNN"):
for time_step in range(self.num_steps):
if time_step > 0: tf.get_variable_scope().reuse_variables()
(cell_output, state) = cell(inputs[:, time_step, :], state)
outputs.append(cell_output)
output = tf.reshape(tf.concat(outputs, 1), [-1, config.hidden_size])
return output, state
def assign_lr(self, session, lr_value):
session.run(self._lr_update, feed_dict={self._new_lr: lr_value})
def export_ops(self, name):
"""Exports ops to collections."""
self._name = name
ops = {util.with_prefix(self._name, "cost"): self._cost}
if self._is_training:
ops.update(lr=self._lr, new_lr=self._new_lr, lr_update=self._lr_update)
| tensorflow.get_variable_scope | 6,124 |
import tensorflow as tf
do_nothing = np.zeros(self.ACTIONS)
do_nothing[0]=1
x_t,r_0,terminal =self.game_state.frame_step(do_nothing)
x_t = cv2.cvtColor(cv2.resize(x_t,(80,80)),cv2.COLOR_BGR2GRAY)
ret,x_t = cv2.threshold(x_t,1,255,cv2.THRESH_BINARY)
s_t = np.stack((x_t,x_t,x_t,x_t),axis=2)
return s_t
def restore_param(self):
Saver = tf.train.Saver()
self.sess.run(tf.global_variables_initializer())
checkpoint = tf.train.get_checkpoint_state("saved_networks")
if checkpoint and checkpoint.model_checkpoint_path:
Saver.restore(self.sess,checkpoint.model_checkpoint_path)
print("Successfully loaded",checkpoint.model_checkpoint_path)
else:
print("Could not find old network weights")
return Saver
# 定义一个weight,其中命名空间为name,形状为shape
| tensorflow.global_variables_initializer | 6,125 |
import tensorflow as tf
"url.")
tf.flags.DEFINE_string(
"tpu_zone", None,
"[Optional] GCE zone where the Cloud TPU is located in. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
tf.flags.DEFINE_string(
"gcp_project", None,
"[Optional] Project name for the Cloud TPU-enabled project. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
| tensorflow.flags.DEFINE_string | 6,126 |
import tensorflow as tf
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_shape()[-1]],
initializer=tf.random_normal_initializer(stddev=stddev))
# print("w", w.get_shape())
try:
deconv = tf.nn.conv2d_transpose(input_, w, output_shape=output_shape,
| tensorflow.random_normal_initializer | 6,127 |
from tensorflow.python.ops import math_ops
thresholds = [(i + 1) * 1.0 / (num_thresholds - 1)
for i in range(num_thresholds-2)]
thresholds = [0.0 - kepsilon] + thresholds + [1.0 + kepsilon]
(tp, fn, tn, fp, tp_update_op, fn_update_op, tn_update_op,
fp_update_op) = _tp_fn_tn_fp(predictions, labels, thresholds, weights)
# Add epsilons to avoid dividing by 0.
epsilon = 1.0e-6
assert array_ops.squeeze(fp).get_shape().as_list()[0] == num_thresholds
def compute_auc(tp, fn, tn, fp, name):
"""Computes the roc-auc or pr-auc based on confusion counts."""
recall = math_ops.div(tp + epsilon, tp + fn + epsilon)
if curve == 'ROC':
fp_rate = math_ops.div(fp, fp + tn + epsilon)
x = fp_rate
y = recall
else: # curve == 'PR'.
precision = math_ops.div(tp + epsilon, tp + fp + epsilon)
x = recall
y = precision
return math_ops.reduce_sum(math_ops.mul(
x[:num_thresholds - 1] - x[1:],
(y[:num_thresholds - 1] + y[1:]) / 2.), name=name)
| tensorflow.python.ops.math_ops.div | 6,128 |
import tensorflow as tf
self.D_B_real = self.build_discriminator(self.image_real_B,reuse=True, name="discriminatorB")
self.D_A_real = self.build_discriminator(self.image_real_A,reuse=True, name="discriminatorA")
self.loss_GABA = self.lambda_l2*squared_loss(self.images_fake_A,self.image_real_A) + binary_cross_entropy_loss(labels=tf.ones_like(self.D_B_fake),logits=self.D_B_fake)
self.loss_GBAB = self.lambda_l2*squared_loss(self.images_fake_B_,self.image_real_B) + binary_cross_entropy_loss(labels=tf.ones_like(self.D_A_fake),logits=self.D_A_fake)
self.generator_loss = self.loss_GABA + self.loss_GBAB
self.D_B_loss_real = binary_cross_entropy_loss(tf.ones_like(self.D_B_real),self.D_B_real)
self.D_B_loss_fake = binary_cross_entropy_loss(tf.zeros_like(self.D_B_fake),self.D_B_fake)
self.D_B_loss = (self.D_B_loss_real + self.D_B_loss_fake) / 2.0
self.D_A_loss_real = binary_cross_entropy_loss(tf.ones_like(self.D_A_real),self.D_A_real)
self.D_A_loss_fake = binary_cross_entropy_loss(tf.zeros_like(self.D_A_fake),self.D_A_fake)
self.D_A_loss = (self.D_A_loss_real + self.D_A_loss_fake) / 2.0
self.discriminator_loss = self.D_B_loss + self.D_A_loss
self.loss_GABA_sum = tf.summary.scalar("g_loss_a2b", self.loss_GABA)
self.loss_GBAB_sum = tf.summary.scalar("g_loss_b2a", self.loss_GBAB)
self.g_total_loss_sum = tf.summary.scalar("g_loss", self.generator_loss)
self.g_sum = tf.summary.merge([self.loss_GABA_sum,self.loss_GBAB_sum,self.g_total_loss_sum])
self.loss_db_sum = tf.summary.scalar("db_loss", self.D_B_loss)
self.loss_da_sum = tf.summary.scalar("da_loss", self.D_A_loss)
self.loss_d_sum = tf.summary.scalar("d_loss",self.discriminator_loss)
| tensorflow.ones_like | 6,129 |
import tensorflow as tf
for i in range(len(hidden_layers_node)):
layer_name = 'layer' + str(i+1)
with tf.variable_scope(layer_name, reuse=tf.AUTO_REUSE):
weights = tf.get_variable('weights', [prev_node, hidden_layers_node[i]],
| tensorflow.variable_scope | 6,130 |
import tensorflow as tf
+ 0.00392377*t**(-8))
a = 7.5
return __phi_f(tf.minimum(x, a)) - __phi_f(a) + __phi_g(tf.maximum(x, a))
N = tf.cast(tf.shape(X)[0], tf.float32)
if y is None:
y = silverman_rule_of_thumb(N)
A = 1/(N*N*tf.sqrt(y))
B = 2.0/(N*tf.sqrt(y+0.5))
A1 = euclidean_norm_squared(tf.subtract(tf.expand_dims(X, 0), tf.expand_dims(X, 1)), axis=2)/(4*y)
B1 = euclidean_norm_squared(X, axis=1)/(2+4*y)
return 1/tf.sqrt(1+y) + A*tf.reduce_sum(__phi(A1)) - B*tf.reduce_sum(__phi(B1))
def cw(X, y=None):
D = tf.cast(tf.shape(X)[1], tf.float32)
N = tf.cast(tf.shape(X)[0], tf.float32)
if y is None:
y = silverman_rule_of_thumb(N)
K = 1/(2*D-3)
A1 = euclidean_norm_squared(tf.subtract(tf.expand_dims(X, 0), tf.expand_dims(X, 1)), axis=2)
A = (1/(N**2)) * tf.reduce_sum((1/tf.sqrt(y + K*A1)))
| tensorflow.sqrt | 6,131 |
import tensorflow as tf
cell, decoder_fn, inputs=None, sequence_length=sequence_length)
if return_final_state:
return final_state
else:
return outputs
@layer
def reshape_layer(tensor, shape, **opts):
out = tf.reshape(tensor, shape=shape)
return out
@layer
def dense_layer(tensor, hidden_dims, weight=None, bias=None, **opts):
original_tensor_shape = tf.shape(tensor)
in_dim = int(tensor.get_shape()[-1])
rank = _rank(tensor)
| tensorflow.reshape | 6,132 |
import tensorflow as tf
writer.close()
def file_based_input_fn_builder(input_file, seq_length, is_training,
drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_length], tf.int64),
"segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
"label_ids": tf.FixedLenFeature([], tf.int64),
"is_real_example": tf.FixedLenFeature([], tf.int64),
}
def _decode_record(record, name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
| tensorflow.FixedLenFeature | 6,133 |
import tensorflow as tf
min_score_thresh=0.65,
min_iou_thresh=0.5,
is_class_agnostic=False)
nms_masks_expected2 = tf.stack([mask2, mask0, mask5, mask4])
nms_scores_expected2 = tf.constant([0.95, 1.0, 0.8, 0.7], dtype=tf.float32)
nms_classes_expected2 = tf.constant([0, 1, 2, 2], dtype=tf.int32)
self.assertAllEqual(nms_masks1.numpy(), nms_masks_expected1.numpy())
self.assertAllClose(nms_scores1.numpy(), nms_scores_expected1.numpy())
| tensorflow.constant | 6,134 |
import tensorflow as tf
self.num_layers = num_layers
self.grus = []
self.inits = []
self.dropout_mask = []
self.scope = scope
for layer in range(num_layers):
input_size_ = input_size if layer == 0 else 2 * num_units
gru_fw = tf.contrib.rnn.GRUCell(num_units)
gru_bw = tf.contrib.rnn.GRUCell(num_units)
init_fw = tf.tile(tf.Variable(
tf.zeros([1, num_units])), [batch_size, 1])
init_bw = tf.tile(tf.Variable(
tf.zeros([1, num_units])), [batch_size, 1])
mask_fw = dropout(tf.ones([batch_size, 1, input_size_], dtype=tf.float32),
keep_prob=keep_prob, is_train=is_train, mode=None)
mask_bw = dropout(tf.ones([batch_size, 1, input_size_], dtype=tf.float32),
keep_prob=keep_prob, is_train=is_train, mode=None)
self.grus.append((gru_fw, gru_bw, ))
self.inits.append((init_fw, init_bw, ))
self.dropout_mask.append((mask_fw, mask_bw, ))
| tensorflow.zeros | 6,135 |
import tensorflow as tf
initializer = tf.contrib.layers.xavier_initializer()
var = _variable_on_cpu(name, shape, initializer)
else:
# initializer = tf.truncated_normal_initializer(stddev=stddev)
with tf.device('/cpu:0'):
var = tf.truncated_normal(shape, stddev=np.sqrt(2 / shape[-1]))
var = tf.round(var * tf.constant(1000, dtype=tf.float32)) / tf.constant(1000, dtype=tf.float32)
var = tf.Variable(var, name='weights')
if wd is not None:
weight_decay = tf.multiply(tf.nn.l2_loss(var), wd, name='weight_loss')
tf.add_to_collection('losses', weight_decay)
return var
| tensorflow.Variable | 6,136 |
import tensorflow as tf
total_loss = tf.identity(loss, name='total_loss')
tf.summary.scalar('loss', total_loss)
if mode == tf.estimator.ModeKeys.EVAL:
return tf.estimator.EstimatorSpec(mode=mode, loss=loss, predictions=predictions, eval_metric_ops=metrics)
if mode == tf.estimator.ModeKeys.TRAIN:
global_step = tf.train.get_or_create_global_step()
lr_values = [params['warmup_learning_rate']] + [base_learning_rate * decay for decay in params['lr_decay_factors']]
learning_rate = tf.train.piecewise_constant(tf.cast(global_step, tf.int32),
[params['warmup_steps']] + [int(float(ep)*params['steps_per_epoch']) for ep in params['decay_boundaries']],
lr_values)
truncated_learning_rate = tf.maximum(learning_rate, tf.constant(params['end_learning_rate'], dtype=learning_rate.dtype), name='learning_rate')
tf.summary.scalar('lr', truncated_learning_rate)
optimizer = tf.train.MomentumOptimizer(learning_rate=truncated_learning_rate,
momentum=params['momentum'])
# Batch norm requires update_ops to be added as a train_op dependency.
| tensorflow.cast | 6,137 |
import tensorflow as tf
custom_getter=tf_util.outer_scope_getter("train_model")):
train_model = self.policy(self.sess, self.observation_space, self.action_space, self.n_envs,
self.n_steps + 1, n_batch_train, reuse=True, **self.policy_kwargs)
with tf.variable_scope("moving_average"):
# create averaged model
ema = tf.train.ExponentialMovingAverage(self.alpha)
ema_apply_op = ema.apply(self.params)
def custom_getter(getter, name, *args, **kwargs):
name = name.replace("polyak_model/", "")
val = ema.average(getter(name, *args, **kwargs))
| tensorflow.train.ExponentialMovingAverage | 6,138 |
import tensorflow as tf
[batch_size * seq_length, width])
output_tensor = tf.gather(flat_sequence_tensor, flat_positions)
return output_tensor
# add sequence mask for:
# 1. random shuffle lm modeling---xlnet with random shuffled input
# 2. left2right and right2left language modeling
# 3. conditional generation
def generate_seq2seq_mask(attention_mask, mask_sequence, seq_type, **kargs):
if seq_type == 'seq2seq':
if mask_sequence is not None:
seq_shape = get_shape_list(mask_sequence, expected_rank=2)
seq_len = seq_shape[1]
ones = tf.ones((1, seq_len, seq_len))
a_mask = tf.matrix_band_part(ones, -1, 0)
s_ex12 = tf.expand_dims(tf.expand_dims(mask_sequence, 1), 2)
s_ex13 = tf.expand_dims(tf.expand_dims(mask_sequence, 1), 3)
a_mask = (1 - s_ex13) * (1 - s_ex12) + s_ex13 * a_mask
# generate mask of batch x seq_len x seq_len
a_mask = tf.reshape(a_mask, (-1, seq_len, seq_len))
out_mask = attention_mask * a_mask
else:
ones = tf.ones_like(attention_mask[:1])
mask = (tf.matrix_band_part(ones, -1, 0))
out_mask = attention_mask * mask
else:
out_mask = attention_mask
return out_mask | tensorflow.expand_dims | 6,139 |
import tensorflow as tf
self.conv5_1 = self.conv_layer(self.pool4, "conv5_1")
self.conv5_2 = self.conv_layer(self.conv5_1, "conv5_2")
self.conv5_3 = self.conv_layer(self.conv5_2, "conv5_3")
self.conv5_4 = self.conv_layer(self.conv5_3, "conv5_4")
self.pool5 = self.max_pool(self.conv5_4, 'pool5')
self.fc6 = self.fc_layer(self.pool5, "fc6")
assert self.fc6.get_shape().as_list()[1:] == [4096]
self.relu6 = tf.nn.relu(self.fc6)
self.fc7 = self.fc_layer(self.relu6, "fc7")
self.relu7 = tf.nn.relu(self.fc7)
self.fc8 = self.fc_layer(self.relu7, "fc8")
log("finished building VGG19 in %ds" % (time.time() - start_time))
return self.fc8
def avg_pool(self, bottom, name):
return tf.nn.avg_pool(bottom, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name)
| tensorflow.nn.relu | 6,140 |
import tensorflow as tf
with tf.variable_scope('anchor_generator'):
if offset is None:
offset = [stride[0]/2, stride[1]/2]
features_width = tf.cast(features_width, tf.int32)
features_height = tf.cast(features_height, tf.int32)
scales = tf.convert_to_tensor(scales, dtype=tf.float32)
ratios = tf.convert_to_tensor(ratios, dtype=tf.float32)
offset = tf.convert_to_tensor(offset, dtype=tf.float32)
scales_grid, ratios_grid = tf.meshgrid(scales,
ratios)
scales_grid = tf.reshape(scales_grid, [-1, 1])
ratios_grid = tf.reshape(ratios_grid, [-1, 1])
| tensorflow.convert_to_tensor | 6,141 |
import tensorflow as tf
#rnn_outputs.append(state)
#final_state = rnn_outputs[-1] # 得到最后的state
cell = tf.contrib.rnn.BasicRNNCell(num_units=state_size)
rnn_outputs, final_state = tf.nn.dynamic_rnn(cell, rnn_inputs, initial_state=init_state)
'''预测,损失,优化'''
with tf.variable_scope('softmax'):
W = tf.get_variable('W', [state_size, num_classes])
b = tf.get_variable('b', [num_classes], initializer=tf.constant_initializer(0.0))
'''因为rnn_outputs是三维的,这里需要将其转成2维的,
矩阵运算后再转换回来[batch_size, num_steps, num_classes]'''
logits = tf.reshape(tf.matmul(tf.reshape(rnn_outputs, [-1, state_size]), W) +b, \
shape=[batch_size, num_steps, num_classes])
predictions = tf.nn.softmax(logits)
y_as_list = tf.unstack(y, num=num_steps, axis=1)
losses = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y,logits=logits)
| tensorflow.constant_initializer | 6,142 |
import tensorflow as tf
if FLAGS.input_file is not None:
for input_pattern in FLAGS.input_file.split(","):
input_files.extend(tf.gfile.Glob(input_pattern))
if FLAGS.input_dir is not None:
for filename in tf.gfile.ListDirectory(FLAGS.input_dir):
input_files.extend(tf.gfile.Glob(os.path.join(FLAGS.input_dir, filename)))
tf.logging.info("*** Input Files ***")
for input_file in input_files:
tf.logging.info(" %s" % input_file)
validation_input_files = []
if FLAGS.validation_input_file is None and FLAGS.validation_input_dir is None:
validation_input_files = input_files
else:
if FLAGS.validation_input_file is not None:
for input_pattern in FLAGS.validation_input_file.split(","):
validation_input_files.extend(tf.gfile.Glob(input_pattern))
| tensorflow.logging.info | 6,143 |
import tensorflow as tf
target_weights = get_weights(targets[:, 1:], utils.EOS_ID, include_first_eos=True)
parameters = dict(encoders=encoders[1:], decoder=encoders[0], training=training)
attention_states, encoder_state, encoder_input_length[1:] = multi_encoder(
encoder_inputs[1:], encoder_input_length=encoder_input_length[1:], **parameters)
decoder_inputs = encoder_inputs[0][:, :-1]
batch_size = tf.shape(decoder_inputs)[0]
pad = tf.ones(shape=tf.stack([batch_size, 1]), dtype=tf.int32) * utils.BOS_ID
decoder_inputs = tf.concat([pad, decoder_inputs], axis=1)
outputs, _, states, attns, _, _, _ = attention_decoder(
attention_states=attention_states, initial_state=encoder_state, decoder_inputs=decoder_inputs,
encoder_input_length=encoder_input_length[1:], **parameters
)
chaining_loss = sequence_loss(logits=outputs, targets=encoder_inputs[0], weights=input_weights[0])
if 'lstm' in decoder.cell_type.lower():
| tensorflow.stack | 6,144 |
import tensorflow as tf
"""
mu, var = self.build_prior_mean_var(test_points, num_latent, True)
jitter = tfhacks.eye(tf.shape(mu)[0], var.dtype) * 1e-06
L = tf.batch_cholesky(tf.transpose(var, (2, 0, 1)) + jitter)
V_shape = [tf.shape(L)[0], tf.shape(L)[1], num_samples]
V = tf.random_normal(V_shape, dtype=L.dtype)
samples = tf.expand_dims(tf.transpose(mu), -1) + tf.batch_matmul(L, V)
return tf.transpose(samples)
@autoflow((tf.float64, [None, None]), (tf.float64, [None, None]),
(tf.float64, [None, None]))
def compute_posterior_mean_var(self, X, Y, test_points):
| tensorflow.batch_matmul | 6,145 |
import tensorflow as tf
if use_tpu:
def tpu_scaffold():
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
return tf.train.Scaffold()
scaffold_fn = tpu_scaffold
elif not do_serve:
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
tf.logging.info("**** Trainable Variables ****")
for var in tvars:
init_string = ""
if var.name in initialized_variable_names:
init_string = ", *INIT_FROM_CKPT*"
tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
init_string)
output_spec = None
if mode == tf.estimator.ModeKeys.TRAIN:
| tensorflow.logging.info | 6,146 |
import tensorflow as tf
output0 = f(tf.constant([1]), tf.constant([2]))
| tensorflow.constant | 6,147 |
import tensorflow as tf
trg_len = tf.shape(attention_weights)[1]
src_indices = tf.tile(tf.reshape(tf.range(src_len), shape=[1, 1, src_len]), [batch_size, trg_len, 1])
trg_indices = tf.tile(tf.reshape(tf.range(trg_len), shape=[1, trg_len, 1]), [batch_size, 1, src_len])
source_length = encoder_input_length[0]
target_length = tf.to_int32(tf.reduce_sum(trg_mask, axis=1))
true_src_len = tf.reshape(source_length, shape=[batch_size, 1, 1]) - 1
true_trg_len = tf.reshape(target_length, shape=[batch_size, 1, 1]) - 1
src_mask = tf.to_float(tf.sequence_mask(source_length, maxlen=src_len))
mask = tf.matmul(tf.expand_dims(trg_mask, axis=2), tf.expand_dims(src_mask, axis=1))
monotonous = tf.sqrt(((true_trg_len * src_indices - true_src_len * trg_indices) ** 2)
/ (true_trg_len**2 + true_src_len**2))
monotonous = tf.to_float(monotonous < monotonicity_dist)
non_monotonous = (1 - monotonous) * mask
attn_loss = tf.reduce_sum(attention_weights * tf.stop_gradient(non_monotonous)) / tf.to_float(batch_size)
if monotonicity_decay:
decay = tf.stop_gradient(0.5 ** (tf.to_float(global_step) / monotonicity_decay))
else:
decay = 1.0
xent_loss += monotonicity_weight * decay * attn_loss
losses = [xent_loss, reinforce_loss, baseline_loss_]
return losses, [outputs], encoder_state, attention_states, attention_weights, samples, beam_fun, initial_data
| tensorflow.to_float | 6,148 |
import tensorflow as tf
tf.app.flags.DEFINE_integer(
'save_summary_steps', 500,
'The frequency with which summaries are saved, in seconds.')
tf.app.flags.DEFINE_integer(
'save_checkpoints_secs', 7200,
'The frequency with which the model is saved, in seconds.')
# model related configuration
tf.app.flags.DEFINE_integer(
'train_image_size', 352,
'The size of the input image for the model to use.')
tf.app.flags.DEFINE_integer(
'resnet_size', 50,
'The size of the ResNet model to use.')
tf.app.flags.DEFINE_integer(
| tensorflow.app.flags.DEFINE_integer | 6,149 |
import tensorflow as tf
elif x.dtype == tf.uint32 or x.dtype == tf.uint64:
TypeError('Data type %r is not supported' % x.dtype)
x = tf.sparse.reduce_sum(x, axis=0)
elif isinstance(x, tf.RaggedTensor):
raise NotImplementedError(
'Elementwise sum does not support RaggedTensors.')
else:
x = tf.reduce_sum(input_tensor=x, axis=0)
output_dtype, sum_fn = _sum_combine_fn_and_dtype(x.dtype)
return _numeric_combine(
inputs=[x],
fn=sum_fn,
default_accumulator_value=0,
reduce_instance_dims=reduce_instance_dims,
| tensorflow.reduce_sum | 6,150 |
import tensorflow as tf
)
# Increment episode count.
with tf.control_dependencies(control_inputs=(assignment,)):
assignment = tf.assign_add(ref=self.episode_count, value=num_episodes)
# Increment memory index.
with tf.control_dependencies(control_inputs=(assignment,)):
assignment = tf.assign(
ref=self.episode_indices[-1],
value=tf.where(self.memory_index + num_instances > self.capacity,
self.episode_indices[self.episode_count - 1], self.capacity - 1)
)
| tensorflow.control_dependencies | 6,151 |
import tensorflow as tf
with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)):
cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True)
| tensorflow.nn.rnn_cell.BasicLSTMCell | 6,152 |
import tensorflow as tf
tf.float32, size=self.num_cells + 2, clear_after_read=False)
anchors_w_1 = tf.TensorArray(
tf.float32, size=self.num_cells + 2, clear_after_read=False)
arc_seq = tf.TensorArray(tf.int32, size=self.num_cells * 4)
if prev_c is None:
assert prev_h is None, "prev_c and prev_h must both be None"
prev_c = [tf.zeros([1, self.lstm_size], tf.float32)
for _ in range(self.lstm_num_layers)]
prev_h = [tf.zeros([1, self.lstm_size], tf.float32)
for _ in range(self.lstm_num_layers)]
inputs = self.g_emb
for layer_id in range(2):
next_c, next_h = stack_lstm(inputs, prev_c, prev_h, self.w_lstm)
prev_c, prev_h = next_c, next_h
anchors = anchors.write(layer_id, tf.zeros_like(next_h[-1]))
anchors_w_1 = anchors_w_1.write(
layer_id, tf.matmul(next_h[-1], self.w_attn_1))
def _condition(layer_id, *args):
return tf.less(layer_id, self.num_cells + 2)
def _body(layer_id, inputs, prev_c, prev_h, anchors, anchors_w_1, arc_seq,
entropy, log_prob):
indices = tf.range(0, layer_id, dtype=tf.int32)
start_id = 4 * (layer_id - 2)
prev_layers = []
for i in range(2): # index_1, index_2
next_c, next_h = stack_lstm(inputs, prev_c, prev_h, self.w_lstm)
prev_c, prev_h = next_c, next_h
| tensorflow.zeros_like | 6,153 |
import tensorflow as tf
# add by wangxiao
# define the inputs of signature
def serving_input_fn():
label_ids = tf.placeholder(tf.int32, [None], name='label_ids')
input_ids = tf.placeholder(tf.int32, [None, FLAGS.max_seq_length], name='input_ids')
input_mask = tf.placeholder(tf.int32, [None, FLAGS.max_seq_length], name='input_mask')
segment_ids = tf.placeholder(tf.int32, [None, FLAGS.max_seq_length], name='segment_ids')
input_fn = tf.estimator.export.build_raw_serving_input_receiver_fn({
'label_ids': label_ids,
'input_ids': input_ids,
'input_mask': input_mask,
'segment_ids': segment_ids,
})()
return input_fn
| tensorflow.estimator.export.build_raw_serving_input_receiver_fn | 6,154 |
from tensorflow.python.framework import ops
Raises:
TypeError: If `x` cannot be cast to the `dtype`.
"""
with ops.op_scope([x], name, "Cast") as name:
if isinstance(x, ops.SparseTensor):
values_cast = cast(x.values, dtype, name=name)
return ops.SparseTensor(x.indices, values_cast, x.shape)
else:
# TODO(touts): Handle what Josh said.
#
# Could return ops.convert_to_tensor(x, dtype=dtype, ...) here, but that
# allows some conversions that cast() can't do, e.g. casting numbers to
# strings.
x = ops.convert_to_tensor(x, name="x")
if x.dtype.base_dtype == dtype:
return x
return gen_math_ops.cast(x, dtype, name=name)
def to_float(x, name="ToFloat"):
"""Casts a tensor to type `float32`.
Args:
x: A `Tensor` or `SparseTensor`.
name: A name for the operation (optional).
Returns:
| tensorflow.python.framework.ops.convert_to_tensor | 6,155 |
import tensorflow as tf
slim.conv2d_transpose, slim.separable_conv2d,
slim.fully_connected],
weights_regularizer=weights_regularizer,
biases_regularizer=biases_regularizer,
biases_initializer=tf.constant_initializer(0.0)):
gtboxes_and_label_h, gtboxes_and_label_r = tf.py_func(self.get_gtboxes_and_label,
inp=[inputs_list[i][1],
inputs_list[i][2],
inputs_list[i][3]],
Tout=[tf.float32, tf.float32])
gtboxes_and_label_h = tf.reshape(gtboxes_and_label_h, [-1, 5])
| tensorflow.py_func | 6,156 |
import tensorflow as tf
lambda_term = lambdas * label_priors * (target_recall - 1.0) * maybe_log2
loss = tf.reshape(weighted_loss + lambda_term, original_shape)
| tensorflow.reshape | 6,157 |
import tensorflow as tf
biases = tf.get_variable('biases', [output_node],
initializer=tf.constant_initializer(0.0))
layer_out = tf.matmul(prev_x, weights) + biases
# Output of Network
y = layer_out
# Global step
with tf.variable_scope('training_step', reuse=tf.AUTO_REUSE):
global_step = tf.get_variable("global_step", [],
dtype=tf.int32,
initializer=tf.constant_initializer(0),
trainable=False)
# Loss value
reg_item = tf.contrib.layers.l1_l2_regularizer(L1_reg,
| tensorflow.variable_scope | 6,158 |
import tensorflow as tf
if non_linear_fn is None:
return output
else:
activation = non_linear_fn(output)
return activation
def batch_norm(x, b_train, scope, reuse=False):
with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
n_out = x.get_shape().as_list()[-1]
beta = tf.get_variable('beta', initializer=tf.constant(0.0, shape=[n_out]))
gamma = tf.get_variable('gamma', initializer=tf.constant(1.0, shape=[n_out]))
batch_mean, batch_var = tf.nn.moments(x, [0], name='moments')
ema = tf.train.ExponentialMovingAverage(decay=0.9)
| tensorflow.variable_scope | 6,159 |
import tensorflow as tf
self.layers = []
# Temp(First) Conv Layer
with tf.variable_scope("temp_conv") as scope:
filter_shape = [3, embedding_size, 4, 64]
W = tf.get_variable(name='W_1', shape=filter_shape,
initializer=he_normal,
| tensorflow.variable_scope | 6,160 |
import tensorflow as tf
except ValueError:
tf.get_variable_scope().reuse_variables()
return tf.get_variable(name, *args, **kwargs)
| tensorflow.get_variable | 6,161 |
import tensorflow as tf
with tf.variable_scope("coref_layer", reuse=(i > 0)):
top_antecedent_emb = tf.gather(top_span_emb, top_antecedents) # [k, c, emb]
top_antecedent_scores = top_fast_antecedent_scores + self.get_slow_antecedent_scores(top_span_emb, top_antecedents, top_antecedent_emb, top_antecedent_offsets, top_span_speaker_ids, genre_emb) # [k, c]
top_antecedent_weights = tf.nn.softmax(tf.concat([dummy_scores, top_antecedent_scores], 1)) # [k, c + 1]
top_antecedent_emb = tf.concat([tf.expand_dims(top_span_emb, 1), top_antecedent_emb], 1) # [k, c + 1, emb]
attended_span_emb = tf.reduce_sum(tf.expand_dims(top_antecedent_weights, 2) * top_antecedent_emb, 1) # [k, emb]
with tf.variable_scope("f"):
f = tf.sigmoid(util.projection(tf.concat([top_span_emb, attended_span_emb], 1), util.shape(top_span_emb, -1))) # [k, emb]
top_span_emb = f * attended_span_emb + (1 - f) * top_span_emb # [k, emb]
top_antecedent_scores = tf.concat([dummy_scores, top_antecedent_scores], 1) # [k, c + 1]
| tensorflow.variable_scope | 6,162 |
from tensorflow.python.client import device_lib
gamma=0.99,
learning_starts=learning_starts,
learning_freq=4,
frame_history_len=4,
target_update_freq=10000,
grad_norm_clipping=10,
restore=restore,
checkpoint_dir=checkpoint_dir
)
env.close()
return save_path
def get_available_gpus():
from tensorflow.python.client import device_lib
local_device_protos = device_lib.list_local_devices()
return [x.physical_device_desc for x in local_device_protos if x.device_type == 'GPU']
def set_global_seeds(i):
try:
import tensorflow as tf
except ImportError:
pass
else:
tf.set_random_seed(i)
np.random.seed(i)
random.seed(i)
| tensorflow.python.client.device_lib.list_local_devices | 6,163 |
import tensorflow as tf
self.D = dim_feature[1]
self.M = dim_embed
self.H = dim_hidden
self.T = n_time_step
self._start = word_to_idx['<START>']
self._null = word_to_idx['<NULL>']
self.weight_initializer = tf.contrib.layers.xavier_initializer()
self.const_initializer = tf.constant_initializer(0.0)
self.emb_initializer = tf.random_uniform_initializer(minval=-1.0, maxval=1.0)
# Place holder for features and captions
self.features = tf.placeholder(tf.float32, [None, self.L, self.D])
self.captions = tf.placeholder(tf.int32, [None, self.T + 1])
def _get_initial_lstm(self, features):
with tf.variable_scope('initial_lstm'):
features_mean = tf.reduce_mean(features, 1)
| tensorflow.random_uniform_initializer | 6,164 |
from tensorflow.python.framework import ops
mid = segment_ids_shape.ndims
if mid is None:
return [tensor_shape.unknown_shape()]
else:
num_segments = tensor_util.ConstantValue(op.inputs[2])
return [tensor_shape.TensorShape([num_segments]).concatenate(
data_shape[mid:])]
@ops.RegisterShape("LinSpace")
def _LinspaceShape(op):
num = tensor_util.ConstantValue(op.inputs[2])
return [tensor_shape.vector(num)]
| tensorflow.python.framework.ops.RegisterShape | 6,165 |
import tensorflow as tf
if self._offset:
self._set_default_initializer(self.BETA)
self._beta = tf.get_variable(
self.BETA,
shape=self._mean_shape,
initializer=self._initializers[self.BETA])
else:
self._beta = None
if self._scale:
self._set_default_initializer(self.GAMMA)
self._gamma = tf.get_variable(
self.GAMMA,
shape=self._mean_shape,
initializer=self._initializers[self.GAMMA])
else:
self._gamma = None
out = tf.nn.batch_normalization(
input_batch,
mean,
variance,
| tensorflow.get_variable | 6,166 |
import tensorflow as tf
#add_layer 函数里面所有的with都是为了tensorboard添加上去的
def add_layer(inputs, in_size, out_size, activation_function=None,nameScope="layer"):
# add one more layer and return the output of this layer
with tf.name_scope(nameScope):
with tf.name_scope('weights'):
Weights = tf.Variable(tf.random_normal([in_size, out_size]), name='W')
with tf.name_scope('biases'):
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b')
with tf.name_scope('Wx_plus_b'):
Wx_plus_b = tf.add(tf.matmul(inputs, Weights), biases)
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b, )
| tensorflow.name_scope | 6,167 |
import tensorflow as tf
# on the one hand; but on the other hand, we get less frequent parameter updates, which
# slows down learning. In this code, we found that making local steps be much
# smaller than 20 makes the algorithm more difficult to tune and to get to work.
self.runner = RunnerThread(env, pi, 20)
grads = tf.gradients(self.loss, pi.var_list)
tf.summary.scalar("model/policy_loss", pi_loss / bs)
tf.summary.scalar("model/value_loss", vf_loss / bs)
tf.summary.scalar("model/entropy", entropy / bs)
| tensorflow.gradients | 6,168 |
import tensorflow as tf
box_xy, box_wh, obj, cls = tf.split(logits, (2, 2, 1, num_classes), axis=-1)
box_xy = tf.sigmoid(box_xy)
obj = tf.sigmoid(obj)
cls = tf.sigmoid(cls)
anchors = anchors.astype(np.float32)
grid_shape = x_shape[1:3]
# print(grid_shape)
grid_h, grid_w = grid_shape[0], grid_shape[1]
# print(grid_h,tf.range(grid_h))
grid = tf.meshgrid(tf.range(grid_w), tf.range(grid_h))
grid = tf.expand_dims(tf.stack(grid, axis=-1), axis=2) # [gx, gy, 1, 2]
box_xy = (box_xy + tf.cast(grid, dtype)) * stride
box_wh = tf.exp(box_wh) * anchors
box_x1y1 = box_xy - box_wh / 2.
box_x2y2 = box_xy + box_wh / 2.
box = tf.concat([box_x1y1, box_x2y2], axis=-1)
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)
| tensorflow.cast | 6,169 |
import tensorflow as tf
return (loss, per_example_loss, logits, probabilities)
def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps, use_tpu,
use_one_hot_embeddings):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
"""The `model_fn` for TPUEstimator."""
tf.logging.info("*** Features ***")
for name in sorted(features.keys()):
tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
input_ids = features["input_ids"]
input_mask = features["input_mask"]
segment_ids = features["segment_ids"]
label_ids = features["label_ids"]
is_real_example = None
if "is_real_example" in features:
is_real_example = tf.cast(features["is_real_example"], dtype=tf.float32)
else:
is_real_example = tf.ones(tf.shape(label_ids), dtype=tf.float32)
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
| tensorflow.logging.info | 6,170 |
import tensorflow as tf
bounds=bounds,
var_list=variables, # supply with bounds to match order!
tol=1e-14,
)
tf.scalar_summary('nll', nll)
init_op = tf.initialize_all_variables()
# from http://stackoverflow.com/a/35907755/1199693
config = tf.ConfigProto(graph_options=tf.GraphOptions(
# optimizer_options=tf.OptimizerOptions(opt_level=tf.OptimizerOptions.L2))) # L2 werkt niet (wrs eruit gehaald)
optimizer_options=tf.OptimizerOptions(opt_level=tf.OptimizerOptions.L1)))
# start session
with tf.Session(config=config) as sess:
# Merge all the summaries and write them out to /tmp/mnist_logs (by default)
summarize_merged = tf.merge_all_summaries()
summary_writer = tf.train.SummaryWriter('./train/%i' % int(time.time()), sess.graph)
# Run the init operation.
sess.run(init_op)
true_vars = {}
for v in variables:
key = v.name[:v.name.find(':')]
true_vars[key] = v.eval()
true_vars['m0'] = m0.eval()
print("name\t" + "\t".join([v.name.ljust(10) for v in variables]) + "\t | <nll>\t\t | step")
| tensorflow.Session | 6,171 |
import tensorflow as tf
self.fc1 = tf.contrib.layers.fully_connected(self.flatten, self.config.cifar10_cnn["fc1_nb_units"])
self.fc2 = tf.contrib.layers.fully_connected(self.fc1, self.config.data["num_categories"], activation_fn=None)
# Compute loss
with tf.name_scope("loss"):
self.loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=self.fc2, labels=self.y))
# Optimizer
with tf.name_scope("training_op"):
self.training_op = tf.compat.v1.train.AdamOptimizer(self.learning_rate).minimize(self.loss)
# Perf metrics
with tf.name_scope("accuracy"):
prediction = tf.equal(tf.argmax(self.fc2, 1), tf.argmax(self.y, 1))
self.accuracy = tf.reduce_mean(tf.cast(prediction, tf.float32))
| tensorflow.argmax | 6,172 |
import tensorflow as tf
# print(pred_strings)
# print(self.labels)
loss = self.loss_layer(logits, true_tag_ids, nwords, crf_params)
metrics = self.compute_metrics(
true_tag_ids, pred_ids, num_tags, indices, nwords
)
if self.mode == tf.estimator.ModeKeys.EVAL:
return tf.estimator.EstimatorSpec(
self.mode, loss=loss, eval_metric_ops=metrics
)
elif self.mode == tf.estimator.ModeKeys.TRAIN:
optimizer_params = self.params.get("optimizer_params", {})
global_step = tf.train.get_or_create_global_step()
# apply learning rate decay if it's setup already.
lr_decay_params = optimizer_params.pop("learning_rate_exp_decay", {})
| tensorflow.estimator.EstimatorSpec | 6,173 |
import tensorflow as tf
Returns:
Batch tensor of the new observations.
"""
if indices is None:
indices = tf.range(len(self._batch_env))
observ_dtype = self._parse_dtype(self._batch_env.observation_space)
observ = tf.py_func(
self._batch_env.reset, [indices], observ_dtype, name='reset')
observ = tf.check_numerics(observ, 'observ')
reward = tf.zeros_like(indices, tf.float32)
done = tf.zeros_like(indices, tf.bool)
with tf.control_dependencies([
tf.scatter_update(self._observ, indices, observ),
tf.scatter_update(self._reward, indices, reward),
tf.scatter_update(self._done, indices, done)]):
return tf.identity(observ)
@property
| tensorflow.zeros_like | 6,174 |
import tensorflow as tf
common checkpoint of the model.
Hence, we build a separate variable with a separate saver."""
embedding_shape = [int(len(self.test_set) / FLAGS.batch_size) * FLAGS.batch_size,
self.encode.get_shape().as_list()[1]]
tsv_path = os.path.join(FLAGS.logdir, 'metadata.tsv')
self.embedding_test_ph = tf.placeholder(tf.float32, embedding_shape, name='embedding')
self.embedding_test = tf.Variable(tf.random_normal(embedding_shape), name='test_embedding', trainable=False)
self.embedding_assign = self.embedding_test.assign(self.embedding_test_ph)
self.embedding_saver = tf.train.Saver(var_list=[self.embedding_test])
config = projector.ProjectorConfig()
embedding = config.embeddings.add()
embedding.tensor_name = self.embedding_test.name
| tensorflow.random_normal | 6,175 |
import tensorflow as tf
unmatched_ignored_reg_weights = tf.gather(reg_weights, unmatched_ignored_anchor_indices)
reg_weights= tf.dynamic_stitch(
| tensorflow.dynamic_stitch | 6,176 |
import tensorflow as tf
save_path = os.path.join(self.get_temp_dir(), "basics_with_list")
with self.test_session(graph=tf.Graph()) as sess:
# Build a graph with 2 parameter nodes, and Save and
# Restore nodes for them.
v0 = tf.Variable(10.0, name="v0")
v1 = tf.Variable(20.0, name="v1")
save = tf.train.Saver([v0, v1])
tf.initialize_all_variables().run()
# Check that the parameter nodes have been initialized.
self.assertEqual(10.0, v0.eval())
self.assertEqual(20.0, v1.eval())
| tensorflow.train.Saver | 6,177 |
import tensorflow as tf
indices_input = tf.concat(axis=0, values=[indices, tf.reshape(input_, [-1])])
indices_input = tf.reshape(indices_input, [2, -1])
| tensorflow.reshape | 6,178 |
from tensorflow.python.framework import tensor_shape
@ops.RegisterShape("LogicalAnd")
@ops.RegisterShape("LogicalOr")
@ops.RegisterShape("Maximum")
@ops.RegisterShape("Minimum")
@ops.RegisterShape("Mod")
@ops.RegisterShape("Mul")
@ops.RegisterShape("NotEqual")
@ops.RegisterShape("Pow")
@ops.RegisterShape("Sub")
def _BroadcastShape(op):
"""Common shape function for binary operators that broadcast their inputs."""
shape_x = op.inputs[0].get_shape()
shape_y = op.inputs[1].get_shape()
if shape_x.ndims is None or shape_y.ndims is None:
return [tensor_shape.unknown_shape()]
# To compute the broadcasted dimensions, we zip together shape_x and shape_y,
# and pad with 1 to make them the same length.
broadcasted_dims = reversed(list(six.moves.zip_longest(
reversed(shape_x.dims),
reversed(shape_y.dims),
fillvalue=tensor_shape.Dimension(1))))
# Next we combine the dimensions according to the numpy broadcasting rules.
# http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html
return_dims = []
for (dim_x, dim_y) in broadcasted_dims:
if dim_x.value is None or dim_y.value is None:
# One or both dimensions is unknown. If either dimension is greater than
| tensorflow.python.framework.tensor_shape.unknown_shape | 6,179 |
import tensorflow as tf
current_inputs = text_emb # [num_sentences, max_sentence_length, emb]
for layer in range(self.config["contextualization_layers"]):
with tf.variable_scope("layer_{}".format(layer)):
with tf.variable_scope("fw_cell"):
cell_fw = util.CustomLSTMCell(self.config["contextualization_size"], num_sentences, self.lstm_dropout)
with tf.variable_scope("bw_cell"):
cell_bw = util.CustomLSTMCell(self.config["contextualization_size"], num_sentences, self.lstm_dropout)
state_fw = tf.contrib.rnn.LSTMStateTuple(tf.tile(cell_fw.initial_state.c, [num_sentences, 1]), tf.tile(cell_fw.initial_state.h, [num_sentences, 1]))
state_bw = tf.contrib.rnn.LSTMStateTuple(tf.tile(cell_bw.initial_state.c, [num_sentences, 1]), tf.tile(cell_bw.initial_state.h, [num_sentences, 1]))
(fw_outputs, bw_outputs), _ = tf.nn.bidirectional_dynamic_rnn(
| tensorflow.variable_scope | 6,180 |
import tensorflow as tf
#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:
loss = tf.losses.mean_squared_error(labels, predictions)
| tensorflow.matmul | 6,181 |
import tensorflow as tf
cutout_center_width = tf.random.uniform(
shape=[], minval=0, maxval=image_width,
dtype=tf.int32)
lower_pad = tf.maximum(0, cutout_center_height - length // 2)
upper_pad = tf.maximum(0, image_height - cutout_center_height - length // 2)
left_pad = tf.maximum(0, cutout_center_width - length // 2)
right_pad = tf.maximum(0, image_width - cutout_center_width - length // 2)
cutout_shape = [image_height - (lower_pad + upper_pad),
image_width - (left_pad + right_pad)]
padding_dims = [[lower_pad, upper_pad], [left_pad, right_pad]]
| tensorflow.maximum | 6,182 |
import tensorflow as tf
inputs = tf.reshape(inputs, [-1, self.final_size])
inputs = tf.layers.dense(inputs=inputs, units=self.num_classes)
inputs = tf.identity(inputs, 'final_dense')
return inputs
| tensorflow.layers.dense | 6,183 |
import tensorflow as tf
# Calculate: m(x) m(x)^T + m(x) \mu(x)^T + \mu(x) m(x)^T,
# where m(x) is the mean_function and \mu(x) is fmean
e_mean_mean = expectation(pXnew, mean_function, mean_function) # N x D x D
Lit_q_mu = tf.matrix_triangular_solve(Luu, q_mu, adjoint=True)
e_mean_Kuf = expectation(pXnew, mean_function, (kern, feat)) # N x D x M
# einsum isn't able to infer the rank of e_mean_Kuf, hence we explicitly set the rank of the tensor:
e_mean_Kuf = tf.reshape(e_mean_Kuf, [num_data, num_func, num_ind])
e_fmean_mean = tf.einsum("nqm,mz->nqz", e_mean_Kuf, Lit_q_mu) # N x D x D
e_related_to_mean = e_fmean_mean + tf.matrix_transpose(e_fmean_mean) + e_mean_mean
if full_output_cov:
fvar = (
tf.matrix_diag(tf.tile((eKff - tf.trace(Li_eKuffu_Lit))[:, None], [1, num_func])) +
tf.matrix_diag(tf.einsum("nij,dji->nd", Li_eKuffu_Lit, cov)) +
# tf.matrix_diag(tf.trace(tf.matmul(Li_eKuffu_Lit, cov))) +
tf.einsum("ig,nij,jh->ngh", q_mu, Li_eKuffu_Lit, q_mu) -
# tf.matmul(q_mu, tf.matmul(Li_eKuffu_Lit, q_mu), transpose_a=True) -
fmean[:, :, None] * fmean[:, None, :] +
e_related_to_mean
)
else:
fvar = (
(eKff - tf.trace(Li_eKuffu_Lit))[:, None] +
tf.einsum("nij,dji->nd", Li_eKuffu_Lit, cov) +
tf.einsum("ig,nij,jg->ng", q_mu, Li_eKuffu_Lit, q_mu) -
fmean ** 2 +
tf.matrix_diag_part(e_related_to_mean)
)
return fmean, fvar
| tensorflow.einsum | 6,184 |
import tensorflow as tf
if ent_coef_loss is not None:
with tf.control_dependencies([train_values_op]):
ent_coef_op = entropy_optimizer.minimize(ent_coef_loss, var_list=self.log_ent_coef)
self.infos_names += ['ent_coef_loss', 'ent_coef']
self.step_ops += [ent_coef_op, ent_coef_loss, self.ent_coef]
# Monitor losses and entropy in tensorboard
tf.summary.scalar('policy_loss', policy_loss)
tf.summary.scalar('qf1_loss', qf1_loss)
tf.summary.scalar('qf2_loss', qf2_loss)
tf.summary.scalar('value_loss', value_loss)
tf.summary.scalar("Imitation_loss",self.actor_loss_di)
tf.summary.scalar('entropy', self.entropy)
tf.summary.scalar('importance weight',tf.reduce_mean(self.weight_ph))
if ent_coef_loss is not None:
tf.summary.scalar('ent_coef_loss', ent_coef_loss)
tf.summary.scalar('ent_coef', self.ent_coef)
tf.summary.scalar('learning_rate', tf.reduce_mean(self.learning_rate_ph))
# Retrieve parameters that must be saved
self.params = tf_util.get_trainable_vars("model")
self.target_params = tf_util.get_trainable_vars("target/values_fn/vf")
# Initialize Variables and target network
with self.sess.as_default():
| tensorflow.reduce_mean | 6,185 |
import tensorflow as tf
i_z1_y0_x1 = tf.gather(im_flat, idx_z1_y0_x1)
i_z1_y1_x0 = tf.gather(im_flat, idx_z1_y1_x0)
i_z1_y1_x1 = tf.gather(im_flat, idx_z1_y1_x1)
# Finally calculate interpolated values.
x0_f = tf.to_float(x0)
x1_f = tf.to_float(x1)
y0_f = tf.to_float(y0)
y1_f = tf.to_float(y1)
z0_f = tf.to_float(z0)
z1_f = tf.to_float(z1)
# Check the out-of-boundary case.
x0_valid = tf.to_float(
tf.less_equal(x0, max_x) & tf.greater_equal(x0, 0))
x1_valid = tf.to_float(
tf.less_equal(x1, max_x) & tf.greater_equal(x1, 0))
y0_valid = tf.to_float(
tf.less_equal(y0, max_y) & tf.greater_equal(y0, 0))
y1_valid = tf.to_float(
tf.less_equal(y1, max_y) & tf.greater_equal(y1, 0))
z0_valid = tf.to_float(
tf.less_equal(z0, max_z) & tf.greater_equal(z0, 0))
z1_valid = tf.to_float(
tf.less_equal(z1, max_z) & tf.greater_equal(z1, 0))
w_z0_y0_x0 = tf.expand_dims(((x1_f - x) * (y1_f - y) *
(z1_f - z) * x1_valid * y1_valid * z1_valid),
1)
w_z0_y0_x1 = tf.expand_dims(((x - x0_f) * (y1_f - y) *
(z1_f - z) * x0_valid * y1_valid * z1_valid),
| tensorflow.less_equal | 6,186 |
import tensorflow as tf
K.clear_session()
init_session(gpu_memory_fraction)
def tensorflow_session(gpu_memory_fraction):
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.gpu_options.per_process_gpu_memory_fraction = gpu_memory_fraction
return tf.Session(config=config)
def load_image(path):
img = Image.open(path)
if img.mode != 'RGB':
img = img.convert('RGB')
return img
| tensorflow.Session | 6,187 |
import tensorflow as tf
with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)):
cell = tf.nn.rnn_cell.GRUCell(2)
inp = tf.constant(0.5, shape=[2, 2, 2])
enc_outputs, enc_state = tf.nn.dynamic_rnn(cell, inp, dtype=tf.float32)
attn_states = 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()])
| tensorflow.constant | 6,188 |
import tensorflow as tf
out = img_in
with tf.variable_scope("convnet"):
# original architecture
out = layers.convolution2d(out, num_outputs=32, kernel_size=8, stride=4, activation_fn=tf.nn.relu)
out = layers.convolution2d(out, num_outputs=64, kernel_size=4, stride=2, activation_fn=tf.nn.relu)
out = layers.convolution2d(out, num_outputs=64, kernel_size=3, stride=1, activation_fn=tf.nn.relu)
out = layers.flatten(out)
with tf.variable_scope("action_value"):
out = layers.fully_connected(out, num_outputs=512, activation_fn=tf.nn.relu)
out = layers.fully_connected(out, num_outputs=num_actions, activation_fn=None)
return out
| tensorflow.variable_scope | 6,189 |
import tensorflow as tf
cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True)
outputs_dict, state_dict = tf.nn.seq2seq.one2many_rnn_seq2seq(
enc_inp, dec_inp_dict, cell, 2, dec_symbols_dict, embedding_size=2)
sess.run([tf.global_variables_initializer()])
res = sess.run(outputs_dict["0"])
self.assertEqual(3, len(res))
self.assertEqual((2, 5), res[0].shape)
| tensorflow.global_variables_initializer | 6,190 |
import tensorflow as tf
y_shape = []
for i, s in zip(int_shape(y), tf.unstack(tf.shape(y))):
| tensorflow.shape | 6,191 |
import tensorflow as tf
tgt_larg = tf.where(geq, tgt1, tgt2)
tgt_small = tf.where(geq, tgt2, tgt1)
pred_larg = tf.where(geq, pred1, pred2)
pred_small = tf.where(geq, pred2, pred1)
loss = tf.maximum(0., (tgt_larg - tgt_small) - (pred_larg - pred_small))
if hard_ratio < 1.0:
hard_num = tf.cast(tools.shape(pred1)[0] * hard_ratio, tf.int32)
loss = tf.reshape(loss, [-1])
| tensorflow.maximum | 6,192 |
from tensorflow.contrib.eager.python.examples.revnet import revnet
(images, labels) = random_batch(batch_size, config)
model = revnet.RevNet(config=config)
| tensorflow.contrib.eager.python.examples.revnet.revnet.RevNet | 6,193 |
import tensorflow as tf
def example_reading_spec(self):
data_fields = {"targets": tf.VarLenFeature(tf.int64)}
if self.has_inputs:
data_fields["inputs"] = tf.VarLenFeature(tf.int64)
if self.packed_length:
if self.has_inputs:
data_fields["inputs_segmentation"] = tf.VarLenFeature(tf.int64)
data_fields["inputs_position"] = tf.VarLenFeature(tf.int64)
data_fields["targets_segmentation"] = tf.VarLenFeature(tf.int64)
data_fields["targets_position"] = tf.VarLenFeature(tf.int64)
data_items_to_decoders = None
return (data_fields, data_items_to_decoders)
def eval_metrics(self):
return [
| tensorflow.VarLenFeature | 6,194 |
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_last = feats_audio
nfilt_last = audio_nchannels
for i, ((ntime, nband, nfilt), (ptime, pband)) in enumerate(zip(cnn_filter_shapes, cnn_pool)):
layer_name = 'cnn_{}'.format(i)
with tf.variable_scope(layer_name):
filters = tf.get_variable('filters', [ntime, nband, nfilt_last, nfilt], initializer=cnn_init, dtype=dtype)
biases = tf.get_variable('biases', [nfilt], initializer=tf.constant_initializer(0.1), dtype=dtype)
if cnn_rnn_zack:
padding = 'SAME'
else:
padding = 'VALID'
conv = tf.nn.conv2d(layer_last, filters, [1, 1, 1, 1], padding=padding)
biased = tf.nn.bias_add(conv, biases)
convolved = tf.nn.relu(biased)
pool_shape = [1, ptime, pband, 1]
pooled = tf.nn.max_pool(convolved, ksize=pool_shape, strides=pool_shape, padding='SAME')
print('{}: {}'.format(layer_name, pooled.get_shape()))
| tensorflow.constant_initializer | 6,195 |
import tensorflow as tf
# Calculate the output size.
x_shape = tf.shape(x)
out_shape = calc_out_size_4d(x_shape, ksize, strides, padding)
# Pad input.
x_ = _pad_input(
x, ksize, strides, padding, bsize=[1, blk_shape[1], blk_shape[2], 1], bstrides=bstrides)
# In matrix multiplication mode, the block patch should be the same as the kernel size.
assert_shape = tf.assert_equal(
tf.stack([blk_shape[1], blk_shape[2]]),
tf.stack([ksize[0], ksize[1]]),
message='Expect blk_indices.shape[1] == w.shape[0] and blk_indices.shape[2] == w.shape[1].')
# Currently we do not support strides > 1 in this matrix multiplication mode. Could be supported
# in the future.
assert_strides = tf.assert_equal(
tf.cast(tf.stack([strides[1], strides[2]]), tf.int64),
tf.constant([1, 1], dtype=tf.int64),
message='Strides > 1 not supported.')
| tensorflow.stack | 6,196 |
import tensorflow as tf
emb_values = list()
for embedding_weight in tf_sparse_demo.embedding_weights:
if args.save_params:
filepath = r"./embedding_variables/"
utils.try_make_dirs(filepath)
emb_values.append(embedding_weight.read_value())
else:
emb_values = tf.constant(1.0)
tf_results = list()
with tf.Session(graph=graph) as sess:
sess.run([init_op, iterator_init])
sess.run(restore_op)
sess.graph.finalize()
for step in range(args.iter_num):
loss_v, emb_vector_v = sess.run([*graph_results])
print("*" * 80)
print(f"step: {step}, loss: {loss_v}, embedding_vector:\n{emb_vector_v}")
tf_results.append(emb_vector_v)
| tensorflow.Session | 6,197 |
import tensorflow as tf
Examples
--------
>>> dense_vars = tl.layers.get_variable_with_name('dense', True, True)
"""
if name is None:
raise Exception("please input a name")
logging.info(" [*] geting variables with %s" % name)
# tvar = tf.trainable_variables() if train_only else tf.all_variables()
if train_only:
t_vars = tf.trainable_variables()
else:
try: # TF1.0+
t_vars = tf.global_variables()
except Exception: # TF0.12
t_vars = tf.all_variables()
d_vars = [var for var in t_vars if name in var.name]
if printable:
for idx, v in enumerate(d_vars):
| tensorflow.trainable_variables | 6,198 |
import tensorflow as tf
tf.range(0, batch_size, dtype=tf.int32) * seq_length, [-1, 1]
)
flat_positions = tf.reshape(positions + flat_offsets, [-1])
flat_sequence_tensor = tf.reshape(sequence_tensor, [batch_size * seq_length, width])
output_tensor = tf.gather(flat_sequence_tensor, flat_positions)
return output_tensor
| tensorflow.reshape | 6,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.