Python人脸情绪检测模型加载时出现ValueError的解决咨询
解决人脸情绪检测模型加载时的ValueError问题
错误详情
运行以下代码加载人脸情绪检测模型时触发ValueError:
"Kernel shape must have the same length as input, but received kernel of shape (3, 3, 1, 32) and input of shape (None, None, 48, 48, 1)"
用户代码:
from keras.models import load_model from tensorflow.keras.utils import img_to_array from keras.preprocessing import image import cv2 import numpy as np face_classifier = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml') classifier = load_model("./Emotion_Detection.h5") class_labels = ['Angry', 'Happy', 'Neutral', 'Sad', 'Surprise']
问题原因
错误本质是模型的输入维度与卷积核维度不匹配:
- 模型第一层卷积核形状为
(3,3,1,32),对应4维输入(高度、宽度、输入通道、输出通道),说明训练时模型预期输入是4维张量(格式为(批量大小, 高度, 宽度, 通道数))。 - 当前加载后输入变成5维张量
(None, None, 48, 48, 1),多了一个不必要的维度,导致卷积层无法匹配计算。
解决方案
排查图像预处理环节:检查后续人脸图像处理代码,是否错误增加了维度。比如用
img_to_array转换后,是否额外调用np.expand_dims多扩展了一次维度?如果是,用np.squeeze()去掉多余维度,确保输入图像形状为(48,48,1),批量输入为(None,48,48,1)。修正模型输入层(临时修复):如果无法重新训练模型,加载后可手动修改输入层形状适配正确维度:
from keras.models import load_model, Model from keras.layers import Input # 加载原模型 classifier = load_model("./Emotion_Detection.h5") # 重新定义4维输入层(匹配卷积核要求) new_input = Input(shape=(48, 48, 1)) # 复用原模型网络结构 outputs = classifier(new_input) # 创建适配后的新模型 new_model = Model(inputs=new_input, outputs=outputs) # 后续预测使用new_model替代原classifier
- 重新训练并保存模型(根治方案):如果是训练阶段输入层定义错误,打开训练代码,确认输入层为
Input(shape=(48,48,1)),重新训练后保存模型,确保训练与推理阶段输入维度一致。
内容的提问来源于stack exchange,提问作者Esakkinathan B
相关产品推荐
相关产品推荐

