如何在 Tensorflow 中正确洗牌我的数据

how to properly shuffle my data in Tensorflow

我正在尝试使用 Tensorflow 中的命令打乱我的数据。

图像数据与标签匹配。

如果我使用这样的命令:

shuffle_seed = 10
images = tf.random.shuffle(images, seed=shuffle_seed)
labels = tf.random.shuffle(labels, seed=shuffle_seed)

他们还会相配吗?

如果他们不这样做,我该如何调整我的数据?

如果您使用 Keras API,您可以将 shuffle=True 传递给 fit() 函数,实际上它默认为 True

否则,如果您喜欢手动操作,一种方法是将您的张量转换为 numpy 数组 (tensor.numpy()),创建置换索引并使用方便的 numpy 索引并转换回张量。这是一个例子:

np.random.seed(10)
a1 = tf.range(10)
a1 = tf.reshape(a1, [5, 2])
a2 = tf.range(0, 10, delta=2)
a2 = tf.reshape(a2, [5,1])
print(a1, a2)
a1 = a1.numpy()
a2 = a2.numpy()
shuffled_idx = np.random.permutation(5)
a1[:] = a1[shuffled_idx]
a2[:] = a2[shuffled_idx]
a1 = tf.convert_to_tensor(a1,dtype=tf.int32)
a2 = tf.convert_to_tensor(a2,dtype=tf.int32)
print(a1, a2)

输出:

tf.Tensor(
[[0 1]
 [2 3]
 [4 5]
 [6 7]
 [8 9]], shape=(5, 2), dtype=int32) tf.Tensor(
[[0]
 [2]
 [4]
 [6]
 [8]], shape=(5, 1), dtype=int32)
tf.Tensor(
[[4 5]
 [6 7]
 [0 1]
 [8 9]
 [2 3]], shape=(5, 2), dtype=int32) tf.Tensor(
[[4]
 [6]
 [0]
 [8]
 [2]], shape=(5, 1), dtype=int32)

此解决方案适用于形状 (N, height, width, channels) 的图像和形状 (N,) 完全相同的标签。

我不确定这是否是最快/最有效/最好的方法,也许有一种不转换为 numpy 数组的方法。