Pytorch 实现计算分类器准确率(总分类及子分类)

分类器平均准确率计算:

correct = torch.zeros(1).squeeze().cuda()
total = torch.zeros(1).squeeze().cuda()
for i, (images, labels) in enumerate(train_loader):
      images = Variable(images.cuda())
      labels = Variable(labels.cuda())

      output = model(images)

      prediction = torch.argmax(output, 1)
      correct += (prediction == labels).sum().float()
      total += len(labels)
acc_str = 'Accuracy: %f'%((correct/total).cpu().detach().data.numpy())

分类器各个子类准确率计算:

correct = list(0. for i in range(args.class_num))
total = list(0. for i in range(args.class_num))
for i, (images, labels) in enumerate(train_loader):
      images = Variable(images.cuda())
      labels = Variable(labels.cuda())

      output = model(images)

      prediction = torch.argmax(output, 1)
      res = prediction == labels
      for label_idx in range(len(labels)):
        label_single = label[label_idx]
        correct[label_single] += res[label_idx].item()
        total[label_single] += 1
 acc_str = 'Accuracy: %f'%(sum(correct)/sum(total))
 for acc_idx in range(len(train_class_correct)):
      try:
        acc = correct[acc_idx]/total[acc_idx]
      except:
        acc = 0
      finally:
        acc_str += '\tclassID:%d\tacc:%f\t'%(acc_idx+1, acc)

以上这篇Pytorch 实现计算分类器准确率(总分类及子分类)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Pytorch 实现focal_loss 多类别和二分类示例

    我就废话不多说了,直接上代码吧! import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # 支持多分类和二分类 class FocalLoss(nn.Module): """ This is a implementation of Focal Loss with smooth label cross entropy supported which is pro

  • 使用pytorch和torchtext进行文本分类的实例

    文本分类是NLP领域的较为容易的入门问题,本文记录我自己在做文本分类任务以及复现相关论文时的基本流程,绝大部分操作都使用了torch和torchtext两个库. 1. 文本数据预处理 首先数据存储在三个csv文件中,分别是train.csv,valid.csv,test.csv,第一列存储的是文本数据,例如情感分类问题经常是用户的评论review,例如imdb或者amazon数据集.第二列是情感极性polarity,N分类问题的话就有N个值,假设值得范围是0~N-1. 下面是很常见的文本预处理流

  • 使用PyTorch训练一个图像分类器实例

    如下所示: import torch import torchvision import torchvision.transforms as transforms import matplotlib.pyplot as plt import numpy as np print("torch: %s" % torch.__version__) print("tortorchvisionch: %s" % torchvision.__version__) print(&

  • Pytorch 计算误判率,计算准确率,计算召回率的例子

    无论是官方文档还是各位大神的论文或搭建的网络很多都是计算准确率,很少有计算误判率, 下面就说说怎么计算准确率以及误判率.召回率等指标 1.计算正确率 获取每批次的预判正确个数 train_correct = (pred == batch_y.squeeze(1)).sum() 该语句的意思是 预测的标签与实际标签相等的总数 获取训练集总的预判正确个数 train_acc += train_correct.data[0] #用来计算正确率 准确率 : train_acc / (len(train_

  • Pytorch 实现计算分类器准确率(总分类及子分类)

    分类器平均准确率计算: correct = torch.zeros(1).squeeze().cuda() total = torch.zeros(1).squeeze().cuda() for i, (images, labels) in enumerate(train_loader): images = Variable(images.cuda()) labels = Variable(labels.cuda()) output = model(images) prediction = to

  • destoon实现调用当前栏目分类及子分类和三级分类的方法

    调用当前栏目分类及子分类和三级分类是程序设计里常用的方法,本文就来详细讲述destoon实现调用当前栏目分类及子分类和三级分类的方法.具体操作如下: 在destoon中提供了如下的调用语句: 一级分类名: {$m[catname]} 二级分类名: {$c[catname]} 三级分类名: {$b[catname]} 具体调用示例如下: 一.直接调用分类名称和链接: {loop $maincat $i $m}<dl> {php $child = get_maincat($maincat, $CA

  • WordPress中获取指定分类及其子分类下的文章数目

    获取特定分类文章数 有时候我们想获取某个分类(category)下的文章数目,以便在博客的某个地方显示出来.下面就提供几个获取特定分类的文章数的方法,你可以根据个人喜好选择: 方法一: 将以下PHP代码放置在主题目录下的functions.php中: function wt_get_category_count($input = '') { global $wpdb; if($input == '') { $category = get_the_category(); return $categ

  • 解决pytorch GPU 计算过程中出现内存耗尽的问题

    Pytorch GPU运算过程中会出现:"cuda runtime error(2): out of memory"这样的错误.通常,这种错误是由于在循环中使用全局变量当做累加器,且累加梯度信息的缘故,用官方的说法就是:"accumulate history across your training loop".在默认情况下,开启梯度计算的Tensor变量是会在GPU保持他的历史数据的,所以在编程或者调试过程中应该尽力避免在循环中累加梯度信息. 下面举个栗子: 上代

  • 在Pytorch中计算自己模型的FLOPs方式

    https://github.com/Lyken17/pytorch-OpCounter 安装方法很简单: pip install thop 基本用法: from torchvision.models import resnet50from thop import profile model = resnet50() flops, params = profile(model, input_size=(1, 3, 224,224)) 对自己的module进行特别的计算: class YourMo

  • 在Pytorch中计算卷积方法的区别详解(conv2d的区别)

    在二维矩阵间的运算: class torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True) 对由多个特征平面组成的输入信号进行2D的卷积操作.详解 torch.nn.functional.conv2d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1)

  • pytorch 利用lstm做mnist手写数字识别分类的实例

    代码如下,U我认为对于新手来说最重要的是学会rnn读取数据的格式. # -*- coding: utf-8 -*- """ Created on Tue Oct 9 08:53:25 2018 @author: www """ import sys sys.path.append('..') import torch import datetime from torch.autograd import Variable from torch im

  • 在pytorch 中计算精度、回归率、F1 score等指标的实例

    pytorch中训练完网络后,需要对学习的结果进行测试.官网上例程用的方法统统都是正确率,使用的是torch.eq()这个函数. 但是为了更精细的评价结果,我们还需要计算其他各个指标.在把官网API翻了一遍之后发现并没有用于计算TP,TN,FP,FN的函数... 在动了无数歪脑筋之后,心想pytorch完全支持numpy,那能不能直接进行判断,试了一下果然可以,上代码: # TP predict 和 label 同时为1 TP += ((pred_choice == 1) & (target.d

  • python实现二分类和多分类的ROC曲线教程

    基本概念 precision:预测为对的当中,原本为对的比例(越大越好,1为理想状态) recall:原本为对的当中,预测为对的比例(越大越好,1为理想状态) F-measure:F度量是对准确率和召回率做一个权衡(越大越好,1为理想状态,此时precision为1,recall为1) accuracy:预测对的(包括原本是对预测为对,原本是错的预测为错两种情形)占整个的比例(越大越好,1为理想状态) fp rate:原本是错的预测为对的比例(越小越好,0为理想状态) tp rate:原本是对的

  • php通过分类列表产生分类树数组的方法

    本文实例讲述了php通过分类列表产生分类树数组的方法.分享给大家供大家参考.具体分析如下: 这里$list 为分类列表数组,键为分类 ID,值为分类节点对象,pid 为父分类 ID php代码如下: $tree = array(); foreach ($list as $id => $row) { $pid = $row->pid; if ($pid == 0) { $tree[] = &$list[$id]; } else if (isset($list[$pid])) { $par

随机推荐