【发布时间】:2016-06-28 14:03:17
【问题描述】:
我想在 tensorflow 中使用动态输入进行 for 循环。
我知道reduce_sum 下面的代码就足够了,但是我希望能够以下面描述的方式来制定代码。因此,鉴于我有一个不同大小的数组,我想遍历该数组。
如何遍历动态长度数组?
问题:
TypeError: range() integer end argument expected, got Tensor
如何评估会话之外的 get_sum?
sum = get_sum(x, xshape) 不应在会话内的 for 循环中
例如:
import tensorflow as tf
import numpy as np
x = tf.placeholder(tf.float32, shape=[None])
xshape = tf.placeholder(tf.float32, shape=[])
def get_sum(x, xshape):
sum = 0
for i in range(xshape):
sum += x[i]
init = tf.initialize_all_variables()
sum = get_sum(x, xshape)
with tf.Session() as sess:
sess.run(init)
for i in range(100):
length = np.random.randint(0,10)
a = np.random.randint(0, 10, length)
print sess.run(sum,feed_dict={x:a, xshape:length})
【问题讨论】:
-
如果事先不知道迭代次数,那另一种循环不是更合适吗?
-
什么样的循环?
-
可能是
while循环。 -
同样的问题,你不能得到整数的形状;你将如何使用while循环?-问题是将形状转换为整数,我们需要对其进行评估;问题是怎么回事?
-
所以你的问题与循环无关,而是如何获得某个整数:明白了。
标签: python loops for-loop dynamic tensorflow