Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

model.predict is not a function while using TensorflowJS

Tags:

I have scoured the far reaches of the internet like the following:

  • https://beta.observablehq.com/@cedrickchee/load-and-serve-a-pre-trained-model-in-javascript-with-tensor
  • https://github.com/google/emoji-scavenger-hunt
  • https://medium.com/tensorflow/a-gentle-introduction-to-tensorflow-js-dba2e5257702

All of them have a similar way of predicting from the model:

model.predict()

According to the docs, it should return an object with the predictions in it. However, I am always getting a is not a function error. Below is a snippet of code that I have.

constructor() {
    console.time('Loading of model');
    this.mobileNet = new MobileNet();
    this.mobileNet.loadMobilenet();
    console.timeEnd('Loading of model');
}

const result = tfc.tidy(() => {

    // tfc.fromPixels() returns a Tensor from an image element.
    const raw = tfc.fromPixels(this.CANVAS).toFloat();
    const cropped = this.cropImage(raw);
    const resized = tfc.image.resizeBilinear(cropped, [this.IMAGE_SIZE, this.IMAGE_SIZE])

    // Normalize the image from [0, 255] to [-1, 1].
    const offset = tfc.scalar(127);
    const normalized = resized.sub(offset).div(offset);

    // Reshape to a single-element batch so we can pass it to predict.
    const batched = normalized.expandDims(0);

    console.log(batched)

    // Make a prediction through mobilenet.
    return this.mobileNet.model.predict(batched).dataSync();
});

EDIT Included the code for the model

import * as tfc from '@tensorflow/tfjs-core';
import { loadFrozenModel } from '@tensorflow/tfjs-converter';

const MODEL_URL = '/assets/project-gaea/models/web_model.pb';
const WEIGHTS_URL = '/assets/project-gaea/models/weights_manifest.json';

const INPUT_NODE_NAME = 'input';
const OUTPUT_NODE_NAME = 'MobilenetV1/Predictions/Reshape_1';
const PREPROCESS_DIVISOR = tfc.scalar(255 / 2);

export default class MobileNet {
    constructor() { }

    async loadMobilenet() {
        this.model = await loadFrozenModel(MODEL_URL, WEIGHTS_URL);
    }
}
like image 914
oninross Avatar asked May 29 '18 03:05

oninross


1 Answers

loadFrozenModel() returns a FrozenModel, not a tf.model, so as you can see in this example, FrozenModels use execute() instead of predict()

like image 146
Sebastian Speitel Avatar answered Sep 28 '22 18:09

Sebastian Speitel