在 Tensorflow 2.3 中规范化 BatchDataset

Mat*_*usz 2 python deep-learning keras tensorflow tensorflow-datasets

我正在使用tf.keras.preprocessing.image_dataset_from_directoryTF 2.3 从目录(训练/测试拆分)加载图像。我得到的是一个 tf.data.Dataset (tensorflow.python.data.ops.dataset_ops.BatchDataset实际上)具有形状的对象:

train_ds.take(1)
# <TakeDataset shapes: ((None, 256, 256, 3), (None, 6)), types: (tf.float32, tf.float32)>
Run Code Online (Sandbox Code Playgroud)
for images, labels in train_ds.take(1):
    print(images.shape)
    print(images[0])
# (32, 256, 256, 3)
# tf.Tensor(
# [[[225.75  225.75  225.75 ]
#   [225.75  225.75  225.75 ]
#   [225.75  225.75  225.75 ]
#   ...
#   [215.    214.    209.   ]
#   [215.    214.    209.   ]
#   [215.    214.    209.   ]]
#
#  ...], shape=(256, 256, 3), dtype=float32)
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何/= 255使用该 Dataset 对象对图像 ( )进行标准化。我尝试使用/=运算符本身mapapply方法,甚至将该对象转换为此处提到的列表。似乎没有任何效果,我真的很想在数据集级别解决这个问题,而不是向我的网络添加规范化层。

有任何想法吗?

小智 6

试试这个方法:

def process(image,label):
    image = tf.cast(image/255. ,tf.float32)
    return image,label

ds = tf.keras.preprocessing.image_dataset_from_directory(IMAGE_DIR)
ds = ds.map(process)

Run Code Online (Sandbox Code Playgroud)