无法通过在 tensorflow.js 中加载预训练模型 (loadLayersModel) 进行预测

Unable to predict by loading pre-trained models(loadLayersModel) in tensorflow.js

我已经按照 TensorFlow.js Readme

中所述训练并生成了文件

但是当我预测的时候,它不起作用

<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>

我应该改变什么才能让它预测?

The trained files

这里的问题是 model 变量在 .then(() => ...) 函数的范围内是未知的。您要么需要 return 模型来访问它,要么使用 await/async 语法。

请参阅以下使用 await/async 语法加载模型并预测值的工作代码示例:

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>