在Tensorflow中更改新指定变量的形状

问题描述 投票:1回答:1

如果你用tf.assign validate_shape=False使用the shape is not updated更改tf.Variable。

但是,如果我使用set_shape来设置新的(正确的)形状,我会得到一个ValueError。

这是一个简单的例子:

import tensorflow as tf 

a = tf.Variable([3,3,3])

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    # [3 3 3]
    print(sess.run(a))

    sess.run(tf.assign(a, [4,4,4,4], validate_shape=False))
    # [4 4 4 4]
    print(sess.run(a))

# (3,)
print(a.get_shape())

# ValueError: Dimension 0 in both shapes must be equal, but are 3 and 4. Shapes are [3] and [4].
a.set_shape([4])

如何更改变量的形状?

注意:我知道如果我使用a = tf.Variable([3,3,3], validate_shape=False)代码有效但在我的上下文中我将无法自己初始化变量。

python tensorflow
1个回答
0
投票

告诉图表的静态部分,从一开始就不知道形状。

a = tf.Variable([3,3,3], validate_shape=False)

现在,为了获得形状,你无法静态地知道,所以你必须要问会话,这是完全合理的:

print(sess.run(tf.shape(a)))
© www.soinside.com 2019 - 2024. All rights reserved.