VGG16预处理数据集生成器到数据集映射

发布于 2025-02-01 13:44:10 字数 2439 浏览 5 评论 0原文

我有一个用keras/tensorflow实施的VGG16型号。

当我调用model.fit时,我传递了数据的生成器。 The generator does transforms necessary for a VGGNet:

  1. Preprocess the images with <代码> vgg16.preprocess_input
  2. 通过 to_categorical

可以在下面看到生成器并有效。不幸的是,由于有多个时期,因此我必须设置dataset.repeat(-1)(无限重复),以使生成器不会用完。反过来,这需要一个人传递step_per_epoch,以便可以完成培训的给定迭代。正如您可能想的那样,这是脆弱的(在已知的数据集基数上取决于)!

我已经决定使用dataset.map前方一旦培训DataSet最好预处理。但是,我在构建映射函数方面正在努力,似乎to_categorical不适合tf.tensor。下面是我现在拥有的,但是我不确定是否有潜在错误。

我如何正确地将以下数据集生成器转换为dataset.map函数?


当前dataset generator

这是用Python 3.8和TensorFlow == 2.4.4实现(并已知)的。

from typing import Iterable, Tuple

import numpy as np
import tensorflow as tf


def make_vgg_preprocessing_generator(
    dataset: tf.data.Dataset, num_repeat: int = -1
) -> Iterable[Tuple[tf.Tensor, np.ndarray]]:
    num_classes = len(dataset.class_names)
    for batch_images, batch_labels in dataset.repeat(num_repeat):
        pre_images = tf.keras.applications.vgg16.preprocess_input(batch_images)
        pre_labels = tf.keras.utils.to_categorical(batch_labels, num_classes)
        yield pre_images, pre_labels


train_ds: tf.data.Dataset  # Not provided in this sample
model.fit(
    make_vgg_preprocessing_generator(train_ds)
    epochs=10,
    steps_per_epoch=10,  # Required since default num_repeat is indefinitely
)

dataset.map函数

这是我想要改进的当前翻译。

def vgg_preprocess_dataset(dataset: tf.data.Dataset) -> tf.data.Dataset:
    num_classes = len(dataset.class_names)

    def _preprocess(x: tf.Tensor, y: tf.Tensor) -> Tuple[tf.Tensor, tf.Tensor]:
        pre_x = tf.keras.applications.vgg16.preprocess_input(x)
        pre_y = tf.one_hot(y, depth=num_classes)
        return pre_x, pre_y

    return dataset.map(_preprocess)

I have a VGG16 model implemented with Keras/tensorflow.

When I call model.fit, I pass in a generator of data. The generator does transforms necessary for a VGGNet:

  1. Preprocess the images with vgg16.preprocess_input
  2. Convert the label to a one-hot vector via to_categorical

The generator can be seen below and works. Unfortunately, since there are multiple epochs, I have to set dataset.repeat(-1) (infinitely repeat) so the generator doesn't run out. This in turn requires one to pass a steps_per_epoch so a given iteration of training can complete. As you're probably thinking, this is brittle, (hinges on a known dataset cardinality)!

I have decided it's best to preprocess the training Dataset once up front using Dataset.map. However, I am struggling with the construction of a mapping function, it seems to_categorical doesn't work with a tf.Tensor. Down below is what I have right now, but I am not sure if there's a latent bug.

How can I correctly translate the below Dataset generator into a Dataset.map function?


Current Dataset Generator

This is implemented (and known to work) with Python 3.8 and tensorflow==2.4.4.

from typing import Iterable, Tuple

import numpy as np
import tensorflow as tf


def make_vgg_preprocessing_generator(
    dataset: tf.data.Dataset, num_repeat: int = -1
) -> Iterable[Tuple[tf.Tensor, np.ndarray]]:
    num_classes = len(dataset.class_names)
    for batch_images, batch_labels in dataset.repeat(num_repeat):
        pre_images = tf.keras.applications.vgg16.preprocess_input(batch_images)
        pre_labels = tf.keras.utils.to_categorical(batch_labels, num_classes)
        yield pre_images, pre_labels


train_ds: tf.data.Dataset  # Not provided in this sample
model.fit(
    make_vgg_preprocessing_generator(train_ds)
    epochs=10,
    steps_per_epoch=10,  # Required since default num_repeat is indefinitely
)

Dataset.map Function

Here is my current translation that I would like to improve.

def vgg_preprocess_dataset(dataset: tf.data.Dataset) -> tf.data.Dataset:
    num_classes = len(dataset.class_names)

    def _preprocess(x: tf.Tensor, y: tf.Tensor) -> Tuple[tf.Tensor, tf.Tensor]:
        pre_x = tf.keras.applications.vgg16.preprocess_input(x)
        pre_y = tf.one_hot(y, depth=num_classes)
        return pre_x, pre_y

    return dataset.map(_preprocess)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

话少心凉 2025-02-08 13:44:10

是的,您在正确的道路上!您需要用to_categorical tf.One_hot,就像您一样,tf.one_hot是专门用于张量的,并且是设计的,并且是设计的在这种情况下。接下来,您可能需要与其他一些tf.data.dataset methods 在这里并将它们添加到您的管道中。目前,您的批次大小将是一个样本,并且没有改组。您可能会执行的其他一些处理的示例:

def vgg_preprocess_dataset(dataset: tf.data.Dataset, batch_size=32, shuffle_buffer=1000) -> tf.data.Dataset:
    num_classes = len(dataset.class_names)

    def _preprocess(x: tf.Tensor, y: tf.Tensor):
        pre_x = tf.keras.applications.vgg16.preprocess_input(x)
        pre_y = tf.one_hot(y, depth=num_classes)
        # pre_y = to_categorical(y, num_classes)
        return pre_x, pre_y

    # bigger buffer is better but slower
    dataset = dataset.shuffle(shuffle_buffer) 

    # do your mapping after shuffle
    dataset = dataset.map(_preprocess)

    # next batch it
    dataset = dataset.batch(batch_size)
    
    # this allows your CPU to fetch the next batch (do the above shuffling, mapping, etc) during the 
    # current GPU pass, so that the GPU has minimal downtime
    dataset = dataset.prefetch(2)

    return dataset

ds = vgg_preprocess_dataset(ds)

# and you just pass it right to fit!
model.fit(ds)

Yes, you're on the right track! You'll want to replace to_categorical with tf.one_hot, just as you have, as tf.one_hot is specifically for tensors, and is designed for this context. Next, you might want to play around with some of the other tf.data.Dataset methods here and add them to your pipeline. Right now, your batch size will be one sample, and un-shuffled. An example of some other processing you might do:

def vgg_preprocess_dataset(dataset: tf.data.Dataset, batch_size=32, shuffle_buffer=1000) -> tf.data.Dataset:
    num_classes = len(dataset.class_names)

    def _preprocess(x: tf.Tensor, y: tf.Tensor):
        pre_x = tf.keras.applications.vgg16.preprocess_input(x)
        pre_y = tf.one_hot(y, depth=num_classes)
        # pre_y = to_categorical(y, num_classes)
        return pre_x, pre_y

    # bigger buffer is better but slower
    dataset = dataset.shuffle(shuffle_buffer) 

    # do your mapping after shuffle
    dataset = dataset.map(_preprocess)

    # next batch it
    dataset = dataset.batch(batch_size)
    
    # this allows your CPU to fetch the next batch (do the above shuffling, mapping, etc) during the 
    # current GPU pass, so that the GPU has minimal downtime
    dataset = dataset.prefetch(2)

    return dataset

ds = vgg_preprocess_dataset(ds)

# and you just pass it right to fit!
model.fit(ds)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文