在处理不平衡类别的问题时,一种常用的解决方法是通过随机抽样来平衡数据集。下面是一个示例代码,展示了如何使用Python的imbalanced-learn库来进行不平衡类别的随机抽样:
from imblearn.over_sampling import RandomOverSampler
from imblearn.under_sampling import RandomUnderSampler
from imblearn.combine import SMOTEENN
from sklearn.datasets import make_classification
from collections import Counter
# 创建一个不平衡的示例数据集
X, y = make_classification(n_samples=1000, n_features=20, weights=[0.95, 0.05], random_state=42)
print('Original dataset shape:', Counter(y))
# 使用RandomOverSampler进行过采样
ros = RandomOverSampler(random_state=42)
X_resampled, y_resampled = ros.fit_resample(X, y)
print('Resampled dataset shape (over-sampling):', Counter(y_resampled))
# 使用RandomUnderSampler进行欠采样
rus = RandomUnderSampler(random_state=42)
X_resampled, y_resampled = rus.fit_resample(X, y)
print('Resampled dataset shape (under-sampling):', Counter(y_resampled))
# 使用SMOTEENN进行合成采样
sme = SMOTEENN(random_state=42)
X_resampled, y_resampled = sme.fit_resample(X, y)
print('Resampled dataset shape (SMOTEENN):', Counter(y_resampled))
在这个示例中,我们首先使用make_classification函数生成一个不平衡的示例数据集(其中0类样本占95%,1类样本占5%)。然后,我们分别使用RandomOverSampler进行过采样、RandomUnderSampler进行欠采样,以及SMOTEENN进行合成采样。
最后,我们打印出每种采样方法后的数据集的类别分布情况。通过对比可以看出,在过采样方法中,采样后的数据集中的类别数量会增加,而在欠采样方法中,采样后的数据集中的类别数量会减少。而使用SMOTEENN方法进行合成采样,可以同时进行过采样和欠采样,以更好地平衡数据集。
需要提醒的是,imbalanced-learn库是一个专门处理不平衡类别问题的库,可以安装使用。