本文整理汇总了Python中tensorflow.assert_equal方法的典型用法代码示例。如果您正苦于以下问题:Python tensorflow.assert_equal方法的具体用法?Python tensorflow.assert_equal怎么用?Python tensorflow.assert_equal使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow
的用法示例。
在下文中一共展示了tensorflow.assert_equal方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _assert_correct_number_of_anchors
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import assert_equal [as 别名]
def _assert_correct_number_of_anchors(self, anchors, feature_map_shape_list):
"""Assert that correct number of anchors was generated.
Args:
anchors: box_list.BoxList object holding anchors generated
feature_map_shape_list: list of (height, width) pairs in the format
[(height_0, width_0), (height_1, width_1), ...] that the generated
anchors must align with.
Returns:
Op that raises InvalidArgumentError if the number of anchors does not
match the number of expected anchors.
"""
expected_num_anchors = 0
for num_anchors_per_location, feature_map_shape in zip(
self.num_anchors_per_location(), feature_map_shape_list):
expected_num_anchors += (num_anchors_per_location
* feature_map_shape[0]
* feature_map_shape[1])
return tf.assert_equal(expected_num_anchors, anchors.num_boxes())
示例2: _assert_correct_number_of_anchors
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import assert_equal [as 别名]
def _assert_correct_number_of_anchors(self, anchors_list,
feature_map_shape_list):
"""Assert that correct number of anchors was generated.
Args:
anchors_list: A list of box_list.BoxList object holding anchors generated.
feature_map_shape_list: list of (height, width) pairs in the format
[(height_0, width_0), (height_1, width_1), ...] that the generated
anchors must align with.
Returns:
Op that raises InvalidArgumentError if the number of anchors does not
match the number of expected anchors.
"""
expected_num_anchors = 0
actual_num_anchors = 0
for num_anchors_per_location, feature_map_shape, anchors in zip(
self.num_anchors_per_location(), feature_map_shape_list, anchors_list):
expected_num_anchors += (num_anchors_per_location
* feature_map_shape[0]
* feature_map_shape[1])
actual_num_anchors += anchors.num_boxes()
return tf.assert_equal(expected_num_anchors, actual_num_anchors)
示例3: __call__
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import assert_equal [as 别名]
def __call__(self, x, y):
'''
Return K(x, y), where x and y are possibly batched.
:param x: shape [..., n_x, n_covariates]
:param y: shape [..., n_y, n_covariates]
:return: Tensor with shape [..., n_x, n_y]
'''
batch_shape = tf.shape(x)[:-2]
rank = x.shape.ndims
assert_ops = [
tf.assert_greater_equal(
rank, 2,
message='RBFKernel: rank(x) should be static and >=2'),
tf.assert_equal(
rank, tf.rank(y),
message='RBFKernel: x and y should have the same rank')]
with tf.control_dependencies(assert_ops):
x = tf.expand_dims(x, rank - 1)
y = tf.expand_dims(y, rank - 2)
k_scale = tf.reshape(self.k_scale, [1] * rank + [-1])
ret = tf.exp(
-tf.reduce_sum(tf.square(x - y) / k_scale, axis=-1) / 2)
return ret
示例4: _filter_negative_samples
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import assert_equal [as 别名]
def _filter_negative_samples(labels, tensors):
"""keeps only samples with none-negative labels
Params:
-----
labels: of shape (N,)
tensors: a list of tensors, each of shape (N, .., ..) the first axis is sample number
Returns:
-----
tensors: filtered tensors
"""
# return tensors
keeps = tf.where(tf.greater_equal(labels, 0))
keeps = tf.reshape(keeps, [-1])
filtered = []
for t in tensors:
tf.assert_equal(tf.shape(t)[0], tf.shape(labels)[0])
f = tf.gather(t, keeps)
filtered.append(f)
return filtered
示例5: testReset
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import assert_equal [as 别名]
def testReset(self):
batch_size = 2
key_depth = 3
val_depth = 5
memory_size = 4
memory = transformer_memory.TransformerMemory(
batch_size, key_depth, val_depth, memory_size)
vals = tf.random_uniform([batch_size, memory_size, val_depth], minval=1.0)
logits = tf.random_uniform([batch_size, memory_size], minval=1.0)
update_op = memory.set(vals, logits)
reset_op = memory.reset([1])
mem_vals, mem_logits = memory.get()
assert_op1 = tf.assert_equal(mem_vals[0], vals[0])
assert_op2 = tf.assert_equal(mem_logits[0], logits[0])
with tf.control_dependencies([assert_op1, assert_op2]):
all_zero1 = tf.reduce_sum(tf.abs(mem_vals[1]))
all_zero2 = tf.reduce_sum(tf.abs(mem_logits[1]))
with self.test_session() as session:
session.run(tf.global_variables_initializer())
session.run(update_op)
session.run(reset_op)
zero1, zero2 = session.run([all_zero1, all_zero2])
self.assertAllEqual(0, zero1)
self.assertAllEqual(0, zero2)
示例6: CombineArcAndRootPotentials
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import assert_equal [as 别名]
def CombineArcAndRootPotentials(arcs, roots):
"""Combines arc and root potentials into a single set of potentials.
Args:
arcs: [B,N,N] tensor of batched arc potentials.
roots: [B,N] matrix of batched root potentials.
Returns:
[B,N,N] tensor P of combined potentials where
P_{b,s,t} = s == t ? roots[b,t] : arcs[b,s,t]
"""
# All arguments must have statically-known rank.
check.Eq(arcs.get_shape().ndims, 3, 'arcs must be rank 3')
check.Eq(roots.get_shape().ndims, 2, 'roots must be a matrix')
# All arguments must share the same type.
dtype = arcs.dtype.base_dtype
check.Same([dtype, roots.dtype.base_dtype], 'dtype mismatch')
roots_shape = tf.shape(roots)
arcs_shape = tf.shape(arcs)
batch_size = roots_shape[0]
num_tokens = roots_shape[1]
with tf.control_dependencies([
tf.assert_equal(batch_size, arcs_shape[0]),
tf.assert_equal(num_tokens, arcs_shape[1]),
tf.assert_equal(num_tokens, arcs_shape[2])]):
return tf.matrix_set_diag(arcs, roots)
示例7: _training
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import assert_equal [as 别名]
def _training(self):
"""Perform multiple training iterations of both policy and value baseline.
Training on the episodes collected in the memory. Reset the memory
afterwards. Always returns a summary string.
Returns:
Summary tensor.
"""
with tf.name_scope('training'):
assert_full = tf.assert_equal(
self._memory_index, self._config.update_every)
with tf.control_dependencies([assert_full]):
data = self._memory.data()
(observ, action, old_mean, old_logstd, reward), length = data
with tf.control_dependencies([tf.assert_greater(length, 0)]):
length = tf.identity(length)
observ = self._observ_filter.transform(observ)
reward = self._reward_filter.transform(reward)
policy_summary = self._update_policy(
observ, action, old_mean, old_logstd, reward, length)
with tf.control_dependencies([policy_summary]):
value_summary = self._update_value(observ, reward, length)
with tf.control_dependencies([value_summary]):
penalty_summary = self._adjust_penalty(
observ, old_mean, old_logstd, length)
with tf.control_dependencies([penalty_summary]):
clear_memory = tf.group(
self._memory.clear(), self._memory_index.assign(0))
with tf.control_dependencies([clear_memory]):
weight_summary = utility.variable_summaries(
tf.trainable_variables(), self._config.weight_summaries)
return tf.summary.merge([
policy_summary, value_summary, penalty_summary, weight_summary])
示例8: _training
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import assert_equal [as 别名]
def _training(self):
"""Perform multiple training iterations of both policy and value baseline.
Training on the episodes collected in the memory. Reset the memory
afterwards. Always returns a summary string.
Returns:
Summary tensor.
"""
with tf.name_scope('training'):
assert_full = tf.assert_equal(
self._memory_index, self._config.update_every)
with tf.control_dependencies([assert_full]):
data = self._memory.data()
(observ, action, old_mean, old_logstd, reward), length = data
with tf.control_dependencies([tf.assert_greater(length, 0)]):
length = tf.identity(length)
observ = self._observ_filter.transform(observ)
reward = self._reward_filter.transform(reward)
update_summary = self._perform_update_steps(
observ, action, old_mean, old_logstd, reward, length)
with tf.control_dependencies([update_summary]):
penalty_summary = self._adjust_penalty(
observ, old_mean, old_logstd, length)
with tf.control_dependencies([penalty_summary]):
clear_memory = tf.group(
self._memory.clear(), self._memory_index.assign(0))
with tf.control_dependencies([clear_memory]):
weight_summary = utility.variable_summaries(
tf.trainable_variables(), self._config.weight_summaries)
return tf.summary.merge([
update_summary, penalty_summary, weight_summary])
示例9: conv_elems_1d
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import assert_equal [as 别名]
def conv_elems_1d(x, factor, out_depth=None):
"""Decrease the length and change the dimensionality.
Merge/restore/compress factors positions of dim depth of the input into
a single position of dim out_depth.
This is basically just a strided convolution without overlap
between each strides. The original length has to be divided by factor.
Args:
x (tf.Tensor): shape [batch_size, length, depth]
factor (int): Length compression factor.
out_depth (int): Output depth
Returns:
tf.Tensor: shape [batch_size, length//factor, out_depth]
"""
out_depth = out_depth or x.get_shape().as_list()[-1]
# with tf.control_dependencies( # Dynamic assertion
# [tf.assert_equal(tf.shape(x)[1] % factor, 0)]):
x = tf.expand_dims(x, 1) # [batch_size, 1, length, depth]
x = tf.layers.conv2d(
inputs=x,
filters=out_depth,
kernel_size=(1, factor),
strides=(1, factor),
padding="valid",
data_format="channels_last",
) # [batch_size, 1, length//factor, out_depth]
x = tf.squeeze(x, 1) # [batch_size, length//factor, depth]
return x
示例10: assert_shape_equal
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import assert_equal [as 别名]
def assert_shape_equal(shape_a, shape_b):
"""Asserts that shape_a and shape_b are equal.
If the shapes are static, raises a ValueError when the shapes
mismatch.
If the shapes are dynamic, raises a tf InvalidArgumentError when the shapes
mismatch.
Args:
shape_a: a list containing shape of the first tensor.
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 (all(isinstance(dim, int) for dim in shape_a) and
all(isinstance(dim, int) for dim in shape_b)):
if shape_a != shape_b:
raise ValueError('Unequal shapes {}, {}'.format(shape_a, shape_b))
else: return tf.no_op()
else:
return tf.assert_equal(shape_a, shape_b)
示例11: assert_shape_equal_along_first_dimension
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import assert_equal [as 别名]
def assert_shape_equal_along_first_dimension(shape_a, shape_b):
"""Asserts that shape_a and shape_b are the same along the 0th-dimension.
If the shapes are static, raises a ValueError when the shapes
mismatch.
If the shapes are dynamic, raises a tf InvalidArgumentError when the shapes
mismatch.
Args:
shape_a: a list containing shape of the first tensor.
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 isinstance(shape_b[0], int):
if shape_a[0] != shape_b[0]:
raise ValueError('Unequal first dimension {}, {}'.format(
shape_a[0], shape_b[0]))
else: return tf.no_op()
else:
return tf.assert_equal(shape_a[0], shape_b[0])
示例12: tf_static_adem_score
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import assert_equal [as 别名]
def tf_static_adem_score(context, model_response, reference_response):
rr_size, rr_dim = reference_response.get_shape().as_list()
mr_size, mr_dim = model_response.get_shape().as_list()
ct_size, ct_dim = context.get_shape().as_list()
with tf.control_dependencies(
[tf.assert_equal(rr_size, mr_size, message='responses size not equal'),
tf.assert_equal(ct_size, mr_size, message='context response size not equal')]):
score, M, N = compute_adem_score(
context, model_response, reference_response, mr_dim, ct_dim, rr_dim)
return score, M, N
示例13: tf_static_adem_l1_loss
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import assert_equal [as 别名]
def tf_static_adem_l1_loss(human_score, model_score, M, N):
hs_shape = human_score.get_shape().as_list()
ms_shape = model_score.get_shape().as_list()
with tf.control_dependencies(
[tf.assert_equal(len(hs_shape), 1, message='score should be 1D.'),
tf.assert_equal(len(ms_shape), 1, message='score should be 1D.'),
tf.assert_equal(hs_shape, ms_shape,
message='human and model scores should have an equal amount.')]):
return compute_adem_l1_loss(human_score, model_score, M, N)
示例14: check_image
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import assert_equal [as 别名]
def check_image(image):
assertion = tf.assert_equal(tf.shape(image)[-1], 3, message="image must have 3 color channels")
with tf.control_dependencies([assertion]):
image = tf.identity(image)
if image.get_shape().ndims not in (3, 4):
raise ValueError("image must be either 3 or 4 dimensions")
# make the last dimension 3 so that you can unstack the colors
shape = list(image.get_shape())
shape[-1] = 3
image.set_shape(shape)
return image
# based on https://github.com/torch/image/blob/9f65c30167b2048ecbe8b7befdc6b2d6d12baee9/generic/image.c