生成具有特定比率的 0 和 1 的随机数组 [英] Generate random array of 0 and 1 with a specific ratio

查看:62
本文介绍了生成具有特定比率的 0 和 1 的随机数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一个大小为 N 的随机数组,其中只包含 0 和 1,我希望我的数组在 0 和 1 之间有一些比率.例如,数组的 90% 为 1,其余 10% 为 0(我希望这 90% 与整个数组一起随机).

I want to generate a random array of size N which only contains 0 and 1, I want my array to have some ratio between 0 and 1. For example, 90% of the array be 1 and the remaining 10% be 0 (I want this 90% to be random along with the whole array).

现在我有:

randomLabel = np.random.randint(2, size=numbers)

但我无法控制 0 和 1 之间的比例.

But I can't control the ratio between 0 and 1.

推荐答案

如果你想要一个精确的 1:9 比例:

If you want an exact 1:9 ratio:

nums = numpy.ones(1000)
nums[:100] = 0
numpy.random.shuffle(nums)

如果你想要独立的 10% 概率:

If you want independent 10% probabilities:

nums = numpy.random.choice([0, 1], size=1000, p=[.1, .9])

nums = (numpy.random.rand(1000) > 0.1).astype(int)

这篇关于生成具有特定比率的 0 和 1 的随机数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