You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow.js调用model.predict时出现TypeError错误的原因排查

解决Uncaught (in promise) TypeError: model.predict is not a function错误

核心问题:异步加载模型未处理

tf.loadLayersModel()是异步函数,返回的是Promise对象,不是直接的TensorFlow模型实例。你直接把Promise赋值给model,调用model.predict()自然会报错,因为Promise没有这个方法。

修复方式:

用async/await或者.then()等待模型加载完成:

方式1:使用async/await

// 声明异步函数加载模型
async function loadModel() {
  return await tf.loadLayersModel('./tf_js/model.json');
}

// 初始化模型
let model;
loadModel().then(loadedModel => {
  model = loadedModel;
  // 这里可以初始化人脸检测逻辑,比如启动MediaPipe等
});

方式2:使用.then()链式调用

let model;
tf.loadLayersModel('./tf_js/model.json').then(loadedModel => {
  model = loadedModel;
  // 初始化后续逻辑
});

其他需要修复的问题

1. 模型输入参数传递错误

你的模型需要两个输入,但你用了逗号表达式(faceImage, df),这只会把df作为参数传入。正确做法是传入数组(适配模型输入顺序):

const prediction = model.predict([faceImage, df]);

2. 未声明的全局变量

代码中的w、h、x、y没有用let/const声明,会变成全局变量,建议添加声明:

if (results.detections.length > 0) {
    drawRectangle(
        ctx, results.detections[0].boundingBox,
        {color: 'white', lineWidth: 1, fillColor: '#00000000'});
        
    const w = results.detections[0].boundingBox['width'] * canvas.width;
    const h = results.detections[0].boundingBox['height'] * canvas.height;
    const x = results.detections[0].boundingBox['xCenter'] * canvas.width;
    const y = results.detections[0].boundingBox['yCenter'] * canvas.height;
}

3. 图片加载时机问题

设置face.src = canvas.toDataURL()后,图片需要时间加载,直接调用tf.browser.fromPixels(face)可能会因为图片未加载完成而失败。可以监听face的load事件:

face.src = canvas.toDataURL();
face.onload = () => {
    let faceImage = tf.browser.fromPixels(face);
    faceImage = tf.image.resizeBilinear(faceImage, [224, 224]);
    faceImage = tf.expandDims(faceImage, 0);

    const df = tf.zeros([1, 106], tf.float32);
    
    // 确保模型已加载再执行预测
    if (model) {
        const prediction = model.predict([faceImage, df]);
        const predictionArray = prediction.dataSync();
        console.log("prediction", prediction);
        const maxValue = predictionArray.indexOf(Math.max(...predictionArray));
    }
};

内容的提问来源于stack exchange,提问作者yeon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 19:45:34