【发布时间】:2021-04-27 17:51:00
【问题描述】:
我一直在尝试使用 tfjs 建立一个简单的强化学习示例。但是,在尝试训练模型时,我遇到了以下错误:
Uncaught (in promise) Error: Error when checking target: expected dense_Dense5 to have shape [,1], but got array with shape [3,4]
我建立了如下模型:
const NUM_OUTPUTS = 4;
const model = tf.sequential();
//First hidden Layer, which also defines the input shape of the model
model.add(
tf.layers.dense({
units: LAYER_1_UNITS,
batchInputShape: [null, NUM_INPUTS],
activation: "relu",
})
);
// Second hidden Layer
model.add(tf.layers.dense({ units: LAYER_2_UNITS, activation: "relu" }));
// Third hidden Layer
model.add(tf.layers.dense({ units: LAYER_3_UNITS, activation: "relu" }));
// Fourth hidden Layer
model.add(tf.layers.dense({ units: LAYER_4_UNITS, activation: "relu" }));
// Defining the output Layer of the model
model.add(tf.layers.dense({ units: NUM_OUTPUTS, activation: "relu" }));
model.compile({
optimizer: tf.train.adam(),
loss: "sparseCategoricalCrossentropy",
metrics: "accuracy",
});
训练是由一个计算一些例子的 Q 值的函数完成的:
batch.forEach((sample) => {
const { state, nextState, action, reward } = sample;
// We let the model predict the rewards of the current state.
const current_Q: tf.Tensor = <tf.Tensor>model.predict(state);
// We also let the model predict the rewards for the next state, if there was a next state in the
//game.
let future_reward = tf.zeros([NUM_ACTIONS]);
if (nextState) {
future_reward = <Tensor>model.predict(nextState);
}
let totalValue =
reward + discountFactor * future_reward.max().dataSync()[0];
current_Q.bufferSync().set(totalValue, 0, action);
// We can now push the state to the input collector
x = x.concat(Array.from(state.dataSync()));
// For the labels/outputs, we push the updated Q values
y = y.concat(Array.from(current_Q.dataSync()));
});
await model.fit(
tf.tensor2d(x, [batch.length, NUM_INPUTS]),
tf.tensor2d(y, [batch.length, NUM_OUTPUTS]),
{
batchSize: batch.length,
epochs: 3,
}
);
这似乎是为拟合函数提供示例的正确方法,因为在记录模型时,最后一个密集层的形状是正确的:
Log of the shape of dense_Dense5
但是它会导致上面显示的错误,而不是预期的形状 [3,4] 它检查形状 [,1]。我真的不明白这个形状是从哪里突然来的,非常感谢一些帮助!
为了获得更好的概览,您可以简单地从其 Github 存储库中查看/签出整个项目:
有问题的 tensorflow 代码在 AI 文件夹中。
编辑:
提供模型摘要以及在model.fit(x,y) 中为y 提供的张量形状的一些信息:
【问题讨论】:
-
你能把
batchInputShape: [null, NUM_INPUTS],改成batchInputShape: [NUM_INPUTS]吗?无需添加null。 -
@yudhiesh 将 batchInputShape 更改为
[NUM_INPUTS]是不可能的,因为 batchInputShape 需要至少 2 个维度。但是,我确实尝试使用inputShape: [NUM_INPUTS]代替,您可以为其定义单个维度并自动化批量大小。这会导致相同的错误,尽管 Dense5 层以某种方式被假定为具有形状[,1]它应该具有的形状[batchLength, NUM_OUTPUTS] -
好的
batchInputShape应该是[batch_size, input_shape]。这也是分类还是回归任务?最后一层有一个带有 4 个输出的 relu 激活。 -
@yudhiesh 哦,好点!因为它应该预测动作的 Q 值,所以它是一个回归任务,我想在 RelU 那里不会走得太远。这可能解释了 [,1] 的预期输出形状。使用 RelU 作为输出可能需要一个带有类的标签?我可能应该只在最后一层不使用激活,然后让它只计算没有应用激活函数的值?
-
是的,对于 Q 值,删除最后一层的激活函数就可以了。
标签: tensorflow machine-learning reinforcement-learning tensorflow.js tfjs-node