Schotsl
Schotsl

Reputation: 227

Tensorflow.js loading model returns function predict is not defined

When I load a saved model like this (please dont mind the fact that the predict function has no input)

const tf = require('@tensorflow/tfjs');
require('@tensorflow/tfjs-node');

const model = tf.loadModel('file://./model-1a/model.json').then(() => {
  model.predict();
});

I get this error:

(node:25887) UnhandledPromiseRejectionWarning: TypeError: model.predict is not a function at tf.loadModel.then (/home/ubuntu/workspace/server.js:10:9) at

But when I just create a model instead of loading it works just fine

const model = tf.sequential();
model.add(tf.layers.dense({units: 10, inputShape: [10005]}));
model.add(tf.layers.dense({units: 1, activation: 'linear'}));
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

The model predict function works just fine? I don't know what could be wrong here and I was hopeing someone could help me out.

Upvotes: 1

Views: 5552

Answers (1)

Sebastian Speitel
Sebastian Speitel

Reputation: 7346

You need to work with promises.

loadModel() returns a promise resolving into the loaded model. So to access it you either need to use the .then() notation or be inside an async function and await it.

.then():

tf.loadModel('file://./model-1a/model.json').then(model => {
  model.predict();
});

async/await:

async function processModel(){
    const model = await tf.loadModel('file://./model-1a/model.json');
    model.predict();
}
processModel();

or in a shorter, more direct way:

(async ()=>{
    const model = await tf.loadModel('file://./model-1a/model.json');
    model.predict();
})()

Upvotes: 5

Related Questions