本文整理汇总了Python中tensorflow.round方法的典型用法代码示例。如果您正苦于以下问题:Python tensorflow.round方法的具体用法?Python tensorflow.round怎么用?Python tensorflow.round使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow
的用法示例。
在下文中一共展示了tensorflow.round方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: f1_score
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import round [as 别名]
def f1_score(y_true, y_pred):
"""
Compute the micro f(b) score with b=1.
"""
y_true = tf.cast(y_true, "float32")
y_pred = tf.cast(tf.round(y_pred), "float32") # implicit 0.5 threshold via tf.round
y_correct = y_true * y_pred
sum_true = tf.reduce_sum(y_true, axis=1)
sum_pred = tf.reduce_sum(y_pred, axis=1)
sum_correct = tf.reduce_sum(y_correct, axis=1)
precision = sum_correct / sum_pred
recall = sum_correct / sum_true
f_score = 2 * precision * recall / (precision + recall)
f_score = tf.where(tf.is_nan(f_score), tf.zeros_like(f_score), f_score)
return tf.reduce_mean(f_score)
示例2: _legacy_output_transform_func
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import round [as 别名]
def _legacy_output_transform_func(*expr, out_mul=1.0, out_add=0.0, out_shrink=1, out_dtype=None):
if out_mul != 1.0:
expr = [x * out_mul for x in expr]
if out_add != 0.0:
expr = [x + out_add for x in expr]
if out_shrink > 1:
ksize = [1, 1, out_shrink, out_shrink]
expr = [tf.nn.avg_pool(x, ksize=ksize, strides=ksize, padding="VALID", data_format="NCHW") for x in expr]
if out_dtype is not None:
if tf.as_dtype(out_dtype).is_integer:
expr = [tf.round(x) for x in expr]
expr = [tf.saturate_cast(x, out_dtype) for x in expr]
return expr
示例3: version_10
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import round [as 别名]
def version_10(cls, node, **kwargs):
tensor_dict = kwargs["tensor_dict"]
x = tensor_dict[node.inputs[0]]
y_scale = tensor_dict[node.inputs[1]]
x = tf.cast(x, tf.float32)
y = tf.divide(x, y_scale)
y = tf.round(y)
if len(node.inputs) == 3:
y_zero_point = tensor_dict[node.inputs[2]]
y_dtype = y_zero_point.dtype
y_zero_point = tf.cast(y_zero_point, tf.float32)
y = tf.add(y, y_zero_point)
else: # y_zero_point default dtype = uint8
y_dtype = tf.uint8
y = tf.saturate_cast(y, y_dtype)
return [y]
示例4: pixels_from_softmax
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import round [as 别名]
def pixels_from_softmax(frame_logits, pure_sampling=False,
temperature=1.0, gumbel_noise_factor=0.2):
"""Given frame_logits from a per-pixel softmax, generate colors."""
# If we're purely sampling, just sample each pixel.
if pure_sampling or temperature == 0.0:
return common_layers.sample_with_temperature(frame_logits, temperature)
# Gumbel-sample from the pixel sofmax and average by pixel values.
pixel_range = tf.to_float(tf.range(256))
for _ in range(len(frame_logits.get_shape().as_list()) - 1):
pixel_range = tf.expand_dims(pixel_range, axis=0)
frame_logits = tf.nn.log_softmax(frame_logits)
gumbel_samples = discretization.gumbel_sample(
common_layers.shape_list(frame_logits)) * gumbel_noise_factor
frame = tf.nn.softmax((frame_logits + gumbel_samples) / temperature, axis=-1)
result = tf.reduce_sum(frame * pixel_range, axis=-1)
# Round on the forward pass, not on the backward one.
return result + tf.stop_gradient(tf.round(result) - result)
示例5: _bbox_to_mask
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import round [as 别名]
def _bbox_to_mask(yy, region_size, dtype):
# trim bounding box exeeding region_size on top and left
neg_part = tf.nn.relu(-yy[:2])
core = tf.ones(tf.to_int32(tf.round(yy[2:] - neg_part)), dtype=dtype)
y1 = tf.maximum(yy[0], 0.)
x1 = tf.maximum(yy[1], 0.)
y2 = tf.minimum(region_size[0], yy[0] + yy[2])
x2 = tf.minimum(region_size[1], yy[1] + yy[3])
padding = (y1, region_size[0] - y2, x1, region_size[1] - x2)
padding = tf.reshape(tf.stack(padding), (-1, 2))
padding = tf.to_int32(tf.round(padding))
mask = tf.pad(core, padding)
# trim bounding box exeeding region_size on bottom and right
rs = tf.to_int32(tf.round(region_size))
mask = mask[:rs[0], :rs[1]]
mask.set_shape((None, None))
return mask
示例6: quantizer
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import round [as 别名]
def quantizer(w, config, reuse=False, temperature=1, L=5, scope='image'):
"""
Quantize feature map over L centers to obtain discrete $\hat{w}$
+ Centers: {-2,-1,0,1,2}
+ TODO: Toggle learnable centers?
"""
with tf.variable_scope('quantizer_{}'.format(scope, reuse=reuse)):
centers = tf.cast(tf.range(-2,3), tf.float32)
# Partition W into the Voronoi tesellation over the centers
w_stack = tf.stack([w for _ in range(L)], axis=-1)
w_hard = tf.cast(tf.argmin(tf.abs(w_stack - centers), axis=-1), tf.float32) + tf.reduce_min(centers)
smx = tf.nn.softmax(-1.0/temperature * tf.abs(w_stack - centers), dim=-1)
# Contract last dimension
w_soft = tf.einsum('ijklm,m->ijkl', smx, centers) # w_soft = tf.tensordot(smx, centers, axes=((-1),(0)))
# Treat quantization as differentiable for optimization
w_bar = tf.round(tf.stop_gradient(w_hard - w_soft) + w_soft)
return w_bar
示例7: test_output_head_activations_work
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import round [as 别名]
def test_output_head_activations_work():
"""Tests that output head activations work properly"""
nn_instance = NN(layers_info=[4, 7, 9, [5, 10, 3]], hidden_activations="relu",
output_activation=["softmax", None, "relu"])
x = np.random.random((20, 2)) * -20.0
out = nn_instance(x)
assert out.shape == (20, 18)
sums = tf.reduce_sum(out[:, :5], axis=1)
sums_others = tf.reduce_sum(out[:, 5:], axis=1)
sums_others_2 = tf.reduce_sum(out[:, 5:15], axis=1)
sums_others_3 = tf.reduce_sum(out[:, 15:18], axis=1)
for row in range(out.shape[0]):
assert tf.math.equal(np.round(sums[row], 4), 1.0), sums[row]
assert not tf.math.equal(np.round(sums_others[row], 4), 1.0), np.round(sums_others[row], 4)
assert not tf.math.equal(np.round(sums_others_2[row], 4), 1.0), np.round(sums_others_2[row], 4)
assert not tf.math.equal(np.round(sums_others_3[row], 4), 1.0), np.round(sums_others_3[row], 4)
for col in range(3):
assert out[row, 15 + col] >= 0.0, out[row, 15 + col]
示例8: get_scheduled_sample_inputs
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import round [as 别名]
def get_scheduled_sample_inputs(
self, done_warm_start, groundtruth_items, generated_items, batch_size):
with tf.variable_scope("scheduled_sampling", reuse=tf.AUTO_REUSE):
if self.hparams.mode != tf.estimator.ModeKeys.TRAIN:
feedself = True
else:
# Scheduled sampling:
# Calculate number of ground-truth frames to pass in.
feedself = False
iter_num = tf.train.get_global_step()
# TODO(mbz): what should it be if it's undefined?
if iter_num is None:
iter_num = _LARGE_STEP_NUMBER
k = self.hparams.scheduled_sampling_k
num_ground_truth = tf.to_int32(
tf.round(
tf.to_float(batch_size) *
(k / (k + tf.exp(tf.to_float(iter_num) / tf.to_float(k))))))
if feedself and done_warm_start:
# Feed in generated stuff.
output_items = generated_items
elif done_warm_start:
output_items = []
for item_gt, item_gen in zip(groundtruth_items, generated_items):
# Scheduled sampling
output_items.append(self.scheduled_sample(
item_gt, item_gen, batch_size, num_ground_truth))
else:
# Feed in ground_truth
output_items = groundtruth_items
return output_items
# TODO(mbz): use tf.distributions.kl_divergence instead.
示例9: mode
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import round [as 别名]
def mode(self):
return tf.round(self.ps)
示例10: _compute_new_static_size
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import round [as 别名]
def _compute_new_static_size(image, min_dimension, max_dimension):
"""Compute new static shape for resize_to_range method."""
image_shape = image.get_shape().as_list()
orig_height = image_shape[0]
orig_width = image_shape[1]
num_channels = image_shape[2]
orig_min_dim = min(orig_height, orig_width)
# Calculates the larger of the possible sizes
large_scale_factor = min_dimension / float(orig_min_dim)
# Scaling orig_(height|width) by large_scale_factor will make the smaller
# dimension equal to min_dimension, save for floating point rounding errors.
# For reasonably-sized images, taking the nearest integer will reliably
# eliminate this error.
large_height = int(round(orig_height * large_scale_factor))
large_width = int(round(orig_width * large_scale_factor))
large_size = [large_height, large_width]
if max_dimension:
# Calculates the smaller of the possible sizes, use that if the larger
# is too big.
orig_max_dim = max(orig_height, orig_width)
small_scale_factor = max_dimension / float(orig_max_dim)
# Scaling orig_(height|width) by small_scale_factor will make the larger
# dimension equal to max_dimension, save for floating point rounding
# errors. For reasonably-sized images, taking the nearest integer will
# reliably eliminate this error.
small_height = int(round(orig_height * small_scale_factor))
small_width = int(round(orig_width * small_scale_factor))
small_size = [small_height, small_width]
new_size = large_size
if max(large_size) > max_dimension:
new_size = small_size
else:
new_size = large_size
return tf.constant(new_size + [num_channels])
示例11: _compute_new_dynamic_size
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import round [as 别名]
def _compute_new_dynamic_size(image, min_dimension, max_dimension):
"""Compute new dynamic shape for resize_to_range method."""
image_shape = tf.shape(image)
orig_height = tf.to_float(image_shape[0])
orig_width = tf.to_float(image_shape[1])
num_channels = image_shape[2]
orig_min_dim = tf.minimum(orig_height, orig_width)
# Calculates the larger of the possible sizes
min_dimension = tf.constant(min_dimension, dtype=tf.float32)
large_scale_factor = min_dimension / orig_min_dim
# Scaling orig_(height|width) by large_scale_factor will make the smaller
# dimension equal to min_dimension, save for floating point rounding errors.
# For reasonably-sized images, taking the nearest integer will reliably
# eliminate this error.
large_height = tf.to_int32(tf.round(orig_height * large_scale_factor))
large_width = tf.to_int32(tf.round(orig_width * large_scale_factor))
large_size = tf.stack([large_height, large_width])
if max_dimension:
# Calculates the smaller of the possible sizes, use that if the larger
# is too big.
orig_max_dim = tf.maximum(orig_height, orig_width)
max_dimension = tf.constant(max_dimension, dtype=tf.float32)
small_scale_factor = max_dimension / orig_max_dim
# Scaling orig_(height|width) by small_scale_factor will make the larger
# dimension equal to max_dimension, save for floating point rounding
# errors. For reasonably-sized images, taking the nearest integer will
# reliably eliminate this error.
small_height = tf.to_int32(tf.round(orig_height * small_scale_factor))
small_width = tf.to_int32(tf.round(orig_width * small_scale_factor))
small_size = tf.stack([small_height, small_width])
new_size = tf.cond(
tf.to_float(tf.reduce_max(large_size)) > max_dimension,
lambda: small_size, lambda: large_size)
else:
new_size = large_size
return tf.stack(tf.unstack(new_size) + [num_channels])
示例12: denorm_boxes_graph
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import round [as 别名]
def denorm_boxes_graph(boxes, shape):
"""Converts boxes from normalized coordinates to pixel coordinates.
boxes: [..., (y1, x1, y2, x2)] in normalized coordinates
shape: [..., (height, width)] in pixels
Note: In pixel coordinates (y2, x2) is outside the box. But in normalized
coordinates it's inside the box.
Returns:
[..., (y1, x1, y2, x2)] in pixel coordinates
"""
h, w = tf.split(tf.cast(shape, tf.float32), 2)
scale = tf.concat([h, w, h, w], axis=-1) - tf.constant(1.0)
shift = tf.constant([0., 0., 1., 1.])
return tf.cast(tf.round(tf.multiply(boxes, scale) + shift), tf.int32)
示例13: distance_tensor
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import round [as 别名]
def distance_tensor(self, X, Nbrs, boxsize, B, N, M, d):
"""Calculates distance tensor for batch of molecules.
B = batch_size, N = max_num_atoms, M = max_num_neighbors, d = num_features
Parameters
----------
X: tf.Tensor of shape (B, N, d)
Coordinates/features tensor.
Nbrs: tf.Tensor of shape (B, N, M)
Neighbor list tensor.
boxsize: float or None
Simulation box length [Angstrom].
Returns
-------
D: tf.Tensor of shape (B, N, M, d)
Coordinates/features distance tensor.
"""
flat_neighbors = tf.reshape(Nbrs, [-1, N * M])
neighbor_coords = tf.gather(X, flat_neighbors, batch_dims=-1, axis=1)
neighbor_coords = tf.reshape(neighbor_coords, [-1, N, M, d])
D = neighbor_coords - tf.expand_dims(X, 2)
if boxsize is not None:
boxsize = tf.reshape(boxsize, [1, 1, 1, d])
D -= tf.round(D / boxsize) * boxsize
return D
示例14: _ratio_enum
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import round [as 别名]
def _ratio_enum(anchor, ratios):
"""
Enumerate a set of anchors for each aspect ratio wrt an anchor.
"""
w, h, x_ctr, y_ctr = _whctrs(anchor)
size = w * h
size_ratios = size / ratios
ws = tf.round(tf.sqrt(size_ratios))
hs = tf.round(ws * ratios)
anchors = _mkanchors(ws, hs, x_ctr, y_ctr)
return anchors
示例15: __binary_accuracy
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import round [as 别名]
def __binary_accuracy(from_logits=False):
"""
Calculate binary accuracy, ignoring the magic number
:param from_logits: From logits space or not. If you want to use logits, please use from_logits=True
:type from_logits: boolean
:return: Function for Binary classification accuracy which matches Keras losses API
:rtype: function
:Returned Funtion Parameter:
| **function(y_true, y_pred)**
| - **y_true** (*tf.Tensor*): Ground Truth
| - **y_pred** (*tf.Tensor*): Prediction
| Return (*tf.Tensor*): Binary Classification Accuracy
:History: 2018-Jan-31 - Written - Henry Leung (University of Toronto)
"""
# DO NOT correct y_true for magic number, just let it goes wrong and then times a correction terms
def binary_accuracy_internal(y_true, y_pred):
if from_logits:
y_pred = tf.nn.sigmoid(y_pred)
return tf.reduce_mean(tf.cast(tf.equal(y_true, tf.round(y_pred)), tf.float32), axis=-1) * magic_correction_term(
y_true)
if not from_logits:
binary_accuracy_internal.__name__ = 'binary_accuracy' # set the name to be displayed in TF/Keras log
else:
binary_accuracy_internal.__name__ = 'binary_accuracy_from_logits' # set the name to be displayed in TF/Keras log
return binary_accuracy_internal