我正在TF2中阅读tf.Variable in Tensorflow r2.0:
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:形状必须相等,但对于2和1 输入形状为'AssignAddVariableOp_4'(op:'AssignAddVariableOp'): [],2。
还有以下原因返回假?
tf.shape(v) == tf.shape(tf.constant([1.0, 21],tf.float32))
我的另一个问题是,当我们进入TF 2时,我们不应该再使用tf.Session()了吗?似乎we should never run session.run(),但API文档使用tf.compat.v1等来实现此功能。那么为什么他们在TF2文档中使用它?
任何帮助将不胜感激。
CS
答案 0 :(得分:0)
正如在错误中明确指出的那样,期望assign_add
上的形状为[2,2]的形状为[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中,默认情况下仍启用急切执行,但是,如果您需要禁用急切执行并可以使用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))