【问题标题】:How to swap elements in a array with a probability of p?如何以 p 的概率交换数组中的元素?
【发布时间】:2020-12-12 20:33:54
【问题描述】:

假设我有一个 numpy 数组a = np.random.randint(0,20,10) 我想以p 的概率排列它的元素,即如果p = 0.2 每个元素有 20% 的概率与另一个元素交换位置。我知道numpy.random.permutate() 函数,但这仅允许排列数组中的所有元素。这可以在python中有效地完成吗?

【问题讨论】:

    标签: python arrays numpy numpy-ndarray


    【解决方案1】:

    诀窍是首先选择哪些元素将成为参与排列的候选者。

    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]
    

    【讨论】:

    • 这个答案看起来不错,但根据 OP 的预期,可能会有轻微错误。置换函数可以将部分或所有元素保留在其原始位置。因此,如果被选中意味着元素可以移动,这是正确的。如果它的意思是必须移动,那就不太对了。
    猜你喜欢
    • 2015-12-28
    • 2017-09-08
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-21
    • 1970-01-01
    • 2016-03-16
    相关资源
    最近更新 更多