我如何使用提供的需要 tf.Tensor 的 preprocess_input 函数预处理 tf.data.Dataset?
How can I preprocess a tf.data.Dataset using a provided preprocess_input function that expects a tf.Tensor?
有点一头雾水,我正在寻找使用 ResNet50 在 ImageNet 上预训练的方法将迁移学习应用于问题。
我已经准备好迁移学习过程,但需要我的数据集以正确的形式 tf.keras.applications.resnet50.preprocess_input
handily does. Except it works on a numpy.array
or tf.Tensor
and I'm using image_dataset_from_directory
加载数据,这给了我一个 tf.data.Dataset
.
有没有一种简单的方法可以使用提供的 preprocess_input
函数来预处理我的这种形式的数据?
或者,该函数指定:
The images are converted from RGB to BGR, then each color channel is zero-centered with respect to the ImageNet dataset, without scaling.
因此,在数据管道中或作为模型的一部分实现此目的的任何其他方式也是可以接受的。
您可以使用 tf.data.Dataset
的 map
函数将 preprocess_input
函数应用于每批图像:
import tensorflow as tf
import pathlib
import matplotlib.pyplot as plt
dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
data_dir = tf.keras.utils.get_file('flower_photos', origin=dataset_url, untar=True)
data_dir = pathlib.Path(data_dir)
batch_size = 32
train_ds = tf.keras.utils.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="training",
seed=123,
image_size=(180, 180),
batch_size=batch_size)
def display(ds):
images, _ = next(iter(ds.take(1)))
image = images[0].numpy()
image /= 255.0
plt.imshow(image)
def preprocess(images, labels):
return tf.keras.applications.resnet50.preprocess_input(images), labels
train_ds = train_ds.map(preprocess)
display(train_ds)
有点一头雾水,我正在寻找使用 ResNet50 在 ImageNet 上预训练的方法将迁移学习应用于问题。
我已经准备好迁移学习过程,但需要我的数据集以正确的形式 tf.keras.applications.resnet50.preprocess_input
handily does. Except it works on a numpy.array
or tf.Tensor
and I'm using image_dataset_from_directory
加载数据,这给了我一个 tf.data.Dataset
.
有没有一种简单的方法可以使用提供的 preprocess_input
函数来预处理我的这种形式的数据?
或者,该函数指定:
The images are converted from RGB to BGR, then each color channel is zero-centered with respect to the ImageNet dataset, without scaling.
因此,在数据管道中或作为模型的一部分实现此目的的任何其他方式也是可以接受的。
您可以使用 tf.data.Dataset
的 map
函数将 preprocess_input
函数应用于每批图像:
import tensorflow as tf
import pathlib
import matplotlib.pyplot as plt
dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
data_dir = tf.keras.utils.get_file('flower_photos', origin=dataset_url, untar=True)
data_dir = pathlib.Path(data_dir)
batch_size = 32
train_ds = tf.keras.utils.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="training",
seed=123,
image_size=(180, 180),
batch_size=batch_size)
def display(ds):
images, _ = next(iter(ds.take(1)))
image = images[0].numpy()
image /= 255.0
plt.imshow(image)
def preprocess(images, labels):
return tf.keras.applications.resnet50.preprocess_input(images), labels
train_ds = train_ds.map(preprocess)
display(train_ds)