yudhiesh
yudhiesh

Reputation: 6799

How to reshape 3D tensor in Tensorflow.js to 4D tensor?

I am using a custom model that takes as input [null, 224,224,3]

But I am getting the error below when I try to make predictions on the model.

Total size of new array must be unchanged.

Tensor being passed in:

Tensor
  dtype: int32
  rank: 3
  shape: [224,224,3]
  values:
    [[[124, 130, 132],
      [137, 148, 147],
      [123, 134, 127],
      ...,
      [0  , 0  , 0  ],
      [0  , 0  , 0  ],
      [0  , 0  , 0  ]],
  const getPrediction = async tensor => {
    if (!tensor) {
      console.log("Tensor not found!");
      return;
    }
    const reshapeLayers = tf.layers.reshape({
      targetShape: [1, 224, 224, 3]
    });
    reshapeLayers.apply(tensor);
    const model = await loadedModel;

    const prediction = model.predict(reshapeLayers, 1);
    console.log(`Predictions: ${JSON.stringify(prediction)}`);

    if (!prediction || prediction.length === 0) {
      return;
    }

    // Only take the predictions with a probability of 30% and greater
    if (prediction[0].probability > 0.3) {
      //Stop looping
      cancelAnimationFrame(requestAnimationFrameId);
      setPredictionFound(true);
      setModelPrediction(prediction[0].className);
      tensor.dispose();
    }
  };

Upvotes: 1

Views: 1154

Answers (1)

edkeveked
edkeveked

Reputation: 18371

You are passing to model.predict a layer instead of a tensor. It should rather be

model.predict(tensor.reshape([1,224,224,3]))

Upvotes: 3

Related Questions