我有两个不同形状的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版本中存活的东西。
这似乎是一个非常简单的解决方案:
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]))
假设我们有两个数组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]]
对连接列表进行就地洗牌的一种方法是使用种子(可以是随机的)并使用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]
编辑:修正了重新播种随机状态的代码