使用 compute_class_weight 自动计算 balanced 权重

解读

在国内真实面试中,面试官问“怎么用 compute_class_weight 自动算 balanced 权重”并不是想听你背 API,而是想确认三件事:

  1. 你知道类别不平衡会带来什么后果(指标虚高、模型偏向 majority);
  2. 你能把权重正确地喂给模型,而不是只打印出来看一眼;
  3. 你理解 balanced 策略背后的数学:用样本数的倒数做归一化,让各类在损失函数里“等权”。

因此,回答必须给出“数据 → 权重 → 模型”的完整闭环,并点出常见坑:标签编码不一致、多分类 vs 二分类、样本权重与类别权重的区别。

知识点

  • sklearn.utils.class_weight.compute_class_weight 接口签名
    compute_class_weight(class_weight='balanced', classes=np.unique(y), y=y)
  • balanced 公式:n_samples / (n_classes * np.bincount(y))
  • 返回的是按 classes 参数顺序排列的 float 数组,必须和模型内部标签顺序严格对齐
  • 可直接用于:LogisticRegression、SVC、RandomForestClassifier、GradientBoostingClassifier 等带 class_weight 参数的 estimator;也可手动转成 sample_weight 给 fit 的 sample_weight 参数
  • 与 sample_weight 区别:类别权重作用于损失函数,样本权重可更细粒度(如单条样本)
  • 交叉验证一致性:在 Pipeline 内部用 balanced 权重时,必须用 sklearn 的 stratified CV,避免折叠内类别分布漂移导致权重失真

答案

现场写代码+解释,建议分三步:

import numpy as np
from sklearn.utils.class_weight import compute_class_weight
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score

# 1. 造一份国内常见的极度不平衡样本,比如金融风控的违约数据
X = np.random.randn(10000, 20)
y = np.concatenate([np.zeros(9800), np.ones(200)])   # 违约率 2%

# 2. 自动计算 balanced 权重
classes = np.unique(y)               # 必须显式传入,保证顺序
weights = compute_class_weight(class_weight='balanced',
                                classes=classes,
                                y=y)
weight_dict = dict(zip(classes, weights))
print("balanced 权重:", weight_dict)   # {0.0: 0.51, 1.0: 25.0}

# 3. 把权重喂给模型,并用分层交叉验证验证效果
clf = LogisticRegression(max_iter=1000, class_weight='balanced')  # 内部会复用同样的公式
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
score = cross_val_score(clf, X, y, scoring='f1', cv=cv).mean()
print("F1 均值:", score)

关键点强调:

  • 如果面试官追问“为什么不用 sample_weight”,答:LogisticRegression 支持 class_weight,底层自动把类别权重映射成样本权重,代码更简洁且与 stratified CV 无缝兼容。
  • 如果问“多分类怎么办”,答:compute_class_weight 同样返回 K 个权重,只要 classes 参数与模型标签顺序一致即可,无需改动代码逻辑。

拓展思考

  1. 生产环境落地:在离线训练时把 weight_dict 序列化成 json,线上推理无需改动,因为权重只影响训练阶段损失;但若用 sample_weight,需要把权重随样本一起落库,增加存储。
  2. 与代价敏感矩阵区别:balanced 权重只关注样本量,不关注业务代价;金融场景里坏账召回的代价远高于误杀,此时应在 balanced 基础上手动放大少数类权重,例如 weight_dict[1] *= 2。
  3. AutoML 调参:在 GridSearchCV 中,不能把 class_weight 当普通超参枚举(如 {'class_weight':[None,'balanced',{0:1,1:10}]}),否则每次换字典都会重新算权重,搜索空间爆炸;正确做法是固定 balanced,把代价敏感系数单独抽出来作为乘子去搜。