Search code examples
pythonnumpymatrixprobability

Matrix Elements Ratio Control


I am using the code

import numpy as np
P=np.random.choice([0, 1], (10000, 10, 10, 10))

to generate 10,000 3D binary matrices. But I need to control the ratio of ones to zeros in each of the matrices. What I mean is that for any given matrix, I want 70% of its elements to be 1 and the rest to be 0. Is there a way for doing so? A probabilistic approach would work as well. For example, if, for any given matrix, the probability of each of its elements to be 1 could be equal to 70% that would work too.


Solution

  • You should specify probablity parameter in numpy.random.choice

    import numpy as np
    
    size = (10000, 10, 10, 10)
    prob_0 = 0.3 # 30% of zeros
    prob_1 = 1 - prob_0 # 70% of ones
    
    P = np.random.choice([0, 1], size=size, p=[prob_0, prob_1])
    

    However this will allow to control the ratio in the overall 4d array, not in each sub-array.