如何在TensorFlow.js中使用maxPooling层时使用optimizer.minimize

当我使用optimizer.minimize()model.predict()来训练一个带有损失函数的模型时,在TensorFlow.js中遇到了问题。这仅在我在卷积神经网络中使用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()方法中的反向传播支持。你可以使用Model.apply()方法并设置{training: true}标志来修复你的代码。

即,将

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

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注