如何测试多类别/标签图像分类器?

时间:2020-10-24 09:30:08

标签: python tensorflow keras deep-learning multilabel-classification

我正在尝试测试图像分类器的准确性。 我只做过二进制分类,对于深度学习来说还很陌生。

我真的不想做混淆矩阵。 我想对图像进行逐一分类。

有人知道如何用图像一一测试分类器的准确性吗? 带有代码片段将非常有帮助

这是我的代码

我只是做了平时在二进制分类中所做的事情。 但是我现在被困在如何上课

model = load_model('./model.h5')

test_image = ImageDataGenerator(
    rescale=1. / 255
)

test_generator = test_image.flow_from_directory(
    './test',
    (32, 32),
    batch_size=20,
    class_mode='categorical',
    shuffle=False
)

loss, accuracy = model.evaluate_generator(
    generator=test_generator,
    steps=1
)

labels = test_generator.class_indices

2 个答案:

答案 0 :(得分:0)

我假设您使用的是TF> = 2.0

您可以尝试以下方法:

import numpy as np
from keras.preprocessing import image

path = 'path-to-file'
img = image.load_img(path, target_size=(32, 32))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)

images = np.vstack([x])
classes = model.predict(images, batch_size=10)

答案 1 :(得分:0)

在“ ./test”目录中,放置要分类的图像。然后,使用下面的代码为每个图像打印出预测的类,为每个图像输出的真实类以及图像的文件名。

file_names=test_generator.filenames  # save list of test files names to be used later
tlabels=test_generator.labels # save test labels to be used later
class_dict=test_generator.class_indices
# code below determines test batch size and test steps
# so you go through the test images exactly once
length=len(file_names) # determine number of images
b_max=80 # set maximum batch size you will allow
test_batch_size=sorted([int(length/n) for n in range(1,length+1) if length % n ==0 and length/n<=b_max],reverse=True)[0]
test_steps=int(length/batch_size)
# make predictions
preds=model.predict(test_gen, batch_size=test_batch_size, verbose=0, steps=test_steps)
new_dict={} 
for key in class_dict: # set key in new_dict to value in class_dict and value in new_dict to key in class_dict
    value=class_dict[key]
    new_dict[value]=key
print('PREDICTED CLASS     TRUE CLASS       FILENAME            ERROR  STATUS' ) # adjust spacing based on your class names
error_list=[] # empty list to store if the prediction was correct or not
error_file_list=[]
for i, p in enumerate(preds):
    pred_index=np.argmax(p) # get the index that has the highest probability
    if pred_index == tlabels[i]:
        error_list.append ('No') # correct classification
    else:
        error_list.append('Yes')
        error_file_list.append(file_names[i])
    pred_class=new_dict[pred_index]  # find the predicted class based on the index
    true_class=new_dict[tlabels[i]] # use the test label to get the true class of the test file
    file=file_names[i]
    print(f'    {pred_class:10s}       {true_class:10s}    {file:25s}   {error_list[i]}')