在pytorch中计算准确率,召回率和F1值的操作

 更新时间:2021年05月13日 09:44:37   作者:coding_zhang  
这篇文章主要介绍了在pytorch中计算准确率,召回率和F1值的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

看代码吧~

predict = output.argmax(dim = 1)
confusion_matrix =torch.zeros(2,2)
for t, p in zip(predict.view(-1), target.view(-1)):
    confusion_matrix[t.long(), p.long()] += 1
a_p =(confusion_matrix.diag() / confusion_matrix.sum(1))[0]
b_p = (confusion_matrix.diag() / confusion_matrix.sum(1))[1]
a_r =(confusion_matrix.diag() / confusion_matrix.sum(0))[0]
b_r = (confusion_matrix.diag() / confusion_matrix.sum(0))[1]

补充:pytorch 查全率 recall 查准率 precision F1调和平均 准确率 accuracy

看代码吧~

def eval():
    net.eval()
    test_loss = 0
    correct = 0
    total = 0
    classnum = 9
    target_num = torch.zeros((1,classnum))
    predict_num = torch.zeros((1,classnum))
    acc_num = torch.zeros((1,classnum))
    for batch_idx, (inputs, targets) in enumerate(testloader):
        if use_cuda:
            inputs, targets = inputs.cuda(), targets.cuda()
        inputs, targets = Variable(inputs, volatile=True), Variable(targets)
        outputs = net(inputs)
        loss = criterion(outputs, targets)
        # loss is variable , if add it(+=loss) directly, there will be a bigger ang bigger graph.
        test_loss += loss.data[0]
        _, predicted = torch.max(outputs.data, 1)
        total += targets.size(0)
        correct += predicted.eq(targets.data).cpu().sum()
        pre_mask = torch.zeros(outputs.size()).scatter_(1, predicted.cpu().view(-1, 1), 1.)
        predict_num += pre_mask.sum(0)
        tar_mask = torch.zeros(outputs.size()).scatter_(1, targets.data.cpu().view(-1, 1), 1.)
        target_num += tar_mask.sum(0)
        acc_mask = pre_mask*tar_mask
        acc_num += acc_mask.sum(0)
    recall = acc_num/target_num
    precision = acc_num/predict_num
    F1 = 2*recall*precision/(recall+precision)
    accuracy = acc_num.sum(1)/target_num.sum(1)
#精度调整
    recall = (recall.numpy()[0]*100).round(3)
    precision = (precision.numpy()[0]*100).round(3)
    F1 = (F1.numpy()[0]*100).round(3)
    accuracy = (accuracy.numpy()[0]*100).round(3)
# 打印格式方便复制
    print('recall'," ".join('%s' % id for id in recall))
    print('precision'," ".join('%s' % id for id in precision))
    print('F1'," ".join('%s' % id for id in F1))
    print('accuracy',accuracy)

补充:Python scikit-learn,分类模型的评估,精确率和召回率,classification_report

分类模型的评估标准一般最常见使用的是准确率(estimator.score()),即预测结果正确的百分比。

混淆矩阵:

准确率是相对所有分类结果;精确率、召回率、F1-score是相对于某一个分类的预测评估标准。

