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

更换BirdRecognizerPython模型.pb后输入维度不匹配问题求助

图像分类模型维度不匹配问题解决建议

问题描述

更换model.pb文件后,运行图像分类代码出现维度不匹配错误:

File "/Users/Desktop/poc/BirdRecognizerPython/bird_recog.py", line 60, in <module>
    predictions = sess.run(prob_tensor, {input_node: [augmented_image] })
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/Documents/virtualenv_dir/ka_ai/lib/python3.11/site-packages/tensorflow/python/client/session.py", line 972, in run
    result = self._run(None, fetches, feed_dict, options_ptr,
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/Documents/virtualenv_dir/ka_ai/lib/python3.11/site-packages/tensorflow/python/client/session.py", line 1189, in _run
    raise ValueError(
ValueError: Cannot feed value of shape (1, 227, 227, 3) for Tensor Placeholder:0, which has shape (None, 224, 224, 3)

尝试添加以下代码后,出现新的维度错误:

augmented_image = np.expand_dims(augmented_image, axis=0) # Convert to float32 
augmented_image = augmented_image.astype(np.float32)

错误信息:

ValueError: Cannot feed value of shape (1, 1, 227, 227, 3) for Tensor Placeholder:0, which has shape (None, 224, 224, 3)

核心问题分析

  1. 新模型的输入占位符要求尺寸为(None, 224, 224, 3),但当前输入图像尺寸是227x227,导致维度不匹配。
  2. 原代码中{input_node: [augmented_image] }已经将单张图像包装成了(1, 227, 227, 3)的批量维度,额外添加的np.expand_dims会多增加一个维度,变成(1,1,227,227,3),进一步加剧维度错误。

解决步骤

  1. 调整图像尺寸至模型要求的224x224
    在图像预处理阶段,将augmented_image的尺寸修改为224x224。例如使用OpenCV调整:

    import cv2
    # 假设augmented_image是(227,227,3)的数组
    augmented_image = cv2.resize(augmented_image, (224, 224))
    

    或使用PIL库:

    from PIL import Image
    import numpy as np
    augmented_image = np.array(Image.fromarray(augmented_image).resize((224, 224)))
    
  2. 移除多余的维度扩展代码
    删除你添加的augmented_image = np.expand_dims(augmented_image, axis=0)这一行,保留类型转换(如果模型需要float32类型输入):

    augmented_image = augmented_image.astype(np.float32)
    
  3. 验证输入维度
    调整后可以打印维度确认:

    print(augmented_image.shape) # 应输出(224,224,3)
    print(np.array([augmented_image]).shape) # 应输出(1,224,224,3),与模型占位符匹配
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 09:00:07