首页 > 解决方案 > ValueError:形状在assign_add()中的等级必须相等

问题描述

我正在阅读TF2 中 Tensorflow r2.0中的 tf.Variable:

import tensorflow as tf

# Create a variable.
w = tf.constant([1, 2, 3, 4], tf.float32, shape=[2, 2])

# Use the variable in the graph like any Tensor.
y = tf.matmul(w,tf.constant([7, 8, 9, 10], tf.float32, shape=[2, 2]))
v= tf.Variable(w)
# The overloaded operators are available too.
z = tf.sigmoid(w + y)
tf.shape(z)
# Assign a new value to the variable with `assign()` or a related method.
v.assign(w + 1)
v.assign_add(tf.constant([1.0, 21]))

ValueError: Shapes must be equal rank, but are 2 and 1 for 'AssignAddVariableOp_4' (op: 'AssignAddVariableOp') with input shapes: [], 2 .

还有为什么下面的返回错误?

tf.shape(v) == tf.shape(tf.constant([1.0, 21],tf.float32))

我的另一个问题是,当我们在 TF 2 中时,我们不应该再使用 tf.Session() 了,对吗?似乎我们永远不应该运行 session.run(),但是 API 文档密钥使用 tf.compat.v1 等执行它。那么为什么他们在 TF2 文档中使用它呢?

任何帮助,将不胜感激。

CS

标签: tensorflow2.0valueerror

解决方案


正如它在错误中明确指出的那样,它期望形状为 [2,2] 的assign_addv 上的形状为 [2,2]。如果您尝试给出除您尝试执行的张量的初始形状之外的任何形状,assign_add则会给出错误。

下面是修改后的代码,具有操作的预期形状。

import tensorflow as tf

# Create a variable.
w = tf.constant([1, 2, 3, 4], tf.float32, shape=[2, 2])

# Use the variable in the graph like any Tensor.
y = tf.matmul(w,tf.constant([7, 8, 9, 10], tf.float32, shape=[2, 2]))
v= tf.Variable(w)
# The overloaded operators are available too.
z = tf.sigmoid(w + y)
tf.shape(z)
# Assign a new value to the variable with `assign()` or a related method.
v.assign(w + 1)
print(v)
v.assign_add(tf.constant([1, 2, 3, 4], tf.float32, shape=[2, 2]))  

v 的输出:

<tf.Variable 'UnreadVariable' shape=(2, 2) dtype=float32, numpy=
array([[3., 5.],
       [7., 9.]], dtype=float32)> 

现在下面的张量比较正在返回True

tf.shape(v) == tf.shape(tf.constant([1.0, 21],tf.float32)) 

<tf.Tensor: shape=(2,), dtype=bool, numpy=array([ True, True])>

谈到你的tf.Session()问题,在 TensorFlow 2.0 中,Eager Execution 默认是启用的,但如果你需要禁用 Eager Execution 并且可以tf.Session像下面这样使用。

import tensorflow as tf

tf.compat.v1.disable_eager_execution()

hello = tf.constant('Hello, TensorFlow!')

sess = tf.compat.v1.Session()

print(sess.run(hello)) 

推荐阅读