python - ValueError:使用 tf.keras.preprocessing.image_dataset_from_directory 时解包的值太多(预期为 2)
问题描述
我想使用函数 tf.keras.preprocessing.image_dataset_from_directory (https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image_dataset_from_directory)创建一个数据集变量和一个标签变量。该文档指出:
返回:一个 tf.data.Dataset 对象。如果 label_mode 为 None,它会产生 float32 形状的张量(batch_size、image_size[0]、image_size[1]、num_channels)、编码图像(有关 num_channels 的规则,请参见下文)。否则,它会产生一个元组 (images, labels),其中 images 具有形状 (batch_size, image_size[0], image_size[1], num_channels),并且标签遵循下面描述的格式。
我的代码如下:
train_ds, labels = tf.keras.preprocessing.image_dataset_from_directory(
directory = data_dir,
labels='inferred',
label_mode = "int",
validation_split=0.2,
subset="training",
seed=123,
image_size=(img_height, img_width),
batch_size=batch_size)
我希望得到一个元组作为返回值,但我得到了错误消息:
Found 2160 files belonging to 2160 classes.
Using 1728 files for training.
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-168-ed9d42ed2ab9> in <module>
7 seed=123,
8 image_size=(img_height, img_width),
----> 9 batch_size=batch_size)
ValueError: too many values to unpack (expected 2)
当我将输出保存在一个变量(只是 train_ds)中并检查该变量时,我得到以下输出:
<BatchDataset shapes: ((None, 120, 30, 3), (None,)), types: (tf.float32, tf.int32)>
如何分别访问内部的两个元组?
解决方案
您可以使用下面的代码绘制它
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 10))
for images, labels in train_ds.take(1):
for i in range(9):
ax = plt.subplot(3, 3, i + 1)
plt.imshow(images[i].numpy().astype("uint8"))
plt.title(int(labels[i]))
plt.axis("off")
代码的实际作用是从数据集中打印九张图像,并为每张图像添加标题。
请注意,无需在第一行代码中获取标签。