Tensorflow可以使用tensor的name索引tensor,用于sess.run

来源:互联网 发布:手机视频聊天软件 编辑:程序博客网 时间:2024/05/21 19:30

具体参考Tensorflow官网:https://www.tensorflow.org/api_docs/python/tf/Session
了解此信息的来源:https://stackoverflow.com/questions/37849322/how-to-understand-the-term-tensor-in-tensorflow

刚刚发现这个功能,一个直接好处就是使得函数接口更加简洁也易于修改,也不会增加太多工作量。原先通过函数构建计算图,为了得到输入输出的tensor索引,函数需要返回相应的tensor的reference。而如果使用name做索引,就不需要返回tensor了。因为验证模型正确性的过程中,会利用到tensorboard,那个时候就已经需要为绝大多数重要tensor命名了,并不会增加太多工作量。

具体例子如下:

import tensorflow as tfa = tf.placeholder(dtype=tf.float32,shape=[1],name='a')b = tf.add(a,tf.ones(1),name='b')sess = tf.Session()sess.run('b:0',feed_dict={'a:0':[3,]})

其中名字后面的’:’之后接数字为EndPoints索引值(An operation allocates memory for its outputs, which are available on endpoints :0, :1, etc, and you can think of each of these endpoints as a Tensor.),通常情况下为0,因为大部分operation都只有一个输出。
还要注意给不同tensor赋予同一个name(经常发生在实现循环神经网络的过程中)会导致tensor的name被系统自动修正。下面是一个简单的例子:

a = tf.placeholder(dtype=tf.float32,shape=[1],name='a')c = tf.ones(1,name='a')print(a,c)

返回

Tensor("a:0", shape=(1,), dtype=float32) Tensor("a_1:0", shape=(1,), dtype=float32)

注意到’:’后面的EndPoints索引并没有改变,而是前面name的部分做了修正,加入’_1’避免歧义。

原创粉丝点击