将MobilenetV3集成到React-Native Expo时遇张量形状不匹配错误求助
解决方案
1. 匹配输入张量与模型训练时的尺寸
你的输入张量尺寸是[1,285,285,3],但模型训练时在pipeline.config中配置的输入尺寸(image_resizer_config)大概率不是这个值。打开训练用的pipeline.config,找到image_resizer_config节点,查看fixed_shape_resizer的height和width(比如常见的224x224或320x320),将输入图片resize到对应尺寸。
修改convertBase64ToTensor函数,加入尺寸调整逻辑:
const convertBase64ToTensor = async (base64) => { // 从base64创建张量 const imgTensor = await tf.browser.fromPixelsAsync(base64); // 替换为你pipeline.config里的尺寸 const targetSize = [224, 224]; const resizedTensor = tf.image.resizeBilinear(imgTensor, targetSize); // 增加batch维度,转float32并归一化(模型输入通常需要归一化) const inputTensor = resizedTensor.expandDims(0).cast('float32').div(tf.scalar(255)); // 释放中间张量避免内存泄漏 imgTensor.dispose(); resizedTensor.dispose(); return inputTensor; };
2. 修正输入数据类型
日志显示输入张量是int32类型,但MobileNetV3这类模型的输入通常要求float32并做归一化(像素值除以255),上面的代码已经包含了类型转换和归一化操作,解决数据类型不匹配的问题。
3. 确保模型转换时指定正确的输出节点
目标检测模型有多个输出节点,转换时需要明确指定,避免输出形状不匹配。重新转换模型时,加上正确的输出节点参数:
tensorflowjs_converter --input_format=tf_saved_model --output_node_names='detection_boxes,detection_scores,detection_classes,num_detections' ./saved_model ./tfjs_model
4. 明确指定模型执行的输出节点
调用模型时,明确指定要获取的输出节点,避免默认返回所有输出导致的形状错误:
const processImagePrediction = async (base64Image) => { const model = await getModel(); const croppedData = await cropPicture(base64Image); setImage(croppedData.uri); const tensor = await convertBase64ToTensor(croppedData.base64); console.log("输入张量形状:", tensor.shape); try { // 指定输出节点 const [boxes, scores, classes, numDetections] = await model.executeAsync(tensor, [ 'detection_boxes', 'detection_scores', 'detection_classes', 'num_detections' ]); console.log("检测结果:", { boxes, scores, classes, numDetections }); // 处理结果后释放张量 boxes.dispose(); scores.dispose(); classes.dispose(); numDetections.dispose(); } catch (error) { console.log(error); } finally { tensor.dispose(); // 释放输入张量 } };
额外检查点
- 确认训练时
pipeline.config中的num_classes和你实际的类别数一致,错误里的39可能对应类别数相关的维度,要保证输入输出的维度匹配。 - 检查模型导出是否正确,确保导出的是用于推理的SavedModel(不是训练中的模型)。
内容的提问来源于stack exchange,提问作者maxnuggets
相关产品推荐
相关产品推荐

