Skip to main content
 首页 » 编程设计

python之循环的可变长度之tensorflow

2025年04月02日33itcoder

我想在 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