1.问题
想查看tensor的值,print后,只能 看到它的类型信息,而我想看的是value。
问题现场:
# -*- coding: utf-8 -*-
import tensorflow as tf
a=tf.constant(2)
b=tf.constant(3)
x=tf.constant(4)
y=tf.constant(5)
print a
print b
print x
print y
输出:
Tensor("Const:0", shape=(), dtype=int32)
Tensor("Const_1:0", shape=(), dtype=int32)
Tensor("Const_2:0", shape=(), dtype=int32)
Tensor("Const_3:0", shape=(), dtype=int32)
其实我想到的就是:
2
3
4
5
原因:
print只能打印输出shape的信息,而要打印输出tensor的值,需要借助 tf.Session
,tf.InteractiveSession
。TensorFlow是惰性语法,没有OP(加减乘除)使用这些Tensor,就不真正计算赋值。
因为我们在建立graph的时候,只建立 tensor 的 结构形状信息 ,并没有 执行 数据的操作。
2.解决
使用tf.Session。
Session
是 Tensorflow 为了控制,和输出文件的执行的语句. 运行 session.run()
可以获得你要得知的运算结果, 或者是你所要运算的部分.
# -*- coding: utf-8 -*-
import tensorflow as tf
a=tf.constant(2)
b=tf.constant(3)
x=tf.constant(4)
y=tf.constant(5)
with tf.Session() as sess:
print sess.run(a)
print sess.run(b)
print sess.run(x)
print sess.run(y)
输出:
2
3
4
5
另外一种使用tf.InteractiveSession
# -*- coding: utf-8 -*-
import tensorflow as tf
a=tf.constant(2)
b=tf.constant(3)
x=tf.constant(4)
y=tf.constant(5)
sess = tf.InteractiveSession()
print a.eval()
print b.eval()
print x.eval()
print y.eval()
3.tf.Session和
tf.InteractiveSession的区别
tf.InteractiveSession()默认自己就是用户要操作的session,而tf.Session()没有这个默认,因此用eval()启动计算时需要指明session。
意思就是在我们使用tf.InteractiveSession()来构建会话的时候,我们可以先构建一个session然后再定义操作(operation),如果我们使用tf.Session()来构建会话我们需要在会话构建之前定义好全部的操作(operation)然后再构建会话。
官方tutorial是这么说的:
The only difference with a regular Session is that an InteractiveSession installs itself as the default session on construction. The methods Tensor.eval() and Operation.run() will use that session to run ops.
翻译一下就是:tf.InteractiveSession()是一种交互式的session方式,它让自己成为了默认的session,也就是说用户在不需要指明用哪个session运行的情况下,就可以运行起来,这就是默认的好处。这样的话就是run()和eval()函数可以不指明session。
参考
1.官方文档:https://www.tensorflow.org/api_docs/python/tf/compat/v1/InteractiveSession
2.二者区别:https://blog.csdn.net/M_Z_G_Y/article/details/80416226