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

时间:2019-05-11 12:15:22

标签: javascript tensorflow 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

1 个答案:

答案 0 :(得分:2)

这里的问题是model函数范围内的.then(() => ...)变量是未知的。您要么需要返回模型以访问它,要么使用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>