seed stringlengths 25 1.88k | seed_api stringlengths 14 102 | index int64 0 1.05k |
|---|---|---|
import tensorflow as tf
return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)
# Calculate loss, which includes softmax cross entropy and L2 regularization.
cross_entropy = tf.cond(n_positives > 0., lambda: tf.losses.sparse_softmax_cross_entropy(labels=glabels, logits=cls_pred), lambda:... | tensorflow.losses.sparse_softmax_cross_entropy | 100 |
import tensorflow as tf
'zero_debias_moving_mean': True,
'fused': fused_batch_norm,
}
inputs.get_shape().assert_has_rank(2)
if log(final_size, 2) != int(log(final_size, 2)):
raise ValueError('`final_size` (%i) must be a power of 2.' % final_size)
if final_size < 8:
raise ValueError('`final... | tensorflow.compat.v1.variable_scope | 101 |
from tensorflow.compat.v1 import ConfigProto, InteractiveSession
import pickle
from tensorflow.compat.v1 import ConfigProto, InteractiveSession
import tensorflow as tf
from speech_utils.ACRNN.tf.model_utils import train
config = ConfigProto(log_device_placement=True)
config.gpu_options.allow_growth = True
session =... | tensorflow.compat.v1.ConfigProto | 102 |
import tensorflow as tf
entropy_bottleneck = EntropyBottleneck()
conditional_entropy_model = SymmetricConditional()
checkpoint = tf.train.Checkpoint(analysis_transform=analysis_transform,
hyper_encoder=hyper_encoder,
hyper_decoder=hy... | tensorflow.train.Checkpoint | 103 |
from tensorflow.python.ops import array_ops
b_grads = b_module.bspmm(a_indices, a_values, a_shape, grad, adjoint_a=True, adjoint_b=False)
bg_row=tf.shape(b_grads[0])[0]
bg_col=tf.shape(b_grads[0])[1]
b_grads = tf.reshape(b_grads, (numTensors * bg_row, bg_col))
if adj_b:
b_grads = [array_ops.transpos... | tensorflow.python.ops.array_ops.gather | 104 |
from tensorflow.python.ops import check_ops
`log_prob(x)`. If `validate_args` is `False` and the inputs are
invalid, correct behavior is not guaranteed.
allow_nan_stats: `Boolean`, default `True`. If `False`, raise an
exception if a statistic (e.g. mean/mode/etc...) is undefined for any... | tensorflow.python.ops.check_ops.assert_positive | 105 |
import tensorflow as tf
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=tf.parse_single_example(serialized_e... | tensorflow.decode_raw | 106 |
import tensorflow as tf
def batch_norm(x, train, name, decay=0.99, epsilon=1e-5):
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.rand... | tensorflow.moving_average_variables | 107 |
from tensorflow.contrib.framework.python.ops import variables as contrib_variables
def begin(self):
self._last_step = None
self._global_step_tensor = contrib_variables.get_global_step()
for m in self._monitors:
| tensorflow.contrib.framework.python.ops.variables.get_global_step | 108 |
import tensorflow as tf
actor.add_grad_to_graph(critic.a_grads)
M = Memory(MEMORY_CAPACITY)
saver = tf.train.Saver(max_to_keep=100)
if LOAD_MODEL:
all_ckpt = tf.train.get_checkpoint_state('./data', 'checkpoint').all_model_checkpoint_paths
saver.restore(sess, all_ckpt[-1])
else:
if os.path.isdir(DATA_PAT... | tensorflow.summary.FileWriter | 109 |
from tensorflow.python.ops import control_flow_ops
[cell() for _ in range(num_layers)])
outputs, final_state = core_rnn.static_rnn(
multi_cell, inputs, dtype=dtypes.float32)
trainable_variables = ops.get_collection(
ops.GraphKeys.TRAINABLE_VARIABLES)
gradient... | tensorflow.python.ops.control_flow_ops.group | 110 |
import tensorflow as tf
if not no_moving_average:
moving_mean = self._make_var('moving_mean', (in_ch,), trainable=False, init_constant=0)
moving_variance = self._make_var('moving_variance', (in_ch,), trainable=False, init_constant=1)
if is_train:
... | tensorflow.nn.fused_batch_norm | 111 |
from tensorflow.python.framework import ops
with ops.name_scope(
name, 'expand_and_tile', (tensor, multiple, dim)) as scope:
# Sparse.
if isinstance(tensor, ops.SparseTensorValue):
tensor = ops.SparseTensor.from_value(tensor)
if isinstance(tensor, ops.SparseTensor):
if dim < 0:
... | tensorflow.python.framework.ops.SparseTensor.from_value | 112 |
import tensorflow as tf
# run_config = tf.estimator.RunConfig(
# experimental_distribute=tf.contrib.distribute.DistributeConfig(
# train_distribute=distribution,
# remote_cluster={
# 'worker': ['localhost:5000', 'localhost:5001... | tensorflow.distribute.experimental.MultiWorkerMirroredStrategy | 113 |
from tensorflow.python.estimator.canned import head as head_lib
regressor.export(self._export_dir_base)
def testRankingDontThrowExceptionForForEstimator(self):
learner_config = learner_pb2.LearnerConfig()
learner_config.num_classes = 2
learner_config.constraints.max_tree_depth = 1
model_dir = te... | tensorflow.python.estimator.canned.head._binary_logistic_head_with_sigmoid_cross_entropy_loss | 114 |
from tensorflow.python.framework import ops
Raises:
TypeError: If `x` cannot be cast to the `bfloat16`.
"""
return cast(x, types.bfloat16, name=name)
ops.Tensor._override_operator("__neg__", neg)
ops.Tensor._override_operator("__abs__", abs)
# __invert__ corresponds to the ~ operator. Here we follow the ... | tensorflow.python.framework.ops.Tensor._override_operator | 115 |
import tensorflow as tf
self.dataset = datasets.FlowersData(FLAGS.data_dir)
else:
raise ValueError('Unknown dataset. Must be one of imagenet or flowers.')
self.local_parameter_device_flag = FLAGS.local_parameter_device
if self.job_name:
self.task_index = FLAGS.task_index
self... | tensorflow.train.ClusterSpec | 116 |
import tensorflow as tf
))
assignments.append(tf.scatter_update(ref=self.terminal_memory, indices=indices, updates=terminal))
assignments.append(tf.scatter_update(ref=self.reward_memory, indices=indices, updates=reward))
# Add episode indices.
with tf.control_de... | tensorflow.assign_add | 117 |
import tensorflow as tf
self.initialize_tf_vars()
logger.log(self.sess.graph)
self.has_setup = True
self.setup_args = SimpleNamespace(
sampler_cls=sampler_cls, sampler_args=sampler_args)
def initialize_tf_vars(self):
"""Initialize all uninitialized variables i... | tensorflow.report_uninitialized_variables | 118 |
import tensorflow as tf
fname = os.path.join(tf.resource_loader.get_data_files_path(),
'samples/configs/' + model_name + '.config')
label_map_path = os.path.join(tf.resource_loader.get_data_files_path(),
'data/pet_label_map.pbtxt')
data_path = os.path.jo... | tensorflow.resource_loader.get_data_files_path | 119 |
import tensorflow as tf
loss = tf.maximum(0., (tgt_larg - tgt_small) - (pred_larg - pred_small))
if hard_ratio < 1.0:
hard_num = tf.cast(tools.shape(pred1)[0] * hard_ratio, tf.int32)
loss = tf.reshape(loss, [-1])
hard_loss, _ = tf.math.top_k(loss, k=hard_num)
return hard_loss
... | tensorflow.math.top_k | 120 |
import tensorflow as tf
def get_valid_batch(image,label,batch_size):
images,labels=tf.train.batch([image,label],batch_size=batch_size)
| tensorflow.train.batch | 121 |
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_io... | tensorflow.python.ops.array_ops.diag_part | 122 |
from tensorflow.contrib.layers.python.layers import feature_column_ops
def _get_linear_feature_columns(self):
if not self._linear_feature_columns:
return None
feature_column_ops.check_feature_columns(self._linear_feature_columns)
return sorted(set(self._linear_feature_columns), key=lambda x: x.key... | tensorflow.contrib.layers.python.layers.feature_column_ops.check_feature_columns | 123 |
import tensorflow as tf
self.saver = tf.train.Saver(tf.global_variables())
def _get_lstm_cell(self, config, is_training):
if config.rnn_mode == BASIC:
return tf.contrib.rnn.BasicLSTMCell(
config.hidden_size, forget_bias=0., state_is_tuple=True,
reuse... | tensorflow.contrib.rnn.LSTMBlockCell | 124 |
from tensorflow.core.protobuf import queue_runner_pb2
tf.initialize_all_variables()
# Creates a saver.
save = tf.train.Saver({"v0": v0})
# Adds a set of collections.
tf.add_to_collection("int_collection", 3)
tf.add_to_collection("float_collection", 3.5)
tf.add_to_collection("s... | tensorflow.core.protobuf.queue_runner_pb2.QueueRunnerDef | 125 |
import tensorflow as tf
for key, value in zip(act_values_dict.keys(), act_values):
act_values_dict[key] += value
summary = tf.Summary()
current_global_step = sess.run(global_step)
| tensorflow.Summary | 126 |
from tensorflow.python.ops import math_ops
```
entropy = alpha - log(beta) + log(Gamma(alpha))
+ (1-alpha)digamma(alpha)
```
where digamma(alpha) is the digamma function.""")
def _entropy(self):
return (self.alpha +
math_ops.log(self.beta) +
math_ops.lgamma... | tensorflow.python.ops.math_ops.digamma | 127 |
import tensorflow as tf
# make some fake noise
data_size = 100
noise_tensor = tf.random_normal((data_size, INPUT_DIM))
real_data_tensor = tf.random_uniform((data_size, OUTPUT_DIM))
dataset = tf.data.Dataset.from_tensor_slices((noise_tensor, real_data_tensor))
dataset = dataset.repeat().shuffle... | tensorflow.data.Dataset.from_tensor_slices | 128 |
from tensorflow.python.ops import math_ops
`values`, or if either `metrics_collections` or `updates_collections` are
not a list or tuple.
"""
is_below_threshold = math_ops.to_float(math_ops.less(values, threshold))
return streaming_mean(is_below_threshold, _mask_weights(ignore_mask, weights),
... | tensorflow.python.ops.math_ops.less | 129 |
import tensorflow as tf
assert size[0] % 2 == 1 and size[1] % 2 == 1, "REFLECTION PAD ONLY WORKING FOR ODD FILTER SIZE.. " + str(size)
pad_x = size[0] // 2
pad_y = size[1] // 2
input = tf.pad(input, [[0, 0], [pad_x, pad_x], [pad_y, pad_y], [0, 0]], "REFLECT")
... | tensorflow.layers.conv2d | 130 |
import tensorflow as tf
self.yp1 = tf.argmax(tf.reduce_max(outer, axis=2), axis=1)
self.yp2 = tf.argmax(tf.reduce_max(outer, axis=1), axis=1)
losses = tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=logits1, labels=self.y1)
losses2 = tf.nn.sparse_s... | tensorflow.contrib.layers.apply_regularization | 131 |
from tensorflow.contrib.eager.python.examples.revnet import config as config_
for grad, var in zip(grads, vars_):
if grad is not None:
self.assertEqual(grad.shape, var.shape)
def test_training_graph(self):
"""Test model training in graph mode."""
with tf.Graph().as_default():
... | tensorflow.contrib.eager.python.examples.revnet.config.get_hparams_cifar_38 | 132 |
import tensorflow as tf
for path in paths:
spectrograms.append(np.load("spectrogram/" + path + ".npy"))
if spectrograms[-1].shape[0] > max_x:
max_x = spectrograms[-1].shape[0]
return spectrograms, max_x
# In[4]:
tf.reset_default_graph()
sess = tf.InteractiveSession()
model = Mod... | tensorflow.InteractiveSession | 133 |
from tensorflow.python.ops import gen_nn_ops
type `tf.float32`.
ksize: A list of ints that has length >= 4. The size of the window for
each dimension of the input tensor.
strides: A list of ints that has length >= 4. The stride of the sliding
window for each dimension of the input tensor.
... | tensorflow.python.ops.gen_nn_ops._max_pool | 134 |
import tensorflow as tf
round(FLAGS.train_batch_size * FLAGS.target_train_batch_multiplier))
finetune_data = tfds.load(name=FLAGS.target_dataset, split='train')
finetune_data = finetune_data.shuffle(512).repeat().batch(
target_train_batch_size)
target_val_batch_size = int(
round(FL... | tensorflow.data.Dataset.zip | 135 |
from tensorflow.python.ops import math_ops
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_ops.logical_not(label_is_pos)
true_positives = _create_local('true_positives... | tensorflow.python.ops.math_ops.logical_and | 136 |
from tensorflow.python.ops import gen_math_ops
TypeError: If `x` cannot be cast to the `dtype`.
"""
with ops.op_scope([x], name, "Cast") as name:
if isinstance(x, ops.SparseTensor):
values_cast = cast(x.values, dtype, name=name)
return ops.SparseTensor(x.indices, values_cast, x.shape)
else:... | tensorflow.python.ops.gen_math_ops.cast | 137 |
import tensorflow as tf
Args:
private_samples: a tensor of shape [num_samples, num_features].
shared_samples: a tensor of shape [num_samples, num_features].
weight: the weight of the incoherence loss.
name: the name of the tf summary.
"""
with tf.name_scope(name):
private_samples -= tf.reduc... | tensorflow.nn.l2_normalize | 138 |
import tensorflow as tf
initializer=tf.constant_initializer(0),
trainable=False)
with tf.colocate_with(self.means):
self.ema_means = tf.get_variable(
| tensorflow.colocate_with | 139 |
import tensorflow.contrib.slim as slim
def get_gtboxes_and_label(self, gtboxes_and_label_h, gtboxes_and_label_r, num_objects):
return gtboxes_and_label_h[:int(num_objects), :].astype(np.float32), \
gtboxes_and_label_r[:int(num_objects), :].astype(np.float32)
def main(self):
with... | tensorflow.contrib.slim.get_or_create_global_step | 140 |
import tensorflow as tf
)
)
'''
with tf.train.MonitoredTrainingSession(
checkpoint_dir=params.output, hooks=train_hooks,
save_checkpoint_secs=None, config=config) as sess:
while not sess.should_stop():
| tensorflow.train.MonitoredTrainingSession | 141 |
import tensorflow as tf
if not white:
q_mu = tf.matrix_triangular_solve(Luu, q_mu, lower=True)
Luu_tiled = tf.tile(Luu[None, :, :], [num_func, 1, 1]) # remove line once issue 216 is fixed
q_sqrt_r = tf.matrix_triangular_solve(Luu_tiled, q_sqrt_r, lower=True)
Li_eKuf = tf.matrix_trian... | tensorflow.matrix_triangular_solve | 142 |
import tensorflow as tf
self.epsilon = epsilon
self.axis = axis
self.center=center
self.scale=scale
with tf.variable_scope(name) as scope:
with tf.variable_scope('bn') :
self.gamma= tf.get_variable('gamma',[dims], initializer=tf.constant_initializer(1... | tensorflow.layers.batch_normalization | 143 |
import tensorflow as tf
# use the TPU version of RunConfig
config = tf.contrib.tpu.RunConfig(
| tensorflow.contrib.tpu.RunConfig | 144 |
import tensorflow as tf
objectives.append((Objective(name, contra_loss, min, include, exclude)))
elif name == 'reward' and config.r_loss == 'l2':
pred = heads[name](features)
l2_loss = tf.compat.v1.losses.mean_squared_error(target[name], pred)
# l2_loss = tf.nn.l... | tensorflow.compat.v1.losses.mean_squared_error | 145 |
import tensorflow as tf
tf.reshape(byte, shape=[]), 3, **JPEG_OPT)
image = resize_shortest_edge(image, jpeg_shape, 224)
image = center_crop(image, 224)
return image
image = tf.cond(is_bad, bad, good)
# TODO other imgproc
image = lighting(imag... | tensorflow.image.random_flip_left_right | 146 |
import tensorflow as tf
else:
fvar = (
(eKff - tf.trace(Li_eKuffu_Lit))[:, None] +
tf.einsum("nij,dji->nd", Li_eKuffu_Lit, cov) +
tf.einsum("ig,nij,jg->ng", q_mu, Li_eKuffu_Lit, q_mu) -
fmean ** 2 +
tf.matrix_diag_part(e_relate... | tensorflow.matrix_diag_part | 147 |
from tensorflow.python.ops import variable_scope
@contextlib.contextmanager
def as_default(self):
yield
def create_eager_var_store():
if context.in_eager_mode():
return variable_scope.EagerVariableStore()
else:
return DummyVariableStore()
def scheduled_sampling(hparams, problem_hparams, dp, sh... | tensorflow.python.ops.variable_scope.EagerVariableStore | 148 |
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.sequence_mask | 149 |
import tensorflow as tf
else:
i_direction = 1
variable_scope_name = 'RNN_{0}/RNN/MultiRNNCell/Cell{1}'.format(
i_direction, i)
with tf.variable_scope(variable_scope_name):
layer_output, final_state = tf.nn.dynam... | tensorflow.nn.rnn_cell.LSTMStateTuple | 150 |
import tensorflow as tf
images,labels=tf.train.batch([image,label],batch_size=batch_size)
return tf.reshape(images,[batch_size,4096]),tf.reshape(labels,[batch_size])
def get_valid_batch(image,label,batch_size):
images,labels=tf.train.batch([image,label],batch_size=batch_size)
return tf.reshape(im... | tensorflow.contrib.layers.xavier_initializer_conv2d | 151 |
from tensorflow.core.framework import op_def_pb2
inputs: A list of (name, data type) pairs of function arguments.
outputs: A list of (name, data type) pairs of function return values.
"""
self._sig = op_def_pb2.OpDef()
self._sig.name = func_name
| tensorflow.core.framework.op_def_pb2.OpDef | 152 |
from tensorflow.keras.layers import Dense, Conv2D, MaxPool2D, Flatten
#removed GOAL_SIZE
flat1b = Dense(units=RNN_SIZE-loc_layer_size)(flat1a)
# FC layers for goal_pos input
# goal_layer1 = Dense(units=GOAL_SIZE)(goal_pos)
# goal_layer2 = Dense(units=GOAL_SIZE)(goal_layer1)
# FC layers to find next lo... | tensorflow.keras.layers.Dense | 153 |
from tensorflow.contrib.distributions.python.ops import distribution_util
@distribution_util.AppendDocstring(
"""Note: when `rate` is an integer, there are actually two modes: `rate`
and `rate - 1`. In this case we return the larger, i.e., `rate`.""")
def _mode(self):
return math_ops.floor(self.rat... | tensorflow.contrib.distributions.python.ops.distribution_util.assert_integer_form | 154 |
import tensorflow as tf
neighbor, weight, _ = get_full_neighbor(nodes, hop_edge_types)
next_nodes, next_idx = tf.unique(neighbor.values, out_idx=tf.int64)
next_indices = tf.stack([neighbor.indices[:, 0], next_idx], 1)
next_values = weight.values
next_shape = tf.stack([tf.size(nodes), tf.size(next_n... | tensorflow.size | 155 |
from tensorflow.python.framework import tensor_util
x = ops.convert_to_tensor(x, name="x")
def slice_shape(start_sum, size, name):
"""Closure to slice out shape."""
start_sum = start_sum if start_sum else (
array_ops.zeros((), dtype=dtypes.int32, name="zero"),)
if (x.get... | tensorflow.python.framework.tensor_util.constant_value | 156 |
from tensorflow.contrib.summary import summary_test_util
dev_data = data.SnliData(fake_train_file, word2index)
test_data = data.SnliData(fake_train_file, word2index)
# 2. Create a fake config.
config = _test_spinn_config(
data.WORD_VECTOR_LEN, 4,
logdir=os.path.join(self._temp_data_dir... | tensorflow.contrib.summary.summary_test_util.events_from_file | 157 |
import tensorflow as tf
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)
tf.summary.scal... | tensorflow.random_shuffle | 158 |
import tensorflow as tf
features[spec.name] = feature
return tf.train.Example(features=tf.train.Features(feature=features))
def _input_fn_builder(self, input_file, is_training):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
def input_fn(params):
... | tensorflow.contrib.data.map_and_batch | 159 |
from tensorflow.python.summary import summary
if grad_values is not None:
var_name = variable.name.replace(":", "_")
if "gradients" in summaries:
summary.histogram("gradients/%s" % var_name, grad_values)
if "gradient_norm" in summaries:
summary.scalar("gradient_norm/%... | tensorflow.python.summary.summary.histogram | 160 |
from tensorflow.python.framework import ops
grad,
use_locking=self._use_locking).op
def _apply_sparse(self, grad, var):
delta = ops.IndexedSlices(grad.values * self._learning_rate_tensor,
grad.indices, grad.dense_shape)
return var.scatter_sub(delta, use_locking=... | tensorflow.python.framework.ops.IndexedSlices | 161 |
from tensorflow.contrib.metrics.python.ops import confusion_matrix_ops
labels = array_ops.reshape(labels, [-1])
weights = _mask_weights(ignore_mask, weights)
if weights is not None:
weights_rank = weights.get_shape().ndims
if weights_rank > 1:
weights = array_ops.reshape(weights, [-1... | tensorflow.contrib.metrics.python.ops.confusion_matrix_ops.confusion_matrix | 162 |
import tensorflow as tf
ious = iou_of(tf.expand_dims(gt_boxes, axis=0), tf.expand_dims(corner_form_priors, axis=1))
# size: num_priors
best_target_per_prior = tf.math.reduce_max(ious, axis=1)
best_target_per_prior_index = tf.math.argmax(ious, axis=1)
# size: num_targets
best_prior_per_ta... | tensorflow.math.argmax | 163 |
from tensorflow.python.training import gradient_descent
def _setupSparse(self, is_distributed, dtype):
with self._maybeWithDevice("/job:ps" if is_distributed else None):
var0 = variables.Variable(
[[0.0, 1.0], [2.0, 3.0], [4.0, 5.0]], dtype=dtype)
var1 = variables.Variable(
[[0.0,... | tensorflow.python.training.gradient_descent.GradientDescentOptimizer | 164 |
from tensorflow.python.ops import math_ops
predictions, labels = tensor_util.remove_squeezable_dimensions(
predictions, labels)
predictions.get_shape().assert_is_compatible_with(labels.get_shape())
if labels.dtype != predictions.dtype:
predictions = math_ops.cast(predictions, labels.dtype)
is_correct... | tensorflow.python.ops.math_ops.equal | 165 |
from tensorflow.python.ops import data_flow_ops
aggmeth = tf.AggregationMethod.DEFAULT
grads = tf.gradients(loss, params, aggregation_method=aggmeth)
if FLAGS.staged_vars:
grad_dtypes = [grad.dtype for grad in grads]
grad_shapes = [grad.shape for grad in grads]
grad_stage = ... | tensorflow.python.ops.data_flow_ops.StagingArea | 166 |
import tensorflow.contrib.graph_editor as ge
ts_all = ge.filter_ts(fwd_ops, True) # get the tensors
ts_all = [t for t in ts_all if '/read' not in t.name]
ts_all = set(ts_all) - set(xs) - set(ys)
# construct list of tensors to checkpoint during forward pass, if not
# given as input
if type(chec... | tensorflow.contrib.graph_editor.filter_ts_from_regex | 167 |
import tensorflow as tf
'bounding_box_samples': _float_feature(d['bounding_box_samples']),
'depth_renders': _float_feature(d['depth_renders']),
'mesh_name': _bytes_feature(d['mesh_name']),
'near_surface_samples': _float_feature(d['near_surface_samples']),
'grid': _float_feature(d['grid'])... | tensorflow.io.FixedLenFeature | 168 |
from tensorflow.python.ops import math_ops
indices_at_minval = math_ops.equal(
math_ops.abs(sensitivities - sensitivity), min_val)
indices_at_minval = math_ops.to_int64(indices_at_minval)
indices_at_minval = math_ops.cumsum(indices_at_minval)
tf_index = math_ops.argmax(indices_at_minv... | tensorflow.python.ops.math_ops.cumsum | 169 |
import tensorflow as tf
token_type_ids.append(e.token_type_ids)
attention_mask.append(e.attention_mask)
labels.append(e.label_ids)
# parse examples to dataset
def _to_dataset(x, dtype=tf.int32):
x = tf.ragged.constant(x, dtype=dtype)
d = tf.d... | tensorflow.ragged.constant | 170 |
import tensorflow as tf
if int(X.get_shape()[-1]) != (r**2) * n_out_channels:
raise Exception(_err_log)
# bsize, a, b, c = X.get_shape().as_list()
# bsize = tf.shape(X)[0] # Handling Dimension(None) type for undefined batch dim
# Xs=tf.split(X,r,3) #b*h*w... | tensorflow.depth_to_space | 171 |
import tensorflow as tf
st = tf.SparseTensor(indices, values, shape)
st_handles = add_many_sparse_to_tensors_map(st)
st_roundtrip = take_many_sparse_from_tensors_map(
sparse_map_op=st_handles.op, sparse_handles=st_handles)
st_roundtrip_op = st_roundtrip.values.op
s... | tensorflow.deserialize_many_sparse | 172 |
import tensorflow as tf
layer = tf.contrib.layers.batch_norm(layer, is_training=True, center=True,
scale=False, decay=decay, activation_fn=activation_fn, updates_collections=None, scope=vs, reuse=True) # updates_collections=None
else:
layer = tf.c... | tensorflow.contrib.layers.layer_norm | 173 |
import tensorflow as tf
x = tf.image.random_brightness(x, max_delta=0.8*s)
x = tf.image.random_contrast(x, lower=lower, upper=upper)
x = tf.image.random_saturation(x, lower=lower, upper=upper)
x = tf.image.random_hue(x, max_delta=0.2*s)
x = tf.clip_by_value(x, 0, 1)
return x
def color_drop(image):
image... | tensorflow.image.rgb_to_grayscale | 174 |
import tensorflow as tf
"float", [None, self.time_steps, self.n_input], name="INPUT_IMAGE")
# x is shaped [batch_size,time_steps,num_inputs]
if is_dynamic_rnn:
lstm_input = tf.transpose(x, perm=[1, 0, 2])
outputs, _ = tf.lite.experimental.nn.dynamic_rnn(
lstm_layer, lstm_input, d... | tensorflow.nn.static_rnn | 175 |
import tensorflow as tf
KK = tf.matmul(K, K, transpose_b=True)
K_trace = tf.expand_dims(tf.expand_dims(tf.trace(KK), -1), -1)
K_loss = tf.reduce_mean(tf.abs(KK / K_trace - tf.eye(2)))
loss_total_gen = crit_gen + rep_loss + K_loss
gen_var = model.get_gen_vars()
dis_var = model.dis.trainable_variables
grad... | tensorflow.optimizers.Adam | 176 |
from tensorflow.contrib.learn.python.learn.estimators import tensor_signature
def predict_proba(self, x, batch_size=None):
"""Returns prediction probabilities for given features (classification).
Args:
x: features.
batch_size: OVerride default batch size.
Returns:
Numpy array of pred... | tensorflow.contrib.learn.python.learn.estimators.tensor_signature.tensors_compatible | 177 |
import tensorflow as tf
"""
reg_l2 = tf.keras.regularizers.l2(5e-7)
if padding == 'SYMMETRIC' or padding == 'REFLECT':
p = (kernel_size - 1) // 2
x = tf.pad(x, [[0,0],[p,p],[p,p], [p,p],[0,0]], padding)
x = tf.keras.layers.Conv3D(filters, kernel_size, activation=activation, kernel... | tensorflow.keras.layers.Conv3D | 178 |
import tensorflow as tf
w1 = tf.get_variable('weight1', [784, 1024], initializer=tf.random_normal_initializer())
b1 = tf.get_variable('bias1', [1024], initializer=tf.constant_initializer(0.0))
h1 = tf.nn.relu(tf.matmul(x, w1) + b1)
with tf.variable_scope('layer2'):
w2 = tf.get_varia... | tensorflow.train.GradientDescentOptimizer | 179 |
import tensorflow as tf
next_sentence_log_probs) = get_next_sentence_output(
bert_config, model.get_pooled_output(), next_sentence_labels, clip)
total_loss = masked_lm_loss + next_sentence_loss
tvars = tf.trainable_variables()
initialized_variable_names = {}
scaffold_fn = None
if ini... | tensorflow.train.init_from_checkpoint | 180 |
from tensorflow.contrib.learn.python.learn.datasets import base
fake_data=False,
one_hot=False,
dtype=dtypes.float32,
reshape=True):
if fake_data:
def fake():
return DataSet([], [], fake_data=True, one_hot=one_hot, dtype=dtype)
... | tensorflow.contrib.learn.python.learn.datasets.base.Datasets | 181 |
import tensorflow as tf
sentence_embeddings = tf.divide(
| tensorflow.divide | 182 |
import tensorflow as tf
average_loss_per_example = tf.nn.seq2seq.sequence_loss_by_example(
| tensorflow.nn.seq2seq.sequence_loss_by_example | 183 |
import tensorflow as tf
# Note: tf.nn.softmax_cross_entropy_with_logits
# expects logits, Keras expects probabilities.
if not from_logits:
# transform back to logits
epsilon = _to_tensor(_EPSILON, output.dtype.base_dtype)
output = tf.clip_by_value(output, epsilon, 1 - epsilon)
output = tf.log(out... | tensorflow.nn.sigmoid_cross_entropy_with_logits | 184 |
from tensorflow.python.framework import ops
@ops.RegisterGradient("SparseScatter")
def _sparse_scatter_grad(op, grad):
| tensorflow.python.framework.ops.RegisterGradient | 185 |
from tensorflow.python.ops import clip_ops
return train_tensor
def _clip_gradients_by_norm(grads_and_vars, clip_gradients):
"""Clips gradients by global norm."""
gradients, variables = zip(*grads_and_vars)
clipped_gradients, _ = clip_ops.clip_by_global_norm(gradients, clip_gradients)
return list(zip(clip... | tensorflow.python.ops.clip_ops.clip_by_global_norm | 186 |
import tensorflow as tf
logits = tf.reduce_sum(tf.multiply(output_layer,output_weights),-1)
| tensorflow.multiply | 187 |
import tensorflow as tf
"""
with tf.variable_scope(scope) as sc:
kernel_d, kernel_h, kernel_w = kernel_size
num_in_channels = inputs.get_shape()[-1].value
kernel_shape = [kernel_d, kernel_h, kernel_w,
num_in_channels, num_output_channels]
kernel = _variab... | tensorflow.nn.conv3d | 188 |
import tensorflow as tf
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))
| tensorflow.contrib.framework.load_variable | 189 |
import tensorflow as tf
dataset = tf.data.Dataset.from_tensors(data).repeat(
| tensorflow.data.Dataset.from_tensors | 190 |
import tensorflow as tf
if single_file:
dataset_path = os.path.join(dataset_path, 'train_annotated.json')
else:
dataset_path = os.path.join(dataset_path, 'dev_annotated.json')
def load_dataset():
dataset = []
if single_file:
# Opening with GFile allows to use remotely stored files, e.g... | tensorflow.io.gfile.listdir | 191 |
import tensorflow as tf
## End new version
if self._normalize_cols:
logits_vec = logits_vec - tf.math.reduce_logsumexp(
logits_vec, axis=0)[None]
relabel_indices = tf.random.categorical(logits=logits_vec, num_samples=1)
| tensorflow.math.reduce_logsumexp | 192 |
import tensorflow as tf
def main(argv=None):
start1 = time.time()
import os
os.environ['CUDA_VISIBLE_DEVICES'] = FLAGS.gpu_list
if not tf.gfile.Exists(FLAGS.checkpoint_path):
tf.gfile.MkDir(FLAGS.checkpoint_path)
else:
if not FLAGS.restore:
tf.gfile.DeleteRecursively(FL... | tensorflow.gfile.DeleteRecursively | 193 |
from tensorflow.python.ops import partitioned_variables
weight_collections=[parent_scope],
scope=scope)
hidden_layer_partitioner = (
partitioned_variables.min_max_variable_partitioner(
max_partitions=num_ps_replicas))
for layer_id, num_hidden_units in enumerate(hidden_units):
w... | tensorflow.python.ops.partitioned_variables.min_max_variable_partitioner | 194 |
from tensorflow.contrib.layers.python.layers import utils
return mean, variance
def build_moving_stats():
return (
tf.identity(self._moving_mean),
tf.identity(self._moving_variance),
)
mean, variance = utils.smart_cond(
use_batch_stats,
build_batch_stats,... | tensorflow.contrib.layers.python.layers.utils.smart_cond | 195 |
import tensorflow as tf
[per_example_loss, label_ids, logits, is_real_example])
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
eval_metrics=eval_metrics,
scaffold_fn=scaffold_fn)
else:
# The code to modify out_put... | tensorflow.contrib.tpu.TPUEstimatorSpec | 196 |
from tensorflow.python.ops import math_ops
batch_dims: `Tensor` (1D, `int32`).
event_dims: `Tensor` (1D, `int32`).
"""
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 (
... | tensorflow.python.ops.math_ops.range | 197 |
import tensorflow as tf
# data for self-attention
rep_map_dp = dropout(rep_map, keep_prob, is_train)
rep_dep_tensor_dp, _, _ = reduce_data_rep_max_len(rep_map_dp, dep_selection)
rep_head_tensor_dp, _, _ = reduce_data_rep_max_len(rep_map_dp, head_selection)
# mask generation
dep_idxs = tf.tile(... | tensorflow.not_equal | 198 |
import tensorflow as tf
def get_config(self):
return {
"initial_learning_rate": self.initial_learning_rate,
"maximal_learning_rate": self.maximal_learning_rate,
"step_size": self.step_size,
"scale_mode": self.scale_mode,
}
@tf.keras.utils.register_... | tensorflow.keras.utils.register_keras_serializable | 199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.