How to save a Tensorflow.js model?

柔情痞子 提交于 2020-01-13 09:57:05

问题


I would like to make a user interface that creates,saves and trains tensorflow.js models. But i can't save a model after creating it. I even copied this code from the tensorflow.js documenation but it does't work:

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

I always get the error message "Uncaught SyntaxError: await is only valid in async function" .How can I fix this? thanks!


回答1:


You need to be in an async environment. Either create an async function (async function name(){...}) and call it when you need to or the shortest way would be a self invoking async arrow function:

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



回答2:


Create an async function and invoke it:

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


来源:https://stackoverflow.com/questions/53054968/how-to-save-a-tensorflow-js-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!