【问题标题】:How to preprocess a huge dataset and save it such that I can train the data in Python如何预处理一个巨大的数据集并保存它以便我可以在 Python 中训练数据
【发布时间】:2019-07-24 20:10:25
【问题描述】:

我想预处理一个庞大的图像数据集(600k),用于训练模型。但是,它占用了太多内存,我一直在寻找解决方案,但没有一个适合我的问题。这是我的代码的一部分。我还是深度学习的新手,我认为我在预处理数据方面做得不好。如果有人知道如何解决这个内存问题,将不胜感激。

# Read the CSV File
data_frame = pd.read_csv("D:\\Downloads\\ndsc-beginner\\train.csv")

#Load the image
def load_image(img_path, target_size=(256, 256)):
    #Check if the img_path has .jpg behind the name
    if img_path[-4:] != '.jpg':
        # Load the image
        img = load_img(img_path+'.jpg',
                       target_size=target_size, grayscale=True)
    else:
        #Load the image
        img = load_img(img_path, target_size=target_size, grayscale=True)
    # Convert to a numpy array
    return img_to_array(img) 


IMG_SIZE = 256
image_arr = []
# Get the category column values
category_id = data_frame['Category']
# Change the category to one-hot - has 50 categories
dummy_cat_id = keras.utils.np_utils.to_categorical(category_id, 50)
# Get the image paths column values
path_list = data_frame.iloc[1:, -1]
# Batch generator
def batch_gen(data, batch_size):
    for i in range(0, len(data), batch_size):
        yield data[i:i+batch_size]
# Append the numpy array(img) and category label into an array.
def extract_data(data_frame):
    total_count = len(path_list)
    batch_size = 1000
    index = 0
    for path in batch_gen(path_list,batch_size):
        for mini_path in path:
            image_arr.append([load_image(mini_path), dummy_cat_id[index]])
            print(index)
            index+= 1

#extract_data(data_frame)
random.shuffle(image_arr)


# Features and Labels for training data
trainImages = np.array([i[0] for i in image_arr]
                      ).reshape(-1, IMG_SIZE, IMG_SIZE, 1)
trainLabels = np.array([i[1] for i in image_arr])

trainImages = trainImages.astype('float32')
trainImages /= 255.0

【问题讨论】:

  • 要认识到的主要一点是,RAM 是一种有限的资源。如果你遇到内存错误,你只是有太多的数据,无法将它们全部保存在内存中。在这种情况下,您需要分块进行预处理并写入磁盘,并确保您不会一次将所有数组保存在内存中。要搜索的关键字是“批量处理图像/数据”
  • 你是在window还是unix上工作?

标签: python keras deep-learning


【解决方案1】:

我看到,在预处理过程中,您只是将图像设为灰度并对其进行标准化。 如果您使用的是 Keras,您可以使用以下内容进行标准化以及将图像转换为灰度 确保提供包含图像所在的类文件夹的路径。如果需要,您可以将课程模式更改为分类模式

train_datagen = ImageDataGenerator(rescale=1./255)
train_gen = train_datagen.flow_from_directory(
        f'{readPath}/training/',
        target_size=(100,100),
        color_mode='grayscale',
        batch_size=32,
        classes=['cat','dog'],
        class_mode='binary'
    )

您可以使用 model.fit_generator() 函数进行训练

【讨论】:

    猜你喜欢
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 2020-06-26
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 2020-10-03
    相关资源
    最近更新 更多