Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a Tensorflow.js model?

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!

like image 214
Karkadan Avatar asked Oct 29 '18 22:10

Karkadan


People also ask

How do I save a JSON model?

Save Your Neural Network Model to JSON This can be saved to a file and later loaded via the model_from_json() function that will create a new model from the JSON specification. The weights are saved directly from the model using the save_weights() function and later loaded using the symmetrical load_weights() function.

How do I save a TensorFlow model in R?

Call save_model_tf() to save a model's architecture, weights, and training configuration in a single file/folder. This allows you to export a model so it can be used without access to the original Python code*. Since the optimizer-state is recovered, you can resume training from exactly where you left off.


2 Answers

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
})()
like image 145
Sebastian Speitel Avatar answered Oct 13 '22 07:10

Sebastian Speitel


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();
like image 2
Harry Avatar answered Oct 13 '22 07:10

Harry