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

标签 python tensorflow keras tensorflow-datasets tf.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)

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

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

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

最佳答案

以防万一您想将文件路径添加为数据集的一部分:

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>

enter image description here

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

关于python - 如何从 Keras 中的 image_dataset_from_directory() 附加或获取 MapDataset 文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70260531/

相关文章:

python - 从标签 python 中提取值

python - 改变 tensorflow 图并恢复训练

json - TensorFlow 形状和类型推断

python - 如何在 TensorFlow 的 eager 执行中使用 Keras.applications 的 ResNeXt?

machine-learning - 同时对不同的输出使用不同的损失函数 Keras?

python - 如何将图像转换为 .tflite 输入

python - 在 Python 中使用 Tab 键?

Python 数组赋值

python - 是否有(已经)一种方法来比较 2 个模型实例,一个字段一个字段,看它们是否相等?

python - 如何修改ImageDataGenerator中的flow_from_directory或preprocessing_function?