关于eval 函数和run函数
- eval函数:返回传入字符串的表达式的结果。
# coding:utf-8
import tensorflow as tf
x = 1
y = 2
print(eval('x+y'))
输出结果:
3
- run函数:常用于 Session.run() 执行图
# coding:utf-8
import tensorflow as tf
matrix1 = tf.Variable([[3., 3.]])
matrix2 = tf.constant([[2.], [2.]])
preduct = tf.matmul(matrix1, matrix2)
sess_ = tf.InteractiveSession() # 默认会话
tf.global_variables_initializer().run() # 初始化变量
print(preduct)
print(preduct.eval())
print(sess_.run(preduct))
sess_.close()
输出结果:
Tensor("MatMul:0", shape=(1, 1), dtype=float32)
[[12.]]
[[12.]]
结果分析:
1.执行 print(preduct)
参数 preduct 是一个Tensor(张量)所以打印结果为:
Tensor(“MatMul:0”, shape=(1, 1), dtype=float32)
2.执行 print(preduct.eval()) 和 print(sess_.run(preduct))
在上面的代码块中,对于单一的Tensor,执行两者效果相同
preduct.eval() 等价于 tf.get_default_session().run(preduct)
即 sess_.run(preduct)
对于多个Tensor,你可以使用sess.run()在同一步获取多个Tensor中的值,但是使用Tensor.eval()时只能在同一步当中获取一个tensor值,并且每次使用 eval 和 run时,都会执行整个计算图。
# coding:utf-8
import tensorflow as tf
t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.multiply(t, u)
ut = tf.add(u, t)
with tf.Session() as sess:
tu.eval() # runs one step
ut.eval() # runs one step
print(sess.run([tu, ut])) # evaluates both tensors in a single step
输出结果
[1554.0, 79.0]