TensorFlowJs | tf.loadLayersModel不起作用

时间:2019-07-17 20:24:08

标签: tensorflow.js

使用以下链接中的示例代码: https://js.tensorflow.org/api/latest/#loadLayersModel

检查Chrome的本地存储我确实在其中看到了“ my-model-1”,因此它已保存但未加载回loadModel。我已经在Chrome和IE中验证了本地存储,并且两个浏览器中都存在“ my-model-1”。 IE不会引发错误,而Chrome会引发错误。

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

期望loadedModel.predict可以正常工作,而不是让loadingModel.predict不是函数错误。

1 个答案:

答案 0 :(得分:1)

问题

tf.loadLayersModel返回一个解析为模型的Promisemodel.save也是如此。

解决方案

您需要使用await.then等到Promise解决。这是带有正确的await语句的代码:

(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();
})();

由于仅在此处允许使用async关键字,因此该代码是在await函数中执行的。