javascript - 训练简单策略代理时遇到问题。错误:找不到任何变量与损失函数 y=f(x) 的结果之间的联系
问题描述
我正在尝试使用 tensorflow.js 和节点创建一个用于玩井字游戏的策略网络代理。
当我在游戏结束时运行训练步骤时,我得到以下信息
Error: Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize().
class NNModel {
constructor(learning_rate = 0.01){
this.learning_rate = learning_rate
this.model = this.createModel()
}
train(actions, rewards, boards) {
const optimizer = tf.train.rmsprop(this.learning_rate, 0.99)
optimizer.minimize(() => {
const oneHotLabels = tf.oneHot(actions, BOARD_SIZE).dataSync()
const logits = this.model.predict(tf.tensor(boards)).dataSync()
const crossEntropies = tf.losses.softmaxCrossEntropy(oneHotLabels, logits).asScalar()
const loss = tf.tensor(rewards).mul(crossEntropies)
return loss
})
}
createModel() {
const model = tf.sequential()
model.add(
tf.layers.dense({
units: BOARD_SIZE * 3 * 9,
activation: 'relu',
inputShape: [BOARD_SIZE * 3]
})
)
model.add(
tf.layers.dense({
units: BOARD_SIZE,
})
)
return model
}
}
在我的 SimplePolicyAgent 中,作为每个移动步骤的一部分,我将棋盘状态保存到日志中,使用模型选择移动并将其保存到日志中。
在游戏结束时,我得到结果并创建一个与移动日志长度相同的列表,并根据游戏结果提供奖励。
然后我用动作、奖励和板子调用 train 函数。
我希望这一步可以更新模型权重,以便模型更有可能为给定的棋盘状态选择获胜的动作。
我正在尝试模拟以下 python 实现
#loss
cross_entropies tf.losses.softmax_cross_entropy(one_hot_labels=tf.one_hot(actions, 7), logits=Ylogits)
loss = tf.reduce_sum(rewards * cross_entropies)
#training op
optimizer = tf.train.RMSPropOptimizer(learning_rate=0.001, decay=0.99)
train_op = optimizer.minimize(loss)
感谢您阅读我的问题
解决方案
train(actions, rewards, boards) {
const optimizer = tf.train.rmsprop(this.learning_rate, 0.99)
return optimizer.minimize(() => {
const oneHotLabels = tf.oneHot(actions, BOARD_SIZE)
const logits = this.model.predict(tf.tensor(boards))
const crossEntropies = tf.losses.softmaxCrossEntropy(oneHotLabels, logits)
const loss = tf.sum(tf.tensor(rewards).mul(crossEntropies)).asScalar()
return loss
})
}
这段代码现在运行没有错误,我错误地添加.dataSync()
到oneHotLabels
并且logits
隐藏了最小化函数的变量。
推荐阅读
- javascript - 只点击一次
- google-maps - 颤动谷歌地图在运行时更新地图样式
- interface - 界面中包含的 Graphql 类型未添加到 graphene-django 中的模式
- flutter - 我无法构建我的颤振 Web 项目
- javascript - 隐藏的输入不会触发 React 的 onChange 事件
- python - 将推文导出到数据框
- php - 如何使用 travist/jsencrypt 加密的 phpseclib 类 Crypt_RSA 解密数据
- regex - 如何在第一个角色中开始我的模式
- html - 在两个网格项之间插入一个新的 div
- android - 如何使用 build.gradle 文件中的 V1(Jar 签名)或 V2(完整 APK 签名)