如何在 Keras 中从 image_dataset_from_directory() 的 MapDataset 附加或获取文件名?

How to attach or get filenames from MapDataset from image_dataset_from_directory() in Keras?

我正在训练卷积自动编码器,我有这个加载数据(图像)的代码:

train_ds = tf.keras.preprocessing.image_dataset_from_directory(
    'path/to/images',
    image_size=image_size
)
normalization_layer = layers.experimental.preprocessing.Rescaling(1./255)

def adjust_inputs(images, labels):
    return normalization_layer(images), normalization_layer(images)

normalized_train_ds = train_ds.map(adjust_inputs)

由于我不需要 class 标签,而是将其自身成像为 Y,因此我将函数 adjust_inputs 映射到数据集。但是现在,当我尝试访问属性 filenames 时,出现错误:AttributeError: 'MapDataset' object has no attribute 'filenames'。这是合乎逻辑的,因为 MapDataset 不是 Dataset。

我如何附加或获取我的数据集中已加载图像的文件名?

我真的很惊讶没有一个更简单的界面,这看起来很常见。

我是按照下面的方法做的。

训练完我的模型后,我重新加载了所有图像,这次使用选项 shuffle=False 和 运行 通过我的模型提取特征。由于随机播放关闭,图像和文件路径的顺序是相同的。因此,索引 0 处的图像以及索引 0 处的相应特征在索引 0 处具有其文件路径。

以防万一您想将 filepaths 添加为数据集的一部分:

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, shuffle=False, batch_size=batch_size)

normalization_layer = tf.keras.layers.Rescaling(1./255)
def change_inputs(images, labels, paths):
  x = normalization_layer(images)
  return x, x, tf.constant(paths)

normalized_ds = train_ds.map(lambda images, labels: change_inputs(images, labels, paths=train_ds.file_paths))

images, images, paths = next(iter(normalized_ds.take(1)))

image = images[0]
path = paths[0]
print(path)
plt.imshow(image.numpy())
Found 3670 files belonging to 5 classes.
tf.Tensor(b'/root/.keras/datasets/flower_photos/daisy/100080576_f52e8ee070_n.jpg', shape=(), dtype=string)
<matplotlib.image.AxesImage at 0x7f9b113d1a10>

您只需确保对路径使用相同的批量大小即可。