簡體   English   中英

如何以 p 的概率交換數組中的元素?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM