如何保存Tensorflow.js模型?

时间:2018-10-29 22:43:44

标签: javascript tensorflow tensorflow.js

我想创建一个用于创建,保存和训练tensorflow.js模型的用户界面。但是创建模型后我无法保存模型。我什至从tensorflow.js文档中复制了此代码,但是它不起作用:

const model = tf.sequential(
     {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});
console.log('Prediction from original model:');
model.predict(tf.ones([1, 3])).print();

const saveResults = await model.save('localstorage://my-model-1');

const loadedModel = await tf.loadModel('localstorage://my-model-1');
console.log('Prediction from loaded model:');
loadedModel.predict(tf.ones([1, 3])).print();

我总是收到错误消息“ 未捕获的SyntaxError:等待仅在异步函数中有效” 。如何解决此问题?谢谢!

2 个答案:

答案 0 :(得分:5)

您需要处于异步环境中。创建一个异步函数(async function name(){...})并在需要时调用它,或者最简单的方法是自调用异步箭头函数:

(async ()=>{
   //you can use await in here
})()

答案 1 :(得分:2)

创建一个异步函数并调用它:

async function main() {
  const model = tf.sequential({
    layers: [tf.layers.dense({ units: 1, inputShape: [3] })]
  });
  console.log("Prediction from original model:");
  model.predict(tf.ones([1, 3])).print();

  const saveResults = await model.save("localstorage://my-model-1");

  const loadedModel = await tf.loadModel("localstorage://my-model-1");
  console.log("Prediction from loaded model:");
  loadedModel.predict(tf.ones([1, 3])).print();
}

main();