【问题标题】:Tensorflow.js loading model returns function predict is not definedTensorflow.js 加载模型返回函数预测未定义
【发布时间】:2018-09-27 20:55:36
【问题描述】:

当我像这样加载保存的模型时(请不要介意预测函数没有输入的事实)

const tf = require('@tensorflow/tfjs');
require('@tensorflow/tfjs-node');

const model = tf.loadModel('file://./model-1a/model.json').then(() => {
  model.predict();
});

我收到此错误:

(node:25887) UnhandledPromiseRejectionWarning: TypeError: model.predict 不是函数 在 tf.loadModel.then (/home/ubuntu/workspace/server.js:10:9) 在

但是当我只是创建一个模型而不是加载它时,它工作得很好

const model = tf.sequential();
model.add(tf.layers.dense({units: 10, inputShape: [10005]}));
model.add(tf.layers.dense({units: 1, activation: 'linear'}));
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

模型预测功能正常吗?我不知道这里可能出了什么问题,我希望有人能帮助我。

【问题讨论】:

    标签: javascript tensorflow.js


    【解决方案1】:

    您需要使用promises

    loadModel() 返回解析到加载模型的承诺。因此,要访问它,您要么需要使用.then() 表示法,要么在async 函数和await 中。

    .then():

    tf.loadModel('file://./model-1a/model.json').then(model => {
      model.predict();
    });
    

    async/await:

    async function processModel(){
        const model = await tf.loadModel('file://./model-1a/model.json');
        model.predict();
    }
    processModel();
    

    或者用更短、更直接的方式:

    (async ()=>{
        const model = await tf.loadModel('file://./model-1a/model.json');
        model.predict();
    })()
    

    【讨论】:

    • 谢谢,看来我的问题是我没有将模型作为参数传入。
    • 我想加载一次模型并将其保存在内存中,以便进行多次预测调用的交互式页面。我该怎么做?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    相关资源
    最近更新 更多