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)
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)