python - 循环的可变长度 - tensorflow

标签 python loops for-loop dynamic tensorflow

我想在 tensorflow 中使用动态输入进行 for 循环。

我知道下面的代码 reduce_sum 就足够了,但我希望能够按照下面描述的方式编写代码。因此,鉴于我有一个不同大小的数组,我想遍历该数组。

如何遍历动态长度数组?

问题:

TypeError: range() integer end argument expected, got Tensor

如何计算 session 外的 get_sum?

sum = get_sum(x, xshape) 不应在 session 内的 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})

最佳答案

动态循环在 TensorFlow 中还很年轻,但它们确实存在。以折叠运算符及其实现为例。 https://www.tensorflow.org/versions/master/api_docs/python/control_flow_ops.html#foldl

关于python - 循环的可变长度 - tensorflow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35972194/

相关文章:

python - 如何在 Python 3(0x80 及更高版本)中编写 ANSI 兼容字节?

python - imshow 和 histogram2d : can't get them to work

C++ 无限循环瓶颈?

c++ - 从体积或区域中的起点向外迭代而不对其进行排序

python - 将 numpy ndarray 写入 Image

MySql sql递归循环

loops - Lua 中的 "in"关键字有什么作用?

java - 我怎样才能简化这个奇数代码?

python - 有什么方法可以循环遍历 a-z 而不是编写多个 for 循环语句?

python - 使用 Python 中的其他数据库更新 2D 数据库 (CSV)?