如何将Tensorflow.js中的3D张量重塑为4D张量?

时间:2020-09-11 02:57:53

标签: tensorflow deep-learning tensorflow-lite tensorflow.js

我正在使用一个以[null,224,224,3]作为输入的自定义模型

但是,当我尝试对模型进行预测时,出现以下错误。

Total size of new array must be unchanged.

张量被传入:

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();
    }
  };

1 个答案:

答案 0 :(得分:2)

您正在传递给model.predict一层而不是张量。应该是

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