Tensorflow中的单元测试类tf.test
概述
Tensorflow中有一个类tf.test用来做单元测试,它继承于类unittest.TestCase,里面包含了Tensorflow做单元测试相关的方法。
示例
import tensorflow as tf
class SquareTest(tf.test.TestCase):
def testSquare(self):
with self.test_session():
# 平方操作
x = tf.square([2, 3])
# 测试x的值是否等于[4,9]
self.assertAllEqual(x.eval(), [4, 9])
if __name__ == "__main__":
tf.test.main()
程序从入口运行,tf.test.main()运行所有的单元测试,通过self.assertAllEqual(x.eval(), [4, 9])判断x的值是否等于[4,9],运行结果如下:
..
----------------------------------------------------------------------
Ran 2 tests in 0.059s
OK
如果把代码改为:
import tensorflow as tf
class SquareTest(tf.test.TestCase):
def testSquare(self):
with self.test_session():
# 平方操作
x = tf.square([2, 3])
# 测试x的值是否等于[3,9]
self.assertAllEqual(x.eval(), [3, 9])
if __name__ == "__main__":
tf.test.main()
运行后,测试失败,有一半错误,结果如下:
AssertionError:
Arrays are not equal
(mismatch 50.0%)
x: array([4, 9], dtype=int32)
y: array([3, 9])
----------------------------------------------------------------------
Ran 2 tests in 0.028s
FAILED (failures=1)
修改代码如下:
import tensorflow as tf class SquareTest(tf.test.TestCase): def tes1tSquare(self): with self.test_session(): # 平方操作 x = tf.square([2, 3]) # 测试x的值是否等于[4,9] self.assertAllEqual(x.eval(), [3, 9]) if __name__ == "__main__": tf.test.main()
运行结果为
---------------------------------------------------------------------- Ran 1 test in 0.018s OK
测试并未执行。
官网链接
#### 转自:https://blog.csdn.net/fegang2002/article/details/82947211