【发布时间】:2021-04-16 04:53:49
【问题描述】:
我有一个 4D 数组训练图像,其尺寸对应于 (image_number,channels,width,height)。我还有一个 2D 目标标签,其维度对应于 (image_number,class_number)。训练时,我想使用 random.shuffle 随机打乱数据,但是如何保持标签按图像的相同顺序打乱?谢谢!
【问题讨论】:
我有一个 4D 数组训练图像,其尺寸对应于 (image_number,channels,width,height)。我还有一个 2D 目标标签,其维度对应于 (image_number,class_number)。训练时,我想使用 random.shuffle 随机打乱数据,但是如何保持标签按图像的相同顺序打乱?谢谢!
【问题讨论】:
from sklearn.utils import shuffle
import numpy as np
X = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]])
y = np.array([0, 1, 2, 3, 4])
X, y = shuffle(X, y)
print(X)
print(y)
[[1 1 1]
[3 3 3]
[0 0 0]
[2 2 2]
[4 4 4]]
[1 3 0 2 4]
【讨论】:
还有另一种简单的方法可以做到这一点。让我们假设总共有N 个图像。然后我们可以执行以下操作:
from random import shuffle
ind_list = [i for i in range(N)]
shuffle(ind_list)
train_new = train[ind_list, :,:,:]
target_new = target[ind_list,]
【讨论】:
list(range(N)),而不是[i for i in range(N)]。
如果你想要一个仅限 numpy 的解决方案,你可以在第一个数组上重新索引第二个数组,假设你在两个数组中都有相同的图像编号:
In [67]: train = np.arange(20).reshape(4,5).T
In [68]: target = np.hstack([np.arange(5).reshape(5,1), np.arange(100, 105).reshape(5,1)])
In [69]: train
Out[69]:
array([[ 0, 5, 10, 15],
[ 1, 6, 11, 16],
[ 2, 7, 12, 17],
[ 3, 8, 13, 18],
[ 4, 9, 14, 19]])
In [70]: target
Out[70]:
array([[ 0, 100],
[ 1, 101],
[ 2, 102],
[ 3, 103],
[ 4, 104]])
In [71]: np.random.shuffle(train)
In [72]: target[train[:,0]]
Out[72]:
array([[ 2, 102],
[ 3, 103],
[ 1, 101],
[ 4, 104],
[ 0, 100]])
In [73]: train
Out[73]:
array([[ 2, 7, 12, 17],
[ 3, 8, 13, 18],
[ 1, 6, 11, 16],
[ 4, 9, 14, 19],
[ 0, 5, 10, 15]])
【讨论】:
根据您想要做什么,您还可以为数组的每个维度随机生成一个数字
random.randint(a, b) #a and b are the extremes of your array
这将在您的对象中随机选择。
【讨论】:
random.randint(a, b) 不保证生成的号码与之前生成的号码不同,因此每次生成唯一号码时都需要手动跟踪,直到所有数据被覆盖。
如果您正在寻找同步/统一随机播放,您可以使用以下函数。
def unisonShuffleDataset(a, b):
assert len(a) == len(b)
p = np.random.permutation(len(a))
return a[p], b[p]
上面的一个仅适用于 2 个 numpy。通过在 func 上添加输入变量的数量,可以扩展到 2 以上。以及函数的返回。
【讨论】: