洗牌vs佩尔穆特纽比

2024-04-18 19:04:58 发布

您现在位置:Python中文网/ 问答频道 /正文

numpy.random.shuffle(x)numpy.random.permutation(x)有什么区别?

我已经读过doc页面,但是我不知道这两者之间是否有什么区别,因为我只是想随机地洗牌数组的元素。

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

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


Tags: numpy元素docrandom页面数组shuffle区别
2条回答

再加上@ecatmur所说的,np.random.permutation在需要无序排列有序对时非常有用,特别是对于分类:

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]

np.random.permutationnp.random.shuffle有两个区别:

  • 如果传递一个数组,它将返回数组的一个shuffledcopynp.random.shuffle重新洗牌数组
  • 如果传递一个整数,它将返回一个无序范围,即np.random.shuffle(np.arange(n))

If x is an integer, randomly permute np.arange(x). If x is an array, make a copy and shuffle the elements randomly.

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

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

相关问题 更多 >