【问题标题】:variable length for loop - tensorflow可变长度循环 - tensorflow
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 现在情况如何?谢谢
  • 动态循环现在得到了很好的支持,并且有许多更高级别的运算符可以使它们更容易使用。您可以这样做,例如 elems = [1, 2, 3, 4, 5, 6] ; sum = tf.foldl(lambda a, x: a + x, elems),查看 tf.foldl 和 tf.scan API 文档。 tensorflow.org/api_docs/python/tf/foldl
猜你喜欢
  • 2018-08-30
  • 1970-01-01
  • 1970-01-01
  • 2017-02-05
  • 1970-01-01
  • 2016-12-01
  • 2021-10-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多