首页 > 解决方案 > TensforflowJS nodejs binding, unable to set custom optimzer

问题描述

I'm just getting started with tensorflowjs and tensorflow in general and I've run into an issue I can't quite solve. I'm trying to change the learning rate for an optimizer, but as soon a I use a custom optimizer I receive the following error:

User-defined optimizer must be an instance of tf.Optimizer

to create my model I'm doing the following (lifted from the docs here):

const model = tf.sequential();
  model.add(tf.layers.dense({units:1, inputShape:[11]}));
  model.compile({
    optimizer: tf.train.sgd(0.000001),
    loss: 'meanSquaredError'
  });

so as far as I can see everything should work. And if I just pass in the default 'sgd' optimzer it does indeed work.

model.compile({loss:'meanSquaredError', optimizer:'sgd'});

and the docs at https://js.tensorflow.org/api/latest/index.html#train.sgd also imply the first code snippet should be returning an SGDOptimizer.

Does anyone have any ideas what I'm doing wrong?

I'm running node V8 with the following tensorflow package

"@tensorflow/tfjs-core": "^0.14.2",
"@tensorflow/tfjs-node": "^0.1.21",

If I create my optimzer and store it in a separate variable. A console.log of that var gives the following:

SGDOptimizer {
  learningRate: 0.000001,
  c: 
   Tensor {
     isDisposedInternal: false,
     shape: [],
     dtype: 'float32',
     size: 1,
     strides: [],
     dataId: {},
     id: 4,
     rankType: '0' } }

So it appears it is initialized

标签: tensorflowtensorflow.js

解决方案


您不应该直接在 package.json 中导入 tfjs-core。如果单独导入 tfjs-node,它将导入正确的 tfjs-core 版本。

问题是你有双重依赖(我们将修复)。


推荐阅读