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

 更新时间:2020年01月02日 09:52:18   作者:WYXHAHAHA123  
今天小编就为大家分享一篇pytorch实现focal loss的两种方式小结,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

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

import torch
import torch.nn.functional as F
import numpy as np
from 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 classWeights
def 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 loss


def 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 loss

if __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的两种方式小结就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • python如何定义带参数的装饰器

    python如何定义带参数的装饰器

    这篇文章主要为大家详细介绍了python如何定义带参数的装饰器,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-03-03
  • Tensorflow安装问题: Could not find a version that satisfies the requirement tensorflow

    Tensorflow安装问题: Could not find a version that satisfies the

    这篇文章主要介绍了Tensorflow安装问题: Could not find a version that satisfies the requirement tensorflow,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-04-04
  • Python将Word文档转换为Markdown格式

    Python将Word文档转换为Markdown格式

    Markdown作为一种轻量级标记语言,以其简洁的语法和广泛的兼容性,本文将介绍如何使用Python将Word文档转换为Markdown文件,需要的可以了解下
    2024-11-11
  • 一文详解python中dataclass的使用技巧

    一文详解python中dataclass的使用技巧

    dataclass是从Python3.7版本开始,作为标准库中的模块被引入,随着Python版本的不断更新,dataclass也逐步发展和完善,为Python开发者提供了更加便捷的数据类创建和管理方式,本文总结了几个我平时使用较多dataclass技巧,需要的朋友可以参考下
    2024-03-03
  • Python Datetime模块和Calendar模块用法实例分析

    Python Datetime模块和Calendar模块用法实例分析

    这篇文章主要介绍了Python Datetime模块和Calendar模块用法,结合实例形式分析了Python日期时间及日历相关的Datetime模块和Calendar模块原理、用法及操作注意事项,需要的朋友可以参考下
    2019-04-04
  • Anaconda安装时默认python版本改成其他版本的两种方式

    Anaconda安装时默认python版本改成其他版本的两种方式

    这篇文章主要给大家介绍了关于Anaconda安装时默认python版本改成其他版本的两种方式,anaconda是一个非常好用的python发行版本,其中包含了大部分常用的库,需要的朋友可以参考下
    2023-10-10
  • Langchain集成管理prompt功能详解

    Langchain集成管理prompt功能详解

    这篇文章主要为大家介绍了Langchain集成管理prompt功能示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-03-03
  • Python批量加密Excel文件的实现示例

    Python批量加密Excel文件的实现示例

    在日常工作中,保护敏感数据是至关重要的,本文主要介绍了Python批量加密Excel文件的实现示例,具有一定的参考价值,感兴趣的可以了解一下
    2023-12-12
  • Python Pandas list列表数据列拆分成多行的方法实现

    Python Pandas list列表数据列拆分成多行的方法实现

    这篇文章主要介绍了Python Pandas list(列表)数据列拆分成多行的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-12-12
  • 学习python的几条建议分享

    学习python的几条建议分享

    熟悉python语言,以及学会python的编码方式。熟悉python库,遇到开发任务的时候知道如何去找对应的模块。知道如何查找和获取第三方的python库,以应付开发任务
    2013-02-02

最新评论