首页 > 解决方案 > 神经网络 + VGG 在测试图像和谷歌图像上非常准确,但在“真实”图像上非常差

问题描述

我做了一个模型来分类狗和猫的图片。模型先在 VGG 上进行迁移学习,然后在来自 kaggle https://www.kaggle.com/c/dogs-vs-cats/data的狗和猫数据集上进行训练。

我在 20,000 张图像上对其进行了训练,然后在剩余的 5000 张图像上对其进行了测试。它非常准确,>95%。当我从谷歌手动抓取一些大约 20-200kb 的图像时,据我所知,它的效果非常好

但是当图像更大(高度/宽度为数千像素)时,就像我的手机一样,它确实很可怕。

为什么会这样?有没有我缺少的图像处理东西?还是学习问题?无论哪种方式,我该如何解决这个问题并使模型可扩展到大图像?

模型:

def get_transfer_model(self):
        model = VGG16(include_top=False, input_shape=(224, 224, 3))  # Use VGG transfer model
        for layer in model.layers:
            layer.trainable = False    # already trained
        
        added_layers = [ 
            Flatten(),
            Dense(512, activation='relu'),
            BatchNormalization(),
            Dropout(0.5),
            Dense(1, activation='sigmoid'))
        ]
        
        result = model.layers[-1].output # init result
        for layer in added_layers:
            result = layer(result)        # apply to result
            
        model = Model(inputs=model.inputs, outputs=result)
        opt = SGD(lr=0.001, momentum=0.9)
        model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])
        return model

结果计算:

from keras.preprocessing.image import load_img, img_to_array
from keras.models import load_model

def result(img_path, weights_path='dogs_cats.h5'):
    img = load_img(img_path, target_size=(224, 224))
    img = img_to_array(img)
    img = img.reshape(1, 224, 244, 3) # reshape to tensor with 3 color channels
    img = img.astype('float32')
    img = img - [123.68, 116.779, 103.939] # center image to trained mean

    model = load_model(weights_path)
    dog = int(model.predict(img)[0][0])
    if dog:
        return 'DOG'
    return 'CAT'

标签: pythonmachine-learningkerasneural-networkimage-recognition

解决方案


推荐阅读