Kacper Rossa
Kacper Rossa

Reputation: 77

How to set a probability of a value becoming a zero for an np.array?

I've got an np.array 219 by 219 with mostly 0s and 2% of nonzeros and I know want to create new arrays where each of the nonzero values has 90% of chance of becoming a zero.

I now know how to change the n-th non zero value to 0 but how to work with probabilities?

Probably this can be modified:

index=0
for x in range(0, 219):
    for y in range(0, 219):
        if (index+1) % 10 == 0:
            B[x][y] = 0
        index+=1
print(B)

Upvotes: 2

Views: 1440

Answers (2)

Chafik Boulealam
Chafik Boulealam

Reputation: 694

# first method
prob=0.3
print(np.random.choice([2,5], (5,), p=[prob,1-prob]))

# second method (i prefer)    
import random
import numpy as np 
def randomZerosOnes(a,b, N, prob):

    if prob > 1-prob:
        n1=int((1-prob)*N)
        n0=N-n1
    else:
        n0=int(prob*N)
        n1=N-n0  
        
    zo=np.concatenate(([a for _ in range(n0)] ,[b  for _ in range(n1)]  ), axis=0  ) 
    random.shuffle(zo)
    return zo
zo=randomZerosOnes(2,5, N=5, prob=0.3)
print(zo)

Upvotes: 0

DSM
DSM

Reputation: 353009

You could use np.random.random to create an array of random numbers to compare with 0.9, and then use np.where to select either the original value or 0. Since each draw is independent, it doesn't matter if we replace a 0 with a 0, so we don't need to treat zero and nonzero values differently. For example:

In [184]: A = np.random.randint(0, 2, (8,8))

In [185]: A
Out[185]: 
array([[1, 1, 1, 0, 0, 0, 0, 1],
       [1, 1, 1, 0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1, 0, 0, 0],
       [0, 1, 0, 1, 0, 0, 0, 1],
       [0, 1, 0, 1, 1, 1, 1, 0],
       [1, 1, 0, 1, 1, 0, 0, 0],
       [1, 0, 0, 1, 0, 0, 1, 0],
       [1, 1, 0, 0, 0, 1, 0, 1]])

In [186]: np.where(np.random.random(A.shape) < 0.9, 0, A)
Out[186]: 
array([[0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 1, 0, 0, 0, 0, 0, 0]])

Upvotes: 3

Related Questions