python - Keras 函数模型提供高验证准确性但不正确的预测

标签 python tensorflow keras deep-learning conv-neural-network

我正尝试在 PASCAL VOC 2012 数据集上使用“ImageNet”预训练权重对 VGG16 架构进行迁移学习。 PASCAL VOC 是一个包含 20 个类别的多标签图像数据集,因此我修改了内置的 VGG16 模型,如下所示:

def VGG16_modified():
    base_model = vgg16.VGG16(include_top=True,weights='imagenet',input_shape=(224,224,3))
    print(base_model.summary())
    x = base_model.get_layer('block5_pool').output
    x = (GlobalAveragePooling2D())(x)
    predictions = Dense(20,activation='sigmoid')(x)

    final_model = Model(input = base_model.input, output = predictions)
    print(final_model.summary())
    return final_model

我的输入图像预处理是这样的:

img_val = []
for i in tqdm(range(dfval.shape[0])):
        img = image.load_img(train_images+y_val[0][i],target_size=(224,224))
        img = image.img_to_array(img)
        img_val.append(img)
x_val = np.array(img_val

我已经使用 pd.get_dummies 为 20 个类转换了这样的分类标签 [[0 0 0 0 1 0 0 0 0 1 0 .... ]] 并且相应的标签是形状 (图像样本数,20)。输入图像的形状是(number of image samples, 224,224, 3)

当我对模型进行几个时期的训练时,我发现验证准确率非常高(大约 90%),但是当我使用相同的验证数据集来预测图像时,它会为每张图像提供相同的类别输出。

我这样训练模型:

model = VGG16_modified()
model.summary()
model.compile(optimizer=Adam(),loss='binary_crossentropy',metrics = ['accuracy'])
model.fit(x_train, y_train, epochs=100, validation_data=(x_val, yval), batch_size=4)
model.save('CAMVGG16trainall.h5')
model.save_weights('CAMVGG16weightstrainall.h5')

后来我加载了模型并尝试预测同一验证数据集的标签。

model = load_model(model)
preds = model.predict(image)

但我对每张图片都得到了相同的输出。输出的形状为 [[0 0 0 ......1 0 0 0...]] 我尝试了更多的时期,更少的时期,通过设置一些不可训练的层,通过设置所有层可训练,改变学习率,使用不同的优化器(SGD),不使用 Imagenet 权重和从头开始训练但没有他们给了我正确的结果。谁能告诉我哪里出错了。

最佳答案

为了社区的利益在此提及解决方案,因为有很多评论可以了解解决方案。

这里的问题是模型被卡住,即 Layers 在 PASCAL VOC 数据集上 not Trained

预训练模型的权重应该被卡住,而在我们的数据集上训练的模型层的权重不应该被卡住。

问题通过设置 layer.trainable = True 得到解决。通过下面的屏幕截图可以更好地理解这一点。

enter image description here

注:图片取自 Aurelien Geron 的机器学习和深度学习一书。

关于python - Keras 函数模型提供高验证准确性但不正确的预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58228998/

相关文章:

python-3.x - sklearn 管道 + keras 顺序模型 - 如何获取历史记录?

python - 在 Amazon SageMaker 中进行预测之前预处理输入数据

python - unittest blacklist namespace 并且任何引用它的尝试都失败

python - 尝试通过 Youtube 数据 API V3 检索 YouTube 评论时出现 AttributeError

TensorFlow、TensorBoard : No scalar data was found

python - 卷积神经网络中的 Keras 形状误差

python - 如何在 weasyprint 中使用自定义字体

python - 在 Django/python 中忽略 user_abort php simil?

python - 优化tensorflow数据集api中的洗牌缓冲区大小

tensorflow - 多任务网络中ValueError : Shape must be rank 0 but is rank 1