生成具有特定比例的0和1的随机数组 [英] Generate random array of 0 and 1 with specific ratio
本文介绍了生成具有特定比例的0和1的随机数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想生成大小为N的随机数组,该数组仅包含0和1,但是我希望我的数组具有介于0和1之间的比率.例如,数组的90%为1,其余的10%为0(但是我想这90%在整个数组中都是随机的.
I want to generate random array of size N which only contains 0 and 1 but I want my array have some ratio between 0 and 1. For example 90% of array be 1 and the remaining 10% be 0(but I want this 90% be random along 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屋!
查看全文