【问题标题】:How to import dataset of images from two directories and adding labels for training and testing?如何从两个目录导入图像数据集并添加标签以进行训练和测试?
【发布时间】:2021-09-29 05:32:49
【问题描述】:

我尝试在 Python 中使用 CNN 进行图像分类。现在我有一个关于如何加载数据集的问题。

我有一个包含两个目录的数据集:一个目录包含 50,000 个用于训练图像的 jpg 文件(ID 介于 0-49,999 之间),另一个目录包含 10,000 个用于测试的 jpg 文件(ID 介于 0-9,999 之间)。还有一个训练标签 CSV 文件。这是一个包含两列的 CSV 文件。第一列表示样本 id,第二列表示样本的标签。标签在0到9之间,我知道图片和标签之间的映射关系。

如何在 Python 中导入数据集?

我尝试使用 CIFAR-10 数据集的代码来加载我的数据集,我的代码如下:

# example of loading the cifar10 dataset
from matplotlib import pyplot
from keras.datasets import cifar10
# load dataset
(trainX, trainy), (testX, testy) = cifar10.load_data()
# summarize loaded dataset
print('Train: X=%s, y=%s' % (trainX.shape, trainy.shape))
print('Test: X=%s, y=%s' % (testX.shape, testy.shape))
# plot first few images
for i in range(9):
    # define subplot
    pyplot.subplot(330 + 1 + i)
    # plot raw pixel data
    pyplot.imshow(trainX[i])
# show the figure
pyplot.show()

对于 CIFAR-10 数据集,训练数据集和测试数据集的形状是 Train: X=(50000, 32, 32, 3), y=(50000, 1) Test: X=(10000, 32, 32, 3), y=(10000, 1)

我可以为我的目录获取类似的训练数据集和测试数据集吗?

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    使用tf.keras.utils.image_dataset_from_directory从目录加载图片。

    下面的示例代码

      data_dir ='directory/path'     
      train_ds = tf.keras.utils.image_dataset_from_directory(
      data_dir,
      validation_split=0.2,
      subset="training",
      seed=123,
      image_size=(img_height, img_width),
      batch_size=batch_size)
    

    【讨论】:

    • 谢谢!请问如何将它们标记为(trainX, trainy), (testX, testy) = cifar10.load_data()
    猜你喜欢
    • 1970-01-01
    • 2021-05-18
    • 2014-01-05
    • 2019-03-15
    • 2020-10-31
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    相关资源
    最近更新 更多