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

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

我正在使用自定义模型作为输入 [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();
    }
  };

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

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