以相同的方式随机化 2 个 numpy 数组

Randomize 2 numpy arrays the same way

我有 2 个 np.ndarray() 对象,我想像这样随机化(或打乱)它们:

>>> a
[[12. 13. 24. ... 23. 45. 67.] [32. 10. 23. ... 23. 45. 67.] [12. 13. 24. ... 23. 45. 67.] ... [12. 13. 24. ... 23. 45. 67.]]
>>> b
[0. 0. 0. ... 1.]
>>> shuffle(a, b)
>>> a
[[12. 13. 24. ... 23. 45. 67.] [32. 10. 23. ... 23. 45. 67.] [12. 13. 24. ... 23. 45. 67.] ... [12. 13. 24. ... 23. 45. 67.]]
>>> b
[1. 0. 0. ... 0.]

变量 b 中的每个数字对应于变量 a 中我的 AI 训练数据的标签。

使用 Numpy

您可以使用 np.c_ 将它们混合在一起,然后将它们放回单独的数组中 -

import numpy as np

#Creating same X and y for demonstration
X = np.arange(0,10).reshape(5,2)
y = np.arange(0,10).reshape(5,2)

c = np.c_[X,y]
np.random.shuffle(c)

X1, y1 = c[:,:X.shape[1]], c[:,:y.shape[1]]

print(X1)
print(y1)
# Note, same order remains

[[8 9]
 [0 1]
 [4 5]
 [6 7]
 [2 3]]

[[8 9]
 [0 1]
 [4 5]
 [6 7]
 [2 3]]

使用 Sklearn

更好的选择是使用 sklearn api -

from sklearn.utils import shuffle
X, y = shuffle(X, y, random_state=0)