python - Tensorflow:ValueError:没有为任何变量提供梯度
问题描述
我很困惑为什么以下函数会引发错误ValueError: No gradients provided for any variable
。
@tf.function
def train_network(model, optimizer, states, actions, rewards):
with tf.GradientTape() as tape:
predictions = model(states)
indices = tf.stack([tf.range(predictions.shape[0], dtype=tf.int64), actions], axis=1)
action_rewards = tf.scatter_nd(indices, rewards, predictions.shape)
loss = tf.keras.losses.MSE(predictions, action_rewards)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
return loss
我传递了模型和优化器,因为它们是类对象的一部分。但是正如我发现的那样,您不能将 tf.function 作为类函数。
如果我用 keras fit 函数尝试同样的事情,它工作得很好,例如。self.model.fit(np.array(states_epoch), np.array(rewards_epoch), batch_size=50)
.
我想用 tf 函数运行它,因为我的训练实际上更复杂,但对于这个例子,我尽可能地精简它。
更多信息:
states 是 float32,actions 是采取的行动的整数列表,reward 是收到的奖励的整数列表。
网络是一个简单的 DNN,优化器是 keras。
解决方案
推荐阅读
- html - 使屏幕阅读器以不同的方式阅读部分
- php - Wp-admin 页面重定向到 404 错误页面
- python - Flask / SQLAlchemy - 模型数据验证
- swift - 使用 Alamofire 结果和 present() 切换视图
- javascript - slate js:如何在悬停时突出显示具有相同标记的相邻组件?
- firebase - 如何在预定的 firebase 函数中调用 https firebase 函数以使其保持温暖并避免冷启动
- c# - RedirectToAction 到 ASP.NET MVC 中的异步方法
- c# - 如何仅使用 for 循环检查 2d 数组是否唯一
- reactjs - 如何在 Gatsby 的模板组件中访问上下文变量?
- sql - SQL Server:按特定日期将数据从一个数据库插入另一个数据库结构