问题描述
我一直在尝试在强化学习中实现策略梯度算法。但是,我在计算自定义损失函数的梯度时遇到错误“ValueError:没有为任何变量提供梯度:”,如下所示:
def loss_function(prob,action,reward):
prob_action = np.array([prob.numpy()[0][action]]) #prob is like ->[0.4900,0.5200] and action is scalar index->1,0
log_prob = tf.math.log(prob_action)
loss = tf.multiply(log_prob,(-reward))
return loss
我正在计算梯度如下:
def update_policy(policy,states,actions,discounted_rewards):
opt = tf.keras.optimizers.SGD(learning_rate=0.1)
for state,reward,action in zip(states,discounted_rewards,actions):
with tf.GradientTape() as tape:
prob = policy(state,training=True)
loss = loss_function(prob,reward)
print(loss)
gradients = tape.gradient(loss,policy.trainable_variables)
opt.apply_gradients(zip(gradients,policy.trainable_variables))
请帮助我解决这个问题。 谢谢
解决方法
正如@gekrone 在评论中指出的那样,这绝对是由于 prob_action 是一个 numpy 数组而不是张量,梯度没有流动。还要注意不要使用 .numpy()
方法。可能会坚持类似的东西
prob_action = prob[0][action]
...
这应该有效。