python-2.7 - Tensorflow while 循环 : dealing with lists

标签 python-2.7 while-loop tensorflow

import tensorflow as tf

array = tf.Variable(tf.random_normal([10]))
i = tf.constant(0)
l = []

def cond(i,l):
   return i < 10

def body(i,l):
   temp = tf.gather(array,i)
   l.append(temp)
   return i+1,l

index,list_vals = tf.while_loop(cond, body, [i,l])

我想以上述代码中描述的类似方式处理张量数组。在while循环的主体中,我想逐个元素地处理数组以应用一些函数。为了演示,我给出了一个小代码片段。但是,它给出了如下错误消息。
ValueError: Number of inputs and outputs of body must match loop_vars: 1, 2

对解决此问题的任何帮助表示赞赏。

谢谢

最佳答案

引用文档:

loop_vars is a (possibly nested) tuple, namedtuple or list of tensors that is passed to both cond and body



您不能将常规 python 数组作为张量传递。你可以做的是:
i = tf.constant(0)
l = tf.Variable([])

def body(i, l):                                               
    temp = tf.gather(array,i)
    l = tf.concat([l, [temp]], 0)
    return i+1, l

index, list_vals = tf.while_loop(cond, body, [i, l],
                                 shape_invariants=[i.get_shape(),
                                                   tf.TensorShape([None])])

形状不变量在那里,因为通常 tf.while_loop预计 while 循环内张量的形状不会改变。
sess = tf.Session()
sess.run(tf.global_variables_initializer())
sess.run(list_vals)
Out: array([-0.38367489, -1.76104736,  0.26266089, -2.74720812,  1.48196387,
            -0.23357525, -1.07429159, -1.79547787, -0.74316853,  0.15982138], 
           dtype=float32)

关于python-2.7 - Tensorflow while 循环 : dealing with lists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41233462/

相关文章:

python - 使用 Mechanize 修改表单

python - 使用子进程处理多个管道命令

python - 如何检查一个字符串中的字母是否在另一字符串中

Python "logging"模块获取日志消息以进行解析

java - 在java中多次搜索文本文档

while-loop - 在 UML 序列图中绘制 while 循环?

python - Tensorflow Windows 访问文件夹被拒绝 :"NewRandomAccessFile failed to Create/Open: Access is denied. ; Input/output error"

python - 如何根据温度读数打开/关闭 LED?

python - 在 tensorflow 中使用 bool 张量选择张量的子集

python - 在 Keras 中加载模型权重时出现问题