【问题标题】:Model gives great training and testing accuracy but not working well when doing prediction模型提供了很好的训练和测试准确性,但在进行预测时效果不佳
【发布时间】:2020-05-29 06:17:09
【问题描述】:

您好,我正在使用 VGG16 预训练模型进行深度学习的迁移学习。我想从 VGG16 中提取特征来构建我自己的模型,因为我只能访问 CPU。这是我的构建和训练设置。

import os
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from sklearn.metrics import confusion_matrix

from keras.applications import Xception, VGG16, ResNet50
conv_base = VGG16(weights='imagenet',include_top=False,input_shape=(224, 224, 3))

conv_base.summary()
base_dir = 'NewDCDatatset'

train_dir = os.path.join(base_dir, 'Train')
validation_dir = os.path.join(base_dir, 'Validation')
test_dir = os.path.join(base_dir, 'Test')

datagen = ImageDataGenerator(rescale=1./255)
batch_size = 5

def extract_features(directory, sample_count):
    features = np.zeros(shape=(sample_count, 7 , 7 , 512))
    labels = np.zeros(shape=(sample_count,2))
    generator = datagen.flow_from_directory(directory,target_size=(224, 224),batch_size=batch_size,class_mode='categorical')
    i = 0
    for inputs_batch, labels_batch in generator:
        features_batch = conv_base.predict(inputs_batch)
        features[i * batch_size : (i + 1) * batch_size] = features_batch
        labels[i * batch_size : (i + 1) * batch_size] = labels_batch
        i += 1
        if i * batch_size >= sample_count:
            break
    return features, labels

train_features, train_labels = extract_features(train_dir, 2000)
validation_features, validation_labels = extract_features(validation_dir,420 )
test_features, test_labels = extract_features(test_dir, 420)

train_features = np.reshape(train_features, (2000, 7 * 7 * 512))
validation_features = np.reshape(validation_features, (420, 7 * 7 * 512))
test_features = np.reshape(test_features, (420, 7 * 7 * 512))

from keras import models
from keras import layers
from keras import optimizers
model = models.Sequential()
model.add(layers.Dense(64, activation='relu', input_dim=7 * 7 * 512))
model.add(layers.Dense(2, activation='softmax'))
model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['acc'])
history = model.fit(train_features, train_labels,epochs=2,batch_size=5,shuffle=True)
print(model.evaluate(test_features,test_labels))

model.save('TLFACE.h5')

#predictions = model.predict_generator(test_features,steps = 5)

#print(predictions)

这是我通过模型预测新图像以对猫和狗进行分类的方式的设置,但我没有得到那么准确的结果,我很少能够正确分类任何图像。我不知道我在做什么错误,是调整图像大小还是预测时发生了什么。

from keras.models import load_model
deep = load_model('TLFACE.h5')

from PIL import Image
import numpy as np
import cv2

file_nam = '4705.jpg'
img = cv2.imread(file_nam)
img = cv2.imshow('frame',img)
cv2.waitKey(1000)

img = Image.open(file_nam).convert("L")

img = img.resize((256,98))
im2arr = np.array(img)
im2arr = im2arr.reshape(1,25088)
# Predicting the Test set r1esults
y_pred = deep.predict(im2arr)
print(y_pred)
print(y_pred[0][0])

【问题讨论】:

  • 好吧,不用看你的代码,你解释的问题有时可以通过限制网络大小来解决,迫使它泛化。您使用了多少百分比的数据进行训练以及测试了多少?
  • 我有 4000 张训练图像(每班 2000 张图像)和 420 张测试图像(每班 210 张)。
  • 那么它在那些 4000 和 420 图像上表现良好呢?测试图像和“新图像”有什么区别?
  • 是的,在测试数据集上评估模型时,Em 获得 92% 的训练准确率和 90% 的测试准确率。但是当我在新图像(与测试图像文件夹不同甚至不同)上预测它时,它并没有给出好的结果。
  • 好的,看来您的测试数据实际上不是测试数据,而是某种训练数据。测试数据的想法是它们不应该以任何方式影响网络,即应该隔离测试数据。测试数据和您所说的“新图像”应该没有区别。请参阅这篇关于交叉验证的文章:machinelearningmastery.com/k-fold-cross-validation

标签: python numpy tensorflow machine-learning keras


【解决方案1】:

根据您的代码,您的模型会收到大小为1 x 7*7*512 = 1 x 25088 的特征向量。此功能是conv_base 模型中的图像编码(在您的extract_features 方法中实现)。

但是,在您的示例中,在预测时您只需拍摄一张图像,将其重塑为(256,98),然后展平为(1,25088)。你完全跳过了extract_features 阶段。换句话说,您尝试使用与训练期间使用的完全不同的数据进行预测(以及fit 方法下的自动化测试)。您需要使用完全相同的预处理方法进行测试,这意味着首先将图像重新缩放为224x224x3 的大小,然后使用conv_base 模型提取特征,最后使用您的新模型对提取的特征进行预测。

话虽如此,我还是建议您使用非常“肮脏”的实现,这种方式组织不当,很容易混淆。您实际上想要构建一个对图像执行分类的单一模型,而不是执行提取特征等所有繁重的编码,因此您可以使用类似的东西:

pretrained_vgg16 = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
pretrained_vgg16.trainable = False  # This is important if you don't want to modify your base model weights during training.
new_model = models.Sequential([pretrained_vgg16, 
                               layers.Flatten(),
                               layers.Dense(64, activation='relu'),
                               layers.Dense(2,activation='softmax')])

另外,请注意,在训练期间决定是否要修改预训练模型的权重非常重要。如果没有,则需要调用pretrained_vgg16.trainable = False 行。

现在您可以将new_model.fit 与生成器一起使用,该生成器会加载图像并将它们重新缩放为224x224x3,而无需显式提取特征。另一个重要的评论是原始 VGG16 模型可能是在标准化数据上训练的(这意味着像素值被标准化为在[0,1] 范围内),您还需要对图像执行相同的预处理以获得理想结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 2019-07-09
    • 2020-01-02
    • 2021-11-12
    • 2021-04-03
    • 2020-11-06
    • 1970-01-01
    相关资源
    最近更新 更多