[英]Numpy: Replace random elements in an array
我已经google了一下,没有找到任何好的答案。
问题是,我有一个2d numpy数组,我想在随机位置替换它的一些值。
我找到了一些使用numpy.random.choice为数组创建掩码的答案。 不幸的是,这不会在原始数组上创建视图,因此我无法替换其值。
所以这是我想做的一个例子。
想象一下,我有2d数组的浮点值。
[[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.]]
然后我想替换任意数量的元素。 如果我可以用参数调整将要替换多少元素,那将是很好的。 可能的结果可能如下所示:
[[ 3.234, 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 2.234]]
我无法想到实现这一目标的好方法。 感谢帮助。
编辑
感谢所有快速回复。
只需使用相同形状的随机数字屏蔽输入数组。
import numpy as np
# input array
x = np.array([[ 1., 2., 3.], [ 4., 5., 6.], [ 7., 8., 9.]])
# random boolean mask for which values will be changed
mask = np.random.randint(0,2,size=x.shape).astype(np.bool)
# random matrix the same shape of your data
r = np.random.rand(*x.shape)*np.max(x)
# use your mask to replace values in your input array
x[mask] = r[mask]
产生这样的东西:
[[ 1. 2. 3. ]
[ 4. 5. 8.54749399]
[ 7.57749917 8. 4.22590641]]
您可以使用scipy创建bernoulli随机变量,参数p将控制您最终替换的数组中的值百分比。 然后根据bernoulli随机变量的值是0还是1来替换原始数组中的值。
from scipy.stats import bernoulli as bn
import numpy as np
array = np.array([[ 1., 2., 3.],[ 4., 5., 6.],[ 7., 8., 9.]])
np.random.seed(123)
flag = bn.rvs(p=0.5,size=(3,3))
random_numbers = np.random.randn(3,3)
array[flag==0] = random_numbers[flag==0]
当数组是一维的时,很容易随机选择索引,所以我建议将数组重新整形为1D,改变随机元素,然后重新塑造回原始形状。
例如:
import numpy as np
def replaceRandom(arr, num):
temp = np.asarray(arr) # Cast to numpy array
shape = temp.shape # Store original shape
temp = temp.flatten() # Flatten to 1D
inds = np.random.choice(temp.size, size=num) # Get random indices
temp[inds] = np.random.normal(size=num) # Fill with something
temp = temp.reshape(shape) # Restore original shape
return temp
所以这有点像:
>>> test = np.arange(24, dtype=np.float).reshape(2,3,4)
>>> print replaceRandom(test, 10)
[[[ 0. -0.95708819 2. 3. ]
[ -0.35466096 0.18493436 1.06883205 7. ]
[ 8. 9. 10. 11. ]]
[[ -1.88613449 13. 14. 15. ]
[ 0.57115795 -1.25526377 18. -1.96359786]
[ 20. 21. 2.29878207 23. ]]]
在这里,我已经用正态分布替换了元素 - 但显然你可以用你想要的任何东西替换对np.random.normal
的调用。
没有真正优化,但一个起点可以帮助您找到一种方法:
import numpy as np
a = np.array( [[ 1., 2., 3.], [ 4., 5., 6.], [ 7., 8., 9.]])
def replace(ar,nbr):
x,y = ar.shape
s = x*y
mask = [1]*nbr + [0]*(s-nbr)
np.random.shuffle(mask)
mask = np.array(mask) == 1
ar.reshape( (s) )[mask] = [ np.random.random() for _ in range(nbr) ]
您可以随机生成n
整数来索引数组的展平视图(1D版本),并将这些索引值设置为等于n
随机值:
In [1]: import numpy as np
In [2]: x = np.arange(1, 10).reshape(3, 3).astype(float)
In [3]: m = np.product(x.shape)
In [4]: n = 3
In [5]: x.ravel()[np.random.randint(0, m, size=n)] = np.random.rand(n)
In [6]: x
Out[6]:
array([[ 0.28548823, 0.28819589, 3. ],
[ 4. , 5. , 6. ],
[ 7. , 8. , 0.28772056]])
如果希望值大于1,可以按某种因子缩放随机生成的值; 例如, np.random.rand(n) * m
将产生介于0和np.product(x.shape)
之间的值。
请注意,默认情况下numpy.ravel
在numpy.ravel
运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.