Tensorflow.js 加载模型返回函数 predict 未定义 [英] Tensorflow.js loading model returns function predict is not defined
问题描述
当我像这样加载保存的模型时(请不要介意预测函数没有输入的事实)
When I load a saved model like this (please dont mind the fact that the predict function has no input)
const tf = require('@tensorflow/tfjs');
require('@tensorflow/tfjs-node');
const model = tf.loadModel('file://./model-1a/model.json').then(() => {
model.predict();
});
我收到此错误:
(节点:25887)未处理的承诺拒绝警告:类型错误:model.predict 不是函数在 tf.loadModel.then (/home/ubuntu/workspace/server.js:10:9)在
(node:25887) UnhandledPromiseRejectionWarning: TypeError: model.predict is not a function at tf.loadModel.then (/home/ubuntu/workspace/server.js:10:9) at
但是当我只是创建一个模型而不是加载它时它工作得很好
But when I just create a model instead of loading it works just fine
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'});
模型预测功能工作正常吗?我不知道这里有什么问题,我希望有人能帮助我.
The model predict function works just fine? I don't know what could be wrong here and I was hopeing someone could help me out.
推荐答案
您需要使用 承诺.
loadModel()
返回解析为加载模型的承诺.因此,要访问它,您要么需要使用 .then()
表示法,要么在 async
函数内并 await
它.
loadModel()
returns a promise resolving into the loaded model. So to access it you either need to use the .then()
notation or be inside an async
function and await
it.
.then()
:
tf.loadModel('file://./model-1a/model.json').then(model => {
model.predict();
});
异步/等待
:
async function processModel(){
const model = await tf.loadModel('file://./model-1a/model.json');
model.predict();
}
processModel();
或更短、更直接的方式:
or in a shorter, more direct way:
(async ()=>{
const model = await tf.loadModel('file://./model-1a/model.json');
model.predict();
})()
这篇关于Tensorflow.js 加载模型返回函数 predict 未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!