侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

pytorch实现focal loss的两种方式小结

Python  /  管理员 发布于 5年前   296

我就废话不多说了,直接上代码吧!

import torchimport torch.nn.functional as Fimport numpy as npfrom torch.autograd import Variable'''pytorch实现focal loss的两种方式(现在讨论的是基于分割任务)在计算损失函数的过程中考虑到类别不平衡的问题,假设加上背景类别共有6个类别'''def compute_class_weights(histogram):  classWeights = np.ones(6, dtype=np.float32)  normHist = histogram / np.sum(histogram)  for i in range(6):    classWeights[i] = 1 / (np.log(1.10 + normHist[i]))  return classWeightsdef focal_loss_my(input,target):  '''  :param input: shape [batch_size,num_classes,H,W] 仅仅经过卷积操作后的输出,并没有经过任何激活函数的作用  :param target: shape [batch_size,H,W]  :return:  '''  n, c, h, w = input.size()  target = target.long()  input = input.transpose(1, 2).transpose(2, 3).contiguous().view(-1, c)  target = target.contiguous().view(-1)  number_0 = torch.sum(target == 0).item()  number_1 = torch.sum(target == 1).item()  number_2 = torch.sum(target == 2).item()  number_3 = torch.sum(target == 3).item()  number_4 = torch.sum(target == 4).item()  number_5 = torch.sum(target == 5).item()  frequency = torch.tensor((number_0, number_1, number_2, number_3, number_4, number_5), dtype=torch.float32)  frequency = frequency.numpy()  classWeights = compute_class_weights(frequency)  '''  根据当前给出的ground truth label计算出每个类别所占据的权重  '''  # weights=torch.from_numpy(classWeights).float().cuda()  weights = torch.from_numpy(classWeights).float()  focal_frequency = F.nll_loss(F.softmax(input, dim=1), target, reduction='none')  '''  上面一篇博文讲过  F.nll_loss(torch.log(F.softmax(inputs, dim=1),target)的函数功能与F.cross_entropy相同  可见F.nll_loss中实现了对于target的one-hot encoding编码功能,将其编码成与input shape相同的tensor  然后与前面那一项(即F.nll_loss输入的第一项)进行 element-wise production  相当于取出了 log(p_gt)即当前样本点被分类为正确类别的概率  现在去掉取log的操作,相当于 focal_frequency shape [num_samples]  即取出ground truth类别的概率数值,并取了负号  '''  focal_frequency += 1.0#shape [num_samples] 1-P(gt_classes)  focal_frequency = torch.pow(focal_frequency, 2) # torch.Size([75])  focal_frequency = focal_frequency.repeat(c, 1)  '''  进行repeat操作后,focal_frequency shape [num_classes,num_samples]  '''  focal_frequency = focal_frequency.transpose(1, 0)  loss = F.nll_loss(focal_frequency * (torch.log(F.softmax(input, dim=1))), target, weight=None,           reduction='elementwise_mean')  return lossdef focal_loss_zhihu(input, target):  '''  :param input: 使用知乎上面大神给出的方案 https://zhuanlan.zhihu.com/p/28527749  :param target:  :return:  '''  n, c, h, w = input.size()  target = target.long()  inputs = input.transpose(1, 2).transpose(2, 3).contiguous().view(-1, c)  target = target.contiguous().view(-1)  N = inputs.size(0)  C = inputs.size(1)  number_0 = torch.sum(target == 0).item()  number_1 = torch.sum(target == 1).item()  number_2 = torch.sum(target == 2).item()  number_3 = torch.sum(target == 3).item()  number_4 = torch.sum(target == 4).item()  number_5 = torch.sum(target == 5).item()  frequency = torch.tensor((number_0, number_1, number_2, number_3, number_4, number_5), dtype=torch.float32)  frequency = frequency.numpy()  classWeights = compute_class_weights(frequency)  weights = torch.from_numpy(classWeights).float()  weights=weights[target.view(-1)]#这行代码非常重要  gamma = 2  P = F.softmax(inputs, dim=1)#shape [num_samples,num_classes]  class_mask = inputs.data.new(N, C).fill_(0)  class_mask = Variable(class_mask)  ids = target.view(-1, 1)  class_mask.scatter_(1, ids.data, 1.)#shape [num_samples,num_classes] one-hot encoding  probs = (P * class_mask).sum(1).view(-1, 1)#shape [num_samples,]  log_p = probs.log()  print('in calculating batch_loss',weights.shape,probs.shape,log_p.shape)  # batch_loss = -weights * (torch.pow((1 - probs), gamma)) * log_p  batch_loss = -(torch.pow((1 - probs), gamma)) * log_p  print(batch_loss.shape)  loss = batch_loss.mean()  return lossif __name__=='__main__':  pred=torch.rand((2,6,5,5))  y=torch.from_numpy(np.random.randint(0,6,(2,5,5)))  loss1=focal_loss_my(pred,y)  loss2=focal_loss_zhihu(pred,y)  print('loss1',loss1)  print('loss2', loss2)'''in calculating batch_loss torch.Size([50]) torch.Size([50, 1]) torch.Size([50, 1])torch.Size([50, 1])loss1 tensor(1.3166)loss2 tensor(1.3166)'''

以上这篇pytorch实现focal loss的两种方式小结就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。


  • 上一条:
    pytorch 图像预处理之减去均值,除以方差的实例
    下一条:
    pytorch中交叉熵损失(nn.CrossEntropyLoss())的计算过程详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客