【问题标题】:Conditional Numpy shuffling有条件的 Numpy 洗牌
【发布时间】:2021-06-19 14:30:57
【问题描述】:

问题
假设您有一个结构化的np.array

first_array = np.array([1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9])

并且您想创建一个新的np.array,大小相同,但被打乱了。

例如

second_array = np.random.shuffle(first_array)

second_array 
# np.array([3, 2, 9, 5, 6, 1, 1, 6, 9, 7, 8, 5, 2, 7, 8, 3, 4, 4])
                      

到目前为止,一切都很好。但是,随机洗牌会导致一些重复项彼此非常接近,这是我试图避免的。

问题
如何打乱这个数组,使整数顺序是伪随机的,但每个重复项很有可能彼此相距很远?这个问题有更具体的术语吗?

【问题讨论】:

标签: python numpy random shuffle


【解决方案1】:

这不仅仅是numpy 的算法问题。一种天真的方法是使用最小目标间距 (spacing_condition) 拆分数组,这些数字应该至少相距那么远。

import numpy as np
first_array = np.array([1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9])
spacing_condition = 3
subarrays = np.split(first_array, spacing_condition)

下一步是从subarrays中依次选择,这将保证spacing condition,并从该子数组中删除选择。

但是,在最后两步中,简单循环对于大型数组来说会很慢。在幼稚的实现之后,种子只是为了重现。

np.random.seed(42)

def choose_over_spacing(subarrays):
    choices = []
    new_subarrays_ = []
    subarray_indices = np.arange(len(subarrays[0]))
    for subarray in subarrays:
        index_to_choose = np.random.choice(subarray_indices, 1)[0]
        number_choice = subarray[index_to_choose]
        choices.append(number_choice)
        new_subarray = np.delete(subarray, index_to_choose)
        new_subarrays_.append(new_subarray)
    return choices, new_subarrays_

all_choices = []
for _ in np.arange(len(subarrays[0])):
    choices, subarrays =  choose_over_spacing(subarrays)
    all_choices = all_choices + choices

检查结果,我们看到我们保证重复的数字至少相隔 3 个数字,因为我们使用spacing_condition 进行条件化,只要初始拆分有效,就可以选择不同的间距条件。

[2, 6, 8, 3, 6, 7, 2, 5, 9, 3, 4, 9, 1, 4, 8, 1, 5, 7]

【讨论】:

  • 非常感谢您的支持。我正在考虑类似地解决它,这种方法效果很好。我现在正试图弄清楚如何使用二维数组来做同样的事情。我愚蠢地忘记提及这是我的目标。
  • @Novorodnas 对于 2D,您也需要在其他维度中定义间距条件。
  • 我将使用欧几里得距离来做到这一点.. 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2014-01-27
  • 1970-01-01
  • 2014-11-01
  • 2012-09-01
  • 1970-01-01
  • 2021-06-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多