[英]How to swap elements in a array with a probability of p?
假設我有一個 numpy 數組a = np.random.randint(0,20,10)
我想以概率p
排列它的元素,即如果p = 0.2
每個元素有 20% 的概率將 position 與另一個元素交換. 我知道numpy.random.permutate()
function 但這僅允許排列數組中的所有元素。 這可以在 python 中有效地完成嗎?
訣竅是首先選擇哪些元素將成為參與排列的候選者。
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.