Keras Val_acc很好,但对相同数据的预测很差

时间:2018-01-05 11:00:33

标签: python tensorflow keras predict

我使用Keras进行CNN两级分类。训练我的val_acc超过95%。但是,当我预测相同验证数据的结果时,acc小于60%,那是否可能?这是我的代码:

from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
from keras.callbacks import TensorBoard
from keras.preprocessing import image
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(1337) # for reproducibility
%matplotlib inline

img_width, img_height = 230,170

train_data_dir = 'data/Train'
validation_data_dir = 'data/Validation'
nb_train_samples =  13044
nb_validation_samples = 200
epochs =14
batch_size = 32

if K.image_data_format() == 'channels_first':
    input_shape = (1, img_width, img_height)
else:
    input_shape = (img_width, img_height, 1)

model = Sequential()

model.add(Convolution2D(32, (3, 3),data_format='channels_first' , input_shape=(1,230,170))) 
convout1 = Activation('relu')
model.add(convout1)
convout2 = MaxPooling2D(pool_size=(2,2 ), strides= None , padding='valid', data_format='channels_first')
model.add(convout2)

model.add(Convolution2D(32, (3, 3),data_format='channels_first'))
convout3 = Activation('relu')
model.add(convout3)
model.add(MaxPooling2D(pool_size=(2, 2), data_format='channels_first'))

model.add(Convolution2D(64, (3, 3),data_format='channels_first'))
convout4 = Activation('relu')
model.add(convout4)
convout5 = MaxPooling2D(pool_size=(2, 2), data_format='channels_first')
model.add(convout5)

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

train_datagen = ImageDataGenerator(rescale=1. / 255, 
                                   shear_range=0, 
                                   zoom_range=0.2, 
                                   horizontal_flip=False, 
                                   data_format='channels_first')

test_datagen = ImageDataGenerator(rescale=1. / 255, 
                                  data_format='channels_first')
train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary',
    color_mode= "grayscale",
    shuffle=True
)
validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary',
    color_mode= "grayscale",
    shuffle=True
)
model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=nb_validation_samples // batch_size,
    shuffle=True
    )

大纪元37/37

407/407 [==============] - 1775s 4s /步 - 损失:0.12 - acc:0.96 - val_loss:0.02 - val_acc:0.99

#Prediction:
test_data_dir='data/test'
validgen = ImageDataGenerator(horizontal_flip=False, data_format='channels_first')
test_gen = validgen.flow_from_directory(
         test_data_dir,
         target_size=(img_width, img_height),
         batch_size=1,
         class_mode='binary',
         shuffle=False,
         color_mode= "grayscale")

preds = model.predict_generator(test_gen)

在下面的输出中,大约有7个图像属于0级。我对0级验证数据的所有100张图像尝试了同样的情况,只有15张图像被预测为0级,剩余部分被预测为1级

Found 10 images belonging to 1 classes.
[[ 1.]
 [ 1.]
 [ 1.]
 [ 1.]
 [ 1.]
 [ 1.]
 [ 1.]
 [ 0.]
 [ 0.]
 [ 1.]]

2 个答案:

答案 0 :(得分:3)

您没有按照训练和验证图像中的1./255缩放测试图像。理想情况下,测试数据的统计数据应与训练数据类似。

答案 1 :(得分:0)

因此,我决定发布我在Quora中发布的答案,但要注意的是必不可少的部分。我也有与此类似的问题,希望我的回答也能对其他人有所帮助。我决定在Internet上进行研究,并遇到了这个answer by cjbayron

帮助我解决类似问题的是,我在代码中训练了以下内容:

import keras
import os
from keras import backend as K
import tensorflow as tf
import random as rn
import numpy as np

os.environ['PYTHONHASHSEED'] = '0'
np.random.seed(70)
rn.seed(70)
tf.set_random_seed(70)

/******* code for my model ******/

#very important here to save session after completing model.fit 

model.fit_generator(train_batches, steps_per_epoch=4900, validation_data=valid_batches,validation_steps=1225, epochs=40, verbose=2, callbacks=callbacks_list)

saver = tf.train.Saver()
sess = keras.backend.get_session()
saver.save(sess, 'gdrive/My Drive/KerasCNN/model/keras_session/session.ckpt')

保存的会话也会生成以下文件:

  1. / keras_session / checkpoint
  2. /keras_session/session.ckpt.data-00000-of-00001
  3. /keras_session/session.ckpt.index
  4. /keras_session/session.ckpt.meta

我也从Google云端硬盘下载了所有这些文件,并将它们放在本地目录中。您可能会注意到,似乎没有名为 session.ckpt 的文件,而是在saver.restore()中使用了该文件。没关系Tensorflow还可以解决这个问题。它不会带来错误。

在model.load_model()期间

因此在我的Pycharm中,我按如下方式加载了模型:

model=load_model('C:\\Users\\Username\\PycharmProjects\\MyProject\\mymodel\\mymodel.h5')

saver = tf.train.Saver()
sess = keras.backend.get_session()
saver.restore(sess,'C:\\Users\\Username\\PycharmProjects\\MyProject\\mymodel\\keras_session\\session.ckpt')

/***** then predict the images as you wish ******/
pred = model.predict_classes(load_image(os.path.join(test_path, file)))

重要的是要放置恢复代码,如图所示,即在加载模型之后。 完成此操作后,我尝试预测用于训练和验证的相同图像,而这次,该模型错误地预测了每班2张图像。现在我确定我的模型还可以,并且我继续用我的测试图像进​​行预测,即以前从未见过的图像,并且表现很好。