机器学习-类别不平衡-上下采样(Upsampling and Downsampling)

Section I: Brief Introduction on Upsampling/Downsampling

Class imbalance is a quite common problem when working with real-world data-samples from one class or multiple classes are over-represented in a dataset. Intuitively, we can think of several domains where this may occur, such as spam filtering, fraud detection, or screening for diseases.

Here, be warned that one way to deal with imbalanced class proportions during model fitting is a assign a larger penalty to wrong predictions on the minority class . Via scikit-learn, adjusting such a penalty is as convenient as setting the class_weight parameter to class_weight=“balanced”, which is implemented for most classifiers.

FROM
Sebastian Raschka, Vahid Mirjalili. Python机器学习第二版. 南京:东南大学出版社,2018.

Section II: Code and Analyses

第一部分:代码

from sklearn import datasets
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.utils import resample
import warnings
warnings.filterwarnings("ignore")

#Section 1: Load Breast data, i.e., Benign and Malignant
breast=datasets.load_breast_cancer()
X=breast.data
y=breast.target
print("Originally, the number of each class: for class 0, %d, for class 1, %d" % \
      (np.bincount(y)[0],np.bincount(y)[1]))

#Section 2: Upsample samples with replacement for minority class
print("Number of class 0 samples before: ",X[y==0].shape[0])

X_upsampled,y_upsampled=resample(X[y==0],
                                 y[y==0],
                                 replace=True,
                                 n_samples=X[y==1].shape[0],
                                 random_state=1)
print("Number of class 0 samples after: ",X_upsampled.shape[0])

#Section 2: Downsample samples with replacement for minority class
print("Number of class 1 samples before: ",X[y==1].shape[0])

X_downsampled,y_downsampled=resample(X[y==1],
                                 y[y==1],
                                 replace=True,
                                 n_samples=X[y==0].shape[0],
                                 random_state=1)
print("Number of class 1 samples after: ",X_downsampled.shape[0])

第二部分:结果

Originally, the number of each class: for class 0, 212, for class 1, 357
Number of class 0 samples before:  212
Number of class 0 samples after:  357
Number of class 1 samples before:  357
Number of class 1 samples after:  212

参考文献
Sebastian Raschka, Vahid Mirjalili. Python机器学习第二版. 南京:东南大学出版社,2018.

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值