Liam Spring
Liam Spring

Reputation: 59

Array elements value assignment

I intend to create 100 binary arrays of shape (8, 8, 8) in a way that for each of its arrays about 40% of the elements are zero and the rest are 1. I have the following code:

num1=100
size = (num1, 8, 8, 8)
prob_0 = 0.4 # 40% of zeros
prob_1 = 1 - prob_0 # 60% of ones
P = np.random.choice([0, 1], size=size, p=[prob_0, prob_1])

However, it is probabilistic and I am looking for its deterministic version.

Further elaboration: In the above code, it is theoretically possible that I get an array with all the elements being 1 for instance. What I'm looking for is a method that controls value assignment in a way I only get to have arrays that only 40% of its elements are 0 and the rest are 1. In other words, each of the (8, 8, 8) arrays should have a constant number of ones and zeros.

Upvotes: 0

Views: 62

Answers (1)

ronpi
ronpi

Reputation: 490

Just use numpy's Generator to get deterministic results. This is how you can get the exact same array each run.

from numpy.random import default_rng

rng = default_rng(42)    # default random generator

num1=100
size = (num1, 8, 8, 8)
prob_0 = 0.4 # 40% of zeros
prob_1 = 1 - prob_0 # 60% of ones
P = rng.choice([0, 1], size=size, p=[prob_0, prob_1])

Upvotes: 1

Related Questions