numpy.random.shuffle(x)
和numpy.random.permutation(x)
有什么区别?我已经阅读了文档页面,但无法确定两者之间是否有任何区别,如果我只想随机打乱数组的元素。更确切地说,假设我有一个数组
x=[1,4,2,8]
。如果我想生成x的随机排列,那么在
shuffle(x)
和permutation(x)
之间有什么区别?numpy.random.shuffle(x)
和numpy.random.permutation(x)
有什么区别?x=[1,4,2,8]
。shuffle(x)
和permutation(x)
之间有什么区别?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
继@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]
在@ecatmur的基础上,这里是一个简短的解释。首先,我创建了一个数组,其形状为3,3,包含从0到8的数字。
import numpy as np
x1 = np.array(np.arange(0,9)).reshape(3,3) #array with shape 3,3 and have numbers from 0 to 8
#step1: using np.random.permutation
x_per = np.random.permutation(x1)
print('x_per:', x_per)
print('x_1:', x_1)
#Inference: x1 is not changed and x_per has its rows randomly changed
#The outcome will be
x1: [[0 1 2]
[3 4 5]
[6 7 8]]
x_per:[[3 4 5]
[0 1 2]
[6 7 8]]
#Lets apply shuffling
x2 = np.array(range(9)).reshape(3,3)
x2_shuffle = np.random.shuffle(x2)
print('x2_shuffle:', x2_shuffle)
print('x2', x2)
#Outcome:
x2_shuffle: None
x2 [[3 4 5]
[0 1 2]
[6 7 8]]
panda.Index
上使用时,只有permutation
起作用,而shuffle
不起作用。这种情况如何符合您的解释? - Heisenbergpermutation
强制将其参数转换为 ndarray(通过复制);pandas.Index
与 ndarray 的区别足够大,以至于shuffle
无法在其中运行,但可以在由此创建的 ndarray 上运行。 - ecatmur