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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Keras model.evaluate_generator结果几乎是真实准确度的两倍?相关的知识,希望对你有一定的参考价值。

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

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

显然有些事情是错的。我误解了evaluate_generator结果,还是我没有做forecast_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来匹配训练和验证图像。

答案

修好一切之后,你仍然没有preprocess_input中的ImageDataGenerator

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

使用预处理功能创建ImageDataGenerator

test_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)

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

以上是关于Keras model.evaluate_generator结果几乎是真实准确度的两倍?的主要内容,如果未能解决你的问题,请参考以下文章

keras如何快速入门

keras与tensorflow.python.keras - 使用哪一个?

keras 与 tensorflow.python.keras - 使用哪一个?

keras是啥

Tensorflow+Keras用Tensorflow.keras的方法替代keras.layers.merge

Tensorflow+Keras用Tensorflow.keras的方法替代keras.layers.merge