分类的时候,当不同类别的样本量差异很大时,很容易影响分类结果,因此要么每个类别的数据量大致相同,要么就要进行校正。

sklearn的做法可以是加权,加权就要涉及到class_weight和sample_weight,当不设置class_weight参数时,默认值是所有类别的权值为1

在python中:

# class_weight的传参
class_weight : {dict, 'balanced'}, optional
Set the parameter C of class i to class_weight[i]*C for
SVC. If not given, all classes are supposed to have
weight one. The "balanced" mode uses the values of y to automatically
adjust weights inversely proportional to class frequencies as
``n_samples / (n_classes * np.bincount(y))``
# 当使用字典时,其形式为:Weights associated with classes in the form ``{class_label: weight}``,比如:{0: 1, 1: 1}表示类0的权值为1,类1的权值为1. # sample_weight的传参
sample_weight : array-like, shape (n_samples,)
Per-sample weights. Rescale C per sample. Higher weights
force the classifier to put more emphasis on these points.

1. 在:from sklearn.utils.class_weight import compute_class_weight 里面可以看到计算的源代码。

2. 除了通过字典形式传入权重参数,还可以设置的是:class_weight = 'balanced',例如使用SVM分类:

clf = SVC(kernel = 'linear', class_weight='balanced', decision_function_shape='ovr')
clf.fit(X_train, y_train)

3. 那么'balanced'的计算方法是什么呢?看例子:

import numpy as np

y = [0,0,0,0,0,0,0,0,1,1,1,1,1,1,2,2]  #标签值,一共16个样本

a = np.bincount(y)  # array([8, 6, 2], dtype=int64) 计算每个类别的样本数量
aa = 1/a #倒数 array([0.125 , 0.16666667, 0.5 ])
print(aa) from sklearn.utils.class_weight import compute_class_weight
class_weight = 'balanced'
classes = np.array([0, 1, 2]) #标签类别
weight = compute_class_weight(class_weight, classes, y)
print(weight) # [0.66666667 0.88888889 2.66666667] print(0.66666667*8) #5.33333336
print(0.88888889*6) #5.33333334
print(2.66666667*2) #5.33333334
# 这三个值非常接近
# 'balanced'计算出来的结果很均衡,使得惩罚项和样本量对应

可以看出计算出来的值,乘以样本量之后,三个类别的数字很接近,我想的是:个人觉得惩罚项就用样本量的倒数未尝不可,因为乘以样本量都是1,相当于'balanced'这里是多乘以了一个常数

4. 真正的魔法到了:还记得上面所给出的python中,当class_weight为'balanced'时的计算公式吗?

# weight_ = n_samples / (n_classes * np.bincount(y))``
# 这里
# n_samples为16
# n_classes为3
# np.bincount(y)实际上就是每个类别的样本数量

于是:

print(16/(3*8))  #输出 0.6666666666666666
print(16/(3*6)) #输出 0.8888888888888888
print(16/(3*2)) #输出 2.6666666666666665

是不是跟计算出来的权值一样?这就是class_weight设置为'balanced'时的计算方法了。

5. 当然,需要说明一下传入字典时的情形

import numpy as np

y = [0,0,0,0,0,0,0,0,1,1,1,1,1,1,2,2]  #标签值,一共16个样本

from sklearn.utils.class_weight import compute_class_weight
class_weight = {0:1,1:3,2:5} # {class_label_1:weight_1, class_label_2:weight_2, class_label_3:weight_3}
classes = np.array([0, 1, 2]) #标签类别
weight = compute_class_weight(class_weight, classes, y)
print(weight) # 输出:[1. 3. 5.],也就是字典中设置的值

参考:

https://blog.csdn.net/go_og/article/details/81281387

https://www.zhihu.com/question/265420166/answer/293896934

