简体   繁体   English

如何以 p 的概率交换数组中的元素?

[英]How to swap elements in a array with a probability of p?

Assuming I have a numpy array a = np.random.randint(0,20,10) I would like to permutate its elements with a probability p , ie if p = 0.2 each element has a 20% probability to exchange position with another element.假设我有一个 numpy 数组a = np.random.randint(0,20,10)我想以概率p排列它的元素,即如果p = 0.2每个元素有 20% 的概率将 position 与另一个元素交换. I am aware of the numpy.random.permutate() function but this only allows to permutate all elements in an array.我知道numpy.random.permutate() function 但这仅允许排列数组中的所有元素。 Can this be done efficiently in python?这可以在 python 中有效地完成吗?

The trick is to first choose which elements will be candidates to participate in the permutation.诀窍是首先选择哪些元素将成为参与排列的候选者。

import numpy as np

a = np.random.randint(0,20,10) # original array
p = 0.2

ix = np.arange(a.size)  # indexes of a
will_swap = np.random.random(a.size) <= p  # draw which elements will be candidates for swapping
after_swap = np.random.permutation(ix[will_swap]) # permute the canidadates
ix[will_swap] = after_swap # update ix with the swapped candidates
a = a[ix]
print(a) # --> [0 1 8 3 4 5 6 7 2 9]

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

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