【发布时间】:2020-05-05 14:40:50
【问题描述】:
我正在处理一个包含 300K 图像的数据集,进行多类图像分类。到目前为止,我获取了一个包含大约 7k 图像的小型数据集,但代码要么返回内存错误,要么我的笔记本死了。下面的代码一次将所有图像转换为一个 numpy 数组,这会在执行最后一行代码时导致我的内存出现问题。 train.csv 包含图像文件名和一个热编码标签。 代码是这样的:
data = pd.read_csv('train.csv')
img_width = 400
img_height = 400
img_vectors = []
for i in range(data.shape[0]):
path = 'Images/' + data['Id'][
img = image.load_img(path, target_size=(img_width, img_height, 3))
img = image.img_to_array(img)
img = img/255.0
img_vectors.append(img)
img_vectors = np.array(img_vectors)
错误信息:
MemoryError Traceback (most recent call last)
<ipython-input-13-dd2302ae54e1> in <module>
----> 1 img_vectors = np.array(img_vectors)
MemoryError: Unable to allocate array with shape (7344, 400, 400, 3) and data type float32
我想我需要一批较小的数组来处理所有图像的内存问题,以避免一个数组同时包含所有图像数据。
在早期的项目中,我使用大约 225k 图像进行了没有多标签的图像分类。无论如何,这段代码不会将所有图像数据转换为一个巨大的数组。而是将图像数据分成更小的批次:
#image preparation
if K.image_data_format() is "channels_first":
input_shape = (3, img_width, img_height)
else:
input_shape = (img_width, img_height, 3)
train_datagen = ImageDataGenerator(rescale=1./255, horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(train_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical')
validation_generator = test_datagen.flow_from_directory(validation_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical')
model = Sequential()
model.add(Conv2D(32, (3,3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
...
model.add(Dense(17))
model.add(BatchNormalization(axis=1, momentum=0.6))
model.add(Activation('softmax'))
model.summary()
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
model.fit_generator(
train_generator,
steps_per_epoch=nb_train_samples // batch_size,
epochs=epochs,
validation_data=validation_generator,
validation_steps=nb_validation_samples // batch_size,
class_weight = class_weight
)
所以我真正需要的是一种方法来处理大型图像数据集以进行多标签图像分类,而不会遇到内存问题。 理想的做法是使用包含图像文件名和 one-hot-encoded 标签的 csv 文件以及用于学习的数组批次。
我们将不胜感激任何帮助或猜测。
【问题讨论】:
-
我不太明白你的问题。您在第二部分中自己提供了解决方案:您需要使用图像生成器
-
下面的代码是在没有多标签的情况下进行图像分类。我也不提供带有一个热编码标签的 csv 数据。我不知道如何在第一个代码中实现图像生成器,如果那是解决方案。
-
多标签还是多类?
-
我需要多标签
标签: machine-learning keras deep-learning image-recognition multilabel-classification