≡
  • 网络编程
  • 数据库
  • CMS技巧
  • 软件编程
  • PHP笔记
  • JavaScript
  • MySQL
位置:首页 > 网络编程 > Python

Python之pytorch计算准确率,召回率和F1值的操作的简单示例

人气:317 时间:2021-06-07

这篇文章主要为大家详细介绍了Python之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中计算准确率,召回率和F1值的操作

补充: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)

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

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

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

混淆矩阵:

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

精确率(Precision):

预测结果为正例样本中真实为正例的比例(查的准)()

召回率(Recall):

真实为正例的样本中预测结果为正例的比例(查的全)()

分类的其他评估标准: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
 ...,
'''
 

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

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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持四海网。

本文来自:http://www.q1010.com/181/18839-0.html

注:关于Python之pytorch计算准确率,召回率和F1值的操作的简单示例的内容就先介绍到这里,更多相关文章的可以留意四海网的其他信息。

关键词:python

您可能感兴趣的文章

  • Python之pytorch常用的损失函数用法的简单示例
  • 解决Pytorch训练网络过程中loss突然变为0的问题
  • Python之把classification_report输出到csv文件的简单示例
  • Python之格式化文本段落之textwrap库的简单示例
  • Python之爬虫入门的简单示例
  • Python之逻辑回归的简单示例
  • Python之文本常量与字符串模板之string库的简单示例
  • Python之设置 matplotlib 正确显示中文的四种的简单示例
  • Python之 Pandas知识点之缺失值处理的简单示例
  • Python之提取视频中的音频只需要三行代码!
上一篇:Python类的单继承相关知识的简单示例
下一篇:Python之把classification_report输出到csv文件的简单示例
热门文章
  • Python 处理Cookie的菜鸟教程(一)Cookie库
  • python之pandas取dataframe特定行列的简单示例
  • Python解决json.dumps错误::‘utf8’ codec can‘t decode byte
  • Python通过pythony连接Hive执行Hql的脚本
  • Python 三种方法删除列表中重复元素的简单示例
  • python爬虫代码示例
  • Python 中英文标点转换示例
  • Python 不得不知的开源项目解析
  • Python urlencode编码和url拼接实现方法
  • python按中文拆分中英文混合字符串的简单示例
  • 最新文章
    • Python利用numpy三层神经网络的简单示例
    • pygame可视化幸运大转盘的简单示例
    • Python爬虫之爬取二手房信息的简单示例
    • Python之time库的简单示例
    • OpenCV灰度、高斯模糊、边缘检测的简单示例
    • Python安装Bs4及使用的简单示例
    • django自定义manage.py管理命令的简单示例
    • Python之matplotlib 向任意位置添加一个子图(axes)的简单示例
    • Python图像标签标注软件labelme分析的简单示例
    • python调用摄像头并拍照发邮箱的简单示例

四海网收集整理一些常用的php代码,JS代码,数据库mysql等技术文章。