seed stringlengths 59 2.16k | seed_api stringlengths 14 101 | index int64 0 523 |
|---|---|---|
import tensorflow as tf
utils.add_activation_summary(relu7)
relu_dropout7 = tf.nn.dropout(relu7, keep_prob=keep_prob)
W8 = utils.weight_variable([1, 1, 4096, NUM_OF_CLASSESS], name="W8")
b8 = utils.bias_variable([NUM_OF_CLASSESS], name="b8")
conv8 = utils.conv2d_basic(relu_... | tensorflow.shape | 0 |
from tensorflow.contrib.layers.python.layers import utils
if layer.use_bias:
_add_variable_to_collections(layer.bias, variables_collections, 'biases')
if normalizer_fn is not None:
normalizer_params = normalizer_params or {}
outputs = normalizer_fn(outputs, **normal... | tensorflow.contrib.layers.python.layers.utils.collect_named_outputs | 1 |
from tensorflow.contrib.metrics.python.ops import confusion_matrix_ops
# Accumulate the prediction to current confusion matrix.
current_cm = confusion_matrix_ops.confusion_matrix(
| tensorflow.contrib.metrics.python.ops.confusion_matrix_ops.confusion_matrix | 2 |
import tensorflow.contrib.graph_editor as ge
op._set_device(origin_op.node_def.device)
copied_ops = info._transformed_ops.values()
debug_print("Copied %s to %s", ops_to_copy, copied_ops)
ge.reroute_ts(checkpoints_disconnected_other, checkpoints_other, can_modify=copied_ops)
... | tensorflow.contrib.graph_editor.reroute_ts | 3 |
import tensorflow as tf
self.grads_and_vars, global_step=tf.contrib.framework.get_global_step())
def predict(self, state, sess=None):
sess = sess or tf.get_default_session()
state=featurize_state(state);
return sess.run(self.action, { self.state: [state]... | tensorflow.get_default_session | 4 |
from tensorflow.python.ops import control_flow_ops
# Create slots for the global solution.
for v in var_list:
self._zeros_slot(v, "vstar", self._name)
self._zeros_slot(v, "gold", self._name)
def _apply_dense(self, grad, var):
lr_t = math_ops.cast(self._lr_t, var.dty... | tensorflow.python.ops.control_flow_ops.group | 5 |
import tensorflow as tf
print('\ntranspose(D)=')
print(sess.run(tf.transpose(D)))
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)... | tensorflow.self_adjoint_eig | 6 |
import tensorflow as tf
if activation == 'linear':
cell_basic = tf.contrib.rnn.BasicRNNCell(state_size,activation=tf.identity)
| tensorflow.contrib.rnn.BasicRNNCell | 7 |
import tensorflow as tf
sess.run(train_op)
def testGraphExtension(self):
self._testGraphExtensionSave()
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... | tensorflow.add | 8 |
import tensorflow as tf
expected_cross_terms - np.outer(expected_terms, expected_terms),
self._numpy_dtype)
]
def output_tensor_infos(self):
return [
analyzer_nodes.TensorInfo(
tf.as_dtype(self._numpy_dtype), self._output_shape, None)
]
@common.log_api_use(c... | tensorflow.as_dtype | 9 |
from tensorflow.python.ops import math_ops
where digamma(alpha) is the digamma function.""")
def _entropy(self):
return (self.alpha +
math_ops.log(self.beta) +
math_ops.lgamma(self.alpha) -
(1. + self.alpha) * math_ops.digamma(self.alpha))
@distribution_util.AppendDo... | tensorflow.python.ops.math_ops.lgamma | 10 |
from tensorflow.python.framework import ops
if max_size is None:
batch_size = values_size
else:
batch_size = math_ops.minimum(values_size, max_size - size)
perm = [axis] + [n for n in range(ndim) if n != axis]
batch_values = array_ops.transpose(values, perm)[:batch_size]
def reallocat... | tensorflow.python.framework.ops.control_dependencies | 11 |
from tensorflow.python.ops import array_ops
labels_2d = array_ops.reshape(
math_ops.cast(labels, dtype=dtypes.bool), [1, -1])
# Use static shape if known.
num_predictions = predictions_2d.get_shape().as_list()[0]
# Otherwise use dynamic shape.
if num_predictions is None:
num_predictions = array_o... | tensorflow.python.ops.array_ops.transpose | 12 |
from tensorflow.python.framework import ops
grad_values = grad.values * multiplier
grad = ops.IndexedSlices(grad_values, grad.indices, grad.dense_shape)
| tensorflow.python.framework.ops.IndexedSlices | 13 |
from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib
eval_metric_ops = {
GMM.SCORES: _streaming_sum(loss),
}
return model_fn_lib.ModelFnOps(mode=mode, predictions=predictions,
eval_metric_ops=eval_metric_ops,
... | tensorflow.contrib.learn.python.learn.estimators.model_fn.ModelFnOps | 14 |
import tensorflow as tf
algo.optimize_policy()
sampler.update_goals()
"""
with self.sess.as_default() as sess:
# initialize uninitialized vars (only initialize vars that were not loaded)
uninit_vars = [var for var in tf.global_variables() if not... | tensorflow.variables_initializer | 15 |
from tensorflow.python.client import timeline
lossval = 0.
train_time = time.time() - start_time
step_train_times.append(train_time)
if step >= 0 and (step == 0 or (step + 1) % FLAGS.display_every == 0):
log_fn('%i\t%s\t%.3f' % (
step + 1, get_perf_timing_str(batch_size, step_train_times),
... | tensorflow.python.client.timeline.Timeline | 16 |
from tensorflow.python.ops import array_ops
with ops.device(None):
if all(tensor.shape == tensor_shape.scalar() for tensor in tensors):
with ops.device(tensors[0].device):
values = array_ops.stack(tensors)
with ops.device(device):
return array_ops.unstack(values)
else:
... | tensorflow.python.ops.array_ops.split | 17 |
from tensorflow.python.ops import clip_ops
if "gradient_norm" in summaries:
summary.scalar("gradient_norm/%s" % var_name,
clip_ops.global_norm([grad_values]))
| tensorflow.python.ops.clip_ops.global_norm | 18 |
import tensorflow as tf
fmean ** 2 +
tf.matrix_diag_part(e_related_to_mean)
| tensorflow.matrix_diag_part | 19 |
import tensorflow as tf
input_size_ = input_size if layer == 0 else 2 * num_units
gru_fw = tf.contrib.rnn.GRUCell(num_units)
| tensorflow.contrib.rnn.GRUCell | 20 |
import tensorflow as tf
input_image = np.concatenate([image, mask], axis=2)
sess_config = tf.ConfigProto()
sess_config.gpu_options.allow_growth = True
with tf.Session(config=sess_config) as sess:
input_image = tf.constant(input_image, dtype=tf.float32)
output = model.build_server_graph... | tensorflow.reverse | 21 |
import tensorflow as tf
# What are the average Q values of the original tasks?
if batch_size == num_tasks:
indices = tf.transpose(tf.stack([orig_indices, orig_indices], axis=0))
orig_q_vals = tf.gather_nd(logits_vec, indices)
tf.compat.v2.summary.scalar(
name="orig_q_va... | tensorflow.gather_nd | 22 |
from tensorflow.python.training import training_ops
rate to use.
use_locking: If True use locks for update operations.
name: Optional name prefix for the operations created when applying
gradients. Defaults to "GradientDescent".
"""
super(GradientDescentOptimizer, self).__init__(use... | tensorflow.python.training.training_ops.apply_gradient_descent | 23 |
import tensorflow as tf
mapping_strings = self.load_tag_data()
reverse_vocab_tags = tf.contrib.lookup.index_to_string_table_from_tensor(
mapping_strings, name=name
)
pred_strings = reverse_vocab_tags.lookup(tf.to_int64(pred_ids))
return pred_strings
def id2wor... | tensorflow.to_int64 | 24 |
import tensorflow as tf
e.g. for retarining set the epoch number you want to resume training from
summary_every: int, epoch interval to write summary; higher value means lower frequency
of summary writing
"""
with tf.Graph().as_default(), tf.device('/gpu:0'):
self._setup_m... | tensorflow.device | 25 |
import tensorflow as tf
mask = tf.equal(mask, tf.ones_like(mask))
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]
# Activation
if softmax_stag:
scores = tf.nn.so... | tensorflow.matmul | 26 |
from tensorflow.contrib import layers
parent_scope = "dnn"
input_layer_partitioner = (partitioned_variables.min_max_variable_partitioner(
max_partitions=num_ps_replicas, min_slice_size=64 << 20))
input_layer_scope = parent_scope + "/input_from_feature_columns"
with variable_scope.variable_scope(
i... | tensorflow.contrib.layers.input_from_feature_columns | 27 |
from tensorflow.python.ops import math_ops
grad = ops.IndexedSlices(grad_values, grad.indices, grad.dense_shape)
else:
grad *= math_ops.cast(multiplier, grad.dtype)
multiplied_grads_and_vars.append((grad, var))
| tensorflow.python.ops.math_ops.cast | 28 |
import tensorflow as tf
1. full_cov: True and full_output_cov: True
fvar N x P x N x P
2. full_cov: True and full_output_cov: False
fvar P x N x N
3. full_cov: False and full_output_cov: True
fvar N x P x P
4. full_cov: False and full_output_cov: False
fvar N x P
"""
... | tensorflow.matrix_diag | 29 |
import tensorflow as tf
Args:
matrices: A list of Tensors with shape [..., N_i, M_i] (i.e. a list of
matrices with the same batch dimension).
dtype: Data type to use. The Tensors in `matrices` must match this dtype.
Returns:
A matrix with the input matrices stacked along its main diag... | tensorflow.Dimension | 30 |
import tensorflow as tf
(distance_kernel + '_b_initializer'), None),
name=distance_kernel_kwargs.get((distance_kernel + '_name'),
'MatchingSigmoid'))
return compute_l2_sigmoid_matching_distances
if distance_kernel == common.DISTANCE_KE... | tensorflow.split | 31 |
from tensorflow.python.ops import array_ops
with ops.name_scope(
None, 'average_precision', (predictions, labels, k)) as scope:
# Calculate top k indices to produce [D1, ... DN, k] tensor.
_, predictions_idx = nn.top_k(predictions, k)
predictions_idx = math_ops.to_int64(predictions_idx, name='predi... | tensorflow.python.ops.array_ops.expand_dims | 32 |
from tensorflow.contrib import losses
with ops.control_dependencies([check_shape_op]):
target = array_ops.reshape(
target, shape=[array_ops.shape(target)[0], 1])
return losses.hinge_loss(logits, target)
super(_BinarySvmTargetColumn, self).__init__(
| tensorflow.contrib.losses.hinge_loss | 33 |
from tensorflow.contrib.slim.python.slim.data import dataset
dtype=dtypes.int64,
default_value=array_ops.zeros(
[1], dtype=dtypes.int64))
}
items_to_handlers = {
'image': tfexample_decoder.Image(),
'label': tfexample_decoder.Tensor('image/class/label'),
... | tensorflow.contrib.slim.python.slim.data.dataset.Dataset | 34 |
import tensorflow as tf
# hss(s): eta * (\varphi(s)^T * K^T * \Sigma^{-1} * K * \varphi(s))
varphisKt = tf.matmul(varphis, Kt)
hss = param_eta * tf.reduce_sum(tf.matmul(varphisKt, prec) * varphisKt, axis=1)
Haa = param_eta * prec + Waa
# Haa = 0.5 * (Haa + TT.transpose(Haa))
... | tensorflow.matrix_inverse | 35 |
import tensorflow as tf
with tf.variable_scope(scope):
if self._max_diffusion_step == 0:
pass
else:
for support in self._supports:
x1 = tf.sparse_tensor_dense_matmul(support, x0)
x = self._concat(x, x1)
... | tensorflow.sparse_tensor_dense_matmul | 36 |
import tensorflow as tf
data_format=data_format,
weights_initializer=trunc_normal(0.01),
scope=scope + '/self_gating/transformer_W')
tile_multiples = [1, t, w, h]
tile_multiples.insert(index_c, 1)
weights = tf.tile(weights, tile_multiples)
weights = tf.nn.sigmoid(weights)
return tf.multip... | tensorflow.tile | 37 |
from tensorflow.python.ops import array_ops
x = self._assert_valid_sample(x, check_integer=True)
return x * math_ops.log(self.rate) - math_ops.lgamma(x + 1)
def _mean(self):
return array_ops.identity(self.rate)
def _variance(self):
return array_ops.identity(self.rate)
@distribution_util.Append... | tensorflow.python.ops.array_ops.identity | 38 |
import tensorflow as tf
Returns:
A tuple of possible batch sizes
"""
for device in device_lib.list_local_devices():
if tf.DeviceSpec.from_string(device.name).device_type == "GPU":
if "K20" in device.physical_device_desc:
return (16,)
if "P100" in device.physical... | tensorflow.DeviceSpec.from_string | 39 |
from tensorflow.python.ops import parsing_ops
return self._target_column.logits_to_predictions(logits, proba=True)
def _get_feature_ops_from_example(self, examples_batch):
column_types = layers.create_feature_spec_for_parsing((
self._get_linear_feature_columns() or []) + (
self._get_dnn_... | tensorflow.python.ops.parsing_ops.parse_example | 40 |
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(den... | tensorflow.python.ops.math_ops.truediv | 41 |
from tensorflow.python.framework import ops
def _calc_conv_weight_params(graph, node):
"""Calculates the on-disk size of the weights for Conv2D."""
input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0])
input_shape.assert_is_fully_defined()
filter_shape = graph_util.tensor_shape_from_no... | tensorflow.python.framework.ops.OpStats | 42 |
import tensorflow as tf
for i in range (dim):
dg_i = tf.gradients(flat_grads[i], par) #for each element of grads evaluate the gradients
dg_i_flat = flatten(dg_i) #flatten the resulting hessian onto a 1 d array
hess.append(dg_i_flat) #store row by row
| tensorflow.gradients | 43 |
import tensorflow as tf
self.retrieve_indices = tf.make_template(
| tensorflow.make_template | 44 |
from tensorflow.python.training import device_setter
# Create a run configuration
self._config = BaseEstimator._Config()
# Set device function depending if there are replicas or not.
if self._config.num_ps_replicas > 0:
ps_ops = ['Variable', 'AutoReloadVariable']
self._device_fn = device_s... | tensorflow.python.training.device_setter.replica_device_setter | 45 |
from tensorflow.python.ops import init_ops
"""Gated recurrent unit (GRU) with nunits cells."""
if self._gate_linear is None:
bias_ones = self._bias_initializer
if self._bias_initializer is None:
bias_ones = init_ops.constant_initializer(1.0, dtype=inputs.dtype)
with vs.variable_scope(... | tensorflow.python.ops.init_ops.constant_initializer | 46 |
import tensorflow as tf
max_axis = tf.reduce_max(target, axis, keep_dims=True)
target_exp = tf.exp(target - max_axis)
| tensorflow.exp | 47 |
import tensorflow as tf
initial_output = initial_state[:, -cell_output_size:]
time = tf.constant(0, dtype=tf.int32, name='time')
outputs = tf.TensorArray(dtype=tf.float32, size=time_steps)
samples = tf.TensorArray(dtype=tf.int64, size=time_steps)
inputs = tf.TensorArray(dtype=tf.int64, size=ti... | tensorflow.TensorArray | 48 |
from tensorflow.python.ops import check_ops
if x_value_static < 0:
raise ValueError("%s.value=%d cannot be negative" %
(x.name, x_value_static))
return x
if self.validate_args:
x = control_flow_ops.with_dependencies([
check_ops.assert_rank(x, 0),
... | tensorflow.python.ops.check_ops.assert_rank | 49 |
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.maximum | 50 |
import tensorflow as tf
for matrix in matrices:
matrix_shape = tf.shape(matrix)
row_before_length = current_column
current_column += matrix_shape[-1]
row_after_length = ret_columns - current_column
row_blocks.append(tf.pad(
tensor=matrix,
paddings=tf.... | tensorflow.rank | 51 |
from tensorflow.python.ops import variable_scope as vs
def _adaptive_max_norm(norm, std_factor, decay, global_step, epsilon, name):
"""Find max_norm given norm and previous average."""
with vs.variable_scope(name, "AdaptiveMaxNorm", [norm]):
log_norm = math_ops.log(norm + epsilon)
| tensorflow.python.ops.variable_scope.variable_scope | 52 |
import tensorflow as tf
gru_fw, gru_bw = self.grus[layer]
init_fw, init_bw = self.inits[layer]
mask_fw, mask_bw = self.dropout_mask[layer]
with tf.variable_scope("fw_{}".format(layer)):
out_fw, _ = tf.nn.dynamic_rnn(
... | tensorflow.reverse_sequence | 53 |
import tensorflow as tf
class TranslateDistillProblem(TranslateProblem):
"""Base class for translation problems."""
def is_generate_per_split(self):
return True
def example_reading_spec(self):
data_fields = {"dist_targets": tf.VarLenFeature(tf.int64)}
if self.has_inputs:
data_fields["inputs... | tensorflow.VarLenFeature | 54 |
import tensorflow as tf
# Calculate L1 Distance
distance = tf.reduce_sum(tf.abs(tf.add(xtr, tf.negative(xte))),
reduction_indices=1)
# Prediction: Get min distance index (Nearest neighbor)
pred = tf.arg_min(distance, 0)
accuracy = 0.
| tensorflow.arg_min | 55 |
from tensorflow.python.ops import array_ops
denominator: A scalar `float64` `Tensor`.
name: Name for the returned op.
Returns:
0 if `denominator` == 0, else `numerator` / `denominator`
"""
numerator.get_shape().with_rank_at_most(1)
denominator.get_shape().with_rank_at_most(1)
return control_flow... | tensorflow.python.ops.array_ops.constant | 56 |
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 ... | tensorflow.scalar_mul | 57 |
from tensorflow.contrib.slim.python.slim.data import dataset_data_provider
'tfrecord_dataset'))
height = 300
width = 280
with self.cached_session():
test_dataset = _create_tfrecord_dataset(dataset_dir)
provider = dataset_data_provider.Dat... | tensorflow.contrib.slim.python.slim.data.dataset_data_provider.DatasetDataProvider | 58 |
import tensorflow as tf
# The names are different and will work.
tf.train.Saver({"vee1": v1, "other": [v2]})
def testBasicsWithListOfVariables(self):
save_path = os.path.join(self.get_temp_dir(), "basics_with_list")
with self.test_session(graph=tf.Graph()) as sess:
# Build a graph with 2 ... | tensorflow.Graph | 59 |
import tensorflow.contrib.slim as slim
with tf.Graph().as_default() as graph, tf.device('/cpu:0'):
num_gpu = len(cfgs.GPU_GROUP.strip().split(','))
global_step = slim.get_or_create_global_step()
lr = self.warmup_lr(cfgs.LR, global_step, cfgs.WARM_SETP, num_gpu)
... | tensorflow.contrib.slim.get_or_create_global_step | 60 |
import tensorflow as tf
hparams["kwargs"]["clip_value_max"])
with self.test_session() as sess:
sess.run(tf.global_variables_initializer())
gn_grads_, gn_grads_true_, v_grads_, v_grads_true_ = sess.run(
[gn_grads, gn_grads_true, v_... | tensorflow.contrib.framework.is_tensor | 61 |
from tensorflow.python.framework import dtypes
`uint8` to leave the input as `[0, 255]`, or `float32` to rescale into
`[0, 1]`.
"""
dtype = dtypes.as_dtype(dtype).base_dtype
if dtype not in (dtypes.uint8, dtypes.float32):
raise TypeError('Invalid image dtype %r, expected uint8 or float32' %
| tensorflow.python.framework.dtypes.as_dtype | 62 |
import tensorflow as tf
return h
def minibatch_discrimination(x, n_kernels, dim_per_kernel, name):
with tf.variable_scope(name):
batch_size, nf = x.get_shape().as_list()
h = linear(x, [nf, n_kernels*dim_per_kernel], 'h1')
activation = tf.reshape(h, (batch_size, n_kernels, dim_per_k... | tensorflow.reshape | 63 |
import tensorflow as tf
# Calculate output indices when strides > 1.
blk_indices_crop = tf.strided_slice(blk_indices, [0, 0, 0, 0], [
| tensorflow.strided_slice | 64 |
import tensorflow as tf
# The two terms 'term1' and 'term2' which come from normalizers of the
# 1. Original policy distribution
# 2. The distribution after completing the square
sigma = tf.matrix_inverse(prec)
term1 = -0.5 * param_eta * tf.log(tf.matrix_determinant(2 * np.pi *... | tensorflow.matrix_determinant | 65 |
import tensorflow as tf
return hparams
def _terminate_eval():
tf.logging.info('Timeout passed with no new checkpoints ... terminating eval')
return True
def _get_next_checkpoint():
return tf.contrib.training.checkpoints_iterator(
FLAGS.model_dir,
timeout=FLAGS.eval_timeout,
timeout_fn=_te... | tensorflow.contrib.training.checkpoints_iterator | 66 |
from tensorflow.python.ops import init_ops
clipped_gradients, _ = clip_ops.clip_by_global_norm(gradients, clip_gradients)
return list(zip(clipped_gradients, variables))
def _adaptive_max_norm(norm, std_factor, decay, global_step, epsilon, name):
"""Find max_norm given norm and previous average."""
with vs.va... | tensorflow.python.ops.init_ops.zeros_initializer | 67 |
from tensorflow.contrib.layers.python.ops import sparse_feature_cross_op
cross_dense = sparse_ops.sparse_tensor_to_dense(cross)
with session.Session():
values = cross_dense.eval()
self.assertTrue(numpy.equal(values[0], values[1]).all())
def test_hashed_output_v2_has_no_collision(self):
"""Te... | tensorflow.contrib.layers.python.ops.sparse_feature_cross_op.sparse_feature_cross | 68 |
from tensorflow.python.ops import data_flow_ops
nrof_preprocess_threads = 4
image_size = (args.image_size, args.image_size)
eval_input_queue = data_flow_ops.FIFOQueue(capacity=2000000,
dtypes=[tf.string, tf.int32, tf.int32],
| tensorflow.python.ops.data_flow_ops.FIFOQueue | 69 |
from tensorflow.python.ops import array_ops
raise ValueError('Invalid k=%s.' % k)
with ops.name_scope(None, 'num_relevant', (labels,)) as scope:
# For SparseTensor, calculate separate count for each row.
if isinstance(labels, (ops.SparseTensor, ops.SparseTensorValue)):
labels_sizes = set_ops.set_si... | tensorflow.python.ops.array_ops.fill | 70 |
from tensorflow.python.ops import logging_ops
logit = layers.legacy_fully_connected(
net,
self._num_label_columns(),
weight_collections=[self._dnn_weight_collection],
bias_collections=[self._dnn_weight_collection],
name="dnn_logit")
self._add_hidden_layer_summary(logit, ... | tensorflow.python.ops.logging_ops.histogram_summary | 71 |
from tensorflow.contrib.distributions.python.ops import distribution_util
@distribution_util.AppendDocstring(_poisson_sample_note)
def _log_cdf(self, x):
return math_ops.log(self.cdf(x))
@distribution_util.AppendDocstring(_poisson_sample_note)
def _cdf(self, x):
x = self._assert_valid_sample(x, check... | tensorflow.contrib.distributions.python.ops.distribution_util.AppendDocstring | 72 |
import tensorflow as tf
"""Returns dict of variables to restore from ImageNet-checkpoint."""
vars_to_restore_imagenet = {}
ckpt_var_names = tf.contrib.framework.list_variables(imagenet_ckpt)
ckpt_var_names = [name for (name, unused_shape) in ckpt_var_names]
| tensorflow.contrib.framework.list_variables | 73 |
import tensorflow as tf
# applying maxnorm constraints easier
rel_embedding_shape = [rel_cnt, self.embedding_size * self.embedding_size]
entity_init = tf.truncated_normal(entity_embedding_shape, stddev=init_sd)
rel_init = tf.truncated_normal(rel_embedding_shape, stddev=init_sd)
| tensorflow.truncated_normal | 74 |
import tensorflow as tf
# where m(x) is the mean_function and \mu(x) is fmean
e_mean_mean = expectation(pXnew, mean_function, mean_function) # N x D x D
Lit_q_mu = tf.matrix_triangular_solve(Luu, q_mu, adjoint=True)
e_mean_Kuf = expectation(pXnew, mean_function, (kern, feat)) # N x D ... | tensorflow.trace | 75 |
from tensorflow.python.ops import math_ops
random_tensor += random_ops.random_uniform(
noise_shape, seed=seed, dtype=x.dtype)
# 0. if [keep_prob, 1.0) and 1. if [1.0, 1.0 + keep_prob)
binary_tensor = math_ops.floor(random_tensor)
ret = x * math_ops.inv(keep_prob) * binary_tensor
ret.set_sha... | tensorflow.python.ops.math_ops.inv | 76 |
import tensorflow as tf
# rep_map_dp = dropout(rep_map, keep_prob, is_train)
bn = block_num
bl = block_len
with tf.variable_scope('self_attention'):
# @2.self-attention in block
# mask generation
sl_indices = tf.range(block_len, dtype=tf.... | tensorflow.meshgrid | 77 |
from tensorflow.python.ops import random_ops
def parameterized_vs_naive(shape, num_iters, use_gpu=False):
np.random.seed(1618) # Make it reproducible.
# No CSE/CF.
optimizer_options = tf.OptimizerOptions(opt_level=tf.OptimizerOptions.L0)
config = tf.ConfigProto(
graph_options=tf.GraphOptions(optimizer_... | tensorflow.python.ops.random_ops.truncated_normal | 78 |
from tensorflow.python.ops import nn_ops
self.W_h = W_h
encoder_features = nn_ops.conv2d(encoder_features, W_h, [1, 1, 1, 1], "SAME") # [batch_size, passage_len, 1, attention_vec_size]
| tensorflow.python.ops.nn_ops.conv2d | 79 |
import tensorflow as tf
with tf.variable_scope(scope):
init_w = tf.random_normal_initializer(0., 0.01)
| tensorflow.random_normal_initializer | 80 |
from tensorflow.python.training import ftrl
model_dir=tempfile.mkdtemp(),
linear_feature_columns=(bucketized_feature,),
linear_optimizer=ftrl.FtrlOptimizer(learning_rate=0.1),
dnn_feature_columns=(cont_feature,),
| tensorflow.python.training.ftrl.FtrlOptimizer | 81 |
import tensorflow as tf
st_serialized = tf.serialize_many_sparse(st)
st_deserialized = tf.deserialize_many_sparse(
st_serialized, dtype=values.dtype)
| tensorflow.deserialize_many_sparse | 82 |
import tensorflow as tf
tf.summary.histogram('advantage', adv)
tf.summary.histogram('action_probability', self.mu_ph)
if tf_util.is_image(self.observation_space):
tf.summary.image('observation', train_model.obs_ph)
... | tensorflow.group | 83 |
from tensorflow.python.client import session
expected_out = self._sparse_tensor([[83]])
with self.test_session() as sess:
self._assert_sparse_tensor_equals(expected_out, sess.run(op))
def test_hashed_output_v1_has_collision(self):
"""Tests the old version of the fingerprint concatenation has colli... | tensorflow.python.client.session.Session | 84 |
import tensorflow as tf
# 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(... | tensorflow.random_normal | 85 |
import tensorflow as tf
else:
filter_shape = [k_size, k_size] + [in_channel, out_dims]
if w_init is None:
w_init = tf.contrib.layers.variance_scaling_initializer()
if b_init is None:
b_init = tf.constant_initializer()
w =... | tensorflow.get_variable | 86 |
from tensorflow.contrib.learn.python.learn.estimators import composable_model
self._linear_model = composable_model.LinearComposableModel(
num_label_columns=target_column.num_label_columns,
optimizer=linear_optimizer,
gradient_clip_norm=gradient_clip_norm,
num_ps_replicas=num_ps_rep... | tensorflow.contrib.learn.python.learn.estimators.composable_model.DNNComposableModel | 87 |
from tensorflow.contrib.layers.python.layers import feature_column
constant_op.constant(
iris.target, dtype=dtypes.int32), (-1, 1))
return features, labels
iris = test_data.prepare_iris_data_for_logistic_regression()
cont_features = [
feature_column.real_valued_column(str... | tensorflow.contrib.layers.python.layers.feature_column.sparse_column_with_hash_bucket | 88 |
import tensorflow as tf
tf.logging.info("Total trainable variables size: %d", total_size)
learning_rate = get_learning_rate_decay(params.learning_rate,
global_step, params)
learning_rate = tf.convert_to_tensor(learning_rate, dtype=tf.float32)
... | tensorflow.contrib.layers.optimize_loss | 89 |
import tensorflow as tf
shape = x.get_shape().as_list()
with tf.variable_scope(name):
beta = tf.get_variable('beta', [shape[-1]], initializer=tf.constant_initializer(0.))
gamma = tf.get_variable('gamma', [shape[-1]], initializer=tf.random_normal_initializer(1., 0.02))
pop_mean = tf.get_... | tensorflow.moving_average_variables | 90 |
import tensorflow as tf
self.pool3 = tf.layers.max_pooling2d(self.conv3, 2, 2)
self.conv4 = tf.layers.conv2d(self.pool3,
self.config.cifar10_cnn["num_filters"],
self.config.cifar10_cnn["filter_siz... | tensorflow.contrib.framework.arg_scope | 91 |
from tensorflow.python.training import gradient_descent
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... | tensorflow.python.training.gradient_descent.GradientDescentOptimizer | 92 |
import tensorflow as tf
self.assertFalse(has_nan_or_inf.eval())
self.assertEqual(1.0, grad_scale.eval())
# The final gradient must be finite.
self.assertFalse(tf.is_nan(final_var_grads.a[1]).eval())
self.assertTrue(tf.is_finite(final_var_grads.a[1]).eval())
| tensorflow.is_nan | 93 |
from tensorflow.contrib.learn.python.learn import ops
def test_categorical_variable(self):
random_seed.set_random_seed(42)
with self.cached_session() as sess:
cat_var_idx = array_ops.placeholder(dtypes.int64, [2, 2])
embeddings = ops.categorical_variable(
cat_var_idx, n_classes=5, embe... | tensorflow.contrib.learn.python.learn.ops.categorical_variable | 94 |
import tensorflow as tf
num_func = tf.shape(q_mu)[1] # output dimension (D)
q_sqrt_r = tf.matrix_band_part(q_sqrt, -1, 0) # D x M x M
eKuf = tf.transpose(expectation(pXnew, (kern, feat))) # M x N (psi1)
if Luu is None:
Kuu = feat.Kuu(kern, jitter=settings.numerics.jitter_level) # M x M
... | tensorflow.matrix_triangular_solve | 95 |
from tensorflow.contrib.learn.python.learn.estimators import tensor_signature
def _check_inputs(self, features, targets):
if self._features_info is not None:
if not tensor_signature.tensors_compatible(features, self._features_info):
raise ValueError('Features are incompatible with given informatio... | tensorflow.contrib.learn.python.learn.estimators.tensor_signature.create_signatures | 96 |
from tensorflow.python.ops import partitioned_variables
max_partitions=num_ps_replicas, min_slice_size=64 << 20))
input_layer_scope = parent_scope + "/input_from_feature_columns"
with variable_scope.variable_scope(
input_layer_scope,
values=list(six.itervalues(features)),
partitioner=input_... | tensorflow.python.ops.partitioned_variables.min_max_variable_partitioner | 97 |
import tensorflow as tf
trainable: If `True`, the default, also adds the variable to the graph
collection `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as
the default list of variables to use by the `Optimizer` classes.
dual_rate_factor: A floating point value or `Tensor`. The learning r... | tensorflow.contrib.framework.model_variable | 98 |
from tensorflow.contrib import layers
def default_input_fn(unused_estimator, examples):
return layers.parse_feature_columns_from_examples(examples,
| tensorflow.contrib.layers.parse_feature_columns_from_examples | 99 |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 6