seed
stringlengths 25
2.89k
| seed_api
stringlengths 14
102
| index
int64 0
14.8k
|
---|---|---|
import tensorflow as tf
mask = tf.equal(mask, tf.ones_like(mask))
hidden_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer
input_size = query.get_shape().as_list()[-1]
# Trainable parameters
w1 = tf.Variable(tf.random_normal([hidden_size, attention_size], stddev=0.1))
w2 = tf.Variable(tf.random_normal([input_size, attention_size], stddev=0.1))
b = tf.Variable(tf.random_normal([attention_size], stddev=0.1))
v = tf.Variable(tf.random_normal([attention_size], stddev=0.1))
with tf.name_scope('v'):
# Applying fully connected layer with non-linear activation to each of the B*T timestamps;
# the shape of `tmp` is (B,T,D)*(D,A)=(B,T,A), where A=attention_size
tmp1 = tf.tensordot(facts, w1, axes=1)
tmp2 = tf.tensordot(query, w2, axes=1)
tmp2 = tf.reshape(tmp2, [-1, 1, tf.shape(tmp2)[-1]])
tmp = tf.tanh((tmp1 + tmp2) + b)
# For each of the timestamps its vector of size A from `tmp` is reduced with `v` vector
v_dot_tmp = tf.tensordot(tmp, v, axes=1, name='v_dot_tmp') # (B,T) shape
key_masks = mask # [B, 1, T]
# key_masks = tf.expand_dims(mask, 1) # [B, 1, T]
paddings = tf.ones_like(v_dot_tmp) * (-2 ** 32 + 1)
v_dot_tmp = tf.where(key_masks, v_dot_tmp, paddings) # [B, 1, T]
alphas = tf.nn.softmax(v_dot_tmp, name='alphas') # (B,T) shape
# Output of (Bi-)RNN is reduced with attention vector; the result has (B,D) shape
#output = tf.reduce_sum(facts * tf.expand_dims(alphas, -1), 1)
| tensorflow.tensordot | 200 |
import tensorflow as tf
input_files, max_seq_length, max_predictions_per_seq, is_training, num_cpu_threads=4
):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
def input_fn(params):
"""The actual input function."""
batch_size = params["batch_size"]
name_to_features = {
"input_ids": tf.FixedLenFeature([max_seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([max_seq_length], tf.int64),
"segment_ids": tf.FixedLenFeature([max_seq_length], tf.int64),
"masked_lm_positions": tf.FixedLenFeature(
[max_predictions_per_seq], tf.int64
),
"masked_lm_ids": tf.FixedLenFeature([max_predictions_per_seq], tf.int64),
"masked_lm_weights": tf.FixedLenFeature(
[max_predictions_per_seq], tf.float32
),
"next_sentence_labels": tf.FixedLenFeature([1], tf.int64),
| tensorflow.FixedLenFeature | 201 |
import tensorflow as tf
# TODO(koz4k): Translate it to T2TModel or remove.
def feed_forward_gaussian_fun(action_space, config, observations):
"""Feed-forward Gaussian."""
if not isinstance(action_space, gym.spaces.box.Box):
raise ValueError("Expecting continuous action space.")
mean_weights_initializer = tf.initializers.variance_scaling(
scale=config.init_mean_factor)
logstd_initializer = tf.random_normal_initializer(config.init_logstd, 1e-10)
flat_observations = tf.reshape(observations, [
tf.shape(observations)[0], tf.shape(observations)[1],
functools.reduce(operator.mul, observations.shape.as_list()[2:], 1)])
with tf.variable_scope("network_parameters"):
with tf.variable_scope("policy"):
x = flat_observations
for size in config.policy_layers:
x = tf.layers.dense(x, size, activation=tf.nn.relu)
mean = tf.layers.dense(
x, action_space.shape[0], activation=tf.tanh,
kernel_initializer=mean_weights_initializer)
logstd = tf.get_variable(
"logstd", mean.shape[2:], tf.float32, logstd_initializer)
logstd = tf.tile(
logstd[None, None],
[tf.shape(mean)[0], tf.shape(mean)[1]] + [1] * (mean.shape.ndims - 2))
with tf.variable_scope("value"):
x = flat_observations
| tensorflow.variable_scope | 202 |
import tensorflow as tf
zs = tf.map_fn(loop_hyper_encoder, ys, dtype=tf.float32, parallel_iterations=1, back_prop=False)
print("Hyper Encoder")
z_hats, _ = entropy_bottleneck(zs, False)
print("Quantize hyperprior")
def loop_hyper_deocder(z):
z = tf.expand_dims(z, 0)
loc, scale = hyper_decoder(z)
return tf.squeeze(loc, [0]), tf.squeeze(scale, [0])
locs, scales = tf.map_fn(loop_hyper_deocder, z_hats, dtype=(tf.float32, tf.float32),
parallel_iterations=1, back_prop=False)
lower_bound = 1e-9# TODO
scales = tf.maximum(scales, lower_bound)
print("Hyper Decoder")
z_strings, z_min_v, z_max_v = entropy_bottleneck.compress(zs)
z_shape = tf.shape(zs)[:]
print("Entropy Encode (Hyper)")
y_strings, y_min_v, y_max_v = conditional_entropy_model.compress(ys, locs, scales)
y_shape = tf.shape(ys)[:]
| tensorflow.map_fn | 203 |
import tensorflow as tf
a0 = logits - tf.reduce_max(logits, 1, keepdims=True)
ea0 = tf.exp(a0)
| tensorflow.exp | 204 |
from tensorflow.python.framework import ops
ValueError: if either `batch_ndims` or `event_ndims` are: `None`,
negative, not `int32`.
"""
if batch_ndims is None: raise ValueError("batch_ndims cannot be None")
if event_ndims is None: raise ValueError("event_ndims cannot be None")
self._batch_ndims = batch_ndims
self._event_ndims = event_ndims
self._validate_args = validate_args
with ops.name_scope(name) as ns:
self._name = ns
with ops.name_scope("init"):
self._batch_ndims = self._assert_non_negative_int32_scalar(
ops.convert_to_tensor(
batch_ndims, name="batch_ndims"))
self._batch_ndims_static, self._batch_ndims_is_0 = (
self._introspect_ndims(self._batch_ndims))
self._event_ndims = self._assert_non_negative_int32_scalar(
ops.convert_to_tensor(
event_ndims, name="event_ndims"))
self._event_ndims_static, self._event_ndims_is_0 = (
| tensorflow.python.framework.ops.name_scope | 205 |
import tensorflow as tf
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
def conv(inpOp, nIn, nOut, kH, kW, dH, dW, padType, name, phase_train=True, use_batch_norm=True, weight_decay=0.0):
with tf.variable_scope(name):
l2_regularizer = lambda t: l2_loss(t, weight=weight_decay)
kernel = tf.get_variable("weights", [kH, kW, nIn, nOut],
initializer=tf.truncated_normal_initializer(stddev=1e-1),
regularizer=l2_regularizer, dtype=inpOp.dtype)
cnv = tf.nn.conv2d(inpOp, kernel, [1, dH, dW, 1], padding=padType)
if use_batch_norm:
conv_bn = batch_norm(cnv, phase_train)
else:
conv_bn = cnv
biases = tf.get_variable("biases", [nOut], initializer=tf.constant_initializer(), dtype=inpOp.dtype)
bias = tf.nn.bias_add(conv_bn, biases)
conv1 = tf.nn.relu(bias)
return conv1
def convLinear(inpOp, nIn, nOut, kH, kW, dH, dW, padType, name, phase_train=True, use_batch_norm=True, weight_decay=0.0):
with tf.variable_scope(name):
l2_regularizer = lambda t: l2_loss(t, weight=weight_decay)
| tensorflow.nn.conv2d | 206 |
import tensorflow as tf
gradvar = self._optimizer.compute_gradients(loss, replaced_list, *args, **kwargs)
final_gradvar = []
for orig_var, (grad, var) in zip(var_list, gradvar):
if var is not orig_var:
grad = tf.cast(grad, orig_var.dtype)
if self._scale != 1.0:
grad = tf.scalar_mul(1. / self._scale, grad)
final_gradvar.append((grad, orig_var))
| tensorflow.cast | 207 |
from tensorflow.contrib.learn.python.learn.summary_writer_cache import SummaryWriterCache
super(StepCounter, self).__init__(every_n_steps=every_n_steps)
self._summary_tag = "global_step/sec"
self._last_reported_step = None
self._last_reported_time = None
self._summary_writer = summary_writer
if summary_writer is None and output_dir:
self._summary_writer = SummaryWriterCache.get(output_dir)
def set_estimator(self, estimator):
super(StepCounter, self).set_estimator(estimator)
if self._summary_writer is None:
self._summary_writer = SummaryWriterCache.get(estimator.model_dir)
| tensorflow.contrib.learn.python.learn.summary_writer_cache.SummaryWriterCache.get | 208 |
import tensorflow as tf
'''
Convolution op wrapper, use RELU activation after convolution
Args:
layer_name:
x: input tensor
Returns:
4D tensor
'''
# x.get_shape()[-1] : Dimension(3)
# x.get_shape()[-1].value : 3
in_channels = x.get_shape()[-1].value
with tf.variable_scope(layer_name):
w = tf.get_variable(name='weights',
trainable=is_pretrain,
shape=[kernel_size[0],kernel_size[1],in_channels,out_channels],
initializer=tf.contrib.layers.xavier_initializer())
b = tf.get_variable(name='bias',
trainable=is_pretrain,
shape=[out_channels],
initializer=tf.constant_initializer(0.0))
x = tf.nn.conv2d(x,w,strides,padding='SAME',name='conv')
x = tf.nn.bias_add(x,b,name='bias_add')
x = tf.nn.relu(x,name='relu')
return x
def pool(layer_name, x, kernel_size=[1,2,2,1], strides=[1,2,2,1], is_max_pool=True):
'''
Pooling op
Args:
| tensorflow.contrib.layers.xavier_initializer | 209 |
import tensorflow as tf
self._add_loss_summary('loss_total', self.loss_total)
self.summs_train = tf.summary.merge_all('train')
# reconstructions
with tf.name_scope('decodings'):
self.image_summaries = {
'orig': self._add_decoding_summary('0_original_input', self.input),
'reco': self._add_decoding_summary('1_reconstruction', self.eval_decode),
'pred': self._add_decoding_summary('2_prediction', self.eval_decode),
'midd': self._add_decoding_summary('3_averaged', self.eval_decode),
'nois': self._add_decoding_summary('4_noisy', self.eval_decode)
}
# visualization
fig = vis.get_figure()
fig.canvas.draw()
self.vis_placeholder = tf.placeholder(tf.uint8, ut.fig2rgb_array(fig).shape)
self.vis_summary = tf.summary.image('visualization', self.vis_placeholder)
# embedding
dists = l2(self.embedding_test[:-1] - self.embedding_test[1:])
self.dist = dists
metrics = []
metrics.append(tf.summary.histogram('point_distance', dists))
metrics.append(tf.summary.scalar('training/trajectory_length', tf.reduce_sum(dists)))
self.blur_ph = tf.placeholder(dtype=tf.float32)
metrics.append(tf.summary.scalar('training/blur_sigma', self.blur_ph))
pred = self.embedding_test[1:-1]*2 - self.embedding_test[0:-2]
pred_error = l2(pred - self.embedding_test[2:])
mean_dist, mean_pred_error = tf.reduce_mean(dists), tf.reduce_mean(pred_error)
| tensorflow.summary.image | 210 |
import tensorflow as tf
patches = tf.random.shuffle(patches)
# rand_idx = tf.reshape(tf.random.shuffle(tf.range(0,n_patch)),[n_patch])
# patches = tf.gather(patches, rand_idx, axis=0)
rows = tf.split(patches,n_col//self.size,axis=0)
rows = [tf.concat(tf.unstack(x),axis=1) for x in rows]
x_aug = tf.concat(rows,axis=0)
x_aug = tf.convert_to_tensor(x_aug)
return tf.concat([x, x_aug],axis=2)
def mix_scramble(self,x):
# assume square patch
# sizes = tf.convert_to_tensor([1,2,4,8])
# idx = tf.random.categorical([tf.ones_like(sizes)], 1)
# print(idx)
# patch_size = int(sizes[idx[0][0]])
| tensorflow.concat | 211 |
import tensorflow as tf
) = 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()
scaffold_fn = tpu_scaffold
| tensorflow.train.init_from_checkpoint | 212 |
import tensorflow as tf
"""
def optimizer(self):
lr = tf.get_variable('learning_rate', initializer=0.1, trainable=False)
tf.summary.scalar('learning_rate-summary', lr)
return tf.train.MomentumOptimizer(lr, 0.9, use_nesterov=True)
def image_preprocess(self, image):
with tf.name_scope('image_preprocess'):
if image.dtype.base_dtype != tf.float32:
| tensorflow.train.MomentumOptimizer | 213 |
import tensorflow as tf
beam_width=beam_width, blank_index=blank_index, top_paths=1,
blank_label=0)
decoded = tf.sparse.SparseTensor(indices[0], values[0], shape[0])
decoded = tf.cast(tf.sparse.to_dense(decoded), tf.int32)
decoded_u = tf.sparse.SparseTensor(indices_u[0], values_u[0], shape_u[0])
decoded_u = tf.cast(tf.sparse.to_dense(decoded_u), tf.int32)
# Adjust event vals according to representation
decoded = tf.where(tf.not_equal(decoded, 0), decoded+shift, decoded)
decoded_u = tf.where(tf.not_equal(decoded_u, 0), decoded_u+shift, decoded_u)
# Set default vals
| tensorflow.sparse.to_dense | 214 |
import tensorflow as tf
encoder_input_length_ = tf.to_int32(tf.ceil(encoder_input_length_ / strides[1]))
feature_size = encoder_inputs_.shape[2].value
channels = encoder_inputs_.shape[3].value
time_steps = tf.shape(encoder_inputs_)[1]
encoder_inputs_ = tf.reshape(encoder_inputs_, [batch_size, time_steps, feature_size * channels])
conv_outputs_ = encoder_inputs_
| tensorflow.shape | 215 |
import tensorflow as tf
gh_w = gh_w.reshape(-1, 1) / np.sqrt(np.pi)
shape = tf.shape(Fmu)
Fmu, Fvar = [tf.reshape(e, (-1, 1)) for e in (Fmu, Fvar)]
X = gh_x * tf.sqrt(2.0 * Fvar) + Fmu
logp = phi(X)
return tf.reshape(tf.matmul(logp, gh_w), shape)
| tensorflow.sqrt | 216 |
import tensorflow as tf
per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
loss = tf.reduce_mean(per_example_loss)
| tensorflow.reduce_mean | 217 |
import tensorflow as tf
self.assertEqual(networks.min_total_num_images(7, 8, 4), 52)
def test_compute_progress(self):
current_image_id_ph = tf.placeholder(tf.int32, [])
progress = networks.compute_progress(
current_image_id_ph,
| tensorflow.placeholder | 218 |
import tensorflow as tf
print('\ninverse(D)=')
print(sess.run(tf.matrix_inverse(D)))
print('\ndeterminant(D)={:.1f}'.format(sess.run(tf.matrix_determinant(D))))
print('\ncholesky(D):')
print(sess.run(tf.cholesky(identity_matrix)))
print('\nselfAdjointEig(D):')
print(sess.run(tf.self_adjoint_eig(D)))
print(sess.run(tf.div(13, 4)))
print(sess.run(tf.truediv(13, 4)))
print(sess.run(tf.floordiv(13, 4)))
print(sess.run(tf.mod(13.2, 4)))
print(sess.run(tf.cross([1, 0, 0], [0, 1, 0])))
print(sess.run(tf.square([1, 2, 3])))
| tensorflow.self_adjoint_eig | 219 |
import tensorflow as tf
)
self_attn_input = rep_map
context_features = tf.add(scatter_attn[:, :-1], scatter_pooling[:, :-1], 'context_features')
output_mask = rep_mask
else:
self_attn_input = rep_head_tensor
context_features = attn_result
output_mask = rep_head_mask
# context fusion gate
o_bias = tf.get_variable('o_bias', [ivec], tf.float32, tf.constant_initializer(0.))
fusion_gate = tf.nn.sigmoid(
linear(self_attn_input, ivec, True, 0., 'linear_fusion_i', False, wd, keep_prob, is_train) +
linear(context_features, ivec, True, 0., 'linear_fusion_a', False, wd, keep_prob, is_train) +
o_bias)
output = fusion_gate * self_attn_input + (1 - fusion_gate) * context_features
return output, output_mask
def self_attention_for_selected_head(
| tensorflow.constant_initializer | 220 |
import tensorflow as tf
FLAGS.enable_check_numerics = False
p = self.TestParams()
p.input = base_input_generator.BaseSequenceInputGenerator.Params()
task = p.cls(p)
task.CreateVariable(
'a',
py_utils.WeightParams(shape=[], init=py_utils.WeightInit.Constant(0)))
var_a = task.theta.a
# Infinite gradient.
var_grads = py_utils.NestedMap(a=(var_a, tf.log(0.)))
has_nan_or_inf, grad_scale, final_var_grads = task.ScaleGradients(var_grads)
with self.session():
tf.global_variables_initializer().run()
self.assertTrue(has_nan_or_inf.eval())
self.assertEqual(0., grad_scale.eval())
# The final gradient must be finite.
self.assertFalse(tf.is_nan(final_var_grads.a[1]).eval())
| tensorflow.log | 221 |
import tensorflow as tf
if model_str == 'gcn_ae':
opt = OptimizerAE(preds=model.reconstructions,
labels=tf.reshape(tf.sparse_tensor_to_dense(placeholders['adj_orig'],
validate_indices=False), [-1]),
pos_weight=pos_weight,
norm=norm)
elif model_str == 'gcn_vae':
opt = OptimizerVAE(preds=model.reconstructions,
labels=tf.reshape(tf.sparse_tensor_to_dense(placeholders['adj_orig'],
validate_indices=False), [-1]),
model=model, num_nodes=num_nodes,
pos_weight=pos_weight,
norm=norm)
# Initialize session
sess = tf.Session()
| tensorflow.sparse_tensor_to_dense | 222 |
import tensorflow as tf
logits_vec, axis=0)[None]
relabel_indices = tf.random.categorical(logits=logits_vec, num_samples=1)
### Metrics
global_step = tf.compat.v1.train.get_or_create_global_step()
orig_indices = tf.range(
self._sample_batch_size, dtype=relabel_indices.dtype)
with tf.name_scope("relabelling"):
# How often are the originally commanded goals most optimal?
opt_indices = tf.argmax(logits_vec, axis=1)
orig_is_opt = opt_indices == orig_indices
orig_opt_frac = tf.reduce_mean(tf.cast(orig_is_opt, tf.float32))
tf.compat.v2.summary.scalar(
name="orig_task_optimal", data=orig_opt_frac, step=global_step)
# How often is the relabelled goal optimal?
# The relabel_indices are [B, 1], so we need to remove the extra dim.
relabel_is_opt = tf.squeeze(relabel_indices) == orig_indices
| tensorflow.argmax | 223 |
from tensorflow.python.ops import variable_scope
'PR' for the Precision-Recall-curve.
name: An optional variable_scope name.
Returns:
auc: A scalar tensor representing the current area-under-curve.
update_op: An operation that increments the `true_positives`,
`true_negatives`, `false_positives` and `false_negatives` variables
appropriately and whose value matches `auc`.
Raises:
ValueError: If `predictions` and `labels` have mismatched shapes, or if
`weights` is not `None` and its shape doesn't match `predictions`, or if
either `metrics_collections` or `updates_collections` are not a list or
tuple.
"""
with variable_scope.variable_scope(name, 'auc', [predictions, labels]):
if curve != 'ROC' and curve != 'PR':
raise ValueError('curve must be either ROC or PR, %s unknown' %
(curve))
kepsilon = 1e-7 # to account for floating point imprecisions
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
| tensorflow.python.ops.variable_scope.variable_scope | 224 |
from tensorflow.python.training import gradient_descent
def _setupSparse(self, is_distributed, dtype):
with self._maybeWithDevice("/job:ps" if is_distributed else None):
var0 = variables.Variable(
[[0.0, 1.0], [2.0, 3.0], [4.0, 5.0]], dtype=dtype)
var1 = variables.Variable(
[[0.0, 1.0], [0.0, 3.0], [0.0, 5.0]], dtype=dtype)
with self._maybeWithDevice("/job:worker" if is_distributed else None):
grads = ops.IndexedSlices(
constant_op.constant(
[[0.1, 0.1], [0.1, 0.1]], dtype=dtype), [0, 2], [3, 2])
sgd = gradient_descent.GradientDescentOptimizer(3.0)
clip_opt = variable_clipping_optimizer.VariableClippingOptimizer(
sgd, {var0: [1],
var1: [0]}, 2.0)
update_op = clip_opt.apply_gradients(
list(zip([grads, grads], [var0, var1])))
variables.global_variables_initializer().run()
return var0, var1, update_op
def _assertSparseCorrect(self, var0, var1, update_op):
| tensorflow.python.training.gradient_descent.GradientDescentOptimizer | 225 |
import tensorflow as tf
# rgb.set_shape([h,w,c]) # don't set because going to crop anyway
# crop for lsun 96, see realnvp and glow for specifics
rgb = tf.image.random_crop(rgb,size=[h,w,c])
# crop for patch training
crop_h = h//self.crop_factor
crop_w = w//self.crop_factor
rgb = tf.image.random_crop(rgb,size=[crop_h,crop_w,c])
# random left-right flops
rgb = tf.image.random_flip_left_right(rgb)
# cast, bit conversion, compress domain, center
rgb = tf.cast(rgb, tf.float32)
if n_bits < 8:
rgb = tf.floor(rgb/(2**(8-n_bits)))
rgb = rgb/(n_bins) - 0.5
return rgb
def post_process(self, rgb, add_dequantization_noise=True):
| tensorflow.image.random_flip_left_right | 226 |
import tensorflow as tf
X = tf.placeholder(name='X', shape=[None,data_x.shape[1], data_x.shape[2], data_x.shape[3]], dtype=tf.float32)
# Create the output to the network. This is our one hot encoding of 2 possible values (TODO)!
Y = tf.placeholder(name='Y', shape=[None,data_y.shape[1]], dtype=tf.float32)
| tensorflow.placeholder | 227 |
import tensorflow as tf
# Put everything together.
perturbed_deterministic_actions = tf.argmax(perturbable_policy.q_values, axis=1)
deterministic_actions = tf.argmax(policy.q_values, axis=1)
batch_size = tf.shape(policy.obs_ph)[0]
n_actions = ac_space.nvec if isinstance(ac_space, MultiDiscrete) else ac_space.n
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_deterministic_actions)
stochastic_actions = tf.where(chose_random, random_actions, deterministic_actions)
perturbed_output_actions = tf.cond(stochastic_ph, lambda: perturbed_stochastic_actions,
lambda: deterministic_actions)
output_actions = tf.cond(stochastic_ph, lambda: stochastic_actions, lambda: deterministic_actions)
update_eps_expr = eps.assign(tf.cond(update_eps_ph >= 0, lambda: update_eps_ph, lambda: eps))
| tensorflow.where | 228 |
import tensorflow as tf
If `x` is integral, the output is cast to [u]int64. If `x` is sparse and
reduce_inst_dims is False will return 0 in place where column has no values
across batches.
Raises:
TypeError: If the type of `x` is not supported.
"""
with tf.compat.v1.name_scope(name, 'sum'):
if reduce_instance_dims:
x = tf.reduce_sum(input_tensor=tf_utils.get_values(x))
elif isinstance(x, tf.SparseTensor):
if x.dtype == tf.uint8 or x.dtype == tf.uint16:
x = tf.cast(x, tf.int64)
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,
output_dtypes=[output_dtype])[0]
| tensorflow.sparse.reduce_sum | 229 |
import tensorflow as tf
def _get_next_checkpoint():
return tf.contrib.training.checkpoints_iterator(
| tensorflow.contrib.training.checkpoints_iterator | 230 |
import tensorflow as tf
def decode(roi, deltas, variances=None):
with tf.name_scope('BoundingBoxTransform/decode'):
(roi_width, roi_height,
roi_urx, roi_ury) = get_width_upright(roi)
dx, dy, dw, dh = tf.split(deltas, 4, axis=1)
if variances is None:
variances = [1., 1.]
| tensorflow.split | 231 |
import tensorflow as tf
# protanope
self.color_matrix = tf.convert_to_tensor([[0, 2.02344, -2.52581], [0, 1, 0], [0, 0, 1]])
| tensorflow.convert_to_tensor | 232 |
import tensorflow as tf
loss = tf.maximum(0., tgt_posi_dif - pred_posi_dif)
cstr_pct = tf.math.count_nonzero(loss, dtype=tf.float32) / tf.cast(tf.reduce_prod(tf.shape(loss)), tf.float32)
final_loss = tf.reduce_mean(loss)
| tensorflow.math.count_nonzero | 233 |
from tensorflow.python.framework import tensor_shape
returned_shape = []
for i, dim in enumerate(input_shape.dims):
if i != dimension:
returned_shape.append(dim)
return [tensor_shape.TensorShape(returned_shape)]
else:
raise ValueError(
"dimension (%d) must be in the range [0, %d), where %d is the number "
| tensorflow.python.framework.tensor_shape.TensorShape | 234 |
import tensorflow as tf
with tf.variable_scope('Critic'):
| tensorflow.variable_scope | 235 |
import tensorflow as tf
# 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:
t = tf.to_int32(t)
example[name] = t
return example
def input_fn(params):
| tensorflow.to_int32 | 236 |
from tensorflow.python.ops import check_ops
`log_prob(x)`. If `validate_args` is `False` and the inputs are
invalid, correct behavior is not guaranteed.
allow_nan_stats: `Boolean`, default `True`. If `False`, raise an
exception if a statistic (e.g. mean/mode/etc...) is undefined for any
batch member. If `True`, batch members with valid parameters leading to
undefined statistics will return NaN for this statistic.
name: The name to prepend to all ops created by this distribution.
Raises:
TypeError: if `alpha` and `beta` are different dtypes.
"""
parameters = locals()
parameters.pop("self")
with ops.name_scope(name, values=[alpha, beta]) as ns:
with ops.control_dependencies([
check_ops.assert_positive(alpha),
check_ops.assert_positive(beta),
] if validate_args else []):
self._alpha = array_ops.identity(alpha, name="alpha")
self._beta = array_ops.identity(beta, name="beta")
super(InverseGamma, self).__init__(
dtype=self._alpha.dtype,
validate_args=validate_args,
allow_nan_stats=allow_nan_stats,
is_continuous=True,
is_reparameterized=False,
parameters=parameters,
graph_parents=[self._alpha, self._beta],
name=ns)
| tensorflow.python.ops.check_ops.assert_positive | 237 |
import tensorflow as tf
# already in the target shape
return input_tensor
# resize y-z
squeeze_b_x = tf.reshape(input_tensor, [-1, y_size, z_size, c_size], name='reshape_bx')
resize_b_x = tf.compat.v1.image.resize_bilinear(squeeze_b_x, [y_size_new, z_size_new], align_corners=align)
resume_b_x = tf.reshape(resize_b_x, [-1, x_size, y_size_new, z_size_new, c_size], name='resume_bx')
# Reorient
reoriented = tf.transpose(resume_b_x, [0, 3, 2, 1, 4])
| tensorflow.compat.v1.image.resize_bilinear | 238 |
import tensorflow as tf
dtype=DTYPE)
b = tf.get_variable(
"b_cnn_%s" % i, [num], dtype=DTYPE,
initializer=tf.constant_initializer(0.0))
conv = tf.nn.conv2d(
inp, w,
strides=[1, 1, 1, 1],
padding="VALID") + b
# now max pool
| tensorflow.nn.conv2d | 239 |
import tensorflow as tf
if ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path):
print("loading checkpoint...")
saver.restore(sess, ckpt.model_checkpoint_path)
else:
sess.run(tf.global_variables_initializer())
summary_writer = tf.summary.FileWriter('./logs_pretrain', sess.graph)
_x = x[:, :, :, ::-1]
tf.summary.image('x', _x, 4)
summary_op = tf.summary.merge_all()
epoch_learning_rate = init_learning_rate
for epoch in range(1, total_epochs + 1):
if epoch % 10 == 0 :
epoch_learning_rate = epoch_learning_rate / 10
| tensorflow.summary.image | 240 |
import tensorflow as tf
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 = utils.conv2d_transpose_strided(conv8, W_t1, b_t1, output_shape=tf.shape(image_net["pool4"]))
fuse_1 = tf.add(conv_t1, image_net["pool4"], name="fuse_1")
deconv_shape2 = image_net["pool3"].get_shape()
W_t2 = utils.weight_variable([4, 4, deconv_shape2[3].value, deconv_shape1[3].value], name="W_t2")
b_t2 = utils.bias_variable([deconv_shape2[3].value], name="b_t2")
conv_t2 = utils.conv2d_transpose_strided(fuse_1, W_t2, b_t2, output_shape=tf.shape(image_net["pool3"]))
fuse_2 = tf.add(conv_t2, image_net["pool3"], name="fuse_2")
shape = tf.shape(image)
deconv_shape3 = tf.stack([shape[0], shape[1], shape[2], NUM_OF_CLASSESS])
W_t3 = utils.weight_variable([16, 16, NUM_OF_CLASSESS, deconv_shape2[3].value], name="W_t3")
b_t3 = utils.bias_variable([NUM_OF_CLASSESS], name="b_t3")
conv_t3 = utils.conv2d_transpose_strided(fuse_2, W_t3, b_t3, output_shape=deconv_shape3, stride=8)
annotation_pred = tf.argmax(conv_t3, dimension=3, name="prediction")
| tensorflow.add | 241 |
import tensorflow as tf
all_input_mask,
shape=[num_examples, seq_length],
dtype=tf.int32),
"segment_ids":
tf.constant(
all_segment_ids,
shape=[num_examples, seq_length],
dtype=tf.int32),
| tensorflow.constant | 242 |
import tensorflow as tf
q1_in_ph = tf.concat([x, a], axis=-1)
q1_in_dim = q1_in_ph.shape.as_list()[1]
q1_dropout_mask_generator = DropoutMaskGenerator(q1_in_dim, hidden_sizes, model_prob=1.0 - dropout_rate)
q1_dropout_mask_phs = q1_dropout_mask_generator.generate_dropout_mask_placeholders()
q1, q1_reg = mlp_variational(q1_in_ph, q1_dropout_mask_phs, list(hidden_sizes) + [1],
activation, None, dropout_rate)
q1 = tf.squeeze(q1, axis=2)
with tf.variable_scope('q1', reuse=True):
q1_pi, q1_pi_reg = mlp_variational(tf.concat([x, pi[0]], axis=-1), q1_dropout_mask_phs, list(hidden_sizes) + [1],
activation, None, dropout_rate)
q1_pi = tf.squeeze(q1_pi, axis=2)
with tf.variable_scope('q2'):
q2_in_ph = tf.concat([x, a], axis=-1)
q2_in_dim = q2_in_ph.shape.as_list()[1]
q2_dropout_mask_generator = DropoutMaskGenerator(q2_in_dim, hidden_sizes, model_prob=1.0 - dropout_rate)
q2_dropout_mask_phs = q2_dropout_mask_generator.generate_dropout_mask_placeholders()
q2, q2_reg = mlp_variational(q2_in_ph, q2_dropout_mask_phs, list(hidden_sizes) + [1],
activation, None, dropout_rate)
q2 = tf.squeeze(q2, axis=2)
else:
raise ValueError('Please choose a proper nn_type!')
return pi, pi_reg, pi_dropout_mask_generator, pi_dropout_mask_phs,\
| tensorflow.variable_scope | 243 |
import tensorflow as tf
hparams.video_num_input_frames = video_num_input_frames
hparams.video_num_target_frames = video_num_target_frames
else:
return video_num_input_frames, video_num_target_frames
@gin.configurable(module='trax.data', denylist=['dataset', 'training'])
def bair_robot_pushing_preprocess(dataset, training):
"""Pre-processing function that concatenates input and target frames."""
del training
def concat_and_add_mask(features, targets):
"""Concatenate input and output frames to form a language modeling setup."""
inp = features['inputs']
concat = tf.concat([inp, targets], axis=0)
mask = tf.concat([tf.zeros_like(inp), tf.ones_like(targets)], axis=0)
concat = tf.reshape(concat, (-1,))
mask = tf.reshape(mask, (-1,))
concat = tf.cast(concat, tf.int32)
mask = tf.cast(mask, tf.float32)
features['inputs'] = features['targets'] = concat
features['mask'] = mask
return features, concat
dataset = dataset.map(concat_and_add_mask)
return dataset
def sentencepiece_tokenize(stream, spm_path=None, extra_ids=0):
"""Sentencepiece tokenization."""
| tensorflow.ones_like | 244 |
import tensorflow as tf
return rois, rpn_scores
def _crop_pool_layer(self, bottom, rois, name):
with tf.variable_scope(name):
# tf.squeeze()返回一个张量,这个张量是将原始input中所有维度中为1的那些维都删掉的结果
batch_ids = tf.squeeze(tf.slice(rois, [0, 0], [-1, 1], name="batch_id"), [1])
# Get the normalized coordinates of bboxes
bottom_shape = tf.shape(bottom)
height = (tf.to_float(bottom_shape[1]) - 1.) * np.float32(self._feat_stride[0])
width = (tf.to_float(bottom_shape[2]) - 1.) * np.float32(self._feat_stride[0])
# rois除以h,w就得到了rois在特征图上的位置
x1 = tf.slice(rois, [0, 1], [-1, 1], name="x1") / width
y1 = tf.slice(rois, [0, 2], [-1, 1], name="y1") / height
x2 = tf.slice(rois, [0, 3], [-1, 1], name="x2") / width
y2 = tf.slice(rois, [0, 4], [-1, 1], name="y2") / height
# Won't be backpropagated to rois anyway, but to save time
bboxes = tf.stop_gradient(tf.concat([y1, x1, y2, x2], axis=1))
# 'roi_pooling_size', 7
pre_pool_size = cfg.FLAGS.roi_pooling_size * 2
# 把rois对于的特征图上的部分crop出来,然后resize打破14*14的大小
crops = tf.image.crop_and_resize(bottom, bboxes, tf.to_int32(batch_ids), [pre_pool_size, pre_pool_size], name="crops")
return slim.max_pool2d(crops, [2, 2], padding='SAME')
def _dropout_layer(self, bottom, name, ratio=0.5):
return tf.nn.dropout(bottom, ratio, name=name)
def _anchor_target_layer(self, rpn_cls_score, name):
with tf.variable_scope(name):
| tensorflow.slice | 245 |
import tensorflow as tf
# Hidden 2
with tf.name_scope("hidden2"):
weights = tf.Variable(
tf.truncated_normal([128, 32],
stddev=1.0 / math.sqrt(float(128))),
name="weights")
biases = tf.Variable(tf.zeros([32]),
name="biases")
hidden2 = tf.nn.relu(tf.matmul(hidden1, weights) + biases)
# Linear
with tf.name_scope("softmax_linear"):
weights = tf.Variable(
tf.truncated_normal([32, 10],
stddev=1.0 / math.sqrt(float(32))),
name="weights")
biases = tf.Variable(tf.zeros([10]),
name="biases")
logits = tf.matmul(hidden2, weights) + biases
tf.add_to_collection("logits", logits)
| tensorflow.name_scope | 246 |
import tensorflow as tf
if encoder.binary:
raise NotImplementedError
pad = tf.nn.embedding_lookup(embeddings, utils.BOS_ID)
pad = tf.expand_dims(tf.expand_dims(pad, axis=0), axis=1)
pad = tf.tile(pad, [batch_size, 1, 1])
| tensorflow.nn.embedding_lookup | 247 |
import tensorflow as tf
def test_tensor_rearrange():
tensor_rearrange = TensorRearrange(seed=713)
in_node_a = tensor_rearrange.get_placeholder("input_0")
in_node_b = tensor_rearrange.get_placeholder("input_1")
in_node_c = tensor_rearrange.get_placeholder("input_2")
stitched = tf.dynamic_stitch([[1, 10], [[0, 7, 9], [5, 8, 3]], [[6], [4], [2]]],
[in_node_a, in_node_b, in_node_c]) # should be 11,5,4
list_of_parts = tf.dynamic_partition(tf.transpose(stitched, perm=[1, 2, 0]),
[[0, 1, 2, 3], [1, 0, 2, 3], [2, 3, 1, 0], [2, 1, 0, 3], [0, 1, 2, 3]],
num_partitions=4) # after permute becomes 5,4,11, return all partitions 5,11
node_a = tf.div(list_of_parts[0], list_of_parts[1])
node_b = tf.divide(list_of_parts[2], list_of_parts[3])
trace_node = tf.trace(node_a) + node_b # there is a broadcast here
out_node = tf.cast(tf.count_nonzero(trace_node), dtype=tf.float32) + tf.Variable(tf.random_normal(shape=(2, 3)))
placeholders = [in_node_a, in_node_b, in_node_c]
predictions = [out_node]
# Run and persist
tfp = TensorFlowPersistor(save_dir="partition_stitch_misc")
tfp.set_placeholders(placeholders) \
.set_output_tensors(predictions) \
| tensorflow.divide | 248 |
import tensorflow as tf
with tf.name_scope('S'):
S = tf.placeholder(tf.float32, shape=[None, STATE_DIM], name='s')
with tf.name_scope('R'):
R = tf.placeholder(tf.float32, [None, 1], name='r')
| tensorflow.name_scope | 249 |
import tensorflow as tf
if is_training:
d = tf.data.Dataset.from_tensor_slices(tf.constant(input_files))
| tensorflow.constant | 250 |
import tensorflow as tf
# with tf.variable_scope("conv_context") as scope:
def encode(img):
img_h0 = lrelu(conv2d(img, nf0, d_h=ns0, d_w=ns0, name='h0_conv'))
img_h1 = lrelu(conv2d(img_h0, nf1, d_h=ns1, d_w=ns1, name='h1_conv'))
img_h2 = lrelu(conv2d(img_h1, nf2, d_h=ns2, d_w=ns2, name='h2_conv'))
img_h3 = lrelu(conv2d(img_h2, nf3, d_h=ns3, d_w=ns3, name='h3_conv'))
print(img_h3.get_shape())
img_h4 = lrelu(linear(tf.nn.dropout(tf.reshape(img_h3, [self.batch_size, -1]), keep_prob), featsize, 'h4_lin'))
img_z = lrelu(linear(tf.nn.dropout(img_h4, keep_prob), featsize, 'hz_lin'))
return img_h0, img_h1, img_h2, img_h3, img_h4, img_z
with tf.variable_scope("conv") as scope:
srcimg_h0, srcimg_h1, srcimg_h2, srcimg_h3, srcimg_h4, srcimg_z = encode(srcimg)
scope.reuse_variables()
tgtimg_h0, tgtimg_h1, tgtimg_h2, tgtimg_h3, tgtimg_h4, tgtimg_z = encode(tgtimg)
tgtctx_h0, tgtctx_h1, tgtctx_h2, tgtctx_h3, tgtctx_h4, tgtctx_z = encode(tgtctx)
| tensorflow.nn.dropout | 251 |
import tensorflow as tf
else:
x = states
shape = [x.get_shape()[-1], attention_states[0].get_shape()[-1]]
w = tf.get_variable("map_attns/matrix", shape=shape)
b = tf.get_variable("map_attns/bias", shape=shape[-1:])
x = tf.einsum('ijk,kl->ijl', x, w) + b
if chaining_non_linearity:
x = tf.nn.tanh(x)
| tensorflow.get_variable | 252 |
import tensorflow as tf
# Load tarnn model
OPTION = dh.option(pattern=1)
if OPTION == 'B':
logger.info("Loading best model...")
checkpoint_file = cm.get_best_checkpoint(BEST_CPT_DIR, select_maximum_value=True)
else:
logger.info("Loading latest model...")
checkpoint_file = tf.train.latest_checkpoint(CPT_DIR)
logger.info(checkpoint_file)
graph = tf.Graph()
with graph.as_default():
session_conf = tf.ConfigProto(
allow_soft_placement=args.allow_soft_placement,
log_device_placement=args.log_device_placement)
| tensorflow.train.latest_checkpoint | 253 |
import tensorflow as tf
self.input_y = tf.placeholder(tf.float32, [None, num_classes], name="input_y")
self.is_training = tf.placeholder(tf.bool)
initializer = tf.contrib.layers.variance_scaling_initializer()
# Embedding Lookup 16
with tf.device('/cpu:0'), tf.name_scope("embedding"):
if use_he_uniform:
self.embedding_W = tf.get_variable(name='lookup_W', shape=[num_quantized_chars, embedding_size],
initializer=tf.contrib.layers.variance_scaling_initializer())
else:
self.embedding_W = tf.Variable(tf.random_uniform([num_quantized_chars, embedding_size], -1.0, 1.0),name="embedding_W")
| tensorflow.name_scope | 254 |
import tensorflow as tf
"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:
t = tf.to_int32(t)
example[name] = t
| tensorflow.parse_single_example | 255 |
import tensorflow as tf
else: # 创建worker两个网络的具体步骤
with tf.variable_scope(scope): # 这里的scope传入的是worker的名字
self.global_step = globalAC.global_step
| tensorflow.variable_scope | 256 |
import tensorflow as tf
[batch_size, num_classes])
pre_pool = end_points['Conv2d_13_pointwise']
self.assertListEqual(pre_pool.get_shape().as_list(),
[batch_size, 4, 4, 1024])
def testUnknownImageShape(self):
tf.reset_default_graph()
batch_size = 2
height, width = 224, 224
num_classes = 1000
input_np = np.random.uniform(0, 1, (batch_size, height, width, 3))
with self.test_session() as sess:
inputs = tf.placeholder(tf.float32, shape=(batch_size, None, None, 3))
logits, end_points = mobilenet_v1.mobilenet_v1(inputs, num_classes)
self.assertTrue(logits.op.name.startswith('MobilenetV1/Logits'))
self.assertListEqual(logits.get_shape().as_list(),
[batch_size, num_classes])
pre_pool = end_points['Conv2d_13_pointwise']
feed_dict = {inputs: input_np}
tf.global_variables_initializer().run()
pre_pool_out = sess.run(pre_pool, feed_dict=feed_dict)
self.assertListEqual(list(pre_pool_out.shape), [batch_size, 7, 7, 1024])
def testGlobalPoolUnknownImageShape(self):
| tensorflow.placeholder | 257 |
import tensorflow as tf
logits = tf.nn.bias_add(logits, output_bias)
log_probs = tf.nn.log_softmax(logits, axis=-1)
label_ids = tf.reshape(label_ids, [-1])
label_weights = tf.reshape(label_weights, [-1])
| tensorflow.reshape | 258 |
import tensorflow as tf
last = activation[L-1]
labels= tf.transpose(Y)
if last == 'sigmoid' or last == 'softmax': #use cross entropy loss function
logits= tf.transpose(betan*zn[1])
cost = tf.reduce_mean(tf.losses.sigmoid_cross_entropy(logits = logits, multi_class_labels=labels))
elif last == 'esp' or last == 'relu': #use minimum squared error (L2 loss)
out = tf.transpose(zn[0])
cost = tf.reduce_mean(tf.squared_difference(out, labels))/2
return cost
#------------Hessian-------------------
def flatten(tensor):
| tensorflow.transpose | 259 |
import tensorflow as tf
def clip_tensor(t, length):
"""Clips the input tensor along the first dimension up to the length.
Args:
t: the input tensor, assuming the rank is at least 1.
length: a tensor of shape [1] or an integer, indicating the first dimension
of the input tensor t after clipping, assuming length <= t.shape[0].
Returns:
clipped_t: the clipped tensor, whose first dimension is length. If the
length is an integer, the first dimension of clipped_t is set to length
statically.
"""
clipped_t = tf.gather(t, tf.range(length))
if not _is_tensor(length):
clipped_t = _set_dim_0(clipped_t, length)
return clipped_t
def pad_or_clip_tensor(t, length):
"""Pad or clip the input tensor along the first dimension.
Args:
t: the input tensor, assuming the rank is at least 1.
length: a tensor of shape [1] or an integer, indicating the first dimension
of the input tensor t after processing.
| tensorflow.range | 260 |
import tensorflow as tf
query,
query,
], axis=1)
if time_major:
# (T,B,D) => (B,T,D)
facts = tf.array_ops.transpose(facts, [1, 0, 2])
mask = tf.equal(mask, tf.ones_like(mask))
facts_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer
querry_size = query.get_shape().as_list()[-1]
queries = tf.tile(query, [1, tf.shape(facts)[1]])
queries = tf.reshape(queries, tf.shape(facts))
din_all = tf.concat([queries, facts, queries-facts, queries*facts], axis=-1)
d_layer_1_all = tf.layers.dense(din_all, 80, activation=tf.nn.sigmoid, name='f1_att' + stag)
d_layer_2_all = tf.layers.dense(d_layer_1_all, 40, activation=tf.nn.sigmoid, name='f2_att' + stag)
d_layer_3_all = tf.layers.dense(d_layer_2_all, 1, activation=None, name='f3_att' + stag)
d_layer_3_all = tf.reshape(d_layer_3_all, [-1, 1, tf.shape(facts)[1]])
scores = d_layer_3_all
# Mask
# key_masks = tf.sequence_mask(facts_length, tf.shape(facts)[1]) # [B, T]
key_masks = tf.expand_dims(mask, 1) # [B, 1, T]
paddings = tf.ones_like(scores) * (-2 ** 32 + 1)
scores = tf.where(key_masks, scores, paddings) # [B, 1, T]
# Scale
# scores = scores / (facts.get_shape().as_list()[-1] ** 0.5)
# Activation
| tensorflow.layers.dense | 261 |
import tensorflow as tf
end_input,
xlnet_config.d_model,
kernel_initializer=initializer,
activation=tf.tanh,
name="dense_0")
end_logits = tf.contrib.layers.layer_norm(end_logits,
begin_norm_axis=-1)
end_logits = tf.layers.dense(
end_logits,
1,
| tensorflow.contrib.layers.layer_norm | 262 |
import tensorflow as tf
next_sentence_log_probs, axis=-1, output_type=tf.int32)
next_sentence_labels = tf.reshape(next_sentence_labels, [-1])
next_sentence_accuracy = tf.metrics.accuracy(
labels=next_sentence_labels, predictions=next_sentence_predictions)
next_sentence_mean_loss = tf.metrics.mean(
values=next_sentence_example_loss)
return {
| tensorflow.metrics.mean | 263 |
import tensorflow as tf
ckpt_name = 'save/model.ckpt'
fname = 'model.tf'
dst_nodes = ['output/predictions']
saver = tf.train.Saver()
# Create a session and init
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print("training started!!")
print("******************")
# Now iterate over our dataset n_epoch times
for epoch_i in range(epoch):
| tensorflow.global_variables_initializer | 264 |
import tensorflow as tf
def load_graph(model_file):
graph = tf.Graph()
graph_def = tf.compat.v1.GraphDef()
import os
file_ext = os.path.splitext(model_file)[1]
with open(model_file, "rb") as f:
if file_ext == '.pbtxt':
text_format.Merge(f.read(), graph_def)
else:
graph_def.ParseFromString(f.read())
with graph.as_default():
tf.import_graph_def(graph_def, name='')
tf.io.write_graph(graph_def, '/tmp/', 'optimized_graph.pb',as_text=False)
return graph
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--input_graph", default=None,
help="graph/model to be executed")
parser.add_argument("--data_location", default=None,
help="full path to the validation data")
parser.add_argument("--input_height", default=None,
type=int, help="input height")
| tensorflow.import_graph_def | 265 |
import tensorflow as tf
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))
b = tf.get_variable("b", [nh], initializer=tf.constant_initializer(init_bias))
return tf.matmul(x, w)+b
def batch_to_seq(h, nbatch, nsteps, flat=False):
if flat:
h = tf.reshape(h, [nbatch, nsteps])
else:
h = tf.reshape(h, [nbatch, nsteps, -1])
return [tf.squeeze(v, [1]) for v in tf.split(axis=1, num_or_size_splits=nsteps, value=h)]
def seq_to_batch(h, flat = False):
shape = h[0].get_shape().as_list()
if not flat:
assert(len(shape) > 1)
nh = h[0].get_shape()[-1].value
return tf.reshape(tf.concat(axis=1, values=h), [-1, nh])
else:
return tf.reshape(tf.stack(values=h, axis=1), [-1])
def lstm(xs, ms, s, scope, nh, init_scale=1.0):
| tensorflow.reshape | 266 |
import tensorflow as tf
activation_fn=tf.nn.relu, weights_initializer=gauss_initializer,
trainable=False)
out = layers.flatten(out)
with tf.variable_scope("action_value"):
out = layers.fully_connected(out, num_outputs=num_actions, activation_fn=None)
return out
def simple_model_w_feat_eng(img_in, num_actions, scope, reuse=False):
with tf.variable_scope(scope, reuse=reuse):
out = img_in
out = layers.flatten(out)
# stddev = 1/n, where n = number of inputs
gauss_initializer = initializers.xavier_initializer(uniform=False)
with tf.variable_scope("action_value"):
out = layers.fully_connected(
out,
num_outputs=num_actions,
activation_fn=tf.nn.relu,
| tensorflow.variable_scope | 267 |
import tensorflow as tf
],
axis=1)
nearest_hot = tf.one_hot(nearest_idx, depth=self.hparams.block_v_size)
nearest_hot = tf.reduce_mean(nearest_hot, axis=-2)
else:
if self.hparams.random_top_k > 1:
_, top_k_idx = tf.nn.top_k(-dist, k=self.hparams.random_top_k)
nearest_idx = tf.gather(
top_k_idx,
tf.random_uniform(
[1],
minval=0,
maxval=self.hparams.random_top_k - 1,
dtype=tf.int32),
axis=-1)
else:
if self.hparams.use_scales:
dist /= tf.reshape(self.hparams.scales,
| tensorflow.random_uniform | 268 |
import tensorflow as tf
any_buf.Pack(queue_runner)
tf.add_to_collection("user_defined_any_collection", any_buf)
| tensorflow.add_to_collection | 269 |
import tensorflow as tf
gtargets = labels['targets'][num_feature_layers : 2 * num_feature_layers][0]
gscores = labels['targets'][2 * num_feature_layers : 3 * num_feature_layers][0]
with tf.variable_scope(params['model_scope'], default_name = None, values = [features], reuse=tf.AUTO_REUSE):
backbone = xdet_body_v3.xdet_resnet_v3(params['resnet_size'], params['data_format'])
body_cls_output, body_regress_output = backbone(inputs=features, is_training=(mode == tf.estimator.ModeKeys.TRAIN))
| tensorflow.variable_scope | 270 |
import tensorflow as tf
combined_idx = use_identity * distances + (1 - use_identity) * logspace_idx
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 = []
if self.config["use_metadata"]:
top_antecedent_speaker_ids = tf.gather(top_span_speaker_ids, top_antecedents) # [k, c]
same_speaker = tf.equal(tf.expand_dims(top_span_speaker_ids, 1), top_antecedent_speaker_ids) # [k, c]
speaker_pair_emb = tf.gather(tf.get_variable("same_speaker_emb", [2, self.config["feature_size"]]), tf.to_int32(same_speaker)) # [k, c, emb]
feature_emb_list.append(speaker_pair_emb)
tiled_genre_emb = tf.tile(tf.expand_dims(tf.expand_dims(genre_emb, 0), 0), [k, c, 1]) # [k, c, emb]
feature_emb_list.append(tiled_genre_emb)
if self.config["use_features"]:
antecedent_distance_buckets = self.bucket_distance(top_antecedent_offsets) # [k, c]
antecedent_distance_emb = tf.gather(tf.get_variable("antecedent_distance_emb", [10, self.config["feature_size"]]), antecedent_distance_buckets) # [k, c]
feature_emb_list.append(antecedent_distance_emb)
| tensorflow.expand_dims | 271 |
import tensorflow as tf
rgb = rgb/(n_bins) - 0.5
return rgb
def post_process(self, rgb, add_dequantization_noise=True):
n_bits = config.model.data.n_bits
n_bins = 2**n_bits
rgb_out = rgb
# discretization noise
if add_dequantization_noise:
shape = tf.shape(rgb_out)
rgb_out += tf.random_uniform(shape=shape)*(1/n_bins)
return rgb_out
| tensorflow.shape | 272 |
import tensorflow as tf
"""
Implementation of parameterize for a half-Gaussian prior.
"""
def __init__(self, input_shape=None, name='gaussianize', *args, **kwargs):
super().__init__(*args, num_parameters=1, input_shape=input_shape, name=name, **kwargs)
def _forward(self, x1, x2, **kwargs):
log_sigmas = self.parameterizer(x1)
z2, fldj = half_gaussianize(x2, log_sigmas)
return z2, fldj
def _inverse(self, x1, z2, **kwargs):
log_sigmas = self.parameterizer(x1)
x2, ildj = half_gaussianize(z2, log_sigmas, inverse=tf.constant(True))
return x2, ildj
def exponentiate(x, log_lambdas, inverse=tf.constant(False)):
if not inverse:
z = tf.math.exp(log_lambdas)*x
ldj = tf.math.reduce_sum(log_lambdas, axis=[1,2,3])
else:
z = x*tf.math.exp(-log_lambdas)
ldj = -tf.math.reduce_sum(log_lambdas, axis=[1,2,3])
return z, ldj
class Exponentiate(Parameterize):
| tensorflow.constant | 273 |
import tensorflow as tf
eval_spec = tf.estimator.EvalSpec(read_dataset('valid.csv',
tf.estimator.ModeKeys.EVAL,
512),
steps = None,
exporters = exporter)
tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)
| tensorflow.estimator.train_and_evaluate | 274 |
import tensorflow as tf
observations = features["inputs_raw"]
# Axis 0 - Batch.
# Axis 1 - Input Frames, 4 frames.
# Axis 2, 3 - Height & Width.
# Axis 4 - Channels RGB, 3 colours.
x = tf.transpose(observations, [0, 2, 3, 1, 4])
x_shape = common_layers.shape_list(x)
x = tf.reshape(x, x_shape[:-2] + [-1])
dropout = getattr(self.hparams, "dropout_ppo", 0.0)
with tf.variable_scope("feed_forward_cnn_small"):
x = tf.cast(x, tf.float32) / 255.0
x = tf.layers.conv2d(x, 32, (5, 5), strides=(2, 2),
activation=tf.nn.relu, padding="same")
x = tf.layers.conv2d(x, 32, (5, 5), strides=(2, 2),
activation=tf.nn.relu, padding="same")
flat_x = tf.layers.flatten(x)
if self.use_epochs:
epoch = features["epoch"] + tf.zeros([x_shape[0]], dtype=tf.int32)
# Randomly set epoch to 0 in some cases as that's the inference value.
| tensorflow.cast | 275 |
import tensorflow as tf
# Opening with GFile allows to use remotely stored files, e.g.
# in a gs bucket.
dataset_handle = tf.io.gfile.GFile(dataset_path, 'r')
dataset = []
| tensorflow.io.gfile.GFile | 276 |
import tensorflow as tf
def cnn_bi_lstm_model(x, amp_factor, bil_lstm_win_size, num_classes):
logits = cnn_model(x, amp_factor=amp_factor)
logits = tf.reshape(logits, [-1, bil_lstm_win_size, 256*amp_factor])
forward_cell = tf.nn.rnn_cell.LSTMCell(128)
backward_cell = tf.nn.rnn_cell.LSTMCell(128)
encoder_outputs,_ = tf.nn.bidirectional_dynamic_rnn(
forward_cell,
backward_cell,
logits,
dtype=tf.float32
)
encoder_outputs = tf.concat(encoder_outputs, axis=2)
logits = tf.reshape(tf.layers.dense(encoder_outputs, units=num_classes), [-1, bil_lstm_win_size, num_classes])
return logits
def cnn_model(x, amp_factor=1):
with tf.variable_scope('model'):
conv1 = tf.layers.conv2d(x, filters=32*amp_factor, kernel_size=[5, 3],
data_format='channels_last', padding= "same",
strides=(2, 1),
activation=tf.nn.relu)
pool1 = conv1
| tensorflow.concat | 277 |
import tensorflow as tf
same_span = tf.logical_and(same_start, same_end) # [num_labeled, num_candidates]
candidate_labels = tf.matmul(tf.expand_dims(labels, 0), tf.to_int32(same_span)) # [1, num_candidates]
candidate_labels = tf.squeeze(candidate_labels, 0) # [num_candidates]
return candidate_labels
def get_dropout(self, dropout_rate, is_training):
return 1 - (tf.to_float(is_training) * dropout_rate)
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]
return top_antecedents, top_antecedents_mask, top_fast_antecedent_scores, top_antecedent_offsets
| tensorflow.expand_dims | 278 |
import tensorflow as tf
else:
outputs = activation_function(Wx_plus_b, )
return outputs
# 这个就是在tensorboard上可视化的时候的区别:
# 使用with tf.name_scope('inputs')可以将xs和ys包含进来
# 形成一个大的图层,图层的名字就是with tf.name_scope()方法里的参数。
with tf.name_scope('inputs'):
xs = tf.placeholder(tf.float32, [None, 1], name='x_input') # 这个name的属性,也是为了使用tensorboard,添加上来的
ys = tf.placeholder(tf.float32, [None, 1], name='y_input') # 同上
# add hidden layer
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu,nameScope="layerTest1")
# add output layer
| tensorflow.name_scope | 279 |
import tensorflow as tf
import random
import numpy as np
import tensorflow as tf
class Seq2SeqTest(tf.test.TestCase):
def testRNNDecoder(self):
with self.test_session() as sess:
with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)):
inp = [tf.constant(0.5, shape=[2, 2])] * 2
_, enc_state = tf.nn.rnn(
tf.nn.rnn_cell.GRUCell(2), inp, dtype=tf.float32)
dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3
cell = tf.nn.rnn_cell.OutputProjectionWrapper(
tf.nn.rnn_cell.GRUCell(2), 4)
dec, mem = tf.nn.seq2seq.rnn_decoder(dec_inp, enc_state, cell)
sess.run([tf.global_variables_initializer()])
res = sess.run(dec)
self.assertEqual(3, len(res))
self.assertEqual((2, 4), res[0].shape)
| tensorflow.constant | 280 |
from tensorflow.python.framework import ops
value matches `metric`.
"""
default_name = _at_k_name('average_precision', k)
with ops.name_scope(name, default_name, (predictions, labels)) as scope:
# Calculate per-example average precision, and apply weights.
average_precision = sparse_average_precision_at_k(
| tensorflow.python.framework.ops.name_scope | 281 |
import tensorflow as tf
def _compute_loss(self):
def focal_loss(logits, labels, weights=None, alpha=0.25, gamma=2):
logits = tf.nn.sigmoid(logits)
zeros = array_ops.zeros_like(logits, dtype=logits.dtype)
pos_p_sub = array_ops.where(labels > zeros, labels - logits, zeros)
neg_p_sub = array_ops.where(labels > zeros, zeros, logits)
cross_ent = - alpha * (pos_p_sub ** gamma) * tf.log(tf.clip_by_value(logits, 1e-8, 1.0)) \
- (1 - alpha) * (neg_p_sub ** gamma) * tf.log(tf.clip_by_value(1.0 - logits, 1e-8, 1.0))
return tf.reduce_sum(cross_ent, 1)
start_label = tf.one_hot(self.start_label, tf.shape(self.logits1)[1], axis=1)
end_label = tf.one_hot(self.end_label, tf.shape(self.logits2)[1], axis=1)
if self.config.loss_type == 'cross_entropy':
start_loss = tf.nn.softmax_cross_entropy_with_logits(
logits=self.logits1, labels=start_label)
| tensorflow.reduce_sum | 282 |
import tensorflow as tf
testnum:1
}
with tf.Session(config=config) as sess:
sess.run(init)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
tf.train.Saver().restore(sess,path)
total=0.0
for i in range(loop):
a = datetime.now()
| tensorflow.train.start_queue_runners | 283 |
import tensorflow as tf
label_id = label_map[example.label]
if ex_index < 5:
tf.logging.info("*** Example ***")
tf.logging.info("guid: %s" % (example.guid))
tf.logging.info("tokens: %s" % " ".join(
| tensorflow.logging.info | 284 |
import tensorflow as tf
# self.bc_loss = 0.5 * tf.reduce_mean(tf.contrib.keras.backend.categorical_crossentropy(self.optimal_actions_onehot,self.policy))
# self.next_loc_loss_il = 0.2 * tf.reduce_sum(tf.sqrt(tf.square(self.next_loc_mean[:-1,:] - self.il_nextloc)))
# self.imitation_loss = self.bc_loss #+ self.next_loc_loss_il
# Get gradients from local network using local losses and
# normalize the gradients using clipping
local_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope+'/qvalues')
self.gradients = tf.gradients(self.loss, local_vars)
self.var_norms = tf.global_norm(local_vars)
grads, self.grad_norms = tf.clip_by_global_norm(self.gradients, GRAD_CLIP)
# Apply local gradients to global network
global_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, GLOBAL_NET_SCOPE+'/qvalues')
| tensorflow.get_collection | 285 |
import tensorflow as tf
alpha = tf.nn.softmax(out_att)
context = tf.reduce_sum(features * tf.expand_dims(alpha, 2), 1, name='context') #(N, D)
return context, alpha
def _selector(self, context, h, reuse=False):
with tf.variable_scope('selector', reuse=reuse):
w = tf.get_variable('w', [self.H, 1], initializer=self.weight_initializer)
b = tf.get_variable('b', [1], initializer=self.const_initializer)
beta = tf.nn.sigmoid(tf.matmul(h, w) + b, 'beta') # (N, 1)
context = tf.multiply(beta, context, name='selected_context')
return context, beta
def _decode_lstm(self, x, h, context, dropout=False, reuse=False):
with tf.variable_scope('logits', reuse=reuse):
| tensorflow.get_variable | 286 |
from tensorflow.python.framework import ops
@ops.RegisterShape("Complex")
@ops.RegisterShape("Div")
@ops.RegisterShape("Equal")
@ops.RegisterShape("Greater")
@ops.RegisterShape("GreaterEqual")
@ops.RegisterShape("Less")
@ops.RegisterShape("LessEqual")
@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,
| tensorflow.python.framework.ops.RegisterShape | 287 |
import tensorflow as tf
dataset = dataset.map(unicode_decode_chars)
def target_right_length(_, target):
return tf.less(tf.shape(target)[0], max_target_length + 1)
if max_target_length > 0:
| tensorflow.shape | 288 |
import tensorflow as tf
for name, value in zip(self.log_op_names, log_rslt)])
tf.logging.info('iter #%d: %s | speed = %.2f pics / sec' % (idx_iter + 1, log_str, speed))
| tensorflow.logging.info | 289 |
from tensorflow.python.ops import math_ops
Args:
numerator: A real `Tensor`.
denominator: A real `Tensor`, with dtype matching `numerator`.
name: Name for the returned op.
Returns:
0 if `denominator` <= 0, else `numerator` / `denominator`
"""
return math_ops.select(
math_ops.greater(denominator, 0),
math_ops.truediv(numerator, denominator),
0,
name=name)
def _safe_scalar_div(numerator, denominator, name):
"""Divides two values, returning 0 if the denominator is 0.
Args:
numerator: A scalar `float64` `Tensor`.
denominator: A scalar `float64` `Tensor`.
| tensorflow.python.ops.math_ops.truediv | 290 |
import tensorflow as tf
features[spec.name] = feature
return tf.train.Example(features=tf.train.Features(feature=features))
def _input_fn_builder(self, input_file, is_training):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
def input_fn(params):
"""The actual input function."""
d = tf.data.TFRecordDataset(input_file)
if is_training:
d = d.repeat()
d = d.shuffle(buffer_size=100)
return d.apply(
tf.contrib.data.map_and_batch(
self._decode_tfrecord, batch_size=params["batch_size"], drop_remainder=True
)
)
return input_fn
def _decode_tfrecord(self, record):
"""Decodes a record to a TensorFlow example."""
example = tf.parse_single_example(record, self._name_to_feature_config)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name, tensor in example.items():
| tensorflow.contrib.data.map_and_batch | 291 |
import tensorflow as tf
val_val = sess.run(val)
print('\nval=' + str(val_val))
print(f'\nargmax_0={val_val.argmax(0)} argmax_1={val_val.argmax(1)}')
print('\ntf.argmax(val, 0)=' + str(sess.run(tf.argmax(val, 0))))
print('tf.argmax(val, 1)=' + str(sess.run(tf.argmax(val, 1))))
| tensorflow.argmax | 292 |
import tensorflow as tf
from tensorflow.python.ops import control_flow_ops
def conv(inpOp, nIn, nOut, kH, kW, dH, dW, padType, name, phase_train=True, use_batch_norm=True, weight_decay=0.0):
with tf.variable_scope(name):
l2_regularizer = lambda t: l2_loss(t, weight=weight_decay)
kernel = tf.get_variable("weights", [kH, kW, nIn, nOut],
initializer=tf.truncated_normal_initializer(stddev=1e-1),
regularizer=l2_regularizer, dtype=inpOp.dtype)
cnv = tf.nn.conv2d(inpOp, kernel, [1, dH, dW, 1], padding=padType)
if use_batch_norm:
conv_bn = batch_norm(cnv, phase_train)
else:
| tensorflow.truncated_normal_initializer | 293 |
import tensorflow as tf
#TODO: add in an argparse
parser = argparse.ArgumentParser(description='Run ablations on models')
parser.add_argument('experiment_type', type=str,
help='type of ablation')
parser.add_argument('ablation_type', type=str,
help='type of ablation')
parser.add_argument('data_location', type=str,
help='data_location')
args = parser.parse_args()
vdata = np.load(args.data_location)
tf.reset_default_graph()
idim = (36, 64)
keep_prob = tf.placeholder(tf.float32, name='keep_prob')
tftrain = tf.placeholder(tf.bool, name='tftrain')
batch_size=100
if (args.experiment_type == "reach") or (args.experiment_type == "push"):
idim = (48, 48)
tfinput = tf.placeholder(tf.float32, (3, batch_size) + idim + (3, ), name='x')
if args.experiment_type == "reach":
test = ContextAEReach()
elif args.experiment_type == "push":
test = ContextAEPush()
elif args.experiment_type == "pushreal":
test = ContextAEPushReal()
elif args.experiment_type == "sweep":
test = ContextAESweep()
test.build(tfinput, args.ablation_type)
| tensorflow.placeholder | 294 |
import tensorflow as tf
# wrapper to make the optimizer work with TPUs
if params['use_tpu']:
gen_optimizer = tf.contrib.tpu.CrossShardOptimizer(gen_optimizer)
dis_optimizer = tf.contrib.tpu.CrossShardOptimizer(dis_optimizer)
gan_train_ops = tf.contrib.gan.gan_train_ops(gan_model, gan_loss, gen_optimizer, dis_optimizer)
| tensorflow.contrib.tpu.CrossShardOptimizer | 295 |
import tensorflow as tf
x = self._concat(x, x1)
for _ in range(2, self._max_diffusion_step + 1):
x2 = 2 * tf.sparse_tensor_dense_matmul(support, x1) - x0
x = self._concat(x, x2)
x1, x0 = x2, x1
num_matrices = len(self._supports) * self._max_diffusion_step + 1 # Adds for x itself.
x = tf.reshape(x, shape=[num_matrices, self._num_nodes, input_size, batch_size])
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_size],
dtype=dtype,
initializer=tf.contrib.layers.xavier_initializer())
x = tf.matmul(
x, weights) # (batch_size * self._num_nodes, output_size)
biases = tf.get_variable("biases", [output_size],
dtype=dtype,
initializer=tf.constant_initializer(
bias_start, dtype=dtype))
x = tf.nn.bias_add(x, biases)
# Reshape res back to: (batch_size, num_node, state_dim)
return tf.reshape(x, [batch_size, self._num_nodes, output_size]) | tensorflow.contrib.layers.xavier_initializer | 296 |
import tensorflow as tf
@classmethod
def nonlinearity_grad_override(cls, op, grad):
output = op.outputs[0]
input = op.inputs[0]
ref_input = cls._deeplift_ref[op.name]
ref_output = activation(op.type)(ref_input)
delta_out = output - ref_output
delta_in = input - ref_input
instant_grad = activation(op.type)(0.5 * (ref_input + input))
return tf.compat.v1.where(tf.abs(delta_in) > 1e-5, grad * delta_out / delta_in,
original_grad(instant_grad.op, grad))
def _init_references(self):
# print ('DeepLIFT: computing references...')
sys.stdout.flush()
self._deeplift_ref.clear()
ops = []
g = tf.compat.v1.get_default_graph()
for op in g.get_operations():
| tensorflow.abs | 297 |
import tensorflow as tf
n_factor, channels])
res = tf.transpose(res, [0, 1, 3, 5, 2, 4])
res = tf.reshape(
res,
| tensorflow.reshape | 298 |
import tensorflow as tf
update_mean_op = moving_averages.assign_moving_average(
variable=self._moving_mean,
value=mean,
decay=self._decay_rate,
name="update_moving_mean").op
update_second_moment_op = moving_averages.assign_moving_average(
variable=self._moving_second_moment,
value=second_moment,
decay=self._decay_rate,
name="update_moving_second_moment").op
return update_mean_op, update_second_moment_op
def build_no_ops():
return (tf.no_op(), tf.no_op())
# 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_moment_op = utils.smart_cond(
is_training,
build_update_ops,
build_no_ops,
)
# Every new connection creates a new op which adds its contribution
# to the running average when ran.
tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_mean_op)
| tensorflow.no_op | 299 |