【发布时间】:2018-09-17 22:01:34
【问题描述】:
更新:请参阅下面的新部分。
当我运行 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
编辑:
在 cmets 中 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 来匹配训练和验证图像。
【问题讨论】:
-
看来你有一个多标签模型,在这种情况下你不应该使用 predict_classes 因为每个预测中可能有多个正确的类。
-
我应该使用什么来代替 predict_classes?另外 - 我有 6 种类型 - 我不认为单个图像可以有多个类别。
-
那你用错了模型,因为你有一个多标签模型(sigmoid输出+二元交叉熵损失)。
-
Softmax 输出和分类交叉熵损失。
-
是的,没错。不,课堂模式应该是分类的。
标签: python deep-learning keras