使用TensorFlowJS时出现model.predict is not a function错误求助
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

