Tensorflow.js 加载模型 returns 未定义函数预测

Tensorflow.js loading model returns function predict is not defined

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

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 is not a function at tf.loadModel.then (/home/ubuntu/workspace/server.js:10:9) at

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

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'});

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

您需要与 promises 一起工作。

loadModel() returns 承诺解析为加载的模型。因此,要访问它,您要么需要使用 .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();
})()