I am looking to make a numpy array randomly initialized with zeros and ones, I found the following question here that descripbes the basic random array and how to control the dimensions. However, I need my array to have at least a single '1' on each sub array of the nested axis. See example:
import numpy as np
size = (3, 5, 5)
proba_0 = 0.7
n_positions = np.random.choice([0,1], size=size, p=[proba_0, 1-proba_0])
print(n_positions)
[[[0 1 1 0 0]
[0 0 0 0 0]
[0 0 0 1 1]
[1 0 0 0 0]
[0 1 0 0 0]]
[[0 1 1 1 1]
[0 0 1 1 0]
[1 0 0 1 1]
[0 0 1 0 0]
[0 1 0 1 1]]
[[0 0 0 0 1]
[0 0 1 0 1]
[0 0 0 0 1]
[0 0 0 1 0]
[0 0 0 0 0]]]
This issue here is that at the following position in this array n_positions[0][1]
the data is populted ONLY with zeros. I need there to be at least one '1' in each row on axis 2. I can increase the probability of 1s occuring but this doesn't eliminate the risk.
I could make this with a loop or a comprehension using a method getting numpy to generate a random numer of ones between 1-5 and then filling out with zeros but its very slow. I am hoping there is a more numpy friendly method built in to achieve this?
Aucun commentaire:
Enregistrer un commentaire