簡體   English   中英

ValueError:使用 tf.optimizers.Adam.minimize 方法時沒有為任何變量提供梯度

[英]ValueError: No gradients provided for any variable when using tf.optimizers.Adam.minimize method

我正在嘗試使用這些代碼行與舊版本的 Tensorflow (在 ML 在線課程上看到)做的事情

optimizer = tf.train.AdamOptimizer(learning_rate)
train_step = optimiser.minimize(loss)

並檢查以前回答的問題和文檔,我發現var_list現在是一個必需的參數,如果loss作為張量提供,則必須提供計算損失的磁帶。 所以我必須編寫以下代碼:

optimizer = tf.optimizers.Adam(learning_rate=learning_rate)
params = [w1, b1, w2, b2, w3, b3]
gradients = optimizer.get_gradients(loss=loss, params=params)
train_step = optimizer.minimize(loss=loss, var_list=params, tape=tf.GradientTape(), grad_loss=gradients)

但我仍然收到錯誤:

ValueError: No gradients provided for any variable: (['Variable:0', 'Variable_1:0',
 'Variable_8:0', 'Variable_9:0', 'Variable_12:0', 'Variable_13:0'],). Provided 
`grads_and_vars` is ((None, <tf.Variable 'Variable:0' shape=(784, 512) dtype=float32>),
 (None, <tf.Variable 'Variable_1:0' shape=(512,) dtype=float32>), (None, <tf.Variable 
'Variable_8:0' shape=(512, 64) dtype=float32>), (None, <tf.Variable 'Variable_9:0' 
shape=(64,) dtype=float32>), (None, <tf.Variable 'Variable_12:0' shape=(64, 10) 
dtype=float32>), (None, <tf.Variable 'Variable_13:0' shape=(10,) dtype=float32>)).

我以為我會解決使用get_gradients方法計算梯度並將其作為grad_loss參數提供的問題,但它仍然不起作用。 我什至不完全確定我應該提供所有這六個參數,但我正在使用的神經網絡的架構實際上由兩個隱藏層和一個 output 層組成,每個層都有權重和偏差。

非常感謝你提前

一個可能的解決方案是簡單地使用以前版本的 Tensorflow:

首先我需要以這種方式初始化(我使用 tf1 因為對於其他功能或方法我更喜歡使用更新版本,這意味着我還將import tensorflow as tf

import tensorflow.compat.v1 as tf1
tf.compat.v1.disable_eager_execution()
tf1.disable_v2_behavior()

然后代碼是

optimizer = tf1.train.AdamOptimizer(learning_rate)
train_step = optimizer.minimize(loss=loss)

所以我正在使用舊的AdamOptimizer

但是,如果有人知道如何使用最新版本的 Tensorflow 做同樣的事情,我會非常高興知道。 謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM