I have trained and generated the files as described in TensorFlow.js Readme

but when i predict, it doesn't works

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs/dist/tf.min.js"></script>

<div>
  <h1 id="p">Try Tensorflow</h1>
  <p>model.json</p><input type="file" id="upload-json" />
  <p>weight.bin</p><input type="file" id="upload-weights" />
  <button type="button" id="myBtn" onclick="myFunction()">Try it</button>
  <script>
    function myFunction() {
      const uploadJSONInput = document.getElementById('upload-json');
      const uploadWeightsInput = document.getElementById('upload-weights');
      console.log('start');
      tf.tensor([
        [1, 2],
        [3, 4]
      ]).print(); //no issues umtill here

      const model = tf.loadLayersModel(tf.io.browserFiles(
        [uploadJSONInput.files[0], uploadWeightsInput.files[0]]
      )).then(() => {
        console.log('will print now');
        model.predict(tf.tensor2d([5], [1, 1])).print();
      });
      console.log(model.predict(tf.tensor2d([5], [1, 1])).print());

    }
  </script>
</div>

What should i change to make it predict?

The trained files

1 Answers

2
Thomas Dondorf On Best Solutions

The problem here is that the model variable is not known in the scope of the .then(() => ...) function. You either need to return the model to access it or use await/async syntax.

See the following working code sample which uses await/async syntax to load the model and predict the value:

async function loadModel() {
  const uploadJSONInput = document.getElementById('upload-json');
  const uploadWeightsInput = document.getElementById('upload-weights');

  const model = await tf.loadLayersModel(tf.io.browserFiles(
    [uploadJSONInput.files[0], uploadWeightsInput.files[0]]
  ));
  model.predict(tf.tensor2d([5], [1, 1])).print();
}
document.querySelector('#myBtn').addEventListener('click', loadModel);
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs/dist/tf.min.js"></script>

<div>
  <h1 id="p">Try Tensorflow</h1>
  <p>model.json</p><input type="file" id="upload-json" />
  <p>weight.bin</p><input type="file" id="upload-weights" />
  <button type="button" id="myBtn">Try it</button>
</div>