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

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

我有一个 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)

您可以使用 np.random.random 创建一个随机数数组来与 0.9 进行比较,然后使用 np.where 到 select 原始值或 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]])
# 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)