javascript - 如何在 TensorFlow.js 中将 optimizer.minimize 与 maxPooling 层一起使用
问题描述
在 TensorFlow.js 中使用optimizer.minimize()
withmodel.predict()
训练具有损失函数的模型时,我遇到了一个问题。只有当我maxPooling2D
在卷积神经网络中使用类似于下面代码的层时才会发生这种情况。它产生这个错误:Cannot read property 'backend' of undefined
。我不确定是什么原因造成的或如何解决它。tf.layers.conv2d()
使用没有任何池化层的卷积层 ( ) 时不会发生该错误。我正在使用 TensorFlow.js 版本0.14.2
和 Google Chrome 版本71.0.3578.98
。可以使用以下代码重现此错误:
loss = (pred, label) => pred.sub(label).square().mean();
optimizer = tf.train.sgd(0.001);
const input = tf.input({shape: [100, 100, 4]});
const conv = tf.layers.conv2d({
kernelSize: 5,
filters: 8,
strides: 1,
activation: 'relu',
kernelInitializer: 'VarianceScaling'
});
const pool = tf.layers.maxPooling2d({
poolSize: [2, 2],
strides: [2, 2]
});
const flat = tf.layers.flatten();
const dense = tf.layers.dense({units: 10});
const output = dense.apply(flat.apply(pool.apply(conv.apply(input))));
const model = tf.model({inputs: input, outputs: output});
for (var i = 0; i < 10; i++) {
optimizer.minimize(() =>
loss(model.predict([tf.ones([1, 100, 100, 4])]), tf.ones([1, 10]))
);
}
编辑:这已经解决了。有关详细信息,请参阅scai 的答案。
编辑 2:这似乎不是错误,而是使用model.predict()
. 更多信息
解决方案
在 TensorFlow.js 0.14+ 中,有一个更改禁用了 Model.predict() 方法中的反向传播支持。您可以使用带有 {training: true} 标志的 Model.apply() 方法来修复您的代码。
即,改变
optimizer.minimize(() =>
loss(model.predict([tf.ones([1, 100, 100, 4])]), tf.ones([1, 10]))
);
至
optimizer.minimize(() =>
loss(model.apply([tf.ones([1, 100, 100, 4])], {training: true}), tf.ones([1, 10]))
);
推荐阅读
- java - How to call Camel route that reads file?
- c# - 无法从小数中删除尾随零
- html - 哪些 MIME 类型可以显示在浏览器中
- javascript - 设置火力基地后,我收到以下错误:客户端无权访问所需数据
- r - 想要总结 R 中的多个列但没有正确总结
- excel - 如何构建水平循环?
- javascript - 如何更改点击功能添加的img src?
- python - (Python/JSON/MySQL)关于不会传输到数据库的 JSON 财务数据的建议
- python - How to share a variable across modules in Kivy
- reactjs - Unanswered: React Native - Apply animation every-time component updates