在 numpy 数组的列中独立洗牌
Shuffle independently within column of numpy array
我有一个格式为
的 numpy 数组
[[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]
...
[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]]
每一列代表一个数据通道,我需要 独立于其他通道 打乱该列中每一列的内容。我知道 numpy.random.shuffle
只沿着数组的第一个轴洗牌,即。打乱数组中行的顺序。在每一列中进行独立洗牌的最佳方法是什么?
我们可以为每一列生成唯一的行索引,并使用 advanced-indexing
对输入数组进行索引。为了生成唯一索引,我们将使用 ,从而为我们提供一个矢量化解决方案,就像这样 -
idx = np.random.rand(*a.shape).argsort(0)
out = a[idx, np.arange(a.shape[1])]
普通版
我们可以将其概括为涵盖通用 n-dim
数组以及通用 axes
和 np.take_along_axis
and end up something as listed in this post
。
我有一个格式为
的 numpy 数组[[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]
...
[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]]
每一列代表一个数据通道,我需要 独立于其他通道 打乱该列中每一列的内容。我知道 numpy.random.shuffle
只沿着数组的第一个轴洗牌,即。打乱数组中行的顺序。在每一列中进行独立洗牌的最佳方法是什么?
我们可以为每一列生成唯一的行索引,并使用 advanced-indexing
对输入数组进行索引。为了生成唯一索引,我们将使用
idx = np.random.rand(*a.shape).argsort(0)
out = a[idx, np.arange(a.shape[1])]
普通版
我们可以将其概括为涵盖通用 n-dim
数组以及通用 axes
和 np.take_along_axis
and end up something as listed in this post
。