How To Save Model image classifier in TensorflowJS

853 Views Asked by At

I created an image classifier in a browser with TensorFlow.js, the code is running well, but when the page is reloaded, the code needs to train the data again (it takes time), so instead of training data again, I want to save the model and load them. I am trying to save the model with this code

  await model.save('anime/saved-model');

but it doesn't work, btw, this is my code

HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Jotaro atau Giorno</title>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs/dist/tf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/knn-classifier"></script>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
</head>
<body>
<h1>Test Image Giorno and Jotaro</h1>
<input type='file' onchange="readURL(this);" />
<img id="image_baru"  src="#" alt="your image" />
<button id="tombolPrediksi">Prediksi</button>
<h3>output in the console</h3>
</body>
</html>

Javascript

 let mobileneModule;
 let ClassifierKNN;

 function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function (e) {
      $('#image_baru')
      .attr('src', e.target.result)
      .width(300)
      .height(300);};
    reader.readAsDataURL(input.files[0]);}
    }

 const initScript = async function(){
  ClassifierKNN = knnClassifier.create();
  mobileneModule = await mobilenet.load();
    
    const jotaroExample = ()=>{
      for(let i=1; i<=3;i++){
      const im = new Image(300,300);
      im.src = 'anime/jotaro/'+i+'.jpg';
      im.onload = ()=>{
      let trainingImageJotaro = tf.browser.fromPixels(im);
      let predJotaro = mobileneModule.infer(trainingImageJotaro,'conv_preds');
      ClassifierKNN.addExample(predJotaro,"Jotaro Kujo");
      console.log("Giorno ok")
      }
      im.onload();
    }}

    const giornoExample = ()=>{
      for(let i=1; i<=3;i++){
      const im2 = new Image(300,300);
      im2.src = 'anime/giorno/'+i+'.jpg';
      im2.onload = ()=>{
      let trainingImageGiorno = tf.browser.fromPixels(im2);
      let predGiorno = mobileneModule.infer(trainingImageGiorno,'conv_preds');
      ClassifierKNN.addExample(predGiorno,"Giorno Giovanna");
      console.log("Giorno Oke")
    }
    im2.onload();
    }}

    await jotaroExample();
    await giornoExample();
    //save model
    await model.save('anime/saved-model');
    }

    initScript();

    const prediksiGambar = async function(){
      let imgX = document.getElementById('image_baru');
      const tensorX = tf.browser.fromPixels(imgX);
      const logitsX = mobileneModule.infer(tensorX,'conv_preds');
      let result = await ClassifierKNN.predictClass(logitsX);
      console.log('hasil prediksi:');
      console.log(result);
    }
     document.getElementById("tombolPrediksi").addEventListener("click",prediksiGambar);

I hope someone can help me :)

2

There are 2 best solutions below

0
On
  1. For saving to your local device and produce 2 files, the model.json file and a binary file with the weights.
await model.save('downloads://my-model');
  1. For saving the model in the browsers local storage and it will be kept even if the page is refreshed. But note that each browser has a limit for how much it can store.
// saves under the my-model in the browsers storage 
await model.save('localstorage://my-model');

More info from the documentation

1
On

see here

// Create your classifier:
let classifier = knnClassifier.create();
// Add some examples:
classifier.addExample(...);
// Save it to a string:
let str = JSON.stringify(Object.entries(classifier.getClassifierDataset()).map(([label, data])=>[label, Array.from(data.dataSync()), data.shape]) );
// Load it back into a fresh classifier:
classifier = knnClassifier.create();
classifier.setClassifierDataset( Object.fromEntries( JSON.parse(str).map(([label, data, shape])=>[label, tf.tensor(data, shape)]) ) );