精确率(Precision):预测结果为正例样本中真实为正例的比例(查的准)(\tfrac{TP}{TP+FP}

召回率(Recall):真实为正例的样本中预测结果为正例的比例(查的全)(\frac{TP}{TP+FN}

分类的其他评估标准:F1-score,反映了模型的稳健型


demo.py(分类评估,精确率、召回率、F1-score,classification_report):

from sklearn.datasets import fetch_20newsgroups
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import classification_report
 
# 加载数据集 从scikit-learn官网下载新闻数据集(共20个类别)
news = fetch_20newsgroups(subset='all')  # all表示下载训练集和测试集
 
# 进行数据分割 (划分训练集和测试集)
x_train, x_test, y_train, y_test = train_test_split(news.data, news.target, test_size=0.25)
 
# 对数据集进行特征抽取 (进行特征提取,将新闻文档转化成特征词重要性的数字矩阵)
tf = TfidfVectorizer()  # tf-idf表示特征词的重要性
# 以训练集数据统计特征词的重要性 (从训练集数据中提取特征词)
x_train = tf.fit_transform(x_train)
 
print(tf.get_feature_names())  # ["condensed", "condescend", ...]
 
x_test = tf.transform(x_test)  # 不需要重新fit()数据,直接按照训练集提取的特征词进行重要性统计。
 
# 进行朴素贝叶斯算法的预测
mlt = MultinomialNB(alpha=1.0)  # alpha表示拉普拉斯平滑系数,默认1
print(x_train.toarray())  # toarray() 将稀疏矩阵以稠密矩阵的形式显示。
'''
[[ 0.     0.          0.   ...,  0.04234873  0.   0. ]
 [ 0.     0.          0.   ...,  0.          0.   0. ]
 ...,
 [ 0.     0.03934786  0.   ...,  0.          0.   0. ]
'''
mlt.fit(x_train, y_train)  # 填充训练集数据
 
# 预测类别
y_predict = mlt.predict(x_test)
print("预测的文章类别为:", y_predict)  # [4 18 8 ..., 15 15 4]
 
# 准确率
print("准确率为:", mlt.score(x_test, y_test))  # 0.853565365025
 
print("每个类别的精确率和召回率:", classification_report(y_test, y_predict, target_names=news.target_names))
'''
                precision  recall  f1-score  support
    alt.atheism   0.86      0.66     0.75      207
  comp.graphics   0.85      0.75     0.80      238
 sport.baseball   0.96      0.94     0.95      253
 ...,
'''
 

召回率的意义(应用场景):产品的不合格率(不想漏掉任何一个不合格的产品,查全);癌症预测(不想漏掉任何一个癌症患者)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Python中OpenCV Tutorials 20  高动态范围成像的实现步骤

    Python中OpenCV Tutorials 20  高动态范围成像的实现步骤

    这篇文章主要介绍了OpenCV Tutorials 20 - 高动态范围成像,本文还给大家展示了一种称为曝光融合的替代方法,它可以产生低动态范围的图像,需要的朋友可以参考下
    2022-06-06
  • 使用Pytorch搭建模型的步骤

    使用Pytorch搭建模型的步骤

    这篇文章主要介绍了使用Pytorch搭建模型的步骤,帮助大家更好的理解和使用Pytorch,进行机器学习,感兴趣的朋友可以了解下
    2020-11-11
  • OpenCV-Python实现轮廓拟合

    OpenCV-Python实现轮廓拟合

    本文将结合实例代码,介绍OpenCV-Python实现轮廓拟合,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-06-06
  • 简单介绍Python中的len()函数的使用

    简单介绍Python中的len()函数的使用

    这篇文章主要简单介绍了Python中的len()函数的使用,包括在四种情况下的使用小例子,是Python学习当中的基础知识,需要的朋友可以参考下
    2015-04-04
  • 使用Python的Django框架实现事务交易管理的教程

    使用Python的Django框架实现事务交易管理的教程

    这篇文章主要介绍了使用Python的Django框架实现事务交易管理的教程,针对数据库的事务行为进行一系列操作,要的朋友可以参考下
    2015-04-04
  • DRF之请求与响应的实现

    DRF之请求与响应的实现

    本文主要介绍了DRF请求与响应的实现,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧
    2021-07-07
  • python3+PyQt5图形项的自定义和交互 python3实现page Designer应用程序

    python3+PyQt5图形项的自定义和交互 python3实现page Designer应用程序

    这篇文章主要为大家详细介绍了python3+PyQt5图形项的自定义和交互,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-04-04
  • Python利用py-redis实现分布式锁

    Python利用py-redis实现分布式锁

    随着业务的增长,后端技术架构会慢慢的从单体服务转向多服务或者微服务的分布式架构,本文主要为大家介绍了如何利用Py-Redis实现简单的分布式锁,需要的可以参考一下
    2023-08-08
  • python生成大写32位uuid代码

    python生成大写32位uuid代码

    这篇文章主要介绍了python生成大写32位uuid代码,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-03-03
  • Python内置函数——__import__ 的使用方法

    Python内置函数——__import__ 的使用方法

    本篇文章主要介绍了Python内置函数——__import__ 的使用方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-11-11

最新评论