复制训练样例以处理pandas数据帧中的类不平衡

问题描述 投票:6回答:1

我在pandas中有一个包含训练示例的DataFrame,例如:

   feature1  feature2  class
0  0.548814  0.791725      1
1  0.715189  0.528895      0
2  0.602763  0.568045      0
3  0.544883  0.925597      0
4  0.423655  0.071036      0
5  0.645894  0.087129      0
6  0.437587  0.020218      0
7  0.891773  0.832620      1
8  0.963663  0.778157      0
9  0.383442  0.870012      0

我用它生成的:

import pandas as pd
import numpy as np

np.random.seed(0)
number_of_samples = 10
frame = pd.DataFrame({
    'feature1': np.random.random(number_of_samples),
    'feature2': np.random.random(number_of_samples),
    'class':    np.random.binomial(2, 0.1, size=number_of_samples), 
    },columns=['feature1','feature2','class'])

print(frame)

如您所见,训练集是不平衡的(8个样本具有0级,而只有2个样本具有1级)。我想对训练集进行过度采样。具体来说,我想用类1重复训练样本,以便训练集是平衡的(即,类0的样本数与类1的样本数大致相同)。我怎么能这样做?

理想情况下,我想要一个可以推广到多类设置的解决方案(即,类列中的整数可能大于1)。

python pandas machine-learning oversampling
1个回答
11
投票

您可以找到组的最大大小

max_size = frame['class'].value_counts().max()

在您的示例中,这等于8.对于每个组,您可以使用替换的max_size - len(group_size)元素进行采样。这样,如果将它们连接到原始DataFrame,它们的大小将相同,并且您将保留原始行。

lst = [frame]
for class_index, group in frame.groupby('class'):
    lst.append(group.sample(max_size-len(group), replace=True))
frame_new = pd.concat(lst)

您可以使用max_size-len(group)并可能添加一些噪音,因为这将使所有组大小相等。

© www.soinside.com 2019 - 2024. All rights reserved.