seed stringlengths 59 2.16k | seed_api stringlengths 14 101 | index int64 0 523 |
|---|---|---|
import tensorflow as tf
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 accordi... | tensorflow.not_equal | 200 |
import tensorflow as tf
lstm_cell_fw = tf.contrib.rnn.LSTMBlockFusedCell(num_units=num_units, **kwargs)
outputs_fw, (hidden_fw, output_fw) = lstm_cell_fw(t, dtype=tf.float32, sequence_length=nwords)
if bidirectional:
lstm_cell_bw = tf.contrib.rnn.LSTMBlockFusedCell(num_units=num_units, **kwargs)
... | tensorflow.transpose | 201 |
import tensorflow as tf
if self.norm_type == 'layer':
norm_net = tf.contrib.layers.layer_norm(net, center=True, scale=True, activation_fn=activation_fn)
elif self.norm_type == 'batch':
| tensorflow.contrib.layers.layer_norm | 202 |
import tensorflow as tf
}
placeholders.update({
'adj_mats_%d,%d,%d' % (i, j, k): tf.sparse_placeholder(tf.float32)
for i, j in edge_types for k in range(edge_types[i,j])})
| tensorflow.sparse_placeholder | 203 |
from tensorflow.python.ops import variables as vars_
"Got %s." % str(optimizer))
# All trainable variables, if specific variables are not specified.
if variables is None:
variables = vars_.trainable_variables()
# Compute gradients.
gradients = opt.compute_gradients(
| tensorflow.python.ops.variables.trainable_variables | 204 |
import tensorflow as tf
self._cost = tf.reduce_sum(loss)
self._final_state = state
if not is_training:
return
self._lr = tf.Variable(0.0, trainable=False)
tvars = tf.trainable_variables()
grads, _ = tf.clip_by_global_norm(tf.gradients(self._cost, tvars),
... | tensorflow.Variable | 205 |
import tensorflow as tf
def directional_attention_with_selections(
rep_tensor, rep_mask, dep_selection, head_selection, direction=None, hn=None, keep_unselected=True,
scope=None, keep_prob=1., is_train=None, wd=0., activation='elu'):
bs, sl, vec = tf.shape(rep_tensor)[0], tf.shape(rep_tensor)[1]... | tensorflow.logical_and | 206 |
import tensorflow as tf
self.embeddings,
self.inputs,
name='word_embeddings',
)
# Zero out embeddings of pad value
masks = tf.not_equal(self.inputs, pad_value, name='masks')
word_embeddings *= tf.cast(
tf.ex... | tensorflow.count_nonzero | 207 |
from tensorflow.python.ops import math_ops
def get_eval_ops(self, features, logits, targets, metrics=None):
loss = self.loss(logits, targets, features)
result = {"loss": metrics_lib.streaming_mean(loss)}
# Adds default metrics.
if metrics is None:
# TODO(b/29366811): This currently results in... | tensorflow.python.ops.math_ops.sigmoid | 208 |
import tensorflow as tf
def lstm_network(input, scope='lstm_network'):
with tf.variable_scope(scope):
# tf.nn.rnn_cell
lstm_cell1 = tf.contrib.rnn.BasicLSTMCell(lstm_hidden_size_layer1, forget_bias=1.0)
lstm_cell2 = tf.contrib.rnn.BasicLSTMCell(lstm_hidden_size_layer2, forget_bias=1.0)
... | tensorflow.contrib.rnn.MultiRNNCell | 209 |
import tensorflow as tf
x_ += x * (1. - diag_mask)
# Finally, gather everything into a lower triangular matrix.
L_ = tf.gather(x_, tril_mask)
return [L_, tf.transpose(L_)]
tmp = tf.scan(fn, L_flat, initializer=init)
... | tensorflow.scan | 210 |
from tensorflow.python.ops import sparse_ops
hash_key=layers.SPARSE_FEATURE_CROSS_DEFAULT_HASH_KEY)
# Check actual hashed output to prevent unintentional hashing changes.
expected_out = self._sparse_tensor([[83]])
with self.test_session() as sess:
self._assert_sparse_tensor_equals(expected_ou... | tensorflow.python.ops.sparse_ops.sparse_tensor_to_dense | 211 |
from tensorflow.python.framework import sparse_tensor
dnn_hidden_units=(3, 3))
input_fn = test_data.iris_input_multiclass_fn
metrics = classifier.fit(input_fn=input_fn, steps=_ITERS).evaluate(
input_fn=input_fn, steps=100)
self._assertCommonMetrics(metrics)
def benchmarkPartitionedVaria... | tensorflow.python.framework.sparse_tensor.SparseTensor | 212 |
import tensorflow as tf
FLAGS = flags.FLAGS
# augmentation functions
# augment
def random_crop_and_resize(images, ratio=0.8):
b, h, w, c = images.get_shape().as_list()
ch, cw = map(lambda x: int(x * ratio), (h, w))
crop = tf.random_crop(images, size=[b, ch, cw, 3])
crop = tf.image.resize(crop, [h, w])
ret... | tensorflow.random_crop | 213 |
from tensorflow.python.ops import math_ops
mean_average_precision: Scalar `float64` `Tensor` with the mean average
precision values.
update: `Operation` that increments variables appropriately, and whose
value matches `metric`.
"""
default_name = _at_k_name('average_precision', k)
with ops.n... | tensorflow.python.ops.math_ops.to_double | 214 |
from tensorflow.python.framework import ops
if tensor_dtype is None:
if not inputs or not isinstance(inputs, (list, tuple)):
raise ValueError("inputs must be a list of at least one Tensor with the "
"same dtype and shape")
inputs = ops.convert_n_to_tensor_or_indexed_slices(inputs... | tensorflow.python.framework.ops.convert_n_to_tensor_or_indexed_slices | 215 |
from tensorflow.contrib.cudnn_rnn.python.ops import cudnn_rnn_ops
test_configs = self._GetTestConfig()
for config_name, config in test_configs.items():
config = test_configs[config_name]
num_layers = config["num_layers"]
num_units = config["num_units"]
batch_size = config["batch_size"]
... | tensorflow.contrib.cudnn_rnn.python.ops.cudnn_rnn_ops.CudnnLSTM | 216 |
import tensorflow as tf
Evaluate the quality of the logits at predicting the label
'''
correct = tf.equal(tf.arg_max(logits,1), tf.arg_max(labels,1))
correct = tf.cast(correct, tf.int32)
| tensorflow.arg_max | 217 |
from tensorflow.contrib.learn.python.learn.estimators import dnn_linear_combined
{'TF_CONFIG': json.dumps(tf_config)}):
config = run_config.RunConfig()
# Because we did not start a distributed cluster, we need to pass an
# empty ClusterSpec, otherwise the device_setter w... | tensorflow.contrib.learn.python.learn.estimators.dnn_linear_combined.DNNLinearCombinedClassifier | 218 |
from tensorflow.python.layers import core as core_layers
def dropout(self, keep_prob=0.5, input_layer=None):
if input_layer is None:
input_layer = self.top_layer
else:
self.top_size = None
name = 'dropout' + str(self.counts['dropout'])
with tf.variable_scope(name):
if not self.phase... | tensorflow.python.layers.core.dropout | 219 |
import tensorflow as tf
def build_loss(self):
cutoff_vf_manager = tf.reshape(tf.stop_gradient(self.manager_vf), [-1])
dot = tf.reduce_sum(tf.multiply(self.s_diff, self.g), axis=1)
gcut = tf.stop_gradient(self.g)
mag = tf.norm(self.s_diff, axis=1) * tf.norm(gcut, axis=1) + .0001
... | tensorflow.norm | 220 |
import tensorflow as tf
ds = ds.apply(
tf.data.experimental.map_and_batch(
lambda fname, label: (mapper(tf.read_file(fname)), label),
batch_size=batch_size,
| tensorflow.read_file | 221 |
import tensorflow.contrib.graph_editor as ge
# get all bottlenecks in the graph
bottleneck_ts = []
for t in ts:
b = set(ge.get_backward_walk_ops(t.op, inclusive=True, within_ops=fwd_ops))
f = set(ge.get_forward_walk_ops(t.op, incl... | tensorflow.contrib.graph_editor.get_backward_walk_ops | 222 |
from tensorflow.contrib.layers.python.layers import utils
# Only make the ops if we know that `is_training=True`, or the value of
# `is_training` is unknown.
is_training_const = utils.constant_value(is_training)
if is_training_const is None or is_training_const:
update_mean_op, update_variance_op... | tensorflow.contrib.layers.python.layers.utils.smart_cond | 223 |
from tensorflow.python.ops import array_ops
with ops.device(device):
return array_ops.unstack(values)
| tensorflow.python.ops.array_ops.unstack | 224 |
import tensorflow.contrib.graph_editor as ge
scope_name = str(micros)
op_list = []
with tf.name_scope(scope_name):
yield op_list
g = tf.get_default_graph()
op_list.extend(ge.select_ops(scope_name+"/.*", graph=g))
def _to_op(tensor_or_op):
if hasattr(tensor_or_op, "op"):
return tensor_or_op.op
r... | tensorflow.contrib.graph_editor.select_ops | 225 |
import tensorflow as tf
def func1():
# execute at training time
batch_mean, batch_var = tf.nn.moments(x, range(len(shape) - 1))
update_mean = tf.assign_sub(pop_mean, (1 - decay)*(pop_mean - batch_mean))
update_var = tf.assign_sub(pop_var, (1 - decay)*(pop_var - b... | tensorflow.assign_sub | 226 |
import tensorflow as tf
try:
t_vars = tf.global_variables()
| tensorflow.global_variables | 227 |
import tensorflow as tf
#For Imitation Learning Part
# 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.... | tensorflow.global_norm | 228 |
from tensorflow.python.client import device_lib
learning_starts=50000,
learning_freq=4,
frame_history_len=4,
target_update_freq=10000,
grad_norm_clipping=10
)
env.close()
def get_available_gpus():
from tensorflow.python.client import device_lib
local_device_prot... | tensorflow.python.client.device_lib.list_local_devices | 229 |
from tensorflow.python.ops import array_ops
if labels_rank > 1:
labels = array_ops.reshape(labels, [-1])
| tensorflow.python.ops.array_ops.reshape | 230 |
import tensorflow as tf
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
layers = tf.keras.layers
def parse(line):
"""Parse a line from the colors dataset."""
# Each line of the dataset is comma-separated and formatted as
# color_name, r, g, b
# so `items` is a list [color_name, r, g... | tensorflow.string_to_number | 231 |
from tensorflow.python.framework import ops
loss_vec, array_ops.reshape(weight_tensor, shape=(-1,)))
return math_ops.div(
math_ops.reduce_sum(loss_vec),
math_ops.to_float(math_ops.reduce_sum(weight_tensor)),
name="loss")
def _get_linear_vars(self):
if self._get_line... | tensorflow.python.framework.ops.get_collection | 232 |
import tensorflow as tf
gtboxes_and_label_q, num_objects, img_h, img_w])
tower_grads = []
biases_regularizer = tf.no_regularizer
weights_regularizer = tf.contrib.layers.l2_regularizer(cfgs.WEIGHT_DECAY)
with tf.variable_scope(tf.get_... | tensorflow.get_variable_scope | 233 |
from tensorflow.contrib.learn.python.learn import ops
def test_softmax_classifier(self):
with self.cached_session() as session:
features = array_ops.placeholder(dtypes.float32, [None, 3])
labels = array_ops.placeholder(dtypes.float32, [None, 2])
weights = constant_op.constant([[0.1, 0.1], [0.1... | tensorflow.contrib.learn.python.learn.ops.softmax_classifier | 234 |
from tensorflow.python.framework import op_def_registry
def _get_node_def(op):
return op._node_def # pylint: disable=protected-access
def _get_op_def(op):
# pylint: disable=protected-access
if hasattr(op, "_sig"):
return getattr(op, "_sig")
else:
return op_def_registry.get_registered_ops()[op.type... | tensorflow.python.framework.op_def_registry.get_registered_ops | 235 |
import tensorflow as tf
break
if not mute:
tf.logging.info('Finished evaluation')
if max_iterations:
pbar.close()
# List of dicts to dict of lists
metrics = dict(zip(metrics[0], zip(*[m.values() for m in metrics])))
metrics = ... | tensorflow.model_variables | 236 |
from tensorflow.python.ops import math_ops
ops should be added to.
name: An optional variable_scope name.
Returns:
percentage: A tensor representing the current mean, the value of `total`
divided by `count`.
update_op: An operation that increments the `total` and `count` variables
appr... | tensorflow.python.ops.math_ops.less | 237 |
from tensorflow.python.ops import variable_scope
v = variable_scope.get_variable("v", [options.attention_vec_size])
v = tf.expand_dims(tf.expand_dims(v, axis=0), axis=0)
w_c = None
if options.use_coverage:
with variable_scope.variable_scope("coverage"):
... | tensorflow.python.ops.variable_scope.get_variable | 238 |
import tensorflow as tf
trainnum = tf.placeholder(tf.int32)
validnum = tf.placeholder(tf.int32)
learnrate = tf.placeholder(tf.float32)
def getinputs(path):
filename_queue=tf.train.string_input_producer([path])
reader=tf.TFRecordReader()
_,serialized_example=reader.read(filename_queue)
features... | tensorflow.TFRecordReader | 239 |
from tensorflow.python.training import training as train
* `learning_rate` and `learning_rate_decay_fn` are supplied, but no
`global_step` is available.
* `gradients` is empty.
"""
loss = ops.convert_to_tensor(loss)
contrib_framework.assert_scalar(loss)
if global_step is None:
glo... | tensorflow.python.training.training.assert_global_step | 240 |
from tensorflow.python.ops import nn
which fall into the top `k` predictions.
update_op: An operation that increments the `total` and `count` variables
appropriately and whose value matches `recall_at_k`.
Raises:
ValueError: If `predictions` and `labels` have mismatched shapes, or if
`igno... | tensorflow.python.ops.nn.in_top_k | 241 |
from tensorflow.contrib import framework as contrib_framework
supervisor_is_chief=(self._config.task == 0),
supervisor_master=self._config.master,
feed_fn=feed_fn,
max_steps=steps,
fail_on_nan_loss=fail_on_nan_loss)
def _evaluate_model(self, input_fn, steps, feed_fn... | tensorflow.contrib.framework.create_global_step | 242 |
from tensorflow.python.ops import variable_scope as vs
_FuncGraph overrides ops.Graph's create_op() so that we can keep
track of every inputs into every op created inside the function. If
any input is from other graphs, we keep track of it in self.capture
and substitue the input with a place holder.
Each ... | tensorflow.python.ops.variable_scope.get_variable_scope | 243 |
import tensorflow as tf
tf.summary.image('Compare/final_detection_gpu:%d' % i, detections_in_img)
loss_dict = outputs[-1]
total_loss_dict, total_losses = self.loss_dict(loss_dict, num_gpu)
... | tensorflow.get_collection | 244 |
from tensorflow.python.platform import googletest
# the `y` value at the input and the `y` value at the baseline.
expected_val = y_input_val[0] - y_baseline_val[0]
# Calculate the integrated gradients attribution of the input.
ig = integrated_gradients.IntegratedGradients(graph, sess, ... | tensorflow.python.platform.googletest.main | 245 |
from tensorflow.python.ops import math_ops
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)
assert array_ops.squeeze(fp).get_shape().as_list()[0] == num_thres... | tensorflow.python.ops.math_ops.div | 246 |
import tensorflow as tf
ignored_matches,
tf.less(
| tensorflow.less | 247 |
import tensorflow as tf
sess.run(zero_var.initializer)
sess.run(ones_var.initializer)
print(sess.run(zero_var))
print(sess.run(ones_var))
zero_similar = tf.Variable(tf.zeros_like(zero_var))
ones_similar = tf.Variable(tf.ones_like(ones_var))
sess.run(ones_similar.initializer)
sess.run(zero_similar.initializer)
print(... | tensorflow.fill | 248 |
from tensorflow.python.layers import convolutional as conv_layers
strides = [1, d_height, d_width, 1]
if self.data_format == 'NCHW':
strides = [strides[0], strides[3], strides[1], strides[2]]
if mode != 'SAME_RESNET':
conv = conv_layers.conv2d(
input_layer,
num... | tensorflow.python.layers.convolutional.conv2d | 249 |
import tensorflow as tf
# Prediction operation
prediction = tf.sigmoid(model_output)
| tensorflow.sigmoid | 250 |
from tensorflow.python.framework import constant_op
class OpsTest(test.TestCase):
"""Ops tests."""
def test_softmax_classifier(self):
with self.cached_session() as session:
features = array_ops.placeholder(dtypes.float32, [None, 3])
labels = array_ops.placeholder(dtypes.float32, [None, 2])
... | tensorflow.python.framework.constant_op.constant | 251 |
from tensorflow.python.training import training
self._target_column.num_label_columns)],
array_ops.reshape(centered_bias, [-1]))
return centered_bias
def _centered_bias_step(self, targets, features):
centered_bias = ops.get_collection(self._centered_bias_weight_collection)
batch_size... | tensorflow.python.training.training.AdagradOptimizer | 252 |
from tensorflow.python.training import training as train
loss = ops.convert_to_tensor(loss)
contrib_framework.assert_scalar(loss)
if global_step is None:
global_step = train.get_global_step()
else:
train.assert_global_step(global_step)
| tensorflow.python.training.training.get_global_step | 253 |
from tensorflow.python.ops import math_ops
moving_average_variable, value, decay, zero_debias=False)
# quicker adaptation at the beginning
if global_step is not None:
n = math_ops.cast(global_step, dtypes.float32)
decay = math_ops.minimum(decay, n / (n + 1.))
# update averages
m... | tensorflow.python.ops.math_ops.minimum | 254 |
import tensorflow as tf
rnn_inputs = tf.nn.bias_add(tf.matmul(feats_all, rnn_proj_w), rnn_proj_b)
rnn_inputs = tf.reshape(rnn_inputs, [batch_size, rnn_nunroll, rnn_size])
rnn_inputs = tf.split(rnn_inputs, rnn_nunroll, axis=1)
rnn_inputs = [tf.squeeze(input_, [1]) for in... | tensorflow.squeeze | 255 |
import tensorflow as tf
output, state = update(state, input_, context, input_symbol)
output_ = generate(output, input_, context)
argmax = lambda: tf.argmax(output_, 1)
target = lambda: inputs.read(time + 1)
softmax = lambda: tf.squeeze(tf.multinomial(tf.log(tf.nn.softmax(o... | tensorflow.logical_not | 256 |
from tensorflow.contrib.rnn.python.ops import core_rnn
multi_cell = rnn_cell.MultiRNNCell(
[cell() for _ in range(num_layers)])
outputs, final_state = core_rnn.static_rnn(
multi_cell, inputs, dtype=dtypes.float32)
trainable_variables = ops.get_collection(
| tensorflow.contrib.rnn.python.ops.core_rnn.static_rnn | 257 |
import tensorflow as tf
is_dynamic_rnn: Use dynamic_rnn or not.
Returns:
A tuple containing:
- Input tensor of the restored model.
- Prediction tensor of the restored model.
- Output tensor, which is the softwmax result of the prediction tensor.
- new session of the restored m... | tensorflow.reset_default_graph | 258 |
import tensorflow as tf
log_timescale_increment = (
math.log(float(max_timescale) / float(min_timescale)) /
(tf.to_float(num_timescales) - 1))
inv_timescales = min_timescale * tf.exp(
tf.to_float(tf.range(num_timescales)) * -log_timescale_increment)
scaled_time = (
tf.expand_dims(tf.to_fl... | tensorflow.cos | 259 |
from tensorflow.contrib.opt.python.training import variable_clipping_optimizer
with ops.device(device):
yield
else:
yield
def _setupDense(self, is_distributed, dtype):
with self._maybeWithDevice("/job:ps" if is_distributed else None):
var0 = variables.Variable([[0.0, 1.0], [2.0, 3.... | tensorflow.contrib.opt.python.training.variable_clipping_optimizer.VariableClippingOptimizer | 260 |
from tensorflow.python.ops import array_ops
# Check that we got integer for classification.
if not target.dtype.is_integer:
raise ValueError("Target's dtype should be integer "
"Instead got %s." % target.dtype)
# sparse_softmax_cross_entropy_with_logits requires [batch_size] target.
... | tensorflow.python.ops.array_ops.squeeze | 261 |
from tensorflow.python.training import saver as saver_lib
def every_n_step_end(self, step, outputs):
super(ValidationMonitor, self).every_n_step_end(step, outputs)
# TODO(mdan): The use of step below is probably misleading.
# The code should probably use the step from the checkpoint, because
# that'... | tensorflow.python.training.saver.latest_checkpoint | 262 |
from tensorflow.python.framework import ops
"""Moves a list of tensors to a device by concatenating/splitting them."""
# Reset the device setting to avoid weird interactions with device merging
# logic.
with ops.device(None):
if all(tensor.shape == tensor_shape.scalar() for tensor in tensors):
w... | tensorflow.python.framework.ops.device | 263 |
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 = ... | tensorflow.range | 264 |
import tensorflow as tf
serialized_example,
# Defaults are not specified since both keys are required.
features={
'image_raw': tf.FixedLenFeature([], tf.string),
'label': tf.FixedLenFeature([], tf.int64),
})
if FLAGS.contrast_norm == 'areafactor':
image = tf.decode_... | tensorflow.decode_raw | 265 |
from tensorflow.python.ops import state_ops
lr_t = math_ops.cast(self._lr_t, var.dtype.base_dtype)
mu_t = math_ops.cast(self._mu_t, var.dtype.base_dtype)
vstar = self.get_slot(var, "vstar")
gold = self.get_slot(var, "gold") # glod is not sparse
v_diff = state_ops.assign(vstar... | tensorflow.python.ops.state_ops.assign_sub | 266 |
from tensorflow.python.ops import image_ops
from tensorflow.contrib.slim.python.slim.data import tfexample_decoder
from tensorflow.python.client import session
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import image_ops
from tensorflow.python.o... | tensorflow.python.ops.image_ops.resize_bilinear | 267 |
from tensorflow.python.ops import state_ops
old_value = array.value()
assign_op = state_ops.assign(array, new_value, validate_shape=False)
| tensorflow.python.ops.state_ops.assign | 268 |
from tensorflow.python.ops import random_ops
def validateKolmogorovSmirnov(self,
shape,
mean,
stddev,
minval,
maxval,
seed=16... | tensorflow.python.ops.random_ops.parameterized_truncated_normal | 269 |
import tensorflow as tf
encode = tf.placeholder(tf.int32, shape=[None], name="encode")
decode = tf.placeholder(tf.int32, shape=[decode_max_length + 2], name="decode")
weight = tf.placeholder(tf.float32, shape=[decode_max_length + 1], name="weight")
queue = tf.PaddingFIFOQueue(capacity = capacity,
... | tensorflow.PaddingFIFOQueue | 270 |
from tensorflow.python.ops import logging_ops
Returns:
Numpy array of predicted probabilities.
"""
return self._infer_model(x=x, input_fn=input_fn, batch_size=batch_size)
def _get_train_ops(self, features, targets):
"""See base class."""
global_step = variables.get_global_step()
asser... | tensorflow.python.ops.logging_ops.scalar_summary | 271 |
import tensorflow as tf
self._on_training_finish(sess)
except KeyboardInterrupt:
self._on_training_abort(sess)
def inference(self, max=10^6):
self.fetch_datasets()
self.build_ae_model()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# nut.print_... | tensorflow.Session | 272 |
import tensorflow as tf
block_v_size,
block_dim],
initializer=tf.uniform_unit_scaling_initializer())
hparams.bottleneck = functools.partial(
| tensorflow.uniform_unit_scaling_initializer | 273 |
import tensorflow as tf
'warmup_constant':warmup_constant,
}
def _norm(x, g=None, b=None, e=1e-5, axis=[1]):
u = tf.reduce_mean(x, axis=axis, keep_dims=True)
s = tf.reduce_mean(tf.square(x-u), axis=axis, keep_dims=True)
x = (x - u) * tf.rsqrt(s + e)
if g is not None and b is not None:
x = ... | tensorflow.rsqrt | 274 |
from tensorflow.python.framework import tensor_util
"""
with self._name_scope(name, values=[x]):
def make_dims(start_sum, size, name):
"""Closure to make dims range."""
start_sum = start_sum if start_sum else (
array_ops.zeros((), dtype=dtypes.int32, name="zero"),)
if ... | tensorflow.python.framework.tensor_util.constant_value | 275 |
import tensorflow as tf
"mean", [dim], tf.constant_initializer(0.), trainable=False)
step = variable_on_cpu("step", [], tf.constant_initializer(0.), trainable=False)
if scale:
gamma = variable_on_cpu("gamma", [dim], tf.constant_initializer(1.))
beta = variable_on_cpu... | tensorflow.stop_gradient | 276 |
import tensorflow as tf
TIMESERIES_INPUT_LAYER = 'rawdata'
TIMESERIES_COL = '{}_input'.format(TIMESERIES_INPUT_LAYER)
# In each sequence, column index 0 to N_INPUTS - 1 are features, and column index N_INPUTS to SEQ_LEN are labels
N_OUTPUTS = 1
N_INPUTS = SEQ_LEN - N_OUTPUTS
LSTM_SIZE = 3 # number of hidden layers in... | tensorflow.decode_csv | 277 |
import tensorflow as tf
def conv_3d_op(
self,
data,
weights,
strides,
symmetric_weights=False,
dilations=None):
"""3D convolutions for hgru."""
if dilations is None:
dilations = [1, 1, 1, 1, 1]
w_shape = [i... | tensorflow.get_default_graph | 278 |
import tensorflow as tf
argpar = tf.Variable(argpar_num, name="argpar", dtype=tf.float64)
m0 = tf.constant(m0_num, name="m0", dtype=tf.float64)
vdict['argpar'] = argpar
# RooArgusBG argus("argus","Argus PDF",mes,m0,argpar) ;
def argus_pdf(m, m0, c, p=0.5):
t = m / m0
u = 1 - t * t
argus_t_ge_1 = m * tf.... | tensorflow.pow | 279 |
import tensorflow as tf
return x
assert x.dense_shape is not None, "memory_saving_gradients encountered sparse gradients of unknown shape"
indices = x.indices
while indices.shape.ndims < x.values.shape.ndims:
indices = tf.expand_dims(indices, -1)
... | tensorflow.scatter_nd | 280 |
from tensorflow.contrib.learn.python.learn.estimators import run_config
self._export_dir_base = tempfile.mkdtemp() + "export/"
gfile.MkDir(self._export_dir_base)
def testFitAndEvaluateDontThrowException(self):
learner_config = learner_pb2.LearnerConfig()
learner_config.num_classes = 2
learner_co... | tensorflow.contrib.learn.python.learn.estimators.run_config.RunConfig | 281 |
from tensorflow.python.ops import variables
if device is not None:
with ops.device(device):
yield
else:
yield
def _setupDense(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]], dty... | tensorflow.python.ops.variables.Variable | 282 |
from tensorflow.contrib.learn.python.learn.estimators import test_data
'dummy_sparse_column', hash_bucket_size=100))
classifier = dnn_linear_combined.DNNLinearCombinedClassifier(
model_dir=tempfile.mkdtemp(),
linear_feature_columns=linear_features,
dnn_feature_columns=cont_feat... | tensorflow.contrib.learn.python.learn.estimators.test_data.prepare_iris_data_for_logistic_regression | 283 |
import tensorflow as tf
for i in range(len(self.grads_and_vars)):
self.grads.append(self.grads_and_vars[i][0]);
self.vars.append(self.grads_and_vars[i][1]);
self.grads=self.grads[-1*NUM_VARS:];
self.vars=self.vars[-1*NUM_VARS:];
self.train... | tensorflow.contrib.framework.get_global_step | 284 |
import tensorflow as tf
scale = tf.constant([2., 3., 4.])
concentration = tf.constant([2.] * batch_size)
pareto = tfd.Pareto(concentration, scale, validate_args=True)
with self.assertRaisesOpError("not in the support"):
x = tf.placeholder_with_default(input=[2., 3., 3.], shape=[3])
log_pro... | tensorflow.placeholder_with_default | 285 |
import tensorflow as tf
# TODO: move to ops
def _rank(x):
return len(x.get_shape())
def _apply_dropout_mask(tensor_shape, keep_prob=1.0, normalize=True):
random_tensor = keep_prob + tf.random_uniform(tensor_shape, dtype=tf.float32)
binary_mask = tf.floor(random_tensor)
if normalize:
binary_... | tensorflow.reciprocal | 286 |
import tensorflow as tf
optimizer = tf.train.GradientDescentOptimizer(self._lr)
self._train_op = optimizer.apply_gradients(
zip(grads, tvars),
global_step=tf.contrib.framework.get_or_create_global_step())
self._new_lr = tf.placeholder(
| tensorflow.contrib.framework.get_or_create_global_step | 287 |
import tensorflow as tf
self.mu = tf.layers.dense(l_a, num_action, tf.nn.tanh, kernel_initializer=w_init, name='mu') # estimated action value
self.sigma = tf.layers.dense(l_a, num_action, tf.nn.softplus, kernel_initializer=w_init, name='sigma') # estimated variance
# wr... | tensorflow.contrib.distributions.Normal | 288 |
import tensorflow as tf
tf.set_random_seed(93820985)
p = self._testParams()
mdl = p.Instantiate()
mdl.FPropDefaultTheta()
decoder_theta = mdl._MakeDecoderTheta(theta=mdl.theta, input_batch=None)
mdl.BProp()
self.assertEqual(decoder_theta, mdl.theta.decoder)
def testFProp(se... | tensorflow.set_random_seed | 289 |
import tensorflow as tf
#print(np.shape(up1))
up2 = common_deconv2d(up1,self.gf*4,name='up2') # 16x16 -> 32x32
up3 = common_deconv2d(up2,self.gf*2,name='up3') # 32x32 -> 64x64
up4 = common_deconv2d(up3,self.gf,name='up4') ... | tensorflow.contrib.layers.conv2d_transpose | 290 |
from tensorflow.contrib.metrics.python.ops import metric_ops
if weights is None:
return None
return math_ops.to_float(weights)
def _labels_streaming_mean(unused_predictions, labels, weights=None):
return metric_ops.streaming_mean(labels, weights=weights)
def _predictions_streaming_mean(predictio... | tensorflow.contrib.metrics.python.ops.metric_ops.streaming_mean | 291 |
import tensorflow as tf
pred1, pred2 = tf.split(pred, 2, axis=0)
tgt1, tgt2 = tf.split(tgt, 2, axis=0)
geq = tf.cast((tgt1 - tgt2) > 0, tf.bool)
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, pre... | tensorflow.reduce_mean | 292 |
import tensorflow as tf
# Apply the token-preprocessors.
if token_preprocess_fns is not None:
for token_preprocess_fn in token_preprocess_fns:
dataset = token_preprocess_fn(dataset, training)
if debug_print_examples:
def print_examples_and_shapes(x):
if np.random.uniform() < debug_print_exa... | tensorflow.size | 293 |
from tensorflow.python.layers import pooling as pooling_layers
k_height,
k_width,
d_height=2,
d_width=2,
mode='VALID',
input_layer=None,
num_channels_in=None):
"""Construct an average pooling layer."""
if input_layer is None:
... | tensorflow.python.layers.pooling.average_pooling2d | 294 |
import tensorflow as tf
policy = tfp.distributions.MultivariateNormalDiag(mean, tf.exp(logstd))
return NetworkOutput(policy, value, lambda a: tf.clip_by_value(a, -2., 2))
def clip_logits(logits, config):
logits_clip = getattr(config, "logits_clip", 0.)
if logits_clip > 0:
min_logit = tf.reduce_min(logi... | tensorflow.reduce_min | 295 |
from tensorflow.python.ops import math_ops
# "accuracy/threshold_0.500000_mean" metric for binary classification.
metrics = {("accuracy", "classes"): metrics_lib.streaming_accuracy}
predictions = math_ops.sigmoid(logits)
targets_float = math_ops.to_float(targets)
default_metrics = self._defau... | tensorflow.python.ops.math_ops.to_float | 296 |
import tensorflow as tf
Omega = tf.square(bounded - 1.0)
Omega = tf.reduce_sum(tf.reduce_mean(Omega, axis=1)) / (1.0 * tf.reduce_sum(nelems))
out = tf.gradients(Omega, self.W_rec)
out[0] = tf.Print(out[0], [out[0], self.W_rec, Omega], "omega grads")
out[0] = tf.verify_tensor_a... | tensorflow.verify_tensor_all_finite | 297 |
from tensorflow.contrib.learn.python.learn import ops
self.assertEqual(prediction.get_shape()[1], 2)
self.assertEqual(loss.get_shape(), [])
value = session.run(loss, {features: [[0.2, 0.3, 0.2]], labels: [[0, 1]]})
self.assertAllClose(value, 0.55180627)
def test_embedding_lookup(self):
d... | tensorflow.contrib.learn.python.learn.ops.embedding_lookup | 298 |
from tensorflow.contrib.slim.python.slim import queues
width = 280
with self.cached_session():
provider = dataset_data_provider.DatasetDataProvider(
_create_tfrecord_dataset(dataset_dir))
[image] = provider.get(['image'])
[label] = provider.get(['label'])
image = _resize_image(imag... | tensorflow.contrib.slim.python.slim.queues.QueueRunners | 299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.