【发布时间】:2018-01-09 16:55:04
【问题描述】:
我已经阅读了关于这个问题here 和here 的一些答案,但是我仍然对tf.Variable 是和/或不是tf.Tensor 感到有些困惑。
链接的答案涉及tf.Variable 的可变性,并提到tf.Variables 保持其状态(使用默认参数trainable=True 实例化时)。
让我仍然有点困惑的是我在使用tf.test.TestCase编写简单单元测试时遇到的一个测试用例
考虑以下代码 sn-p。我们有一个名为Foo 的简单类,它只有一个属性,tf.Variable 初始化为w:
import tensorflow as tf
import numpy as np
class Foo:
def __init__(self, w):
self.w = tf.Variable(w)
现在,假设您要测试 Foo 的实例是否已使用与通过 w 传入的相同维度的张量初始化 w。最简单的测试用例可以这样写:
import tensorflow as tf
import numpy as np
from foo import Foo
class TestFoo(tf.test.TestCase):
def test_init(self):
w = np.random.rand(3,2)
foo = Foo(w)
init = tf.global_variables_initializer()
with self.test_session() as sess:
sess.run(init)
self.assertShapeEqual(w, foo.w)
if __name__ == '__main__':
tf.test.main()
现在,当您运行测试时,您将收到以下错误:
======================================================================
ERROR: test_init (__main__.TestFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_foo.py", line 12, in test_init
self.assertShapeEqual(w, foo.w)
File "/usr/local/lib/python3.6/site-packages/tensorflow/python/framework/test_util.py", line 1100, in assertShapeEqual
raise TypeError("tf_tensor must be a Tensor")
TypeError: tf_tensor must be a Tensor
----------------------------------------------------------------------
Ran 2 tests in 0.027s
FAILED (errors=1)
您可以通过执行以下操作“绕过”此单元测试错误(即注意 assertShapeEqual 已替换为 assertEqual):
self.assertEqual(list(w.shape), foo.w.get_shape().as_list())
不过,我感兴趣的是 tf.Variable 与 tf.Tensor 的关系。
测试错误似乎表明foo.w NOT 是tf.Tensor,这意味着您可能无法在其上使用tf.Tensor API。但是,请考虑以下交互式 python 会话:
$ python3
Python 3.6.3 (default, Oct 4 2017, 06:09:15)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
>>> import numpy as np
>>> w = np.random.rand(3,2)
>>> var = tf.Variable(w)
>>> var.get_shape().as_list()
[3, 2]
>>> list(w.shape)
[3, 2]
>>>
在上面的会话中,我们创建一个变量并在其上运行get_shape() 方法以检索其形状尺寸。现在,get_shape() 方法是 tf.Tensor API 方法,您可以看到 here。
所以回到我的问题,tf.Tensor API 的哪些部分是 tf.Variable 实现的。如果答案是全部,为什么上面的测试用例会失败?
self.assertShapeEqual(w, foo.w)
与
raise TypeError("tf_tensor must be a Tensor")
我很确定我在这里遗漏了一些基本的东西,或者它可能是 assertShapeEqual 中的一个错误?如果有人能对此有所了解,我将不胜感激。
我在 macOS 上使用以下版本的 tensorflow 和 python3:
tensorflow (1.4.1)
【问题讨论】: