如何将 numpy 数组中的元素随机设置为 0



首先我创建我的数组

myarray = np.random.random_integers(0,10, size=20)

然后,我想将数组中 20% 的元素设置为 0(或其他数字(。我应该怎么做?敷面膜?

您可以使用 np.random.choice 来计算指数,将所选指数的数量限制为百分比:

indices = np.random.choice(np.arange(myarray.size), replace=False,
                           size=int(myarray.size * 0.2))
myarray[indices] = 0

对于在 nd-array 的情况下寻找答案的其他人,正如用户 holi 所建议的那样:

my_array = np.random.rand(8, 50)
indices = np.random.choice(my_array.shape[1]*my_array.shape[0], replace=False, size=int(my_array.shape[1]*my_array.shape[0]*0.2))

我们将维度相乘得到长度为 dim1*dim2 的数组,然后将此索引应用于我们的数组:

my_array[np.unravel_index(indices, my_array.shape)] = 0 

阵列现在被屏蔽。

使用 np.random.permutation 作为随机索引生成器,并取索引的前 20%。

myarray = np.random.random_integers(0,10, size=20)
n = len(myarray)
random_idx = np.random.permutation(n)
frac = 20 # [%]
zero_idx = random_idx[:round(n*frac/100)]
myarray[zero_idx] = 0
如果您希望

20% 是随机的:

random_list = []
array_len = len(myarray)
while len(random_list) < (array_len/5):
    random_int = math.randint(0,array_len)
    if random_int not in random_list:
        random_list.append(random_int)
for position in random_list:
    myarray[position] = 0
return myarray

这将确保您肯定会获得 20% 的值,并且 RNG 多次滚动相同的数字不会导致少于 20% 的值为 0。

假设您的输入 numpy 数组是 A 并且p=0.2 。以下是实现此目的的几种方法。

精确遮罩

ones = np.ones(A.size)
idx = int(min(p*A.size, A.size))
ones[:idx] = 0
A *= np.reshape(np.random.permutation(ones), A.shape)

近似掩蔽

这通常在几个去噪目标中完成,最值得注意的是变形金刚预训练中的掩码语言建模。这是一种更pythonic的方法,可以将一定比例(例如20%(的元素设置为零。

A *= np.random.binomial(size=A.shape, n=1, p=0.8)

另一种选择:

A *= np.random.randint(0, 2, A.shape)

最新更新