【问题标题】:How to shuffle two numpy datasets using TensorFlow 2.0?如何使用 TensorFlow 2.0 打乱两个 numpy 数据集?
【发布时间】:2020-01-19 06:28:25
【问题描述】:

我希望在 TensorFlow 2.0 中编写一个函数,而不是在每次训练迭代之前打乱数据及其目标标签。

假设我有两个 numpy 数据集,X 和 y,分别表示用于分类的数据和标签。我怎样才能同时洗牌

使用sklearn 非常简单:

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

如何在 TensorFlow 2.0 中做同样的事情?我在文档中找到的唯一工具是tf.random.shuffle,但它一次只需要一个对象,我需要喂两个。

【问题讨论】:

标签: python numpy tensorflow tensorflow2.0


【解决方案1】:

如果你只是想以同样的方式洗牌两个数组,你可以这样做:

import tensorflow as tf

# Assuming X and y are initially NumPy arrays
X = tf.convert_to_tensor(X)
y = tf.convert_to_tensor(y)
# Make random permutation
perm = tf.random.shuffle(tf.range(tf.shape(X)[0]))
# Reorder according to permutation
X = tf.gather(X, perm, axis=0)
y = tf.gather(y, perm, axis=0)

但是,您可以考虑使用tf.data.Dataset,它已经提供了shuffle 方法。

import tensorflow as tf

# You may use a placeholder if in graph mode
# (see https://www.tensorflow.org/guide/datasets#consuming_numpy_arrays)
ds = tf.data.Dataset.from_tensor_slices((X, y))
# Shuffle with some buffer size (len(X) will use a buffer as big as X)
ds = ds.shuffle(buffer_size=len(X))

【讨论】:

  • 我们如何从数据集对象中检索具有初始形状的混洗张量 X 和 Y?提前谢谢
【解决方案2】:

与其打乱 x 和 y ,不如打乱它们的索引要容易得多,所以首先生成一个索引列表

indices = tf.range(start=0, limit=tf.shape(x_data)[0], dtype=tf.int32)

然后随机播放这些索引

idx = tf.random.shuffle(indices)

并使用这些索引来打乱数据

x_data = tf.gather(x_data, idx)
y_data = tf.gather(y_data, idx)

你会得到洗牌的数据

【讨论】:

    【解决方案3】:

    先将它们转换成tf.data.Dataset类型。

    x_train = tf.data.Dataset.from_tensor_slices(x)
    y_train = tf.data.Dataset.from_tensor_slices(y)
    

    完成后,您可以简单地随机播放它们:

    x_train, y_train = x_train.shuffle(buffer_size=2, seed=2), y_train.shuffle(buffer_size=2, seed=2)
    dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
    

    在两个训练变量中使用相同的seed,这样您就可以在不丢失特征-目标关系的情况下打乱您的数据。 你甚至可以创建一个随机播放的函数:

    BF = 2
    SEED = 2
    def shuffling(dataset, bf, seed_number):
       return dataset.shuffle(buffer_size=bf, seed=seed_number)
    
    x_train, y_train = shuffling(x_train, BF, SEED), shuffling(y_train, BF, SEED)
    dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-16
      • 1970-01-01
      • 2021-07-06
      • 1970-01-01
      • 2020-02-19
      • 2020-10-29
      • 1970-01-01
      相关资源
      最近更新 更多