sklearn的class_weight设置为'balanced'的计算方法的更多相关文章

  1. sklearn逻辑回归(Logistic Regression)类库总结

    class sklearn.linear_model.LogisticRegression(penalty=’l2’, dual=False, tol=0.0001, C=1.0, fit_inter ...

  2. sklearn逻辑回归(Logistic Regression,LR)调参指南

    python信用评分卡建模(附代码,博主录制) https://study.163.com/course/introduction.htm?courseId=1005214003&utm_ca ...

  3. 逻辑回归原理_挑战者飞船事故和乳腺癌案例_Python和R_信用评分卡(AAA推荐)

    sklearn实战-乳腺癌细胞数据挖掘(博客主亲自录制视频教程) https://study.163.com/course/introduction.htm?courseId=1005269003&a ...

  4. XGBoost、LightGBM、Catboost总结

    sklearn集成方法 bagging 常见变体(按照样本采样方式的不同划分) Pasting:直接从样本集里随机抽取的到训练样本子集 Bagging:自助采样(有放回的抽样)得到训练子集 Rando ...

  5. XGBoost、LightGBM的详细对比介绍

    sklearn集成方法 集成方法的目的是结合一些基于某些算法训练得到的基学习器来改进其泛化能力和鲁棒性(相对单个的基学习器而言)主流的两种做法分别是: bagging 基本思想 独立的训练一些基学习器 ...

  6. CART决策树和随机森林

    CART 分裂规则 将现有节点的数据分裂成两个子集,计算每个子集的gini index 子集的Gini index: \(gini_{child}=\sum_{i=1}^K p_{ti} \sum_{ ...

  7. Python解决数据样本类别分布不均衡问题

    所谓不平衡指的是:不同类别的样本数量差异非常大. 数据规模上可以分为大数据分布不均衡和小数据分布不均衡.大数据分布不均衡:例如拥有1000万条记录的数据集中,其中占比50万条的少数分类样本便于属于这种 ...

  8. 【机器学习基础】逻辑回归——LogisticRegression

    LR算法作为一种比较经典的分类算法,在实际应用和面试中经常受到青睐,虽然在理论方面不是特别复杂,但LR所牵涉的知识点还是比较多的,同时与概率生成模型.神经网络都有着一定的联系,本节就针对这一算法及其所 ...

  9. (原创)(四)机器学习笔记之Scikit Learn的Logistic回归初探

    目录 5.3 使用LogisticRegressionCV进行正则化的 Logistic Regression 参数调优 一.Scikit Learn中有关logistics回归函数的介绍 1. 交叉 ...

随机推荐

  1. docker批量删除镜像

    docker rmi `docker images | grep swb | grep -v grep | awk '{print $3}'` 参考: https://blog.csdn.net/hi ...

  2. StandardServer.await: Invalid command '' received

    tomcat服务运行时 后台提输出警告:StandardServer.await: Invalid command '' received 这个警告是 多个tomcat启动时会出现端口占用的情况, 将 ...

  3. [ kvm ] 三种基础网络模型创建及分析

    1. 前言 最近在模拟生产环境在做测试,本来准备用 vmware 直接来实现的,本着学以致用的道理,选择直接在linux 环境使用 kvm 来模拟测试,遇到的第一个问题就是,网络环境的模拟.这里对比v ...

  4. 【tensorflow-v2.0】如何将模型转换成tflite模型

    前言 TensorFlow Lite 提供了转换 TensorFlow 模型,并在移动端(mobile).嵌入式(embeded)和物联网(IoT)设备上运行 TensorFlow 模型所需的所有工具 ...

  5. 小技巧——解决Github项目clone慢的问题

    设置github的项目git命令走sock代理 git config --global http.https://github.com.proxy socks5://127.0.0.1:1086(so ...

  6. nginx deny 封IP

    官方文档地址:http://nginx.org/en/docs/http/ngx_http_access_module.html#deny Syntax: deny address | CIDR | ...

  7. [转帖]从0开始的高并发(一)--- Zookeeper的基础概念

    从0开始的高并发(一)--- Zookeeper的基础概念 https://juejin.im/post/5d0bd358e51d45105e0212db 前言 前面几篇以spring作为主题也是有些 ...

  8. FORMAT 的用法

    https://www.cnblogs.com/gaodu2003/archive/2008/12/22/1359927.html Format 格式指令具有以下的形式:"%" [ ...

  9. Python之虚拟环境virtualenv、pipreqs生成项目依赖第三方包

    virtualenv简介 含义: virtual:虚拟,env:environment环境的简写,所以virtualenv就是虚拟环境,顾名思义,就是虚拟出来的一个新环境,比如我们使用的虚拟机.doc ...

  10. linux端口映射

    参考文章: http://jingyan.baidu.com/article/ed15cb1b2a332e1be36981ed.html http://www.myhack58.com/Article ...