如何为np.array设置值变为零的概率?

时间:2018-08-06 00:35:25

标签: python numpy probability

我有一个np.array 219 x 219,其中大多数为0和2%的非零值,我知道要创建一个新数组,其中每个非零值都有90%的机会成为零。

我现在知道如何将第n个非零值更改为0,但是如何使用概率呢?

可能可以修改:

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)

2 个答案:

答案 0 :(得分:1)

您可以使用np.random.random创建一个随机数数组以与0.9进行比较,然后使用np.where选择原始值或0。由于每次绘制都是独立的,因此不会如果将0替换为0就很重要,因此我们不需要区别对待零值和非零值。例如:

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

答案 1 :(得分:0)

# 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)
相关问题