我有两个不同形状的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版本中存活的东西。


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

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算法。

你可以使用NumPy的数组索引:

def unison_shuffled_copies(a, b):
    assert len(a) == len(b)
    p = numpy.random.permutation(len(a))
    return a[p], b[p]

这将导致创建单独的统一打乱数组。

你的“可怕”解决方案对我来说并不可怕。对两个相同长度的序列调用shuffle()会导致对随机数生成器的相同次数的调用,并且这些是shuffle算法中唯一的“随机”元素。通过重置状态,可以确保对随机数生成器的调用将在对shuffle()的第二次调用中给出相同的结果,因此整个算法将生成相同的排列。

如果您不喜欢这样,另一种解决方案是将数据存储在一个数组中,而不是从一开始就存储在两个数组中,并在这个数组中创建两个视图,模拟您现在拥有的两个数组。您可以将单个数组用于变换,而将视图用于所有其他目的。

示例:让我们假设数组a和b是这样的:

a = numpy.array([[[  0.,   1.,   2.],
                  [  3.,   4.,   5.]],

                 [[  6.,   7.,   8.],
                  [  9.,  10.,  11.]],

                 [[ 12.,  13.,  14.],
                  [ 15.,  16.,  17.]]])

b = numpy.array([[ 0.,  1.],
                 [ 2.,  3.],
                 [ 4.,  5.]])

我们现在可以构造一个包含所有数据的数组:

c = numpy.c_[a.reshape(len(a), -1), b.reshape(len(b), -1)]
# array([[  0.,   1.,   2.,   3.,   4.,   5.,   0.,   1.],
#        [  6.,   7.,   8.,   9.,  10.,  11.,   2.,   3.],
#        [ 12.,  13.,  14.,  15.,  16.,  17.,   4.,   5.]])

现在我们创建了模拟原始a和b的视图:

a2 = c[:, :a.size//len(a)].reshape(a.shape)
b2 = c[:, a.size//len(a):].reshape(b.shape)

a2和b2的数据与c共享。要同时洗牌两个数组,请使用numpy.random.shuffle(c)。

在生产代码中,你当然会尽量避免创建原始的a和b,而直接创建c, a2和b2。

这个解决方案可以适用于a和b具有不同的dtype的情况。

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

举个例子,这就是我正在做的:

combo = []
for i in range(60000):
    combo.append((images[i], labels[i]))

shuffle(combo)

im = []
lab = []
for c in combo:
    im.append(c[0])
    lab.append(c[1])
images = np.asarray(im)
labels = np.asarray(lab)

非常简单的解决方案:

randomize = np.arange(len(x))
np.random.shuffle(randomize)
x = x[randomize]
y = y[randomize]

这两个数组x y现在都以同样的方式随机洗牌

我扩展了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]

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

对连接列表进行就地洗牌的一种方法是使用种子(可以是随机的)并使用numpy.random.shuffle进行洗牌。

# Set seed to a random number if you want the shuffling to be non-deterministic.
def shuffle(a, b, seed):
   np.random.seed(seed)
   np.random.shuffle(a)
   np.random.seed(seed)
   np.random.shuffle(b)

就是这样。这将以完全相同的方式对a和b进行洗牌。这也是在原地完成的,这总是一个加分项。

编辑,不要使用np.random.seed(),而是使用np.random.RandomState

def shuffle(a, b, seed):
   rand_state = np.random.RandomState(seed)
   rand_state.shuffle(a)
   rand_state.seed(seed)
   rand_state.shuffle(b)

当调用它时,只需传入任意种子来提供随机状态:

a = [1,2,3,4]
b = [11, 22, 33, 44]
shuffle(a, b, 12345)

输出:

>>> a
[1, 4, 2, 3]
>>> b
[11, 44, 22, 33]

编辑:修正了重新播种随机状态的代码

你可以像这样创建一个数组:

s = np.arange(0, len(a), 1)

然后洗牌:

np.random.shuffle(s)

现在使用这个s作为数组的参数。相同的打乱参数返回相同的打乱向量。

x_data = x_data[s]
x_label = x_label[s]

James在2015年写了一个很有用的sklearn解决方案。但是他添加了一个随机状态变量,这是不需要的。在下面的代码中,自动假设来自numpy的随机状态。

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)

只使用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对数据进行拆分。使用片分割或引用-取决于应用程序。

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

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。

假设我们有两个数组a和b。

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

我们首先可以通过排列一维来获得行下标

indices = np.random.permutation(a.shape[0])
[1 2 0]

然后使用高级索引。 在这里,我们使用相同的下标来一致地洗牌两个数组。

a_shuffled = a[indices[:,np.newaxis], np.arange(a.shape[1])]
b_shuffled = b[indices[:,np.newaxis], np.arange(b.shape[1])]

这相当于

np.take(a, indices, axis=0)
[[4 5 6]
 [7 8 9]
 [1 2 3]]

np.take(b, indices, axis=0)
[[6 6 6]
 [4 2 0]
 [9 1 1]]
from np.random import permutation
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data #numpy array
y = iris.target #numpy array

# Data is currently unshuffled; we should shuffle 
# each X[i] with its corresponding y[i]
perm = permutation(len(X))
X = X[perm]
y = y[perm]

只要使用numpy…

首先将两个输入数组合并,1D数组为标签(y), 2D数组为数据(x),并使用NumPy shuffle方法进行shuffle。最后把他们分开回来。

import numpy as np

def shuffle_2d(a, b):
    rows= a.shape[0]
    if b.shape != (rows,1):
        b = b.reshape((rows,1))
    S = np.hstack((b,a))
    np.random.shuffle(S)
    b, a  = S[:,0], S[:,1:]
    return a,b

features, samples = 2, 5
x, y = np.random.random((samples, features)), np.arange(samples)
x, y = shuffle_2d(train, test)

这似乎是一个非常简单的解决方案:

import numpy as np
def shuffle_in_unison(a,b):

    assert len(a)==len(b)
    c = np.arange(len(a))
    np.random.shuffle(c)

    return a[c],b[c]

a =  np.asarray([[1, 1], [2, 2], [3, 3]])
b =  np.asarray([11, 22, 33])

shuffle_in_unison(a,b)
Out[94]: 
(array([[3, 3],
        [2, 2],
        [1, 1]]),
 array([33, 22, 11]))

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

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)

上面的大多数解都是可行的,但是如果你有列向量,你必须先转置它们。这里有一个例子

def shuffle(self) -> None:
    """
    Shuffles X and Y
    """
    x = self.X.T
    y = self.Y.T
    p = np.random.permutation(len(x))
    self.X = x[p].T
    self.Y = y[p].T