本文整理汇总了Python中tensorflow.tuple方法的典型用法代码示例。如果您正苦于以下问题:Python tensorflow.tuple方法的具体用法?Python tensorflow.tuple怎么用?Python tensorflow.tuple使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow
的用法示例。
在下文中一共展示了tensorflow.tuple方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testWhile_NestedInput
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import tuple [as 别名]
def testWhile_NestedInput(self):
with self.test_session() as sess:
named = collections.namedtuple("named", ("a", "b"))
loop_vars = [named(a=tf.constant(0.0), b=tf.constant(1.0)),
(tf.constant(2.0), tf.constant(3.0)),
tf.constant(4.0)]
c = lambda lv0, _1, _2: lv0.a < 100.0
def b(lv0, lv1, lv2):
lv0 = named(a=lv0.a + 1, b=lv0.b)
lv1 = (lv1[0] + 1, lv1[1])
lv2 += 2
return [lv0, lv1, lv2]
r = tf.while_loop(c, b, loop_vars)
self.assertTrue(isinstance(r, list))
self.assertTrue(isinstance(r[0], named))
self.assertTrue(isinstance(r[1], tuple))
self.assertTrue(isinstance(r[2], tf.Tensor))
r_flattened = nest.flatten(r)
self.assertEqual(
[100.0, 1.0, 102.0, 3.0, 4.0 + 100*2.0],
sess.run(r_flattened))
示例2: _get_state_variables
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import tuple [as 别名]
def _get_state_variables(self, batch_size, cell):
"""For each layer, get the initial state and make a variable out of it
to enable updating its value.
Args:
batch_size (int): Batch size.
cell (tf.BasicLSTMCell): LSTM cell to get the initial state for.
Returns:
tupel: Tupel of the state variables and there zero states.
"""
# For each layer, get the initial state and make a variable out of it
# to enable updating its value.
zero_state = cell.zero_state(batch_size, tf.float32)
state_variables = []
for state_c, state_h in zero_state:
state_variables.append(
tf.contrib.rnn.LSTMStateTuple(
tf.Variable(state_c, trainable=False),
tf.Variable(state_h, trainable=False)))
# Return as a tuple, so that it can be fed to dynamic_rnn as an initial state
return tuple(state_variables), zero_state
示例3: _get_state_update_op
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import tuple [as 别名]
def _get_state_update_op(self, state_variables, new_states):
"""Add an operation to update the train states with the last state tensors
Args:
state_variables (tf.Variable): State variables to be updated
new_states (tf.Variable): New state of the state variable.
Returns:
tf.Operation: Return a tuple in order to combine all update_ops into a
single operation. The tuple's actual value should not be used.
"""
# Add an operation to update the train states with the last state tensors
update_ops = []
for state_variable, new_state in zip(state_variables, new_states):
# Assign the new state to the state variables on this layer
update_ops.extend([
state_variable[0].assign(new_state[0]),
state_variable[1].assign(new_state[1])
])
# Return a tuple in order to combine all update_ops into a single operation.
# The tuple's actual value should not be used.
return tf.tuple(update_ops)
示例4: expand_bboxes
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import tuple [as 别名]
def expand_bboxes(xmin, xmax, ymin, ymax, cfg):
"""
Expand the bboxes.
"""
w = xmax - xmin
h = ymax - ymin
w = w * cfg.WIDTH_EXPANSION_FACTOR
h = h * cfg.HEIGHT_EXPANSION_FACTOR
half_w = w / 2.
half_h = h / 2.
xmin = tf.clip_by_value(xmin - half_w, 0, 1)
xmax = tf.clip_by_value(xmax + half_w, 0, 1)
ymin = tf.clip_by_value(ymin - half_h, 0, 1)
ymax = tf.clip_by_value(ymax + half_h, 0, 1)
return tf.tuple([xmin, xmax, ymin, ymax])
示例5: _precision_recall
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import tuple [as 别名]
def _precision_recall(n_gbboxes, n_detections, scores, tp, fp, scope=None):
"""Compute precision and recall from scores, true positives and false
positives booleans arrays
"""
# Sort by score.
with tf.name_scope(scope, 'prec_rec', [n_gbboxes, scores, tp, fp]):
# Sort detections by score.
scores, idxes = tf.nn.top_k(scores, k=n_detections, sorted=True)
tp = tf.gather(tp, idxes)
fp = tf.gather(fp, idxes)
# Computer recall and precision.
dtype = tf.float64
tp = tf.cumsum(tf.cast(tp, dtype), axis=0)
fp = tf.cumsum(tf.cast(fp, dtype), axis=0)
recall = _safe_div(tp, tf.cast(n_gbboxes, dtype), 'recall')
precision = _safe_div(tp, tp + fp, 'precision')
return tf.tuple([precision, recall])
示例6: _rev_layer_forward
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import tuple [as 别名]
def _rev_layer_forward(xs, f, g, f_side_input, g_side_input,
gate_outputs=False):
"""Forward for 1 reversible layer."""
x1, x2 = xs
y1 = x1 + (f(x2, f_side_input) if f_side_input else f(x2))
y2 = x2 + (g(y1, g_side_input) if g_side_input else g(y1))
out = (y1, y2)
if gate_outputs:
out = tf.tuple(out)
return out
示例7: precision_recall
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import tuple [as 别名]
def precision_recall(num_gbboxes, tp, fp, scope=None):
"""Compute precision and recall from true positives and false
positives booleans arrays
"""
# Sort by score.
with tf.name_scope(scope, 'precision_recall'):
# Computer recall and precision.
tp = tf.reduce_sum(tf.cast(tp, tf.float32), axis=0)
fp = tf.reduce_sum(tf.cast(fp, tf.float32), axis=0)
recall = tfe_math.safe_divide(tp, tf.cast(num_gbboxes, tf.float32), 'recall')
precision = tfe_math.safe_divide(tp, tp + fp, 'precision')
return tf.tuple([precision, recall])
示例8: configure_gcs
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import tuple [as 别名]
def configure_gcs(credentials=None, block_cache=None, device=None):
"""Configures the GCS file system for a given a session.
Warning: GCS `credentials` may be transmitted over the network unencrypted.
Please ensure that the network is trusted before using this function. For
users running code entirely within Google Cloud, your data is protected by
encryption in between data centers. For more information, please take a look
at https://cloud.google.com/security/encryption-in-transit/.
Args:
credentials: [Optional.] A JSON string
block_cache: [Optional.] A BlockCacheParams to configure the block cache .
device: [Optional.] The device to place the configure ops.
"""
def configure(credentials, block_cache):
"""Helper function to actually configure GCS."""
if credentials:
if isinstance(credentials, dict):
credentials = json.dumps(credentials)
creds = gcs_configure_credentials(credentials)
else:
creds = tf.constant(0)
if block_cache:
cache = gcs_configure_block_cache(
max_cache_size=block_cache.max_bytes,
block_size=block_cache.block_size,
max_staleness=block_cache.max_staleness)
else:
cache = tf.constant(0)
return tf.tuple([creds, cache])
if device:
with ops.device(device):
return configure(credentials, block_cache)
return configure(credentials, block_cache)
示例9: minimize
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import tuple [as 别名]
def minimize(self, loss, variables=None):
""""""
variables = variables or tf.trainable_variables()
gradients = tf.gradients(loss, variables,
colocate_gradients_with_ops=True,
gate_gradients=True,
aggregation_method=2)
gradients = {variable: gradient for variable, gradient in zip(variables, gradients) if gradient is not None}
variable_steps = {}
variable_indices = {}
updates = [tf.assign_add(self.global_step, 1)]
for variable, gradient in six.iteritems(gradients):
if isinstance(gradient, tf.Tensor):
step, update = self.dense_update(gradient, variable)
variable_steps[variable] = step
updates.extend(update)
else:
step, indices, update = self.sparse_update(gradient, variable)
variable_steps[variable] = step
variable_indices[variable] = indices
updates.extend(update)
variable_steps = self.clip_by_global_norm(variable_steps)
for variable, step in six.iteritems(variable_steps):
if variable in variable_indices:
indices = variable_indices[variable]
updates.append(tf.scatter_sub(variable, indices, step))
else:
updates.append(tf.assign_sub(variable, step))
return tf.tuple(updates)[0]
#=============================================================
示例10: average_precision
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import tuple [as 别名]
def average_precision(
num_gt_boxes,
tp,
fp,
score,
class_name,
metrics_collections=None,
updates_collections=None,
):
"""Compute average precision.
Args:
num_gt_boxes(tf.Tensor): a scalar tensor. number of gt boxes.
tp(tf.Tensor): tp vector. elements are int or bool.
fp(tf.Tensor): fp vector. elements are int or bool.
score(tf.Tensor): score vector.
class_name(str): class_name
Return:
average precision(tf.Tensor): scalar
presicion_array(tf.Tensor): vector of presicion.
recall_array(tf.Tensor): vector of recall.
presicion(tf.Tensor): scalr of presicion.
recall(tf.Tensor): scalar of recall.
"""
# replace non-alpha-num string.
class_name = re.sub('[^0-9a-zA-Z]+', '_', class_name)
(tp_value, fp_value, scores_value, num_gt_boxes_value), update_op = \
_streaming_tp_fp_array(num_gt_boxes, tp, fp, score, class_name,
metrics_collections=metrics_collections, updates_collections=updates_collections)
precision_array, recall_array, precision, recall = \
_precision_recall(tp_value, fp_value, scores_value, num_gt_boxes_value, class_name)
average_precision = _average_precision(precision_array, recall_array)
return tf.tuple([average_precision, precision_array, recall_array, precision, recall]), update_op
示例11: _precision_recall
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import tuple [as 别名]
def _precision_recall(
tp,
fp,
scores,
num_gt_boxes,
class_name,
dtype=tf.float64,
scope=None):
"""Compute precision and recall from scores, true positives and false
positives booleans arrays
"""
default_name = 'precision_recall_{}'.format(class_name)
# Sort by score.
with tf.compat.v1.name_scope(scope, default_name, [num_gt_boxes, tp, fp, scores]):
num_detections = tf.size(scores)
# Sort detections by score.
scores, idxes = tf.nn.top_k(scores, k=num_detections, sorted=True)
tp = tf.gather(tp, idxes)
fp = tf.gather(fp, idxes)
# Computer recall and precision.
tp = tf.cumsum(tf.cast(tp, dtype), axis=0)
fp = tf.cumsum(tf.cast(fp, dtype), axis=0)
recall = _safe_div_ones(tp, tf.cast(num_gt_boxes, dtype), 'recall')
precision = _safe_div_zeros(tp, tp + fp, 'precision')
scalar_precision = tf.cond(
tf.equal(tf.size(precision), 0),
true_fn=lambda: tf.constant(0, dtype=dtype),
false_fn=lambda: precision[-1],
name="scalar_precision"
)
scalar_recall = tf.cond(
tf.equal(tf.size(recall), 0),
true_fn=lambda: tf.constant(0, dtype=dtype),
false_fn=lambda: recall[-1],
name="scalar_recall"
)
return tf.tuple([precision, recall, scalar_precision, scalar_recall])
示例12: stop_gradient_tuple
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import tuple [as 别名]
def stop_gradient_tuple(self, inputs):
""" Stop gradients through tf.tuple. """
for i, _ in enumerate(inputs):
inputs[i] = tf.stop_gradient(inputs[i])
return inputs
示例13: create_bbox_batch
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import tuple [as 别名]
def create_bbox_batch(cls, inputs, batch_size=64):
""" Create batch indices for bboxes. """
batch = []
for indices in inputs:
indices = tf.random_shuffle(indices)
start = [0] * 2
size = [tf.minimum(batch_size, tf.shape(indices)[0]), -1]
sample = tf.slice(indices, start, size)
sample.set_shape([None, 1])
batch.append(sample)
batch = tf.tuple(batch)
return batch
示例14: _get_rois_and_labels
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import tuple [as 别名]
def _get_rois_and_labels(self, rois, labels, indices):
with tf.variable_scope('get_rois_and_labels'):
output_rois = []
output_labels = []
for i, index in enumerate(indices):
output_rois.append(tf.gather_nd(rois[i], index))
output_labels.append(tf.gather_nd(labels[i], index))
output_rois = tf.tuple(output_rois)
output_labels = tf.tuple(output_labels)
return output_rois, output_labels
示例15: _unstack_tuple
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import tuple [as 别名]
def _unstack_tuple(self, inputs, tensor_sizes):
size = len(tensor_sizes)
start_position = tf.constant(0)
output = []
dim = len(inputs.get_shape().as_list())-1
for i in range(size):
output.append(tf.slice(inputs, begin=[start_position, *([0]*dim)], size=[tensor_sizes[i], *([-1]*dim)]))
start_position = start_position + tensor_sizes[i]
return tf.tuple(output)