shuffle vs permute numpy

Dot*_*tPi 66 python numpy shuffle permutation scipy

numpy.random.shuffle(x)和之间有什么区别numpy.random.permutation(x)

我已经阅读了doc页面,但是当我想随机改组数组元素时,我无法理解两者之间是否存在任何差异.

更确切地说,假设我有一个数组x=[1,4,2,8].

如果我想生成x的随机排列,那么shuffle(x)和之间的区别是permutation(x)什么?

eca*_*mur 85

np.random.permutation有两点不同np.random.shuffle:

  • 如果传递一个数组,它将返回一个数组的混乱副本 ; np.random.shuffle将阵列移动到位
  • 如果传递一个整数,它将返回一个洗牌范围,即 np.random.shuffle(np.arange(n))

如果x是整数,则随机置换np.arange(x).如果x是一个数组,则复制并随机地移动元素.

源代码可能有助于理解这一点:

3280        def permutation(self, object x):
...
3307            if isinstance(x, (int, np.integer)):
3308                arr = np.arange(x)
3309            else:
3310                arr = np.array(x)
3311            self.shuffle(arr)
3312            return arr
Run Code Online (Sandbox Code Playgroud)

  • 当在 `panda.Index` 上使用时,只有 `permutation` 有效而 `shuffle` 无效。这个案例如何符合你的解释? (2认同)

hli*_*117 24

np.random.permutation当需要对有序对进行混洗时,添加到@ecatmur所说的内容非常有用,特别是对于分类:

from np.random import permutation
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
y = iris.target

# 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]
Run Code Online (Sandbox Code Playgroud)

  • 为了澄清@hlin117,这仅在 x 和 y 是 numpy 数组时才有效。如果您尝试使用 python 内置列表来执行此操作,则会抛出 TypeError。 (2认同)