Generate random array of 0 and 1 with specific rat

2019-06-15 13:49发布

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).

right now I have:

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

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

3条回答
迷人小祖宗
2楼-- · 2019-06-15 14:25

Without using numpy, you could do as follows:

import random
percent = 90

nums = percent * [1] + (100 - percent) * [0]
random.shuffle(nums)
查看更多
Fickle 薄情
3楼-- · 2019-06-15 14:40

If you want an exact 1:9 ratio:

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

If you want independent 10% probabilities:

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

or

nums = (numpy.random.rand(1000) > 0.1).astype(int)
查看更多
再贱就再见
4楼-- · 2019-06-15 14:41

Its difficult to get an exact count but you can get approximate answer by assuming that random.random returns a uniform distribution. This is strictly not the case, but is only approximately true. If you have a truly uniform distribution then it is possible. You can try something like the following:

In [33]: p = random.random(10000)
In [34]: p[p <= 0.1] = 0
In [35]: p[p > 0] = 1
In [36]: sum(p == 0)
Out[36]: 997
In [37]: sum(p == 1)
Out[37]: 9003

Hope this helps ...

查看更多
登录 后发表回答