【问题标题】:ValueError: too many values to unpack (expected 2) when using tf.keras.preprocessing.image_dataset_from_directoryValueError:使用 tf.keras.preprocessing.image_dataset_from_directory 时解包的值太多(预期为 2)
【发布时间】:2021-01-21 20:39:17
【问题描述】:

我想使用函数 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),编码图像(有关规则,请参见下文 频道数)。 否则,它会产生一个元组(图像,标签),其中 图像具有形状 (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)>

如何分别访问里面的两个元组?

【问题讨论】:

  • 标签仅使用 train_ds 而不是 train_ds。您可以从 train_ds 中获取 image_batch、labels_batch。谢谢!
  • 谢谢,但是如何从 train_ds 访问这两个列表?

标签: python keras tensorflow-datasets


【解决方案1】:

你可以用下面的代码来绘制它

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")

代码的实际作用是从您的数据集中打印九张图像并为每张图像添加标题。
请注意,您无需在第一行代码中获取标签。

【讨论】:

    猜你喜欢
    • 2017-08-29
    • 1970-01-01
    • 2014-07-31
    • 2017-12-14
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多