我有两个不同形状的numpy数组,但具有相同的长度(前维数)。我想对它们进行洗牌,以便相应的元素继续对应——即根据它们的前导索引对它们进行一致的洗牌。

这段代码可以工作,并说明了我的目标:

def shuffle_in_unison(a, b):
    assert len(a) == len(b)
    shuffled_a = numpy.empty(a.shape, dtype=a.dtype)
    shuffled_b = numpy.empty(b.shape, dtype=b.dtype)
    permutation = numpy.random.permutation(len(a))
    for old_index, new_index in enumerate(permutation):
        shuffled_a[new_index] = a[old_index]
        shuffled_b[new_index] = b[old_index]
    return shuffled_a, shuffled_b

例如:

>>> a = numpy.asarray([[1, 1], [2, 2], [3, 3]])
>>> b = numpy.asarray([1, 2, 3])
>>> shuffle_in_unison(a, b)
(array([[2, 2],
       [1, 1],
       [3, 3]]), array([2, 1, 3]))

然而,这感觉很笨拙、效率低、速度慢,而且需要复制数组——我宁愿在适当的位置重新排列它们,因为它们会相当大。

还有更好的办法吗?更快的执行和更低的内存使用是我的主要目标,但优雅的代码也会很好。

我的另一个想法是:

def shuffle_in_unison_scary(a, b):
    rng_state = numpy.random.get_state()
    numpy.random.shuffle(a)
    numpy.random.set_state(rng_state)
    numpy.random.shuffle(b)

这工作…但这有点可怕,因为我几乎没有看到它会继续工作的保证——例如,它看起来不像是那种保证在numpy版本中存活的东西。


当前回答

在我看来,使用种子是最简单的方法:

random.seed(seed)
random.shuffle(x_data)
# reset the same seed to get the identical random sequence and shuffle the y
random.seed(seed)
random.shuffle(y_data)

其他回答

有一个众所周知的函数可以处理这个问题:

from sklearn.model_selection import train_test_split
X, _, Y, _ = train_test_split(X,Y, test_size=0.0)

只要将test_size设置为0,就可以避免分裂并得到打乱的数据。 虽然它通常用于分割训练和测试数据,但它也会打乱它们。 从文档

将数组或矩阵分割为随机的训练和测试子集 包装输入验证和的快速实用程序 next (ShuffleSplit()。split(X, y))和应用程序将数据输入到 类中拆分(和可选子采样)数据的单个调用 oneliner。

只使用NumPy在原地将任意数量的数组洗牌在一起。

import numpy as np


def shuffle_arrays(arrays, set_seed=-1):
    """Shuffles arrays in-place, in the same order, along axis=0

    Parameters:
    -----------
    arrays : List of NumPy arrays.
    set_seed : Seed value if int >= 0, else seed is random.
    """
    assert all(len(arr) == len(arrays[0]) for arr in arrays)
    seed = np.random.randint(0, 2**(32 - 1) - 1) if set_seed < 0 else set_seed

    for arr in arrays:
        rstate = np.random.RandomState(seed)
        rstate.shuffle(arr)

可以这样使用

a = np.array([1, 2, 3, 4, 5])
b = np.array([10,20,30,40,50])
c = np.array([[1,10,11], [2,20,22], [3,30,33], [4,40,44], [5,50,55]])

shuffle_arrays([a, b, c])

有几件事需要注意:

断言确保所有输入数组都具有相同的长度 第一个维度。 数组按其第一个维度重新排列-没有返回任何内容。 在正int32范围内的随机种子。 如果需要可重复洗牌,则可以设置种子值。

shuffle之后,可以使用np对数据进行拆分。使用片分割或引用-取决于应用程序。

X = np.array([[1., 0.], [2., 1.], [0., 0.]])
y = np.array([0, 1, 2])
from sklearn.utils import shuffle
X, y = shuffle(X, y, random_state=0)

欲了解更多,请访问http://scikit-learn.org/stable/modules/generated/sklearn.utils.shuffle.html

如果您想避免复制数组,那么我建议您不生成一个置换列表,而是遍历数组中的每个元素,并随机将其交换到数组中的另一个位置

for old_index in len(a):
    new_index = numpy.random.randint(old_index+1)
    a[old_index], a[new_index] = a[new_index], a[old_index]
    b[old_index], b[new_index] = b[new_index], b[old_index]

实现了Knuth-Fisher-Yates shuffle算法。

我扩展了python的random.shuffle()来接受第二个arg:

def shuffle_together(x, y):
    assert len(x) == len(y)

    for i in reversed(xrange(1, len(x))):
        # pick an element in x[:i+1] with which to exchange x[i]
        j = int(random.random() * (i+1))
        x[i], x[j] = x[j], x[i]
        y[i], y[j] = y[j], y[i]

这样,我可以确保洗牌发生在适当的位置,并且函数不会太长或太复杂。