[英]How to enumerate a tensor in tensorflow?
In Google's translate model file--seq2seq.py, they use 'enumerate' to enumerate a tensor in line 1195 as in the pictiure show, why when i try to enumerate a tensor but it shows 'TypeError: 'Tensor' object is not iterable.' 在Google的翻译模型文件seq2seq.py中,他们使用'enumerate'枚举第1195行中的张量,如在图片展示中所示,为什么当我尝试枚举张量但它显示'TypeError:'Tensor'对象是不可迭代的。” and i can't found any clue about how to enumerate a tensor in tensorflow's tutorial,can anyone help me? 我在tensorflow的教程中找不到有关如何枚举张量的任何线索,有人可以帮助我吗? Thanks! 谢谢! BY the way: my tensor is rank 4 enter image description here 顺便说一句:我是张4级在这里输入图像描述
You can slice and index tensors. 您可以切片和索引张量。 The only difference is that you need to run a session to get the values. 唯一的区别是您需要运行一个会话来获取值。 Here is a example of iterating 这是一个迭代的例子
foo = tf.constant([1,2,3,4,5,6,7,8,9,0])
sess = tf.Session();
for i in range(10):
print(sess.run(foo[i]))
sess.close()
Alternatively you can use a interactive session and directly call print(foo[i].eval())
另外,您可以使用交互式会话并直接调用print(foo[i].eval())
or enable eager execution and it becomes as easy as iterating a Python list. 或启用急切的执行,它变得与迭代Python列表一样容易。
tf.enable_eager_execution()
foo = tf.constant([1,2,3])
for i in foo:
print(i) #this prints the tensor including value
This prints 此打印
tf.Tensor(1, shape=(), dtype=int32) tf.Tensor(1,shape =(),dtype = int32)
tf.Tensor(2, shape=(), dtype=int32) tf.Tensor(2,shape =(),dtype = int32)
tf.Tensor(3, shape=(), dtype=int32) tf.Tensor(3,shape =(),dtype = int32)
In all above you will get a tensor not the exact value 在上述所有内容中,您将得到张量而不是确切值
This method does works for placeholders, constants and Variables. 该方法适用于占位符,常量和变量。
Only thing : For eager mode in Variables, you need to use tf.contrib.eager.Variable
, instead of tf.Variable
唯一的事情:对于Variables中的eager模式,您需要使用tf.contrib.eager.Variable
而不是tf.Variable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.