77. 为不平衡数据集计算平衡类别权重
欺诈、毒性和垃圾邮件标签非常稀少。通过按类别频率的倒数对 loss 进行加权,可以防止模型总是预测多数类。
编写 class_weights(y, n_classes)。返回一个长度为 n_classes 的 float array,其中 weight[c] = n_samples / (n_classes * count[c])。从未出现的类别权重为 0。
def class_weights(y, n_classes)示例 1
输入: class_weights([0, 0, 0, 1], 2)
输出: [0.667, 2.0]
示例 2
输入: y = [0, 2, 2, 2, 2], n_classes = 3
输出: [1.666667, 0.0, 0.416667]
示例 3
输入: y = [0, 1, 2, 0, 1, 2], n_classes = 3
输出: [1.0, 1.0, 1.0]
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
A class's weight is inversely proportional to how often it appears, so first you need a count per class.
提示 2
Count each class with np.bincount, then apply n_samples / (n_classes * count) only to classes with a nonzero count, leaving the others at 0.
提示 3
Pass minlength=n_classes to np.bincount so missing classes still get a slot. Build a zeros array and fill it through a boolean mask like c > 0 to avoid dividing by zero.
理解思路
当某个类别很稀少(例如欺诈)时,模型可以通过始终预测常见类别来获得高分。类别权重通过在 loss 中增加每个稀有样本的权重来解决这个问题。选择平衡公式是为了使权重在样本上的平均值为 1,从而保持整体 loss 的规模和 learning rate 不变。
y = [0, 0, 0, 0, 1, 1, 2], n_classes = 4, 共 7 个样本。Counts: [4, 2, 1, 0]。Class 0 的权重 = 7 / (4 * 4) = 0.4375。Class 1 = 7 / (4 * 2) = 0.875。Class 2 = 7 / (4 * 1) = 1.75。Class 3 从未出现,所以其权重为 0。检查: 4 * 0.4375 + 2 * 0.875 + 1 * 1.75 = 5.25, 且 5.25 / 7 = 0.75,这是因为四个类别中有一个是空的;如果所有类别都出现,样本平均值正好为 1。
当 count[c] > 0 时,weight[c] = n_samples / (n_classes * count[c]),否则为 0,以 float array 形式返回。简单的倒数计数方向相同,但数值太小。常用于欺诈、毒性和垃圾邮件分类器。