python - 类型错误 : 'Tensor' object cannot be interpreted as an integer

标签 python variables tensorflow size shapes

我正在尝试根据数组的大小运行一个循环。如何在 tensorflow 中做到这一点?例如

# input pipeline with all files available in the folder
a = tf.Variable([1,2,3,4,5],dtype = tf.int32)
loop = tf.size(a)
....
for i in range(loop):
    print(sess.run(a))

我想打印数组 a 5 次。但它说循环是一个张量对象,不能作为整数。 我尝试将循环变量作为

loop = tf.cast(tf.size(a),tf.int32),
loop = tf.shape_n(a),
loop = tf.shape(a)[0]

同样的错误。

最佳答案

不太确定你想在这里实现什么。 loop 是一个 tf.Tensorrange 需要一个 integer 作为参数,因此会出现错误。如果只想打印 5 次 a,为什么不直接将 loop 设置为数值 5?

否则,下面的代码应该可以工作,因为 loop.eval() 返回 loop 的值 5:

a = tf.Variable([1,2,3,4,5],dtype = tf.int32)
loop = tf.size(a)
....
for i in range(loop.eval()):
    print(sess.run(a))

如果不想多次执行TF图,看看tf.while_loop .

关于python - 类型错误 : 'Tensor' object cannot be interpreted as an integer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41788431/

相关文章:

python - 我怎样才能将这个格式化的字符串转换成键值字典形式?

python - 如何用python修改存储过程的输入值

python - pandas GroupBy 中按列表列分组

html - 在 Bash CGI 二进制文件中回显变量而不执行可能的恶意代码

python - 修改损失函数中的真实值

python - 如何在 Windows 中设置 LANG 变量?

c++ - 变量类型 global、static、local 和 auto

python - 为什么内部函数不能在python的外部范围内获取变量

tensorflow - 使用 libtensorflow_cc.so 使用 Tensorflow C++ API 的 header 列表

tensorflow - 创建 keras 回调以在训练期间保存每批的模型预测和目标