计算测试集precision、recall、f1-score

问题描述

模型训练完成后,调用已保存的模型,读取训练数据集数据进行预测,并计算训练集的precision、recall、f1-score

实现代码

from keras.utils import image_utils
import numpy as np
import os
import cv2
import tensorflow as tf
from keras.utils.image_utils import img_to_array
from sklearn.metrics import recall_score, f1_score, precision_score, accuracy_score
from sklearn.metrics import classification_report
import tensorflow._api.v2.compat.v1 as tf
tf.disable_v2_behavior()
tf.compat.v1.enable_eager_execution()
model = tf.keras.models.load_model('model.h5')
path="D:/test/Data/test"
Image_width=150
Image_height=150
Image_channels=3
Image_size=(Image_width,Image_height)
Image_shape=(Image_width,Image_height,Image_channels)

#读取真实标签(此处标签有两类,用labels1、labels2表示)
def prepare(path):
    fileList = os.listdir(path)
    data=[]
    labels1=[]
    labels2=[]
    for fileName in fileList:
        image=cv2.imread(os.path.join(path,fileName))
        if image is not None:
            std_image=tf.image.per_image_standardization(image)
            image2=cv2.resize(std_image.numpy(),Image_size)
            image2=img_to_array(image2)
            data.append(image2)
            label1=str(fileName).split("_")[0:1]
            label2=str(fileName).split("_")[1:2]
            labels1.extend(label1)
            labels2.extend(label2)
    data=np.array(data,dtype="float32")
    return data,labels1,labels2

data,labels1,labels2=prepare(path)
labels1=list(map(int, labels1)) #真实类别10123)
labels2=list(map(int, labels2)) #真实类别2  
# print(labels1)
# print(labels2)


#预测
fileList = os.listdir(path)
pre_labels1=[]
pre_labels2=[]
for fileName in fileList:
    image = cv2.imread(os.path.join(path, fileName))
    if image is not None:
        img = image_utils.load_img(os.path.join(path, fileName), target_size=(150, 150))
        img_tensor = image_utils.img_to_array(img)
        img_tensor=np.expand_dims(img_tensor,axis=0)
        img_tensor/=255.
        #模型预测
        prediction=model.predict(img_tensor)
        # print('每一类别的概率值:',prediction)
        pre_y1 = np.argmax(prediction[0])
        pre_y2 = np.argmax(prediction[1])
        # print("预测类别是:",pre_y1,pre_y2)
        pre_labels1.extend([pre_y1])
        pre_labels2.extend([pre_y2])

pre_labels1=list(map(int, pre_labels1)) #预测类别1
pre_labels2=list(map(int, pre_labels2)) #预测类别2
# print(pre_labels1)
# print(pre_labels2)


#计算accurary,recall,f1score
y_true1 = labels1
y_pred1 = pre_labels1
measure_result1 = classification_report(y_true1, y_pred1)
print('measure_result1 = \n', measure_result1)

print("class1_accuracy:%.2f" % accuracy_score(y_true1, y_pred1))
print("class1_precision:%.2f" % precision_score(y_true1, y_pred1, labels=[0, 1, 2, 3], average='macro'))
print("class1_recall:%.2f" % recall_score(y_true1, y_pred1, labels=[0, 1, 2, 3], average='macro'))
print("class1_f1-score:%.2f" % f1_score(y_true1, y_pred1, labels=[0, 1, 2, 3], average='macro'))

你可能感兴趣的:(python,tensorflow)