tfds.load()之后如何在TensorFlow 2.0中应用数据增强

him*_*ani 5 python tensorflow tensorflow-datasets data-augmentation tensorflow2.0

我正在遵循本指南

它显示了如何使用以下tfds.load()方法从新的TensorFlow数据集中下载数据集:

import tensorflow_datasets as tfds    
SPLIT_WEIGHTS = (8, 1, 1)
splits = tfds.Split.TRAIN.subsplit(weighted=SPLIT_WEIGHTS)

(raw_train, raw_validation, raw_test), metadata = tfds.load(
    'cats_vs_dogs', split=list(splits),
    with_info=True, as_supervised=True)
Run Code Online (Sandbox Code Playgroud)

后续步骤显示了如何使用map方法将函数应用于数据集中的每个项目:

def format_example(image, label):
    image = tf.cast(image, tf.float32)
    image = image / 255.0
    # Resize the image if required
    image = tf.image.resize(image, (IMG_SIZE, IMG_SIZE))
    return image, label

train = raw_train.map(format_example)
validation = raw_validation.map(format_example)
test = raw_test.map(format_example)
Run Code Online (Sandbox Code Playgroud)

然后访问元素,我们可以使用:

for features in ds_train.take(1):
  image, label = features["image"], features["label"]
Run Code Online (Sandbox Code Playgroud)

要么

for example in tfds.as_numpy(train_ds):
  numpy_images, numpy_labels = example["image"], example["label"]
Run Code Online (Sandbox Code Playgroud)

但是,该指南未提及任何有关数据增强的内容。我想使用类似于Keras的ImageDataGenerator类的实时数据增强。我尝试使用:

if np.random.rand() > 0.5:
    image = tf.image.flip_left_right(image)
Run Code Online (Sandbox Code Playgroud)

和其他类似的增强功能,format_example()但是,如何验证它正在执行实时增强,而不替换数据集中的原始图像?

我可以通过传递batch_size=-1给完整的数据集并将其转换为Numpy数组tfds.load(),然后使用tfds.as_numpy(),但这将不需要的所有图像加载到内存中。我应该可以用来train = train.prefetch(tf.data.experimental.AUTOTUNE)为下一个训练循环加载足够的数据。

Szy*_*zke 6

您正在从错误的方向解决问题。

首先,使用下载的数据tfds.loadcifar10例如(为简单起见,我们将使用默认TRAINTEST分裂):

import tensorflow_datasets as tfds

dataloader = tfds.load("cifar10", as_supervised=True)
train, test = dataloader["train"], dataloader["test"]
Run Code Online (Sandbox Code Playgroud)

(您可以使用自定义tfds.Split对象来创建验证数据集或其他验证数据集,请参阅文档

train并且testtf.data.Dataset对象,所以你可以使用mapapplybatch和类似的功能分配到每个那些。

下面是一个示例,我将(tf.image大部分使用):

  • 将每个图像转换tf.float64为该0-1范围内的图像(不要使用官方文档中的此愚蠢代码段,这样可以确保正确的图像格式)
  • cache() 结果,因为它们可以在每次使用后重复使用 repeat
  • 随机翻转left_to_right每个图像
  • 随机改变图像的对比度
  • 随机播放数据和批处理
  • 重要说明:数据集用完后,请重复所有步骤。这意味着在一个时期之后,以上所有转换都将再次应用(已缓存的转换除外)。

这是完成上述操作的代码(您可以将lambdas 更改为函子或函数):

train = train.map(
    lambda image, label: (tf.image.convert_image_dtype(image, tf.float32), label)
).cache().map(
    lambda image, label: (tf.image.random_flip_left_right(image), label)
).map(
    lambda image, label: (tf.image.random_contrast(image, lower=0.0, upper=1.0), label)
).shuffle(
    100
).batch(
    64
).repeat()
Run Code Online (Sandbox Code Playgroud)

这样tf.data.Dataset可以直接传递到Keras的fitevaluatepredict方法。

验证它确实像那样工作

我看到您对我的解释高度怀疑,让我们来看一个例子:

1.获取一小部分数据

这是采用单个元素的一种方法,虽然这是不可读和不直观的,但是如果您对...做任何事情,都应该可以Tensorflow

# Horrible API is horrible
element = tfds.load(
    # Take one percent of test and take 1 element from it
    "cifar10",
    as_supervised=True,
    split=tfds.Split.TEST.subsplit(tfds.percent[:1]),
).take(1)
Run Code Online (Sandbox Code Playgroud)

2.重复数据并检查是否相同:

使用Tensorflow 2.0一个实际上可以做到,而没有愚蠢的解决方法(几乎):

element = element.repeat(2)
# You can iterate through tf.data.Dataset now, finally...
images = [image[0] for image in element]
print(f"Are the same: {tf.reduce_all(tf.equal(images[0], images[1]))}")
Run Code Online (Sandbox Code Playgroud)

它毫不奇怪地返回:

Are the same: True
Run Code Online (Sandbox Code Playgroud)

3.随机重复每次重复后,检查数据是否有所不同

在片段repeat的单个元素下面5次并检查哪些相等和哪些不同。

element = (
    tfds.load(
        # Take one percent of test and take 1 element
        "cifar10",
        as_supervised=True,
        split=tfds.Split.TEST.subsplit(tfds.percent[:1]),
    )
    .take(1)
    .map(lambda image, label: (tf.image.random_flip_left_right(image), label))
    .repeat(5)
)

images = [image[0] for image in element]

for i in range(len(images)):
    for j in range(i, len(images)):
        print(
            f"{i} same as {j}: {tf.reduce_all(tf.equal(images[i], images[j]))}"
        )
Run Code Online (Sandbox Code Playgroud)

输出(在我的情况下,每次运行都不同):

0 same as 0: True
0 same as 1: False
0 same as 2: True
0 same as 3: False
0 same as 4: False
1 same as 1: True
1 same as 2: False
1 same as 3: True
1 same as 4: True
2 same as 2: True
2 same as 3: False
2 same as 4: False
3 same as 3: True
3 same as 4: True
4 same as 4: True
Run Code Online (Sandbox Code Playgroud)

你可以施放每这些图像来numpy以及使用和看到的图像为自己skimage.io.imshowmatplotlib.pyplot.imshow或其他替代品。

实时数据可视化的另一个示例

这个答案提供了使用Tensorboard和进行数据增强的更全面,更易读的视图MNIST,可能需要检查一下(是的,无耻的插件,但我想很有用)。

  • 我看你对“tensorflow”没有太大信心,我可以理解。我添加了一个示例,比较“random_flip_left_right”之前和之后的图像。如果您愿意,您可以通过这种方式进行更广泛的测试。 (2认同)
  • 谢谢你的例子!验证步骤之后,事情就清楚多了。 (2认同)