对于二元分类,如何按列对数据进行采样,以便 2/3 的数据包含 0,1/3 包含 1?

发布于 2025-01-10 07:08:30 字数 440 浏览 2 评论 0原文

我有一个包含四列的大型数据集,第三列包含二进制标签(值 01)。该数据集是不平衡的 - 它包含的 0 比 1 多得多。数据看起来像:

3   5   0   0.4
4   5   1   0.1
5   13  0   0.5
6   10  0   0.8
7   25  1   0.3
:   :   :   :

我知道我可以获得一个包含 50% 0 和 50% 1 的平衡子集,例如:

df_sampled = df.groupby(df.iloc[:,2]).sample(n=20000, random_state=1)

但是我如何修改上面给出的一行来改变 0 和 1 的比率?例如,我如何对该数据进行采样(按第三列),以便 2/3 的数据包含零,1/3 包含 1?

I have a large dataset containing four columns and the third column contains the binary label (a value either 0 or 1). This dataset is imbalanced - it contains much more zeros than ones. The data looks like:

3   5   0   0.4
4   5   1   0.1
5   13  0   0.5
6   10  0   0.8
7   25  1   0.3
:   :   :   :

I know that I can obtain a balanced subset containing 50% zeros and 50% ones by for example:

df_sampled = df.groupby(df.iloc[:,2]).sample(n=20000, random_state=1)

But how I can amend the one-liner given above to change the ratio of zeros and ones? For example how can I sample this data (by the third column) so that 2/3 of the data contains zeros and 1/3 contains ones?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

满天都是小星星 2025-01-17 07:08:30

这是一个可能的解决方案:

n_samples = 90000 # total number of samples

df_sampled = pd.concat(
    [group.sample(n=int(n_samples * 2 / 3)) if label == 0
     else group.sample(n=int(n_samples * 1 / 3))
     for label, group in df.groupby(df.iloc[:, 2])]
)

类似的解决方案是:

n_samples = 90000 # total number of samples
ratios = [2 / 3, 1 / 3]

df_sampled = pd.concat(
    [group.sample(n=int(n_samples * ratios[label]))
     for label, group in df.groupby(df.iloc[:, 2])]
)

在这里,我基本上将不同的函数应用于不同的组。

This is a possible solution:

n_samples = 90000 # total number of samples

df_sampled = pd.concat(
    [group.sample(n=int(n_samples * 2 / 3)) if label == 0
     else group.sample(n=int(n_samples * 1 / 3))
     for label, group in df.groupby(df.iloc[:, 2])]
)

A similar solution would be:

n_samples = 90000 # total number of samples
ratios = [2 / 3, 1 / 3]

df_sampled = pd.concat(
    [group.sample(n=int(n_samples * ratios[label]))
     for label, group in df.groupby(df.iloc[:, 2])]
)

Here I'm basically applying a different function to different groups.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文