如何为 CNN 训练 Keras 处理数千张图像

How to deal with thousands of images for CNN training Keras

我有大约 10000k 个图像无法存入内存。所以现在我只能阅读 1000 张图像并对其进行训练...

我的代码在这里:

img_dir = "TrainingSet" # Enter Directory of all images 
image_path = os.path.join(img_dir+"/images",'*.bmp')
files = glob.glob(image_path)
images = []
masks = []
contours = []
indexes = []
files_names = []

for f1 in np.sort(files):
  img = cv2.imread(f1)
  result = re.search('original_cropped_(.*).bmp', str(f1))
  idx = result.group(1)
  mask_path = img_dir+"/masks/mask_cropped_"+str(idx)+".bmp"
  mask = cv2.imread(mask_path,0)
  contour_path = img_dir+"/contours/contour_cropped_"+str(idx)+".bmp"
  contour = cv2.imread(contour_path,0)

  indexes.append(idx)
  images.append(img)
  masks.append(mask)
  contours.append(contour)

train_df = pd.DataFrame({"id":indexes,"masks": masks, "images": images,"contours": contours })
train_df.sort_values(by="id",ascending=True,inplace=True)
print(train_df.shape)

img_size_target = (256,256)

ids_train, ids_valid, x_train, x_valid, y_train, y_valid, c_train, c_valid = train_test_split(
    train_df.index.values,
    np.array(train_df.images.apply(lambda x: cv2.resize(x,img_size_target).reshape(img_size_target[0],img_size_target[1],3))), 
    np.array(train_df.masks.apply(lambda x: cv2.resize(x,img_size_target).reshape(img_size_target[0],img_size_target[1],1))), 
    np.array(train_df.contours.apply(lambda x: cv2.resize(x,img_size_target).reshape(img_size_target[0],img_size_target[1],1))), 
    test_size=0.2, random_state=1337)

#Here we define the model architecture... 
#.....
#End of model definition

# Training 
optimizer = Adam(lr=1e-3,decay=1e-10)    
model.compile(loss="binary_crossentropy", optimizer=optimizer, metrics=["accuracy"])

early_stopping = EarlyStopping(patience=10, verbose=1)
model_checkpoint = ModelCheckpoint("./keras.model", save_best_only=True, verbose=1)
reduce_lr = ReduceLROnPlateau(factor=0.5, patience=5, min_lr=0.00001, verbose=1)

epochs = 200
batch_size = 32

history = model.fit(x_train, y_train,
                validation_data=[x_valid, y_valid], 
                epochs=epochs,
                batch_size=batch_size,
                callbacks=[early_stopping, model_checkpoint, reduce_lr])

我想知道的是如何修改我的代码以便批量处理一小组图像而不将所有其他 10000 张图像加载到内存中?这意味着该算法将在每个时期从目录中读取 X 个图像并对其进行训练,然后继续下一个 X 直到最后一个。

这里的 X 是可以放入内存的合理数量的图像。

使用fit_generator代替适合

def generate_batch_data(num):
    #load X images here
    return images

model.fit_generator(generate_batch_data(X),
        samples_per_epoch=10000, nb_epoch=10)

您可以使用 train_on_batch 代替 fit

关于此主题的 GitHub 讨论:https://github.com/keras-team/keras/issues/2708

np.array(train_df.images.apply(lambda x:cv2.resize(x,img_size_target).reshape(img_size_target[0],img_size_target[1],3)))

您可以先将此过滤器(以及其他 2 个过滤器)应用于每个单独的文件,然后将它们保存到单独脚本中的特殊文件夹(images_prepoc、masks_preproc 等),然后将它们加载回去,以便在当前脚本中使用。

假设实际图像尺寸大于 256x256,您将拥有更快的算法,以单个准备阶段为代价使用更少的内存。