设置一次后更改tf.keras.preprocessing.image_dataset_from_directory的label_mode

问题描述

我正在使用以下代码加载必须传递给卷积变分自动编码器的图像:

import tensorflow as tf

train = tf.keras.preprocessing.image_dataset_from_directory(
  data_dir + 'Train/',label_mode=None,image_size=(img_height,img_width),batch_size=batch_size)

为了能够将其传递给自动编码器,我必须设置label_mode = None。此外,在解码器处接收到的图像还将进一步传递到CNN,以便在需要标签的地方进行分类

如何使train也在以后的CNN label_mode=None最初还返回标签

解决方法

您可以使用标签加载图像,然后创建另一个没有标签的数据集。

import tensorflow as tf

train = tf.keras.preprocessing.image_dataset_from_directory(
  data_dir + 'Train/',label_mode='categorical',image_size=(img_height,img_width),batch_size=batch_size)

X = np.array([])
for x,y in testData:
  if X.size == 0:
    X = x.numpy()
    continue
  X = np.concatenate([X,x.numpy()])
dataset = tf.data.Dataset.from_tensor_slices(X)