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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 21:54:19