我试图在40x40灰度图像的数据集上训练模型,但出现此错误:
ValueError:传递形状为(32,5)的目标数组以输出形状为(None,4),同时用作损失categorical_crossentropy
。这种损失会导致目标与输出的形状相同。
我不知道(32,5)的数组应该从哪里来(32,4),所以我不知道要更改什么。有什么建议吗?
image_generator = ImageDataGenerator(#rescale = 1/255,
shear_range = 0.3,
zoom_range = 0.1,
rotation_range = 30,
width_shift_range = 0.08,
height_shift_range = 0.08,
horizontal_flip = True,
fill_mode = 'nearest',
)
train_image_generator = image_generator.flow_from_directory('/data1/mypath/generated-images/train',
target_size = (40,40),
color_mode = 'grayscale',
batch_size = 32,
class_mode = 'categorical')
test_image_generator = image_generator.flow_from_directory('/data1/mypath/generated-images/test',
target_size = (40,40),
color_mode = 'grayscale',
batch_size = 32,
class_mode = 'categorical',
shuffle = False)
model = Sequential()
model.add(Conv2D(32, kernel_size=(3,3),input_shape=(40,40, 1), activation='relu', padding='same'))
model.add(BatchNormalization(axis=-1))
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Conv2D(32, kernel_size=(3,3),activation='relu', padding='same'))
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Conv2D(64, kernel_size=(3,3), activation='relu', padding='same'))
model.add(BatchNormalization())
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(4))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
early_stopping = EarlyStopping(monitor='val_loss',patience=5)
model.fit_generator(train_image_generator, epochs=150,
validation_data = test_image_generator,
callbacks=[early_stopping]) ```
答案 0 :(得分:0)
检查数据集中的类数。
数组(32,5)
来自数据集的形状。
Y(label)的形状显示为5个类,并且在最后一个输出层中将其声明为(None, 4)
为4。这意味着代码正在从提供的图像路径读取4类。