【问题标题】:How to check if two Tensor shapes are the same including None?如何检查两个张量形状是否相同,包括无?
【发布时间】:2017-03-01 04:27:33
【问题描述】:

我想检查两个张量是否具有相同的形状。

假设我有一些这样的张量:

a = tf.placeholder(tf.float32, shape=[None, 3])
b = tf.placeholder(tf.float32, shape=[None, 3])

我添加了assert a.shape == b.shape。但是,这失败了,可能是由于 None。确实a.shape = (?, 1),而且b.shape(?, 1)。它们在我看来是一样的。

如果没有None,它工作正常。

a = tf.placeholder(tf.float32, shape=[1, 3])
b = tf.placeholder(tf.float32, shape=[1, 3])
assert a.shape == b.shape  # True

如何在形状检查中忽略 None?

总结:

1: a = tf.placeholder(tf.float32, shape=[1, 3])
2: b = tf.placeholder(tf.float32, shape=[1, 3])
3: assert a.shape == b.shape  # True
4: 
5: a = tf.placeholder(tf.float32, shape=[None, 3])
6: b = tf.placeholder(tf.float32, shape=[None, 3])
7: assert a.shape == b.shape  # False

我想让第 7 行中的断言为 True。

【问题讨论】:

    标签: numpy tensorflow


    【解决方案1】:

    您可以使用a.shape.as_list() == b.shape.as_list() 比较两个tf.TensorShape 对象的“相等性”。但是,这样做时应该小心,因为如果两个形状在同一位置包含 None,则不能保证具有这些形状的张量在该维度上具有相同的大小。

    (能够在tf.TensorShape 中表示像batch_size 这样的“符号”维度会很有用,这将使相等性测试更有用。我们正在研究API 的扩展,以便在未来的版本中实现这一点TensorFlow。)

    【讨论】:

    • 谢谢!如果我们有类似 tf.TensorShape.assert_same() 的东西,那就太好了。
    • 另一种选择是使用tf.assert_equal(a.shape, b.shape),尽管它不适用于部分已知的形状。
    • 你也可以使用a.shape.is_compatible_with(b.shape),参考the docs
    猜你喜欢
    • 2016-01-04
    • 2014-08-14
    • 2021-05-28
    • 2015-12-28
    • 2019-08-27
    • 1970-01-01
    • 2023-03-13
    • 2011-06-22
    • 2014-06-11
    相关资源
    最近更新 更多