首页 > 解决方案 > 如何在 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(). 更多信息

标签: javascriptmachine-learningconv-neural-networktensorflow.js

解决方案


在 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]))
);

推荐阅读