Keras Sequential模型预测报min_ndim=4 found ndim=2错误排查
报错原因
报错ValueError: Input 0 of layer sequential is incompatible with the layer: : expected min_ndim=4, found ndim=2. Full shape received: (None, 0)由两个问题直接导致:
- 传入
convert_image_to_array的参数是文件夹目录路径,而非单张图片的文件路径。该函数无法从文件夹路径读取有效图像数据,返回空值,最终生成的输入数组没有有效图像信息。 - 你搭建的是卷积神经网络,第一层Conv2D要求输入为4维张量,格式为
(批量大小, 图像高度, 图像宽度, 通道数),但读取失败后传入模型的是2维空数组,维度完全不匹配,因此触发报错。
另外原代码还有一处笔误:图像像素值归一化应除以255(像素最大值为255),你写的225会导致数值范围偏差,影响预测精度。
修复方案
- 单张图片预测场景:将传入加载函数的路径改为具体图片的完整路径,加载时统一resize到模型训练设定的
(height, width)尺寸,修正归一化参数,参考代码如下:
from tensorflow.keras.preprocessing.image import load_img, img_to_array import numpy as np # 替换为你要测试的单张图片的完整路径,不要填文件夹路径 test_img_path = "C:/Users/HP/Plant Disease Detection Using Deep Learning Approach/input/Potato___Early_blight/具体测试图片文件名.jpg" # 加载图片并resize到模型要求的输入尺寸 im = load_img(test_img_path, target_size=(height, width)) im = img_to_array(im) # 修正归一化除数为255 np_image_li = np.array(im, dtype=np.float16) / 255.0 # 增加批量维度,凑齐4维输入 npp_image = np.expand_dims(np_image_li, axis=0) result = model.predict(npp_image) # 如需获取预测类别,可执行以下代码 pred_label = np.argmax(result, axis=1)
- 批量预测文件夹内所有图片场景:先遍历文件夹下所有图片文件,逐张做预处理再预测,参考代码如下:
import os import numpy as np from tensorflow.keras.preprocessing.image import load_img, img_to_array image_dir = "C:/Users/HP/Plant Disease Detection Using Deep Learning Approach/input/Potato___Early_blight/" for filename in os.listdir(image_dir): # 过滤非图片格式文件 if filename.lower().endswith((".jpg", ".jpeg", ".png")): img_full_path = os.path.join(image_dir, filename) im = load_img(img_full_path, target_size=(height, width)) im = img_to_array(im) np_image_li = np.array(im, dtype=np.float16) / 255.0 npp_image = np.expand_dims(np_image_li, axis=0) result = model.predict(npp_image, verbose=0) pred_label = np.argmax(result, axis=1) print(f"图片{filename}预测类别编号:{pred_label[0]}")
内容的提问来源于stack exchange,提问作者Azeez Fazry
相关产品推荐
相关产品推荐

