Skip to main content
 首页 » 编程设计

python之TensorFlow 2.0 : tf. GradientTape() 返回无结果

2024年11月24日30cloudgamer

我正在尝试在 TensorFlow 2.0 中训练 CNN 模型。这是一个多类分类任务。我正在简化代码以使其更具可读性:

# Loss function 
loss = tf.keras.metrics.CategoricalCrossentropy() 
 
# Optimizer 
optimizer = tf.optimizers.Adam(learning_rate = 0.0005) 
 
 
# Training: 
 
for epoch in range(1000): 
 
    # fetch mini batch of data 
    X_batch, y_batch = fetch_batch( [...] ) 
 
    with tf.GradientTape() as tape: 
        current_loss = loss(y_batch, CNN(X_batch))  # take current loss 
 
    # get the gradient of the loss function 
    gradients = tape.gradient(current_loss, CNN.trainable_variables) 
 
    # update weights 
    optimizer.apply_gradients(zip(gradients, CNN.trainable_variables)) 
 
    [ ... ] 

此时,我得到一个错误:

ValueError: No gradients provided for any variable ...

我知道问题出在哪里:当我调用 tape.gradient() 时出了点问题。如果我检查对象 gradient 这就是我得到的:

print(gradients) 

[None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]

我不明白为什么 gradients 会这样返回。我已经从字面上复制粘贴了用于在 TF 2.0 中训练其他(非 CNN)模型的代码,它们总是运行良好。我的模型的所有其他元素似乎都按预期运行。

--

PS:这个问题不同于this one ,基于 TF 1.x。

请您参考如下方法:

我想你想要 tf.keras.losses.CategoricalCrossentropy 作为你的损失,而不是 metrics 版本。这些实际上是不同的功能,而不是别名。