import tensorflow as tf
import numpy as np
x = np.array([1.0, 1.0, 1.0])
z = tf.ones((1, 3))
out = tf.ones((1, 3))
print('out:', out)
i = tf.constant(0)
def cond(i, _):
return i < 10
def body(i, out):
i = i + 1
out = tf.concat([out, out], axis=0)
return [i, out]
_, out = tf.while_loop(cond, body, [i, out], shape_invariants=[i.get_shape(), tf.TensorShape([None])])
sess = tf.Session()
sess.run(tf.global_variables_initializer())
res = sess.run([_, out])
print(res)
我希望打印([[1,1,1],[1,1,1]]...。) 形状=(10,3)
但打印” ValueError:为ones_1:0指定的形状不变性与循环变量的初始形状不兼容。它以形状(1、3)进入循环,但指定的形状不变性为(?,) 。”
答案 0 :(得分:0)
您应该更改以遵循代码。
_, out = tf.while_loop(cond, body, [i, out], shape_invariants=[i.get_shape(), tf.TensorShape([None,3])])
修改
以上代码用于解决错误。如果要输出(10,3),则应修改body()
。
import tensorflow as tf
import numpy as np
x = np.array([1.0, 1.0, 1.0])
z = tf.ones((1, 3))
out = tf.ones((1, 3))
print('out:', out)
i = tf.constant(0)
def cond(i, _):
return i < 9
def body(i, new_out):
i = i + 1
new_out = tf.concat([new_out, out], axis=0)
return [i, new_out]
_, out = tf.while_loop(cond, body, [i, out], shape_invariants=[i.get_shape(), tf.TensorShape([None,3])])
sess = tf.Session()
sess.run(tf.global_variables_initializer())
res = sess.run([_, out])
print(res[1].shape)
# print
(10, 3)
答案 1 :(得分:0)
您无法获得形状[10,3],而您会获得形状[2 ** n,3],n是cond()函数中的值(i import tensorflow as tf
out = tf.ones((1, 3))
i = tf.constant(0)
def cond(i, _):
i += 1
return i < 4
def body(i, out):
i = i + 1
out = tf.concat([out, out], axis=0)
return i, out
_, out = tf.while_loop(cond, body, [i, out], shape_invariants=[i.get_shape(), tf.TensorShape([None, 3])])
sess = tf.Session()
sess.run(tf.global_variables_initializer())
_, res = sess.run([_, out])
print(res)
print(res.shape)