Machine Learning
Machine Learning

Reputation: 515

TensorFlowJs | tf.loadLayersModel Not Working

Using sample code from the following link: https://js.tensorflow.org/api/latest/#loadLayersModel

Checking the localstorage of Chrome I do see 'my-model-1' there, so it is getting saved but not loaded back into loadedModel. I have verified localstorage in Chrome and IE and 'my-model-1' is there in both browsers. IE doesn't throw an error, while Chrome does throw the error.

const model = tf.sequential({layers: [tf.layers.dense({units: 1, inputShape: [3]})]});
model.predict(tf.ones([1, 3])).print();
const saveResults = model.save('localstorage://my-model-1');
const loadedModel = tf.loadLayersModel('localstorage://my-model-1');
loadedModel.predict(tf.ones([1, 3])).print();

Expected loadedModel.predict to work and instead getting loadedModel.predict is not a function error.

Upvotes: 1

Views: 4536

Answers (1)

Thomas Dondorf
Thomas Dondorf

Reputation: 25230

Problem

tf.loadLayersModel returns a Promise which resolves to the model. The same is also true for model.save.

Solution

You need to either use await or .then to wait until the Promise is resolved. Here is your code with the correct await statements:

(async () => {
  const model = tf.sequential({layers: [tf.layers.dense({units: 1, inputShape: [3]})]});
  model.predict(tf.ones([1, 3])).print();
  const saveResults = await model.save('localstorage://my-model-1');
  const loadedModel = await tf.loadLayersModel('localstorage://my-model-1');
  loadedModel.predict(tf.ones([1, 3])).print();
})();

The code is executed in an async function as only here it is allowed to use the await keyword.

Upvotes: 2

Related Questions