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

如何修复AttributeError: 'Sequential'对象没有'predict_classes'属性?

解决AttributeError: 'Sequential' object has no attribute 'predict_classes'问题

这个错误是因为你使用的TensorFlow/Keras版本进行了更新——predict_classes方法在较新的版本中已被移除,不再是Sequential模型的内置方法,这也是为什么之前代码能正常运行,现在报错。

修复方案

根据口罩检测的二分类场景(戴口罩/未戴口罩),可以用以下两种方式替代predict_classes:

方式1:适用于softmax输出的二分类/多分类

先通过predict获取预测概率,再用np.argmax取概率最大的类别索引:

import numpy as np

def detect_face_mask(img):
    # 获取预测概率数组
    predictions = model.predict(img.reshape(1,224,224,3))
    # 取出概率最大的类别索引
    y_pred = np.argmax(predictions, axis=1)
    return y_pred

方式2:适用于sigmoid输出的二分类

如果模型最后一层是sigmoid激活(单输出节点,输出0-1之间的概率),可以直接用阈值(比如0.5)判断类别:

import numpy as np

def detect_face_mask(img):
    predictions = model.predict(img.reshape(1,224,224,3))
    # 概率大于0.5则为类别1,否则为类别0
    y_pred = (predictions > 0.5).astype(int)
    return y_pred

注意事项

  • 确保已经导入numpy库,若未导入需在代码开头添加import numpy as np
  • 若是多分类任务,直接使用方式1即可,np.argmax会返回对应类别的索引

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 03:49:53