Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用while循环迭代器修改tf变量_Python_Tensorflow - Fatal编程技术网

Python 如何使用while循环迭代器修改tf变量

Python 如何使用while循环迭代器修改tf变量,python,tensorflow,Python,Tensorflow,我想将张量切片并存储在变量中。使用固定数字进行切片效果很好,例如:t[0:2]。但是用另一个张量切片变量是行不通的。例如t[t1:t2]将切片存储在张量中也可以,但是当我尝试将其存储在tf.变量中时,会出现错误 import tensorflow as tf import numpy i=tf.zeros([2,1],tf.int32) i2=tf.get_variable('i2_variable',initializer=i) #putting a multidimensional ten

我想将张量切片并存储在变量中。使用固定数字进行切片效果很好,例如:
t[0:2]
。但是用另一个张量切片变量是行不通的。例如
t[t1:t2]
将切片存储在张量中也可以,但是当我尝试将其存储在tf.变量中时,会出现错误

import tensorflow as tf
import numpy

i=tf.zeros([2,1],tf.int32)
i2=tf.get_variable('i2_variable',initializer=i) #putting a multidimensional tensor in a variable
i4=tf.ones([10,1],tf.int32)
sess=tf.Session()
sess.run(tf.global_variables_initializer()) #initializing variables
itr=tf.constant(0,tf.int32)

def w_c(i2,itr):
    return tf.less(itr,2)

def w_b(i2,itr):
    i2=i4[(itr*0):((itr*0)+2)] #doesnt work
    #i2=i4[0:2] #works
    #i=i4[(itr*0):((itr*0)+2)] #works with tensor i 
    itr=tf.add(itr,1)
    return[i2,itr]
OP=tf.while_loop(w_c,w_b,[i2,itr])
print(sess.run(OP))
我发现以下错误:

ValueError: Input tensor 'i2_variable/read:0' enters the 
loop with shape (2, 1), but has shape (?, 1) after one iteration. 
To allow the shape to vary across iterations, 
use the `shape_invariants` argument of tf.while_loop to specify a less-specific shape.

如果指定
形状不变量
,则代码不会引发错误

   OP=tf.while_loop(w_c,w_b,[i2,itr],shape_invariants=
                                        [ tf.TensorShape([None, None]), 
                                          itr.get_shape()])
它返回这个

  [array([[1],
   [1]]), 2]

即使i2的形状与插入的值相同,也必须设置形状_不变量。无法提供专家意见。但是基于消息
循环的形状(2,1),但是在一次迭代后有形状(?,1)。
我将其放宽为更一般的形式。您也可以阅读我尝试过的tf.assign(i2,i4[(itr*0):((itr*0)+2)]。它正常工作,但在while循环体中不工作。。我得到一个错误,说Tensor对象没有属性“assign”。变量i2没有得到更新,因为它没有在while循环中分配和返回。assign返回一个张量,因此需要将其保存到一个节点中,并将该节点作为while循环变量调用sess.run([OP,i2])将其添加到代码的末尾,您将看到i2值没有改变。我已将答案恢复到其原始状态。你可以问另一个问题。