如何使用 Keras 框架加载本地数据集 (X, y)



我有一个设计用于训练集和测试集文件夹的本地数据集,每个文件夹都包含 3 个类,如下所示:

-Training_Set
   --Class1
     --img1.jpg
     --img2.jpg
     ..
   --Class2
     --img101.jpg
     --img102.jpg
     ..
   --Class3
     --img201.jpg
     --img202.jpg
-Test_Set
       --Class1
         --img10.jpg
         --img11.jpg
         ..
       --Class2
         --img150.jpg
         --img140.jpg
         ..
       --Class3
         --img210.jpg
         --img220.jpg

我想像加载 Cifar 数据集一样加载它:

(trainX, trainY), (testX, testY) = cifar10.load_data()

你可以试试这个(虽然不确定为什么你想要它和cifar完全一样(:

import cv2  # pip install opencv-python
import numpy as np
import os

class ImageLoader:
    """Load images in arrays without batches."""
    def __init__(self, train_dir, test_dir):
        """Create class."""
        self.train_dir = train_dir
        self.test_dir = test_dir
    def load_data(self):
        """Load the data."""
        features, labels = [], []
        for source in [self.train_dir, self.test_dir]:
            input, output = [], []
            for class_name in os.listdir(source):
                if os.path.isdir(class_name):
                    for img_name in os.listdir(class_name):
                        img = cv2.imread(os.path.join(self.train_dir, class_name, img_name))
                        # ...
                        # Modify your image array here.
                        # ...
                        input.append(img)
                        output.append(class_name)  # or other method to convert label
            # Shuffle labels.
            combine = list(zip(input, output))  # zip as list for Python 3
            np.random.shuffle(combine)
            input, output = zip(*combine)
            features.append(input)
            labels.append(output)
        return [[np.array(features[0], dtype=np.float32),
                 np.array(labels[0], dtype=np.float32)],
                [np.array(features[1], dtype=np.float32),
                 np.array(labels[1], dtype=np.float32)]]

cifar10 = ImageLoader('path-to-training', 'path-to-testing')
(trainX, trainY), (testX, testY) = cifar10.load_data()
您可以使用

image-dataset-loader来加载数据集:

pip install image-dataset-loader
from image_dataset_loader import load
(x_train, y_train), (x_test, y_test) = load('/path/to/your/dataset', ['Training_Set', 'Test_Set'])

此外,您可以使用 Keras 的 ImageDataGeneratorflow_from_directory 代替。请参阅此示例和文档。

最新更新