简体   繁体   English

从数组中随机翻转m个值

[英]random flip m values from an array

I have an array with length n , I want to randomly choose m elements from it and flip their value. 我有一个长度为n的数组,我想从中随机选择m元素并将其值翻转。 What is the most efficient way? 最有效的方法是什么?

there are two cases, m=1 case is a special case. 有两种情况, m=1情况是特例。 It can be discussed separately, and m=/=1 . 可以单独讨论,并且m=/=1

My attempt is: 我的尝试是:

import numpy as np
n = 20
m = 5
#generate an array a
a = np.random.randint(0,2,n)*2-1
#random choose `m` element and flip it.
for i in np.random.randint(0,n,m):
    a[m]=-a[m]

Suppose m are tens and n are hundreds. 假设m为数十, n为数百。

To make sure we are not flipping the same element twice or even more times, we can create unique indices in that length range with np.random.choice using its optional replace argument set as False. 为了确保我们不会翻转同一元素两次甚至更多次,我们可以使用np.random.choice并将其可选的replace参数设置为False,在该长度范围内创建唯一索引。 Then, simply indexing into the input array and flipping in one go should give us the desired output. 然后,简单地索引到输入数组中并一次翻转就可以为我们提供所需的输出。 Thus, we would have an implementation like so - 因此,我们将有一个这样的实现-

idx = np.random.choice(n,m,replace=False)
a[idx] = -a[idx]

Faster version : For a faster version of np.random_choice , I would suggest reading up on this post that explores using np.argpartition to simulate identical behavior. 更快的版本:对于np.random_choice的更快版本,我建议您阅读this post使用np.argpartition模拟相同行为的文章。

You can make a random permutation of the array indices, take the first m of them and flip their values: 您可以对数组索引进行随机排列,取其中的前m个并翻转其值:

a[np.random.permutation(range(len(a)))[:m]]*=-1

Using permutation validate you don't choose the same index twice. 使用permutation验证,您不会两次选择相同的索引。

You need to change the index of the array from m to i to actually change the value. 您需要将数组的索引从m更改为i才能实际更改值。 Result: 结果:

import numpy as np
n = 20
m = 5
#generate an array a
a = np.random.randint(0,2,n)*2-1
print(a)
#random choose `i` element and flip it.
for i in np.random.randint(0,n,m):
    a[i] = -a[i]

print(a)

My output: 我的输出:

[ 1  1 -1 -1  1 -1 -1  1  1 -1 -1  1 -1  1  1  1  1 -1  1 -1]
[ 1  1 -1 -1 -1 -1  1  1  1 -1 -1  1 -1 -1  1 -1  1 -1 -1 -1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM