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

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

最佳答案

这里的问题是 model 变量在 .then(() => ...) 函数的范围内未知。您要么需要返回模型才能访问它,要么使用等待/异步语​​法。

请参阅以下工作代码示例,它使用等待/异步语​​法来加载模型并预测值:

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>

关于javascript - 无法通过在tensorflow.js中加载预训练模型(loadLayersModel)进行预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56090268/

相关文章:

python - 将层的一半过滤器设置为不可训练的keras/tensorflow

tensorflow - 检查目标 : expected dense_Dense2 to have shape x, 时出错,但得到形状为 y 的数组

javascript - chrome 扩展脚本在某些页面上加载了两次甚至更多

python - TensorFlow 1.0.0 的prepare_attention API 相当于tensorflow 1.2.0

javascript - onbeforeunload 在 javascript 帮助中加载

python - Python 绑定(bind)在 TensorFlow 源代码中的何处调用核心 C++ 库?

javascript - model.predict 在使用 TensorflowJS 时不是一个函数

javascript - TensorFlow.js 中用于颜色预测的最佳模型类型?

javascript - Bootstrap 4 - 光泽效果和 z-index

HTML 表格单元格中的 Javascript 函数调用