BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / Data processing and features6 of 54 in topic

77. 为不平衡数据集计算平衡类别权重

EasyData processing and features

欺诈、毒性和垃圾邮件标签非常稀少。通过按类别频率的倒数对 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 不变。

Worked example

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 形式返回。简单的倒数计数方向相同,但数值太小。常用于欺诈、毒性和垃圾邮件分类器。
主题
Data processing and features
相似题目
  • 在不泄露测试数据的情况下标准化特征Easy
  • 使用中位数和 IQR 进行特征缩放,防止离群值主导Easy
  • 将一天中的小时和一周中的天数编码为正弦和余弦特征Easy
  • 仅使用在训练集上学习的分位数来裁剪离群值Easy
所有 Data processing and features 道题目
反馈
77 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def class_weights(y, n_classes):
# your code here
pass
​

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 3 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS