繁体   English   中英

如何从 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,因此我将 function adjust_inputs映射到数据集。 但是现在当我尝试访问属性filenames时,出现错误: AttributeError: 'MapDataset' object has no attribute 'filenames' 这是合乎逻辑的,因为 MapDataset 不是 Dataset。

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

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

我按照以下方式做到了。

在训练了我的 model 之后,我刚刚重新加载了所有图像,这次使用选项shuffle=False并通过我的 model 运行它们以提取特征。 由于 shuffle 关闭,图像和文件路径的顺序是相同的。 因此,索引 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))

image, image, path = 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>

在此处输入图像描述

您必须确保对路径使用相同的批量大小。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM