【问题标题】:Tensorflow.js, function predict is not definedTensorflow.js,未定义函数预测
【发布时间】:2019-06-16 13:59:56
【问题描述】:

我正在开发一个 chrome 扩展,我使用我训练有素的 keras 模型,通过库 tensorflow.js 下载它。 正如我从 DevTools 中看到的,模型加载正常,但我不能使用它(不能使用函数predict())。

background.js

const start = async function() {
const model = await tf.loadLayersModel('https://raw.githubusercontent.com/myAcc/myRep/master/model.json');
return model;
}

const model = start();

chrome.extension.onRequest.addListener(function predict(data){
    console.log(data);
    console.log(model.predict(data));
    var prediction = model.predict(data);
    if (prediction[0] == 1){
        alert("Yes");
    }
    else {
        alert("No");
    }
}
                                  );

manifest.json

{
  "manifest_version": 2,
  "name": "my_project",
  "version": "0.1",

  "background": {
        "scripts": ["tf.min.js", "background.js"]
   },
   "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",

  "content_scripts": [
      {
        "matches": [
          "<all_urls>"
        ],
        "js": ["jquery-3.1.1.min.js","content.js"]
      }
   ],
   "permissions":  ["https://*/"]
}

background.js 出现错误

事件处理程序中的错误:TypeError:model.predict 不是函数

我该如何解决?

【问题讨论】:

    标签: javascript json tensorflow google-chrome-extension tensorflow.js


    【解决方案1】:

    您的 async 函数 start 不返回模型。它返回一个解析为模型的 Promise。

    您必须等到此 Promise 解决后才能使用该模型。例如,您可以通过在 Promise 上使用 .then() 并使用它被调用的参数来做到这一点。

    【讨论】:

    • 感谢您的帮助!我改变了我的代码,我也注意到我还有一个错误——没有使用 tf.tensor。现在我的函数看起来像:chrome.extension.onRequest.addListener(function predict(data){ console.log(data); model.then(model =&gt; { var prediction = model.predict(tf.tensor(data)); }); } ); where data = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] 我有一个错误: “检查时出错:预期dense_input 的形状为[null,16],但得到的数组的形状为[16,1]。”。你能帮我告诉我如何解决这个问题吗?
    • 我尝试像var prediction = model.predict(tf.tensor(data).reshape([null, 16])); 一样解决它,但它仍然不起作用未捕获(承诺)错误:尺寸(16)必须与形状的乘积相匹配,16
    • 解决方案是(如果有人感兴趣的话):var prediction = model.predict(tf.tensor(data).reshape([1, 16]));
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    相关资源
    最近更新 更多