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

使用TensorFlowJS时出现model.predict is not a function错误求助

Troubleshooting "is not a function" Error with model.predict() in TensorFlow.js

Hey there, let's figure out why you're running into that frustrating "is not a function" error when calling predict() on your MobileNet model. The root cause here is a common pitfall with asynchronous JavaScript—let's break it down step by step.

Core Issue: Asynchronous Model Loading Isn't Being Awaited

Looking at your constructor code:

constructor() { 
  console.time('Loading of model'); 
  this.mobileNet = new MobileNet(); 
  this.mobileNet.loadMobilenet(); // This is async, but you're not waiting for it to finish
  console.timeEnd('Loading of model'); 
}

Your loadMobilenet() method is marked as async (since it uses await for loadFrozenModel), which means it returns a Promise. When you call it directly in the constructor without await, the constructor continues executing immediately—long before the model finishes loading.

So when you try to call this.mobileNet.model.predict(batched) later, this.mobileNet.model is still undefined (because the async load hasn't completed yet). Trying to call predict() on undefined throws the "is not a function" error you're seeing.

Fix 1: Refactor Initialization to Wait for Model Loading

Since constructors can't be async, you'll need to move the model loading logic into a separate async initialization method. Here's how to adjust your code:

Step 1: Update your main class to use an async init method

class YourMainClass {
  constructor() {
    this.mobileNet = new MobileNet();
    this.CANVAS = // your canvas element;
    this.IMAGE_SIZE = // your image size;
  }

  async init() {
    console.time('Loading of model');
    await this.mobileNet.loadMobilenet(); // Wait for the model to fully load
    console.timeEnd('Loading of model');
  }

  // Your prediction method
  getPrediction() {
    // Now we're guaranteed the model exists
    const result = tfc.tidy(() => {
      const raw = tfc.fromPixels(this.CANVAS).toFloat();
      const cropped = this.cropImage(raw);
      const resized = tfc.image.resizeBilinear(cropped, [this.IMAGE_SIZE, this.IMAGE_SIZE])
      const offset = tfc.scalar(127);
      const normalized = resized.sub(offset).div(offset);
      const batched = normalized.expandDims(0);
      console.log(batched)
      return this.mobileNet.model.predict(batched).dataSync();
    });
    return result;
  }
}

Step 2: Initialize your class properly

// When using your class:
const app = new YourMainClass();
await app.init(); // Wait for model to load before making predictions
const prediction = app.getPrediction();

Fix 2: Add a Guard in Your Prediction Method

If you prefer to keep the initialization closer to the prediction logic, you can add a check to ensure the model is loaded before calling predict():

async getPrediction() {
  // Ensure the model is loaded before proceeding
  if (!this.mobileNet.model) {
    await this.mobileNet.loadMobilenet();
  }

  const result = tfc.tidy(() => {
    // ... your existing prediction code
    return this.mobileNet.model.predict(batched).dataSync();
  });
  return result;
}

Bonus: Verify Model Loading

To confirm the model is loading correctly, add some logging to your MobileNet class's loadMobilenet method:

async loadMobilenet() {
  console.log('Starting model load from:', MODEL_URL);
  this.model = await loadFrozenModel(MODEL_URL, WEIGHTS_URL);
  console.log('Model loaded successfully! Model object:', this.model);
  // Check if predict exists (just for debugging)
  console.log('Does model have predict?', typeof this.model.predict === 'function');
}

This will help you confirm that the model is being loaded properly and that the predict method exists once loading is complete.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:50:33