You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native集成Teachable Machine模型输入维度不匹配报错如何解决

问题解决方法

错误原因分析

  • 第一个报错是模型要求输入为4维张量(结构为[批量大小, 高度, 宽度, 通道数]),你直接传入相机输出的3维张量[高度, 宽度, 通道数],少了批量维度。
  • 第二个报错是Teachable Machine默认创建的图像分类模型输入尺寸固定为224*224,你相机输出的是320*240,尺寸不匹配。
  • 你之前用reshape调整尺寸是错误用法:reshape仅重排张量元素、不改变元素总数量,320*240*3的总元素数和224*224*3完全不一致,必然触发尺寸不匹配报错。

修复步骤

步骤1:调整相机输出尺寸(性能最优方案)

直接修改TensorCamera的resize参数,让相机直接输出符合模型要求的224*224尺寸,避免后续张量缩放的性能开销:

<TensorCamera
  // Standard Camera props
  style={styles.camera}
  type={Camera.Constants.Type.front}
  // Tensor related props
  cameraTextureHeight={textureDims.height}
  cameraTextureWidth={textureDims.width}
  resizeHeight={224} // 修改为模型要求的高度
  resizeWidth={224} // 修改为模型要求的宽度
  resizeDepth={3}
  onReady={makeHandleCameraStream()}
  autorender={true}
/>

步骤2:修改帧处理逻辑,补充张量预处理

扩展批量维度+做归一化处理(Teachable Machine模型要求输入为0-1范围的浮点值,相机输出默认是0-255的像素值),同时新增张量销毁逻辑避免内存泄漏:

const makeHandleCameraStream = ()=> {
  return (images, updatePreview, gl) => {
    const loop = async () => {
      const nextImageTensor = images.next().value;
      let batchedTensor = null;
      let normalizedTensor = null;
      try {
        // 扩展批量维度,变为4维张量 [1, 224, 224, 3]
        batchedTensor = tf.expandDims(nextImageTensor, 0);
        // 像素值归一化到0-1范围
        normalizedTensor = tf.div(batchedTensor, 255.0);
        // 传入模型预测
        const predictions = await model.predict(normalizedTensor);
        console.log(predictions)
        setPredictions(predictions)
      } catch (error) {
        console.log(error.message)
      } finally {
        // 销毁用完的张量,避免内存泄漏
        if (batchedTensor) batchedTensor.dispose();
        if (normalizedTensor) normalizedTensor.dispose();
        if (nextImageTensor) nextImageTensor.dispose();
      }
      requestAnimationFrame(loop);
    };
    loop();
  };
}

可选方案:不修改相机配置的处理方式

如果你需要保留相机输出320*240的尺寸,可在帧处理逻辑中新增张量缩放步骤:

// 在扩展批量维度后添加缩放逻辑
const batchedTensor = tf.expandDims(nextImageTensor, 0);
const resizedTensor = tf.image.resizeBilinear(batchedTensor, [224, 224]);
const normalizedTensor = tf.div(resizedTensor, 255.0);

内容的提问来源于stack exchange,提问作者ChinMhat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 00:57:02