Keras model.evaluate_generator结果几乎是真实准确度的两倍?

时间:2018-04-08 10:55:06

标签: python deep-learning keras

更新:请参阅下面的新章节。

当我运行model.evaluate_generator时,它给出了92%的结果。但是如果我在每个测试图像上运行model.predict_classes并计算正确的分类与不正确的分类,我得到49%......

显然有些事情是错的。我是否误解了evaluate_generator的结果,或者我没有正确地执行predict_classes?

这是model.evaluate_generator调用(它获得92%):

print("test_generator from Directory");
test_generator = test_datagen.flow_from_directory( 
test_dir, 
target_size=(200, 200), 
batch_size=20, 
class_mode='categorical') 

# finally evaluate this model on the test data 
results = model.evaluate_generator( 
test_generator, 
steps=1) 

print('Final test accuracy:', (results[1]*100.0))

为了进行比较,我测试每个文件并与正确的分类进行比较(得到49%):

  img_path = os.path.join(bol, file)
  print(img_path)
  image = load_img(img_path, target_size=(200, 200)) 
  image = img_to_array(image) 
  image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
  image = preprocess_input(image)
  # classify the image 
  print("classifying image...") 
  y_hat = model.predict_classes(image) 
  print(y_hat[0])
  idtype = newdict[y_hat[0]]  #this part is to match predicted class with true class
  destpath = os.path.join(bol, idtype, file)      
  print(idtype)
  if idtype == cat[1]:
    correct = correct + 1
  count = count + 1
  factor = correct / count
  print(str(count) + " - " + str(correct) + " = " + str(factor))

完整代码在此处:https://s3.eu-west-2.amazonaws.com/klondon/food_6_VGG_aug_plus_id.py.txt

编辑:

在评论中,在Matias Valdenegro的帮助下,我修复了我的代码中的一些错误。它现在使用' Softmax'输出和分类交叉熵损失。完整代码:https://s3.eu-west-2.amazonaws.com/klondon/food_6_VGG_aug_plus_id_cat.py.txt

然而 - 核心问题仍然存在。 evaluate_generator(现为71%)的结果与使用predict_classes(53%)的相同图像的手动测试之间存在巨大差异。

我的代码还有其他问题吗?

编辑2:

我尝试过设置shuffle = False和batch_size = 1进行测试,但问题仍然存在。 evaluate_generator仍然返回~70%而predict_classes是~50%

编辑3:

此处修复了代码:https://s3.eu-west-2.amazonaws.com/klondon/food_6_VGG_aug_plus_id_fix.py.txt

问题是:我不应该在predict_classes中使用preprocess_input,除非在训练和验证中也使用它。另外,我应该使用image / = 255来匹配训练&验证图像。

1 个答案:

答案 0 :(得分:1)

修正所有内容后,您仍然没有preprocess_input中的ImageDataGenerator

因此,您手动加载的图像与生成的图像不同。

使用预处理功能创建ImageDataGenerator

test_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)

或者从手动加载中删除预处理功能(如果您的模型已经使用此类生成器进行过培训)。