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

解决Sequential对象无predict_classes属性的AttributeError问题

解决'Sequential' object has no attribute 'predict_classes'错误

问题原因

predict_classes方法在TensorFlow 2.6及以上版本的Keras中已被移除,Sequential模型不再包含该方法,直接调用会触发AttributeError。

解决方案

将代码中调用predict_classes的部分替换为model.predict()结合np.argmax()的组合,实现相同的类别预测功能。

修改后的代码

def fix_dimension(img): 
    new_img = np.zeros((28,28,3))
    for i in range(3):
        new_img[:,:,i] = img
    return new_img
def show_results():
    dic = {}
    characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    for i,c in enumerate(characters):
        dic[i] = c
 
    output = []
    for i,ch in enumerate(char): #iterating over the characters
        img_ = cv2.resize(ch, (28,28), interpolation=cv2.INTER_AREA)
        img = fix_dimension(img_)
        img = img.reshape(1,28,28,3) #preparing image for the model
        # 替换原predict_classes代码
        predictions = model.predict(img, verbose=0)
        y_ = np.argmax(predictions, axis=1)[0]
        character = dic[y_]
        output.append(character) #storing the result in a list
        
    plate_number = ''.join(output)
    
    return plate_number
print(show_results())

说明

  • model.predict(img, verbose=0):返回输入样本的各类别概率分布,verbose=0用于关闭预测过程的日志输出(可选参数)。
  • np.argmax(predictions, axis=1):沿类别维度(axis=1)找出概率最大值对应的索引,这和原predict_classes返回的结果完全一致。

内容的提问来源于stack exchange,提问作者Chaitanya Y S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:15:27