Tensorflow:“错误:没有为任何变量提供梯度”,且存在自定义损失

时间:2020-09-22 14:20:32

标签: python tensorflow gradient-descent backpropagation

尝试运行代码时出现错误

ValueError: No gradients provided for any variable

这是我的代码的样子

optimizer = tf.keras.optimizers.Adam(learning_rate=1e-2)

while True:
    #...other stuff

    if(isTimeToBackprop()):
         vStates = model.predict(modelInput)
         tdTargets = tf.ones(vStates.shape)

         loss = tf.math.reduce_mean(tf.math.squared_difference(vStates, tdTargets))

         callable = lambda : criticLoss
         optimizer.minimize(callable, var_list=model.trainable_variables)
   

涉及的所有变量均为类型

<class 'tensorflow.python.framework.ops.EagerTensor'>

我误会什么?

1 个答案:

答案 0 :(得分:1)

假设您正在使用Tensorflow 2.x,如果尝试创建自定义训练步骤以跟踪模型梯度,则必须在tf.GradientTape上下文管理器下调用模型。

这里,您的代码已更新为可以与GradientTape一起正常使用:

optimizer = tf.keras.optimizers.Adam(learning_rate=1e-2)

while True:
    #...other stuff

    if isTimeToBackprop():
        with tf.GradientTape() as tape:
            vStates = model(modelInput)
            tdTargets = tf.ones(vStates.shape)
            loss = tf.math.squared_difference(vStates, tdTargets)
            loss = tf.reduce_mean(loss)
        
        gradients = tape.gradient(loss, model.trainable_variables)
        optimizer.apply_gradients(zip(gradients, model.trainable_weights))
        # At this point the model is updated

还请注意,我使用的是 call 方法,而不是使用model.predict,这是您训练时应该使用的方法