首页 > 解决方案 > 在 Keras 中微调 InceptionV3 时出错

问题描述

我将使用我的自定义数据集微调 InceptionV3 模型。不幸的是,在使用 model.fit 进行训练时,出现以下错误:

ValueError: Error when checking target: expected dense_6 to have shape (4,) but got array with shape (1,)

首先,我将自己的数据集加载为 training_data,其中包含一对图像和相应的标签。然后,我使用下面的代码将它们转换为特定的数组类型(img_new 和 label_new),以便它与 Keras 的数据和标签输入兼容。

for img, label in training_data:    

    img_new[i,:,:,:] = img
    label_new[i,:] = label
    i=i+1

其次,我微调了下面的初始模型。

InceptionV3_model=keras.applications.inception_v3.InceptionV3(include_top=False, 
                                                              weights='imagenet', 
                                                              input_tensor=None, 
                                                              input_shape=None, 
                                                              pooling=None, 
                                                              classes=1000)

#InceptionV3_model.summary()

    # add a global spatial average pooling layer
x = InceptionV3_model.output
x = GlobalAveragePooling2D()(x)

# let's add a fully-connected layer
x = Dense(1024, activation='relu')(x)

# and a logistic layer -- let's say we have 4 classes
predictions = Dense(4, activation='softmax')(x)

# this is the model we will train
model = Model(inputs=InceptionV3_model.input, outputs=predictions)

    # Transfer Learning
for layer in model.layers[:311]:
    layer.trainable = False
for layer in model.layers[311:]:
    layer.trainable = True

    from keras.optimizers import SGD
model.compile(optimizer=SGD(lr=0.001, momentum=0.9), loss='categorical_crossentropy')

    model.fit(x=X_train, y=y_train, batch_size=3, epochs=3, validation_split=0.2)
model.save_weights('first_try.h5')

有没有人知道使用 model.fit 训练时出了什么问题?

衷心感谢您的帮助。

标签: keras

解决方案


该错误是由于我的标签 r 整数引起的,我必须通过为整数标签设置的 sparse_categorical_crossentropy 编译它,而不是用于单热编码的 categorical_crossentropy。

非常感谢@Amir 的帮助。:-)


推荐阅读