seed stringlengths 59 2.16k | seed_api stringlengths 14 101 | index int64 0 523 |
|---|---|---|
import tensorflow as tf
if self.temperature is not None:
logits /= self.temperature
if self.tanh_constant is not None:
logits = self.tanh_constant * tf.tanh(logits)
index = tf.multinomial(logits, 1)
index = tf.to_int32(index)
| tensorflow.tanh | 100 |
import tensorflow as tf
for var in vars_list:
vname = var.name
from_name = vname
var_value = tf.contrib.framework.load_variable(MODEL_DIR, from_name)
assign_ops.append(tf.assign(var, var_value))
sess.run(assign_ops)
| tensorflow.contrib.framework.load_variable | 101 |
import tensorflow as tf
return default_params
def bilstm_layer(self, embeddings, nwords):
t = tf.transpose(embeddings, perm=[1, 0, 2])
lstm_cell_fw = tf.contrib.rnn.LSTMBlockFusedCell(self.params['lstm_size'])
lstm_cell_bw = tf.contrib.rnn.LSTMBlockFusedCell(self.params['lstm_size'... | tensorflow.contrib.rnn.TimeReversedFusedRNN | 102 |
import tensorflow as tf
p = tf.Variable(tf.zeros([1024, 1024]))
adds = [tf.assign_add(p, ones_t, use_locking=False)
| tensorflow.assign_add | 103 |
from tensorflow.contrib.framework.python.framework import checkpoint_utils
"""
results = self.evaluate(input_fn=input_fn, batch_size=batch_size,
steps=steps)
return np.sum(results[GMM.SCORES])
def weights(self):
"""Returns the cluster weights."""
return checkpoint_uti... | tensorflow.contrib.framework.python.framework.checkpoint_utils.load_variable | 104 |
import tensorflow as tf
return tf.nn.softmax(logits)
preds = GetWordPred(wvsum)
z = tf.tile(tf.reshape(tf.reduce_sum(preds,1),[-1,1]), [1, out_vocab_size])
self.preds, self.z = preds, z
self.probs = tf.div(preds, z) #normalize
self.unweighted_xent = _SafeXEnt(self.y, self.probs)
self._x... | tensorflow.div | 105 |
from tensorflow.python.ops import array_ops
# Accumulate the prediction to current confusion matrix.
current_cm = confusion_matrix_ops.confusion_matrix(
predictions, labels, num_classes, weights=weights, dtype=cm_dtype)
update_op = state_ops.assign_add(total_cm, current_cm)
def compute_mean_i... | tensorflow.python.ops.array_ops.diag_part | 106 |
from tensorflow.python.ops.control_flow_ops import with_dependencies
self._params)
incr_step = state_ops.assign_add(training_util.get_global_step(), 1)
loss = math_ops.reduce_sum(losses)
training_op = with_dependencies([training_op, incr_step], loss)
trainin... | tensorflow.python.ops.control_flow_ops.with_dependencies | 107 |
from tensorflow.python.ops import nn
def __init__(self,
alpha,
beta,
validate_args=False,
allow_nan_stats=True,
name="InverseGammaWithSoftplusAlphaBeta"):
parameters = locals()
parameters.pop("self")
with ops.name_scope(name, valu... | tensorflow.python.ops.nn.softplus | 108 |
import tensorflow as tf
shape_b: a list containing shape of the second tensor.
Returns:
Either a tf.no_op() when shapes are all static and a tf.assert_equal() op
when the shapes are dynamic.
Raises:
ValueError: When shapes are both static and unequal.
"""
if isinstance(shape_a[0], int) and is... | tensorflow.assert_equal | 109 |
import tensorflow as tf
sh = x.get_shape().as_list()
x = tf.reshape(x, [tf.reduce_prod(s[:-1]), sh[-1]])
| tensorflow.reduce_prod | 110 |
import tensorflow as tf
domain_predictions = tf.sigmoid(logits)
domain_loss = tf.losses.log_loss(domain_selection_mask, domain_predictions, weights=weight)
domain_accuracy = util.accuracy_tf(domain_selection_mask, tf.round(domain_predictions))
assert_op = tf.Assert(tf.is_finite(domain_loss), [domain_loss... | tensorflow.round | 111 |
import tensorflow as tf
elif kh == 6 and kw == 6:
return 36.0 * 7.0 / 256.0
elif kh == 7 and kw == 7:
return 49.0 * 21.0 / 1024.0
elif kh == 14 and kw == 14:
return 196.0 * 21.0 / 4096.0
else:
rec = tf.cast(kw * kh, tf.float32)
n_max = 7 + tf.math.ceil(tf.math.log(rec) / tf.math.log(2.))
... | tensorflow.argmin | 112 |
from tensorflow.python.framework import ops
else:
return []
def get_extra_inputs():
"""Returns the captured input tensors by the function.
Returns:
If the default graph is being used to define a function, the
returned list of tensors are those accessed inside the function body
but defined outs... | tensorflow.python.framework.ops.get_default_graph | 113 |
from tensorflow.python.ops import sparse_ops
expanded_shape = array_ops.concat(
0, (array_ops.slice(tensor.shape, [0], expand_dims), [1],
array_ops.slice(tensor.shape, expand_dims, [-1])),
name='expanded_shape')
expanded = sparse_ops.sparse_reshape(
tensor, shape... | tensorflow.python.ops.sparse_ops.sparse_concat | 114 |
import tensorflow as tf
st_serialized = tf.serialize_many_sparse(st)
| tensorflow.serialize_many_sparse | 115 |
import tensorflow as tf
logits /= self.temperature
if self.tanh_constant is not None:
logits = self.tanh_constant * tf.tanh(logits)
index = tf.multinomial(logits, 1)
index = tf.to_int32(index)
index = tf.reshape(index, [1])
| tensorflow.multinomial | 116 |
from tensorflow.python.summary import summary
if summ not in OPTIMIZER_SUMMARIES:
raise ValueError("Summaries should be one of [%s], you provided %s." %
(", ".join(OPTIMIZER_SUMMARIES), summ))
if learning_rate is not None and learning_rate_decay_fn is not None:
if... | tensorflow.python.summary.summary.scalar | 117 |
import tensorflow as tf
import tensorflow as tf
from tensorflow.python.framework import ops
ops.reset_default_graph()
# Create graph
sess = tf.Session()
# Create tensors
# Create data to feed in
x_vals = np.array([1., 3., 5., 7., 9.])
x_data = tf.placeholder(tf.float32)
m = tf.constant(3.)
# Multiplication
prod = ... | tensorflow.placeholder | 118 |
import tensorflow as tf
with tf.variable_scope("evaluation"):
accuracy_1 = tf.reduce_mean(tf.cast(tf.equal(
tf.argmax(output_1, axis=-1),
tf.argmax(y_1, axis=-1)), tf.float32), name="accuracy_1")
accuracy_2 = tf.reduce_mean(tf.cast(tf.equal(
tf.argmax(output_2, ... | tensorflow.divide | 119 |
import tensorflow.contrib.layers as layers
out = layers.convolution2d(out, num_outputs=64, kernel_size=3, stride=1, activation_fn=tf.nn.relu)
out = layers.flatten(out)
with tf.variable_scope("action_value"):
out = layers.fully_connected(out, num_outputs=512, activation_f... | tensorflow.contrib.layers.convolution2d | 120 |
from tensorflow.python.ops import array_ops
next_size = _next_array_size(new_size)
next_shape = array_ops.pack([next_size] + fixed_shape)
new_value = array_ops.zeros(next_shape, dtype=values.dtype)
old_value = array.value()
assign_op = state_ops.assign(array, new_value, validate_shape=Fal... | tensorflow.python.ops.array_ops.shape_internal | 121 |
from tensorflow.contrib.learn.python.learn.estimators import tensor_signature
return self._infer_model(x=x, batch_size=batch_size, proba=True)
def _check_inputs(self, features, targets):
if self._features_info is not None:
if not tensor_signature.tensors_compatible(features, self._features_info):
... | tensorflow.contrib.learn.python.learn.estimators.tensor_signature.tensors_compatible | 122 |
from tensorflow.contrib.learn.python.learn.estimators import test_data
bucketized_feature = feature_column.bucketized_column(
cont_feature, test_data.get_quantile_based_buckets(iris.data, 10))
| tensorflow.contrib.learn.python.learn.estimators.test_data.get_quantile_based_buckets | 123 |
import tensorflow as tf
internals = dict()
for name in sorted(self.internals_memory):
internals[name] = tf.gather(params=self.internals_memory[name], indices=indices)
actions = dict()
| tensorflow.gather | 124 |
from tensorflow.python.ops import state_ops
with ops.control_dependencies([v_diff]): # run v_diff operation before scatter_add
scaled_grad = scatter_add(vstar, indices, grad)
var_update = state_ops.assign_sub(var, lr_t * (scaled_grad + gold))
return control_flow_ops.group(*[var_u... | tensorflow.python.ops.state_ops.scatter_add | 125 |
import tensorflow as tf
eps: a constant to set upper or lower limit for labels, smoothening factor
name: Optional scope/name for op_scope.
Returns:
A tensor with the log loss.
"""
with tf.name_scope(name):
predictions.get_shape().assert_is_compatible_with(labels.get_shape())
prediction... | tensorflow.to_float | 126 |
import tensorflow as tf
####################################
# Utils
####################################
def _do_cutout(self, image, im_width, im_height, cutout_size):
mask = tf.ones([cutout_size, cutout_size], dtype=tf.int32)
start_x = tf.random.uniform(shape=(1,), minval=0, maxval=... | tensorflow.pad | 127 |
import tensorflow.contrib.graph_editor as ge
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, inclusive=False, within_ops=fwd_ops))
# check that there are not shortc... | tensorflow.contrib.graph_editor.get_forward_walk_ops | 128 |
from tensorflow.python.ops import math_ops
def _predictions_streaming_mean(predictions, unused_labels, weights=None):
return metric_ops.streaming_mean(predictions, weights=weights)
def _streaming_auc(predictions, labels, weights=None):
return metric_ops.streaming_auc(
predictions, labels, weights=_... | tensorflow.python.ops.math_ops.greater_equal | 129 |
import tensorflow as tf
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_labels, logits=logits))
Focal_loss = tf.reduce_mean(focal_loss(one_hot_labels, logits, alpha=0.5))
l2_loss = weight_decay * tf.add_n([tf.nn.l2_loss(v) for v in tf.trainable_variables()])
Center_loss, Centers = cente... | tensorflow.control_dependencies | 130 |
import tensorflow as tf
tf.float32)
h = tf.zeros([config.num_layers, self.batch_size, config.hidden_size],
tf.float32)
self._initial_state = (tf.contrib.rnn.LSTMStateTuple(h=h, c=c),)
outputs, h, c = self._cell(inputs, h, c, self._rnn_params, is_training)
outputs = tf.... | tensorflow.contrib.rnn.LSTMStateTuple | 131 |
from tensorflow.python.ops import array_ops
input_c = variables.Variable(
array_ops.ones([num_layers, batch_size, num_units]))
params = variables.Variable(
array_ops.ones([params_size_t]), validate_shape=False)
output, output_h, output_c = model(
is_training=... | tensorflow.python.ops.array_ops.ones | 132 |
import tensorflow as tf
tf_example = tf.train.Example(features=tf.train.Features(feature=features))
writer.write(tf_example.SerializeToString())
writer.close()
def file_based_input_fn_builder(input_file, seq_length, is_training,
drop_remainder):
"""Cre... | tensorflow.FixedLenFeature | 133 |
import tensorflow as tf
xent = -tf.reduce_sum(one_hot_spare_rep * tf.log(word_probs), axis=-1) # [batch_size, max_dec_steps]
| tensorflow.log | 134 |
import tensorflow as tf
def initialize_tf_vars(self):
"""Initialize all uninitialized variables in session."""
with tf.name_scope('initialize_tf_vars'):
uninited_set = [
e.decode()
for e in self.sess.run(tf.report_uninitialized_variables())
]... | tensorflow.report_uninitialized_variables | 135 |
import tensorflow as tf
order_m = tf.convert_to_tensor(value=order_m)
x = tf.convert_to_tensor(value=x)
pmm = _evaluate_legendre_polynomial_pmm_eval(order_m, x)
return tf.where(
tf.equal(degree_l, order_m), pmm,
_evaluate_legendre_polynomial_branch(degree_l, order_m, x, pmm))
def _spherical_harm... | tensorflow.abs | 136 |
import tensorflow as tf
Returns:
A namedtuple of input and target data.
"""
input_text = tf.map_fn(lambda x: x[:-1], chunk)
target_text = tf.map_fn(lambda x: x[1:], chunk)
return (input_text, target_text)
| tensorflow.map_fn | 137 |
from tensorflow.python.ops import math_ops
variance = sq_mean - math_ops.square(mean)
std = math_ops.sqrt(math_ops.maximum(epsilon, variance))
| tensorflow.python.ops.math_ops.maximum | 138 |
import tensorflow as tf
background_indicator = tf.logical_or(negative_matches, ignored_matches)
| tensorflow.logical_or | 139 |
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_preproces... | tensorflow.zeros_like | 140 |
from tensorflow.python.layers import pooling as pooling_layers
"""Construct a max pooling layer."""
if input_layer is None:
input_layer = self.top_layer
else:
self.top_size = num_channels_in
name = 'mpool' + str(self.counts['mpool'])
self.counts['mpool'] += 1
pool = pooling_layers.m... | tensorflow.python.layers.pooling.max_pooling2d | 141 |
import tensorflow as tf
def resnet_model_fn(inputs, training):
"""Our model_fn for ResNet to be used with our Estimator."""
network = resnet_model.imagenet_resnet_v2(
resnet_size=18, num_classes=class_num, mode='se', data_format=None)
inputs= network(inputs=inputs, is_training=training)
... | tensorflow.identity | 142 |
import tensorflow as tf
self.loss1 = tf.reduce_mean(tf.abs(self.Y_hat - self.Y))
self.loss2 = tf.reduce_mean(tf.abs(self.Z_hat - self.Z))
self.loss = self.loss1 + self.loss2
self.optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(self.loss)
# In[3]:
tf.reset_de... | tensorflow.InteractiveSession | 143 |
import tensorflow as tf
x = tf.zeros([1000000], dtype=np.float32)
y = tf.py_func(lambda x: x + 1, [x], [tf.float32])
| tensorflow.py_func | 144 |
import tensorflow as tf
"spm_model": self._args["spm_model"],
"languages": self._args["languages"],
"with_src_lang_tag": self._with_src_lang_tag,
"trg_lang_tag_position": self._trg_lang_tag_position,
}
def inputs_signature(self, mode):
""" Returns th... | tensorflow.TensorShape | 145 |
import tensorflow as tf
y0 = tf.to_int32(tf.floor(y))
y1 = y0 + 1
z0 = tf.to_int32(tf.floor(z))
z1 = z0 + 1
x0_clip = tf.clip_by_value(x0, zero, max_x)
x1_clip = tf.clip_by_value(x1, zero, max_x)
y0_clip = tf.clip_by_value(y0, zero, max_y)
y1_clip = tf.clip_by_value(y1,... | tensorflow.clip_by_value | 146 |
import tensorflow as tf
)
# Extract current batch size (in case this is a partial batch).
cur_batch_size = dynamic_image_shape[0]
# Get static shape of image.
# shape = (3,)
static_image_shape = params["generator_projection_dims"]
pr... | tensorflow.mod | 147 |
import tensorflow as tf
class batch_norm(object):
def __init__(self, epsilon=1e-5, momentum = 0.9, name="batch_norm"):
with tf.variable_scope(name):
self.epsilon = epsilon
self.momentum = momentum
self.name = name
def __call__(self, x):
return tf.contrib.l... | tensorflow.contrib.layers.batch_norm | 148 |
import tensorflow as tf
# layers
self.value_estimate = tf.layers.dense(self.state, 1, kernel_initializer=w_init, name='v') # estimated value for state
# loss and optimizer
self.loss = tf.squared_difference(self.value_estimate, self.target)
self.optimizer = ... | tensorflow.squared_difference | 149 |
from tensorflow.python.ops import gen_resource_variable_ops
@property
def op(self):
return self.get().op
def _read_variable_op(self):
if _enclosing_tpu_context() is None:
return self._primary_var.read_value()
v = gen_resource_variable_ops.read_variable_op(self.handle, self._dtype)
return ... | tensorflow.python.ops.gen_resource_variable_ops.read_variable_op | 150 |
import tensorflow as tf
items: the list of items to decode. These must be a subset of the item
keys in self._items_to_handlers. If `items` is left as None, then all
of the items in self._items_to_handlers are decoded.
Returns:
the decoded items, a list of tensor.
"""
conte... | tensorflow.parse_single_sequence_example | 151 |
from tensorflow.contrib import metrics as metrics_lib
predictions = math_ops.sigmoid(logits)
result["eval_auc"] = metrics_lib.streaming_auc(predictions, targets)
| tensorflow.contrib.metrics.streaming_auc | 152 |
from tensorflow.python.ops import variables
def _BenchmarkOp(self, op, desc):
burn_in_steps = 10
benchmark_steps = 40
with session.Session() as sess:
sess.run(variables.global_variables_initializer())
for i in xrange(burn_in_steps + benchmark_steps):
if i == burn_in_steps:
... | tensorflow.python.ops.variables.global_variables_initializer | 153 |
import tensorflow as tf
Z2 = tf.matmul(Z, A[:,:,n_basis//2:,:])/tf.sqrt(n_basis*.5)
# Compute u_{h+1} and v_{h+1}
U, V = tf.cos(Z1)+tf.cos(Z2), tf.sin(Z1)+tf.sin(Z2)
Z = tf.concat([U, V], 3)/tf.sqrt(n_out*1.)
KL += tf.reduce_mean(alpha_std**2+alpha_mean**2-2*... | tensorflow.sqrt | 154 |
import tensorflow as tf
# Global step
with tf.variable_scope('training_step', reuse=tf.AUTO_REUSE):
global_step = tf.get_variable("global_step", [],
dtype=tf.int32,
initializer=tf.consta... | tensorflow.contrib.layers.l1_l2_regularizer | 155 |
from tensorflow.contrib.layers.python.layers import utils
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,... | tensorflow.contrib.layers.python.layers.utils.constant_value | 156 |
import tensorflow as tf
# 0 <= z < depth, 0 <= y < height & 0 <= x < width.
max_z = tf.to_int32(tf.shape(im)[1] - 1)
max_y = tf.to_int32(tf.shape(im)[2] - 1)
max_x = tf.to_int32(tf.shape(im)[3] - 1)
# Converts scale indices from [-1, 1] to [0, width/height/depth].
x = (x + 1.0) * (... | tensorflow.floor | 157 |
from tensorflow.contrib.slim.python.slim.data import test_utils
data_sources = test_utils.create_tfrecord_files(tmpdir, num_files=1)
| tensorflow.contrib.slim.python.slim.data.test_utils.create_tfrecord_files | 158 |
import tensorflow as tf
return tf.random_normal_initializer(0.0, params.initializer_gain)
elif params.initializer == "normal_unit_scaling":
return tf.variance_scaling_initializer(params.initializer_gain,
mode="fan_avg",
... | tensorflow.variance_scaling_initializer | 159 |
import tensorflow as tf
self.lm_scaling = tf.get_variable("lm_scaling", [], initializer=tf.constant_initializer(1.0))
flattened_lm_emb = tf.reshape(lm_emb, [num_sentences * max_sentence_length * lm_emb_size, lm_num_layers])
flattened_aggregated_lm_emb = tf.matmul(flattened_lm_emb, tf.expand_dims(self.lm_... | tensorflow.sequence_mask | 160 |
from tensorflow.contrib.learn.python.learn.datasets import base
linear_optimizer=ftrl.FtrlOptimizer(learning_rate=0.1),
dnn_feature_columns=(cont_feature,),
dnn_hidden_units=(3, 3),
dnn_optimizer=adagrad.AdagradOptimizer(learning_rate=0.1))
input_fn = test_data.iris_input_logistic_... | tensorflow.contrib.learn.python.learn.datasets.base.load_iris | 161 |
from tensorflow.python.ops import array_ops
# term from the formula above.
# `relevant_precision_per_k` (float64) - Relevant precisions; i.e.,
# precisions at all k for which relevance indicator is true.
relevant_per_k = _sparse_true_positive_at_k(
predictions_idx_per_k, labels_per_k, n... | tensorflow.python.ops.array_ops.ones_like | 162 |
from tensorflow.python.framework import function
self._testGraphExtensionRestore()
def testStrippedOpListDef(self):
with self.test_session():
# Creates a graph.
v0 = tf.Variable(0.0)
var = tf.Variable(10.0)
tf.add(v0, var)
@function.Defun(x=tf.float32)
def minus_one(x):
... | tensorflow.python.framework.function.Defun | 163 |
import tensorflow as tf
if self._is_training:
self._train_op = tf.get_collection_ref("train_op")[0]
self._lr = tf.get_collection_ref("lr")[0]
self._new_lr = tf.get_collection_ref("new_lr")[0]
self._lr_update = tf.get_collection_ref("lr_update")[0]
rnn_params = tf.get_collection_ref("r... | tensorflow.contrib.cudnn_rnn.RNNParamsSaveable | 164 |
from tensorflow.python.ops import math_ops
array_ops.tile(array_ops.transpose(predictions_2d), [num_thresholds, 1]),
thresh_tiled)
pred_is_neg = math_ops.logical_not(pred_is_pos)
# Tile labels by number of thresholds
label_is_pos = array_ops.tile(labels_2d, [num_thresholds, 1])
label_is_neg = math... | tensorflow.python.ops.math_ops.logical_not | 165 |
from tensorflow.python.framework import ops
name: A name for the operation (optional).
Returns:
A Tensor with the same type as `x` if `x.dtype != qint32`
otherwise the return type is `quint8`.
"""
with ops.op_scope([x], name, "Sigmoid") as name:
x = ops.convert_to_tensor(x, name="x")
retur... | tensorflow.python.framework.ops.op_scope | 166 |
from tensorflow.python.training import adagrad
input_fn=_input_fn, steps=100)
self._assertSingleClassMetrics(metrics)
def benchmarkCustomOptimizer(self):
iris = test_data.prepare_iris_data_for_logistic_regression()
cont_feature = feature_column.real_valued_column('feature', dimension=4)
buck... | tensorflow.python.training.adagrad.AdagradOptimizer | 167 |
import tensorflow as tf
# tf.matrix_diag(tf.trace(tf.matmul(Li_eKuffu_Lit, cov))) +
tf.einsum("ig,nij,jh->ngh", q_mu, Li_eKuffu_Lit, q_mu) -
# tf.matmul(q_mu, tf.matmul(Li_eKuffu_Lit, q_mu), transpose_a=True) -
fmean[:, :, None] * fmean[:, None, :] +
... | tensorflow.einsum | 168 |
import tensorflow as tf
dtype=tf.float32,
initializer=tf.constant_initializer(0),
trainable=False)
label = tf.reshape(label, [-1])
centers_batch = tf.gather(centers, label)
diff = (1 - alpha) * (centers_batch - features)
centers = tf.scatter_sub(centers, label, diff)
loss = ... | tensorflow.scatter_sub | 169 |
import tensorflow as tf
np.random.seed(127)
num_elements = 10000
batch_size = 64
indices_batch = np.random.randint(
batch_size, size=num_elements, dtype=np.int64)
indices_value = np.arange(num_elements, dtype=np.int64)
indices = np.asarray(
sorted(zip(indices_batch, indices_valu... | tensorflow.SparseTensor | 170 |
import tensorflow as tf
labels = tf.random_uniform(
[batch_size],
minval=1,
maxval=nclass,
dtype=tf.int32,
name='synthetic_labels')
# Note: This results in a H2D copy, but no computation
# Note: This avoids recomputation of the random values, but still
# ... | tensorflow.contrib.framework.local_variable | 171 |
import tensorflow as tf
x_t_len = tf.strings.length(x_t)
x_t = tf.string_split([x_t], delimiter='').values
z_t = tf.gather(y, m)
z_t_len = tf.strings.length(z_t)
z_t = tf.string_split([z_t], delimiter='').values
for i in ... | tensorflow.string_join | 172 |
from tensorflow.python.framework import ops
ops.register_tensor_conversion_function(ReplicatedVariable, _tensor_conversion)
if not TF_23:
ops.register_dense_tensor_like_type(ReplicatedVariable)
| tensorflow.python.framework.ops.register_dense_tensor_like_type | 173 |
from tensorflow.python.training import server_lib
"worker": ["localhost:%s" % port1],
"ps": ["localhost:%s" % port2]
})
worker = server_lib.Server(cs, job_name="worker", start=True)
ps = server_lib.Server(cs, job_name="ps", start=True)
return worker, ps
@contextlib.contextmanager
| tensorflow.python.training.server_lib.Server | 174 |
import tensorflow as tf
def bilstm_layer(self, embeddings, nwords):
t = tf.transpose(embeddings, perm=[1, 0, 2])
lstm_cell_fw = tf.contrib.rnn.LSTMBlockFusedCell(self.params['lstm_size'])
lstm_cell_bw = tf.contrib.rnn.LSTMBlockFusedCell(self.params['lstm_size'])
lstm_cell_bw = tf.c... | tensorflow.contrib.rnn.LSTMBlockFusedCell | 175 |
from tensorflow.python.framework import ops
Raises:
ValueError: if k is invalid.
"""
if k < 1:
raise ValueError('Invalid k=%s.' % k)
with ops.name_scope(
None, 'average_precision', (predictions, labels, k)) as scope:
# Calculate top k indices to produce [D1, ... DN, k] tensor.
_, predict... | tensorflow.python.framework.ops.name_scope | 176 |
import tensorflow as tf
weights[CLUSTER_CENTROIDS].assign(
weights[CLUSTERING_IMPL].cluster_centroids
)
# Insert clustering variables
weights[PULLING_INDICES].assign(tf.dtypes.cast(
weights[CLUSTERING_IMPL].get_pulling_indices(
weights[ORIGI... | tensorflow.multiply | 177 |
import tensorflow as tf
with tf.Session("", graph=tf.Graph()) as sess:
one = tf.Variable(1.0)
twos = tf.Variable([2.0, 2.0, 2.0])
init = tf.initialize_all_variables()
save = tf.train.Saver(tf.all_variables())
init.run()
save.save(sess, save_path)
| tensorflow.all_variables | 178 |
from tensorflow.python.ops import gen_math_ops
#
# Could return ops.convert_to_tensor(x, dtype=dtype, ...) here, but that
# allows some conversions that cast() can't do, e.g. casting numbers to
# strings.
x = ops.convert_to_tensor(x, name="x")
if x.dtype.base_dtype == dtype:
... | tensorflow.python.ops.gen_math_ops.cast | 179 |
from tensorflow.python.ops import gradients_impl
output, output_h, output_c = model(
is_training=True,
input_data=input_data,
input_h=input_h,
input_c=input_c,
params=params)
all_grads = gradients_impl.gradients(
[output, output_h,... | tensorflow.python.ops.gradients_impl.gradients | 180 |
import tensorflow as tf
y0_f = tf.to_float(y0)
y1_f = tf.to_float(y1)
z0_f = tf.to_float(z0)
z1_f = tf.to_float(z1)
# Check the out-of-boundary case.
x0_valid = tf.to_float(
tf.less_equal(x0, max_x) & tf.greater_equal(x0, 0))
x1_valid = tf.to_float(
tf.less... | tensorflow.less_equal | 181 |
from tensorflow.python.training import server_lib
s.bind(("", 0))
port = s.getsockname()[1]
s.close()
return port
port1 = get_open_port()
port2 = get_open_port()
cs = server_lib.ClusterSpec({
"worker": ["localhost:%s" % port1],
"ps": ["localhost:%s" % port2]
})
... | tensorflow.python.training.server_lib.ClusterSpec | 182 |
from tensorflow.contrib import metrics as contrib_metrics
"eval_loss": loss,
}
elif task_name == "sts-b":
def metric_fn(per_example_loss, label_ids, logits, is_real_example):
"""Compute Pearson correlations for STS-B."""
# Display labels and predictions
... | tensorflow.contrib.metrics.streaming_concat | 183 |
import tensorflow as tf
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` ... | tensorflow.tensordot | 184 |
import tensorflow as tf
A tensor of shape (vec_dim)
"""
if reduction_mode == 'max':
print('USING MAX POOLING FOR REDUCTION!')
vecs_reduced = tf.segment_max(vecs, segment_inds)
elif reduction_mode == 'mean':
print('USING AVG POOLING FOR REDUCTION!')
vecs_reduced = tf.... | tensorflow.segment_mean | 185 |
import tensorflow as tf
zip(grads, tvars),
global_step=tf.train.get_or_create_global_step())
self._new_lr = tf.placeholder(
tf.float32, shape=[], name='new_learning_rate')
self._lr_update = tf.assign(self._lr, self._new_lr)
self.save... | tensorflow.contrib.rnn.BasicLSTMCell | 186 |
import tensorflow as tf
# if encoder.convolution_activation.lower() == 'relu':
encoder_inputs_ = tf.nn.relu(encoder_inputs_)
if encoder.maxout_stride:
if encoder.binary:
raise NotImplementedError
stride = encoder.maxout_s... | tensorflow.ceil | 187 |
from tensorflow.python.ops import control_flow_ops
# return value needs to be the same dtype as no_op() for cond
with ops.control_dependencies([copy_op]):
return control_flow_ops.no_op()
new_size = size + batch_size
array_size = array_ops.shape_internal(array, optimize=False)[0]
maybe_... | tensorflow.python.ops.control_flow_ops.cond | 188 |
import tensorflow as tf
e_mean_Kuf = tf.reshape(e_mean_Kuf, [num_data, num_func, num_ind])
e_fmean_mean = tf.einsum("nqm,mz->nqz", e_mean_Kuf, Lit_q_mu) # N x D x D
e_related_to_mean = e_fmean_mean + tf.matrix_transpose(e_fmean_mean) + e_mean_mean
| tensorflow.matrix_transpose | 189 |
import tensorflow as tf
vx = tf.contrib.lookup.MutableHashTable(key_dtype=tf.string,
value_dtype=tf.int64,
default_value=-1)
vz = tf.contrib.lookup.MutableHashTable(key_dtyp... | tensorflow.contrib.lookup.MutableHashTable | 190 |
import tensorflow as tf
# 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)
output = facts * tf.expand_dims(alphas, -1)
output = tf.reshape(output, tf.shape(facts))
# output = output / (facts.get_shape().as... | tensorflow.concat | 191 |
from tensorflow.python.ops import math_ops
tuple.
"""
predictions, labels = tensor_util.remove_squeezable_dimensions(
predictions, labels)
predictions.get_shape().assert_is_compatible_with(labels.get_shape())
squared_error = math_ops.square(labels - predictions)
return streaming_mean(squared_erro... | tensorflow.python.ops.math_ops.square | 192 |
import tensorflow as tf
def _get_lstm_cell(self, config, is_training):
if config.rnn_mode == BASIC:
return tf.contrib.rnn.BasicLSTMCell(
config.hidden_size, forget_bias=0.0, state_is_tuple=True,
reuse=not is_training)
if config.rnn_mode == BLOCK:
return tf.contrib.rnn.LSTMBloc... | tensorflow.contrib.rnn.LSTMBlockCell | 193 |
import tensorflow as tf
_err_log = "SubpixelConv2d: The number of input channels == (scale x scale) x The number of output channels"
if n_out_channels >= 1:
if int(X.get_shape()[-1]) != (r**2) * n_out_channels:
raise Exception(_err_log)
# bsize, a, b, c = X.get... | tensorflow.depth_to_space | 194 |
from tensorflow.python.ops import math_ops
mean = moving_average("mean", log_norm, decay)
sq_mean = moving_average("sq_mean", math_ops.square(log_norm), decay)
variance = sq_mean - math_ops.square(mean)
std = math_ops.sqrt(math_ops.maximum(epsilon, variance))
max_norms = math_ops.exp(mean + std_fa... | tensorflow.python.ops.math_ops.exp | 195 |
from tensorflow.python.lib.io import file_io
model_name = "vgg19BNReLUmodel.h5"
model.save(model_name)
with file_io.FileIO(model_name, mode='rb') as input_f:
with file_io.FileIO("gs://deeplearningteam11/" + model_name, mode='w+') as output_f:
output_f.write(input_f.r... | tensorflow.python.lib.io.file_io.FileIO | 196 |
import tensorflow.contrib as contrib
scope="dropout2_2")
fc3_1 = contrib.layers.fully_connected(dropout2_1, 32, scope="fc3_1")
fc3_2 = contrib.layers.fully_connected(dropout2_2, 32, scope="fc3_2")
if cross_stitch_enabled:
... | tensorflow.contrib.layers.dropout | 197 |
import tensorflow as tf
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_observat... | tensorflow.check_numerics | 198 |
from tensorflow.python.framework import tensor_shape
logits, labels, name=name)
return cost
@ops.RegisterShape("SparseSoftmaxCrossEntropyWithLogits")
def _SparseSoftmaxCrossEntropyWithLogitsShape(op):
"""Shape function for SparseSoftmaxCrossEntropyWithLogits op."""
logits_shape = op.inputs[0].get_shape()... | tensorflow.python.framework.tensor_shape.vector | 199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.