现在我正在执行以下操作以访问我的图中的张量
graph = tf.get_default_graph()
add_0 = graph.get_tensor_by_name("Add:0")
add_1 = graph.get_tensor_by_name("Add_1:0")
add_2 = graph.get_tensor_by_name("Add_2:0")
当图很短时,这种方法是可以的。但对于较长的图表,它会变得非常无聊。
有没有办法以干净的方式收集所有以 Add 开头的张量?像这样的东西:
add = []
for Add in graph.get_tensors_by_name():
add.append(Add)
(我知道这个伪代码真的是错误的)
这样我得到 add = [add_0, add_1, add_2, ... ]
稍后我想用它来做到这一点:sess.run(add, feed_dict={input: data})
请您参考如下方法:
您可以使用 sess.graph.get_operations() 获取所有张量然后使用 startswith()选择你需要的。测试代码:
import tensorflow as tf
a = tf.constant( [ 1.0 ] )
b = tf.constant( [ 2.0 ] )
c = tf.add( a, b )
d = tf.add( c, b )
with tf.Session() as sess:
tensors = sum( [ operation.outputs
for operation in sess.graph.get_operations()
if operation.name.startswith( "Add") ],
[] )
print( tensors )
print( sess.run( tensors ) )
输出:
tf.Tensor 'Add:0' shape=(1,) dtype=float32, tf.Tensor 'Add_1:0' shape=(1,) dtype=float32
[array([3.], dtype=float32), array([5.], dtype=float32)]
