![](/img/trans.png)
[英]tensorflow:AttributeError: 'module' object has no attribute 'mul'
[英]AttributeError: module 'tensorflow' has no attribute 'assign'
我正在嘗試將我以前的 tf1 代碼遷移到 tf2。 不幸的是,我的代碼沒有處於渴望模式,所以我遇到了更多困難。 我做了以下代碼(尚未訓練),我收到了錯誤消息:
Traceback (most recent call last):
training_op = tf.assign(W, W - learning_rate * gradients)
AttributeError: module 'tensorflow' has no attribute 'assign'
這是我的最小代碼示例 PS:它必須使用復數!
# Data pre-processing
m = 50
n = 20
x_train, y_train, x_test, y_test = get_my_data(x, y, m, n) # data x of size mxn
# Network Declaration
input_size = n
output_size = 1
learning_rate = 0.001 # The optimization learning rate
# Create weight matrix initialized randomely from N~(0, 0.01)
W = tf.Variable(tf.complex(np.random.rand(input_size, output_size),
np.random.rand(input_size, output_size)), name="weights")
with tf.GradientTape() as gtape:
y_out = tf.matmul(x_train, W, name="out")
error = y - y_out
loss = tf.reduce_mean(tf.square(tf.abs(error)), name="mse")
gradients = gtape.gradient(loss, [W])[0]
training_op = tf.assign(W, W - learning_rate * gradients)
我手動執行此操作,因為除非他們更改,否則復數不支持優化器,因此我“手動”執行此操作。
改用tf.compat.v1.assign
。 它對我有用。
tf.assign*
函數可用作 TF 2.0 中tf.Variable
上的方法。 因此,您的示例可以重寫為
with tf.GradientTape() as gtape:
...
W.assign_sub(learning_rate * gradients)
請注意,與 TF 1.X 中的tf.assign
不同, tf.Variable.assing_sub
將急切地執行分配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.