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

Sequential模型无predict_proba属性,替换predict后遇输入形状错误

问题解决步骤

1. 替换predict_proba的正确方式

  • 新版TensorFlow/Keras的Sequential模型已移除predict_proba方法,直接用model.predict(image)替代即可。只要模型最后一层使用softmax激活函数,predict的输出就是各类别的概率值,和原predict_proba效果完全一致。
  • 同时predict_classes也已被弃用,替代方案是对predict的结果调用argmax,直接得到类别索引。

2. 修复输入形状不匹配错误

错误提示expected shape=(None, 64, 64, 3), found shape=(None, 255, 3),核心问题是输入图片未被正确调整为模型要求的64×64尺寸:

  • 检查IMAGE_SIZE常量的定义,确保它被设置为64(与模型输入要求一致)。
  • 检查resize_image函数的实现,确认它确实将图片缩放到(IMAGE_SIZE, IMAGE_SIZE)尺寸,而非其他值(比如错误的255)。
  • 在reshape操作前,确保resize_image返回的图片形状为(IMAGE_SIZE, IMAGE_SIZE, 3)(TensorFlow格式),再reshape成(1, IMAGE_SIZE, IMAGE_SIZE, 3)的批量输入格式。

修改后的完整代码示例

def face_predict(face, image):    
    # 明确指定模型要求的输入尺寸,与模型输入层定义一致
    IMAGE_SIZE = 64
    if K.image_data_format() == 'th' and image.shape != (1, 3, IMAGE_SIZE, IMAGE_SIZE):
        image = resize_image(image, target_size=(IMAGE_SIZE, IMAGE_SIZE))
        image = image.reshape((1, 3, IMAGE_SIZE, IMAGE_SIZE))   
    elif K.image_data_format() == 'tf' and image.shape != (1, IMAGE_SIZE, IMAGE_SIZE, 3):
        image = resize_image(image, target_size=(IMAGE_SIZE, IMAGE_SIZE))
        image = image.reshape((1, IMAGE_SIZE, IMAGE_SIZE, 3))                    
    
    image = image.astype('float32')
    image /= 255
    
    # 替换predict_proba为predict
    result_proba = face.model.predict(image)
    print('result_proba:', result_proba)
    
    # 替换predict_classes为argmax获取类别索引
    result = result_proba.argmax(axis=1)        

    return result[0]

额外注意事项

  • 如果resize_image是自定义函数,需确保使用合适的插值方式(如双线性插值),避免缩放失真影响人脸识别效果。
  • 确认模型输入层的定义为input_shape=(64,64,3)(TensorFlow格式)或(3,64,64)(Theano格式),与代码中的尺寸设置完全匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:05:55