Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random array of 0 and 1 with a specific ratio

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

right now I have:

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

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

like image 446
Am1rr3zA Avatar asked Feb 05 '14 01:02

Am1rr3zA


3 Answers

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)
like image 94
user2357112 supports Monica Avatar answered Nov 02 '22 01:11

user2357112 supports Monica


You could use a binomial distribution:

np.random.binomial(n=1, p=0.9, size=[1000])
like image 44
Juip Avatar answered Nov 02 '22 01:11

Juip


Without using numpy, you could do as follows:

import random
percent = 90

nums = percent * [1] + (100 - percent) * [0]
random.shuffle(nums)
like image 1
mvelay Avatar answered Nov 02 '22 01:11

mvelay