![](/img/trans.png)
[英]ValueError: No gradients provided for any variable - Tensorflow 2.0
[英]"ValueError: No gradients provided for any variable: ['Variable:0']." in Tensorflow2.0
我想通過定義損失“loss_mu”來更新變量參數“mus”並使用 optimizer.adam 對其進行優化,我遇到了一個問題:“ValueError:沒有為任何變量提供梯度:['Variable:0']。”
accs = []
max_acc = 0.9
loss_mu = 0
M = 6
sigma = 0.25
optim_mus = tf.keras.optimizers.Adam(lr=0.05)
mus = tf.Variable(tf.convert_to_tensor(np.concatenate([np.ones([6, ]), np.zeros([6, ])])), dtype=tf.float64)
dist = tfp.distributions.MultivariateNormalDiag(mus, tf.cast(np.ones(2 * M) * sigma, dtype=tf.float64))
thetas = dist.sample((4,))
for i in range(4):
max_acc = dict_m['Max_acc{}'.format(i)]
acc = dict_m['acc{}'.format(i)]
accs += acc
loss_mu -= dist.log_prob(thetas[i]) * (max_acc - np.mean(accs)) / (np.std(accs) + np.finfo(np.float32).eps.item())
loss_mu = loss_mu/self.B
with tf.GradientTape() as Tape:
grad = Tape.gradient(loss_mu, [mus])
optim_mus.apply_gradients(zip(grad, [mus,]))
當我打印 grad 時,我發現它是 [None],我是 tensorflow2.0 的新手,不知道如何修復它
我已經解決了這個問題,我沒有在代碼行“with GradientTape as tape:”下面添加 tape.watch(mus)。 所以 mus 沒有以原始方式更新。 更多細節在ValueError: No gradients provided for any variable: ['Variable:0']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.