Keras模型输入不兼容错误求助:预期通道数3却收到4通道输入
解决Keras输入通道不匹配的ValueError问题
错误
ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 3 but received input with shape [None, 64, 64, 4]的核心原因:你上传的图片是RGBA格式(含透明通道,共4个通道),但模型训练时定义的输入是3通道的RGB图像,两者通道数不匹配。
修复步骤
在
predict函数中,将读取的图像强制转换为RGB格式,去掉透明通道。修改图像尺寸调整的代码:# 原代码 test_image = image.resize((64,64)) # 修改后 test_image = image.resize((64,64)).convert('RGB').convert('RGB')会自动将RGBA或灰度图像转换为3通道的RGB格式,完全匹配模型输入要求。额外检查训练代码,确保训练阶段所有输入图像也都是3通道RGB格式,避免模型与推理阶段的数据格式不一致。
修改后的完整predict函数
def predict(image): classifier_model = "C:/Users/houcem/Desktop/Doctor Sina/code/ECG1.h5" IMAGE_SHAPE = (64,64,3) model = load_model(classifier_model, compile=False) # 转换为RGB格式并调整尺寸 test_image = image.resize((64,64)).convert('RGB') test_image = preprocessing.image.img_to_array(test_image) test_image = np.expand_dims(test_image, axis=0) preds = np.argmax(model.predict(test_image),axis=-1) index = ['Fusion Beat','Normal Beat','Unknown Beat','Supraventricular ectopic Beat','Ventricular ectopic beat'] print("------------------------------------") print("\nprediction -> ",index[preds[0]]) print("\n-------------------------------------") text = "The predicted type is " + str(index[preds[0]]) return text
内容的提问来源于stack exchange,提问作者Houssem Ghanmi
相关产品推荐
相关产品推荐

