如何实现样本的平均化,让不同类别的样本数量趋于一致。给出具体的代码。
时间: 2024-03-03 12:50:52 浏览: 20
实现样本的平均化,可以使用过采样(oversampling)和欠采样(undersampling)等方法。其中,欠采样是随机从多数类中删除一些样本,使得多数类与少数类样本数量接近,而过采样是复制少数类的部分样本,使得多数类与少数类样本数量接近。
以下是一个简单的欠采样的代码实现,假设我们的数据集中有两个类别 0 和 1,其中类别 0 的样本数量较多:
``` python
import numpy as np
from collections import Counter
from sklearn.datasets import make_classification
from imblearn.under_sampling import RandomUnderSampler
# 生成样本不平衡的数据集
X, y = make_classification(n_classes=2, class_sep=2,
weights=[0.9, 0.1], n_informative=3,
n_redundant=1, flip_y=0, n_features=20,
n_clusters_per_class=1, n_samples=1000,
random_state=10)
# 查看原始数据集中各类别的样本数量
print('Original dataset shape %s' % Counter(y))
# 进行欠采样,使得两个类别的样本数量接近
rus = RandomUnderSampler(random_state=42)
X_res, y_res = rus.fit_resample(X, y)
# 查看欠采样后的数据集中各类别的样本数量
print('Resampled dataset shape %s' % Counter(y_res))
```
上述代码中,我们使用了 `make_classification` 生成了一个样本不平衡的数据集,接着使用 `RandomUnderSampler` 进行欠采样,使得两个类别的样本数量接近。最后,我们使用 `Counter` 函数查看了欠采样后的数据集中各类别的样本数量。