样本不均衡解决方法-计算class_weight

样本不均衡的处理方法:

这里介绍2.1:

直接先上代码:

from sklearn.utils import class_weight
import pandas as pd

train_df = pd.read_csv("input/train.csv")
x_train = train_df['Image']
y_train = train_df['Class']

class_weight = class_weight.compute_class_weight('balanced',
                                                 np.unique(y_train),
                                                 y_train)
cw = dict(enumerate(class_weight))

参数类型为字典,将不同的类别映射为不同的权值,该参数用来在训练过程中调整损失函数(只能用于训练)。该参数在处理非平衡的训练数据(某些类的训练样本数很少)时,可以使得损失函数对样本数不足的数据更加关注。

原理解析:

compute_class_weight这个函数的作用是对于输入的样本,平衡类别之间的权重,下面写段测试代码测试这个函数:

# coding:utf-8
 
from sklearn.utils.class_weight import compute_class_weight
 
class_weight = 'balanced'
label = [0] * 9 + [1]*1 + [2, 2]
print(label) # [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2]
classes=[0, 1, 2]
weight = compute_class_weight(class_weight, classes, label)
print(weight) #[ 0.44444444 4.         2.        ]
print(.44444444 * 9) # 3.99999996
print(4 * 1) # 4
print(2 * 2) # 4

如上图所示,可以看到这个函数把样本的平衡后的权重乘积为4,每个类别均如此。

计算公式:

# weight_ = n_samples / (n_classes * np.bincount(y))``
# 这里
# n_samples为16
# n_classes为3
# np.bincount(y)实际上就是每个类别的样本数量
  • 0
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值