网站搜索

javascript - 如何保存 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();

我总是收到错误信息“Uncaught SyntaxError: await 仅在异步函数中有效”。我该如何修复这个问题?谢谢!

答案#1

你需要在异步环境中。要么创建一个异步函数(async function name(){...})并在需要时调用,要么最简短的方法是使用自调用异步箭头函数:

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

答案#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();