我正在尝试使用Keras编写一个卷积神经网络(CNN)。我的数据集包含20,000张图片,分为250个类别,目录结构如下:
dataset/ class1/ 1.png 2.png ... class2/ ... ...
据我所知,加载图片和标签最简单的方法是结合使用ImageDataGenerator和flow_from_directory()
。以下是一个最简工作示例:
from keras.layers import Activation, Convolution2D, MaxPooling2Dfrom keras.models import Sequentialfrom keras.preprocessing.image import ImageDataGeneratorif __name__ == '__main__': # 输入图像尺寸 img_rows, img_cols = 225, 225 input_shape = (img_rows, img_cols, 1) model = Sequential() model.add(Convolution2D(64, 15, 15, input_shape=input_shape, subsample=(3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2))) model.compile(loss='hinge', optimizer='adadelta', metrics=['accuracy']) data = ImageDataGenerator() train_data = data.flow_from_directory(directory='dataset', color_mode='grayscale', target_size=(img_rows, img_cols)) model.fit_generator(train_data, 100, 12)
然而,这会导致以下错误:
Exception: Error when checking model target: expected maxpooling2d_1 to have 4 dimensions, but got array with shape (32, 250)
其中32是batch_size
,250是类别数量。
这是我获取图片/标签的方式有问题吗?
回答:
我的问题并不是标签是字符串,而是CNN架构错误。在MaxPooling2D
之后添加一个Flatten()
层后,我现在能够将网络的输出映射到我的标签上。