[英]How to use mobilenet_v2.preprocess_input on tensorflow dataset
I'm again struggling with the usage of tensorflow datasets.我再次为 tensorflow 数据集的使用而苦苦挣扎。 I'm again loading my images via我再次通过
data = keras.preprocessing.image_dataset_from_directory(
'./data',
labels='inferred',
label_mode='binary',
validation_split=0.2,
subset="training",
image_size=(img_height, img_width),
batch_size=sz_batch,
crop_to_aspect_ratio=True
)
I want to use this dataset in the pre-trained MobileNetV2我想在预训练的 MobileNetV2 中使用这个数据集
model = keras.applications.mobilenet_v2.MobileNetV2(input_shape=(img_height, img_width, 3), weights='imagenet')
The documentation says, that the input data must be scaled to be between -1 and 1 ( https://www.tensorflow.org/api_docs/python/tf/keras/applications/mobilenet_v2/MobileNetV2 ).文档说,输入数据必须缩放到 -1 和 1 之间( https://www.tensorflow.org/api_docs/python/tf/keras/applications/mobilenet_v2/MobileNetV2 )。 To do so, the preprocess_input
function is provided.为此,提供了preprocess_input
function。 When I use this function on my dataset当我在我的数据集上使用这个 function
scaled_data = tf.keras.applications.mobilenet_v2.preprocess_input(data)
I get the error: TypeError: unsupported operand type(s) for /=: 'BatchDataset' and 'float'
我收到错误: TypeError: unsupported operand type(s) for /=: 'BatchDataset' and 'float'
So how can I use this function properly with the tensorflow dataset?那么如何将这个 function 与 tensorflow 数据集正确使用?
Maybe try using tf.data.Dataset.map
:也许尝试使用tf.data.Dataset.map
:
import tensorflow as tf
import pathlib
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 preprocess(images, labels):
return tf.keras.applications.mobilenet_v2.preprocess_input(images), labels
train_ds = train_ds.map(preprocess)
images, _ = next(iter(train_ds.take(1)))
image = images[0]
plt.imshow(image.numpy())
Before preprocessing the images:在预处理图像之前:
After preprocessing the images with tf.keras.applications.mobilenet_v2.preprocess_input
only:仅使用tf.keras.applications.mobilenet_v2.preprocess_input
预处理图像后:
After preprocessing the images with tf.keras.layers.Rescaling(1./255)
only:仅使用tf.keras.layers.Rescaling(1./255)
预处理图像后:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.