在一些任务中,经常需要看tensor的具体值是多少,举个例子,你得查看一部分的feature map,或者是一些数据是否符合训练的预期,那么怎么查看对应tensor的具体值(⊙o⊙)?
有些小伙伴可能会特别不屑,print一下不就好了?哈哈,要是直接print有效, LZ还花这闲工夫干啥!
举个例子,不难.
我们先生成一些随机数
import numpy as np
np.random.seed(100)
triangles = np.random.rand(1, 5, 3, 3).astype('float32')
使用print打印一下:
print triangles
显示如下:
[[[[0.54340494 0.2783694 0.4245176 ]
[0.84477615 0.00471886 0.12156912]
[0.67074907 0.82585275 0.13670659]]
[[0.5750933 0.89132196 0.20920213]
[0.18532822 0.10837689 0.21969749]
[0.9786238 0.8116832 0.17194101]]
[[0.81622475 0.27407375 0.4317042 ]
[0.9400298 0.81764936 0.33611196]
[0.17541045 0.37283206 0.00568851]]
[[0.25242636 0.7956625 0.01525497]
[0.5988434 0.6038045 0.10514768]
[0.38194343 0.03647606 0.89041156]]
[[0.98092085 0.05994199 0.89054596]
[0.5769015 0.7424797 0.63018394]
[0.5818422 0.02043913 0.21002658]]]]
OK,然后我们将数据转化成tensor类型,在使用print进行打印,看下会发生什么?
inp = tf.constant(traingles)
print inp
显示如下:并没有输出具体数值,同样也就没有办法对所获得的tensor进行分析
Tensor("Const:0", shape=(1, 5, 3, 3), dtype=float32)
解决方法有两种:
第一种:利用session.run()进行处理
sess = tf.Session()
print(sess.run(inp))
最后的显示结果如此啊所示:
[[[[0.54340494 0.2783694 0.4245176 ]
[0.84477615 0.00471886 0.12156912]
[0.67074907 0.82585275 0.13670659]]
[[0.5750933 0.89132196 0.20920213]
[0.18532822 0.10837689 0.21969749]
[0.9786238 0.8116832 0.17194101]]
[[0.81622475 0.27407375 0.4317042 ]
[0.9400298 0.81764936 0.33611196]
[0.17541045 0.37283206 0.00568851]]
[[0.25242636 0.7956625 0.01525497]
[0.5988434 0.6038045 0.10514768]
[0.38194343 0.03647606 0.89041156]]
[[0.98092085 0.05994199 0.89054596]
[0.5769015 0.7424797 0.63018394]
[0.5818422 0.02043913 0.21002658]]]]
第二种方法:
with tf.Session():
print(inp.eval())
最后打印结果也是一致的
[[[[0.54340494 0.2783694 0.4245176 ]
[0.84477615 0.00471886 0.12156912]
[0.67074907 0.82585275 0.13670659]]
[[0.5750933 0.89132196 0.20920213]
[0.18532822 0.10837689 0.21969749]
[0.9786238 0.8116832 0.17194101]]
[[0.81622475 0.27407375 0.4317042 ]
[0.9400298 0.81764936 0.33611196]
[0.17541045 0.37283206 0.00568851]]
[[0.25242636 0.7956625 0.01525497]
[0.5988434 0.6038045 0.10514768]
[0.38194343 0.03647606 0.89041156]]
[[0.98092085 0.05994199 0.89054596]
[0.5769015 0.7424797 0.63018394]
[0.5818422 0.02043913 0.21002658]]]]
如果不先注册session,直接运行
print(inp.eval())
那么就会报错,如下所示:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 606, in eval
return _eval_using_default_session(self, feed_dict, self.graph, session)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 3914, in _eval_using_default_session
raise ValueError("Cannot evaluate tensor using `eval()`: No default "
ValueError: Cannot evaluate tensor using `eval()`: No default session is registered. Use `with sess.as_default()` or pass an explicit session to `eval(session=sess)`
Y(o)Y,好啦,这个就是tensorflow输出tensor具体值的一个小技巧,O(∩_∩)O哈哈~,Felaim要继续加油呢!