【T-Tensorflow框架学习】 Tensorflow.eval和Session.run启动计算图的用法和区别

版权声明:转载请声名出处,谢谢 https://blog.csdn.net/u010591976/article/details/82215624

Session.run()和Tensor.eval():
eval() 是tf.Tensor的Session.run() 另外一种写法,但两者有差别,如果你有一个Tensor t,在使用t.eval()时,等价于:tf.get_default_session().run(t).这其中最主要的区别就在于你可以使用sess.run()在同一步获取多个tensor中的值

  1. eval(): 将字符串string对象转化为有效的表达式参与求值运算返回计算结果
  2. 基于Tensorflow的基本原理,首先需要定义图,然后计算图,其中计算图的函数常见的有run()函数,如sess.run()。eval()也是启动计算的一种方式。
  3. 在Tensorflow中不可以直接打印Tensorflow对象,后面必须加上eval()也是这个原因。必须气动计算图才能打印。
  4. eval()只能用于tf.Tensor类对象,也就是有输出的Operation。对于没有输出的Operation, 可以用.run()或者Session.run();Session.run()没有这个限制。

Tensor.run和Tensor.eval的区别
在会话中需要运行节点,会碰到两种方式:Session.run()和Tensor.eval()

#推荐使用with结构,with小写
import tensorflow as tf

arr = np.array([[1,1],[2,2]])
#rank函数看矩阵维度
#tensorflow中打印东西需要加上evl)
c = tf.rank(arr) #返回维度
d = tf.shape(arr) #返回行*列

with tf.Session() as sess:
    c.eval() # runs one step
    d.eval() # runs one step
    sess.run([c,d]) #evaluates both tensors in a single step

    print(sess.run(c), sess.run(d))
    print(sess.run([c,d]))
    print(c.eval(), d.eval())

参考博客:
https://segmentfault.com/a/1190000015287066
https://blog.csdn.net/chengshuhao1991/article/details/78554743

猜你喜欢

转载自blog.csdn.net/u010591976/article/details/82215624