主頁 > 知識庫 > 基于BCEWithLogitsLoss樣本不均衡的處理方案

基于BCEWithLogitsLoss樣本不均衡的處理方案

熱門標簽:廣告地圖標注app 白銀外呼系統(tǒng) 海南400電話如何申請 哈爾濱ai外呼系統(tǒng)定制 騰訊外呼線路 公司電話機器人 陜西金融外呼系統(tǒng) 唐山智能外呼系統(tǒng)一般多少錢 激戰(zhàn)2地圖標注

最近在做deepfake檢測任務(可以將其視為二分類問題,label為1和0),遇到了正負樣本不均衡的問題,正樣本數(shù)目是負樣本的5倍,這樣會導致FP率較高。

嘗試將正樣本的loss權重增高,看BCEWithLogitsLoss的源碼

Examples::
 
    >>> target = torch.ones([10, 64], dtype=torch.float32)  # 64 classes, batch size = 10
    >>> output = torch.full([10, 64], 0.999)  # A prediction (logit)
    >>> pos_weight = torch.ones([64])  # All weights are equal to 1
    >>> criterion = torch.nn.BCEWithLogitsLoss(pos_weight=pos_weight)
    >>> criterion(output, target)  # -log(sigmoid(0.999))
    tensor(0.3135)
 
Args:
    weight (Tensor, optional): a manual rescaling weight given to the loss
        of each batch element. If given, has to be a Tensor of size `nbatch`.
    size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
        the losses are averaged over each loss element in the batch. Note that for
        some losses, there are multiple elements per sample. If the field :attr:`size_average`
        is set to ``False``, the losses are instead summed for each minibatch. Ignored
        when reduce is ``False``. Default: ``True``
    reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
        losses are averaged or summed over observations for each minibatch depending
        on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
        batch element instead and ignores :attr:`size_average`. Default: ``True``
    reduction (string, optional): Specifies the reduction to apply to the output:
        ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
        ``'mean'``: the sum of the output will be divided by the number of
        elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
        and :attr:`reduce` are in the process of being deprecated, and in the meantime,
        specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
    pos_weight (Tensor, optional): a weight of positive examples.
            Must be a vector with length equal to the number of classes.

對其中的參數(shù)pos_weight的使用存在疑惑,BCEloss里的例子pos_weight = torch.ones([64]) # All weights are equal to 1,不懂為什么會有64個class,因為BCEloss是針對二分類問題的loss,后經(jīng)過檢索,得知還有多標簽分類,

多標簽分類就是多個標簽,每個標簽有兩個label(0和1),這類任務同樣可以使用BCEloss。

現(xiàn)在講一下BCEWithLogitsLoss里的pos_weight使用方法

比如我們有正負兩類樣本,正樣本數(shù)量為100個,負樣本為400個,我們想要對正負樣本的loss進行加權處理,將正樣本的loss權重放大4倍,通過這樣的方式緩解樣本不均衡問題。

criterion = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([4]))
 
# pos_weight (Tensor, optional): a weight of positive examples.
#            Must be a vector with length equal to the number of classes.

pos_weight里是一個tensor列表,需要和標簽個數(shù)相同,比如我們現(xiàn)在是二分類,只需要將正樣本loss的權重寫上即可。

如果是多標簽分類,有64個標簽,則

Examples::
 
    >>> target = torch.ones([10, 64], dtype=torch.float32)  # 64 classes, batch size = 10
    >>> output = torch.full([10, 64], 0.999)  # A prediction (logit)
    >>> pos_weight = torch.ones([64])  # All weights are equal to 1
    >>> criterion = torch.nn.BCEWithLogitsLoss(pos_weight=pos_weight)
    >>> criterion(output, target)  # -log(sigmoid(0.999))
    tensor(0.3135)

補充:Pytorch —— BCEWithLogitsLoss()的一些問題

一、等價表達

1、pytorch:

torch.sigmoid() + torch.nn.BCELoss()

2、自己編寫

def ce_loss(y_pred, y_train, alpha=1):
    
    p = torch.sigmoid(y_pred)
    # p = torch.clamp(p, min=1e-9, max=0.99)  
    loss = torch.sum(- alpha * torch.log(p) * y_train \

           - torch.log(1 - p) * (1 - y_train))/len(y_train)
    return loss~

3、驗證

import torch
import torch.nn as nn
torch.cuda.manual_seed(300)       # 為當前GPU設置隨機種子
torch.manual_seed(300)            # 為CPU設置隨機種子
def ce_loss(y_pred, y_train, alpha=1):
   # 計算loss
   p = torch.sigmoid(y_pred)
   # p = torch.clamp(p, min=1e-9, max=0.99)
   loss = torch.sum(- alpha * torch.log(p) * y_train \

          - torch.log(1 - p) * (1 - y_train))/len(y_train)
   return loss
py_lossFun = nn.BCEWithLogitsLoss()
input = torch.randn((10000,1), requires_grad=True)
target = torch.ones((10000,1))
target.requires_grad_(True)
py_loss = py_lossFun(input, target)
py_loss.backward()
print("*********BCEWithLogitsLoss***********")
print("loss: ")
print(py_loss.item())
print("梯度: ")
print(input.grad)
input = input.detach()
input.requires_grad_(True)
self_loss = ce_loss(input, target)
self_loss.backward()
print("*********SelfCELoss***********")
print("loss: ")
print(self_loss.item())
print("梯度: ")
print(input.grad)

測試結果:

– 由上結果可知,我編寫的loss和pytorch中提供的j基本一致。

– 但是僅僅這樣就可以了嗎?NO! 下面介紹BCEWithLogitsLoss()的強大之處:

– BCEWithLogitsLoss()具有很好的對nan的處理能力,對于我寫的代碼(四層神經(jīng)網(wǎng)絡,層之間的激活函數(shù)采用的是ReLU,輸出層激活函數(shù)采用sigmoid(),由于數(shù)據(jù)處理的問題,所以會導致我們編寫的CE的loss出現(xiàn)nan:原因如下:

–首先神經(jīng)網(wǎng)絡輸出的pre_target較大,就會導致sigmoid之后的p為1,則torch.log(1 - p)為nan;

– 使用clamp(函數(shù)雖然會解除這個nan,但是由于在迭代過程中,網(wǎng)絡輸出可能越來越大(層之間使用的是ReLU),則導致我們寫的loss陷入到某一個數(shù)值而無法進行優(yōu)化。但是BCEWithLogitsLoss()對這種情況下出現(xiàn)的nan有很好的處理,從而得到更好的結果。

– 我此實驗的目的是為了比較CE和FL的區(qū)別,自己編寫FL,則必須也要自己編寫CE,不能使用BCEWithLogitsLoss()。

二、使用場景

二分類 + sigmoid()

使用sigmoid作為輸出層非線性表達的分類問題(雖然可以處理多分類問題,但是一般用于二分類,并且最后一層只放一個節(jié)點)

三、注意事項

輸入格式

要求輸入的input和target均為float類型

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • Pytorch BCELoss和BCEWithLogitsLoss的使用
  • Pytorch 的損失函數(shù)Loss function使用詳解
  • Pytorch訓練網(wǎng)絡過程中l(wèi)oss突然變?yōu)?的解決方案
  • pytorch MSELoss計算平均的實現(xiàn)方法
  • pytorch loss反向傳播出錯的解決方案

標簽:常德 四川 益陽 惠州 黑龍江 上海 黔西 鷹潭

巨人網(wǎng)絡通訊聲明:本文標題《基于BCEWithLogitsLoss樣本不均衡的處理方案》,本文關鍵詞  基于,BCEWithLogitsLoss,樣本,;如發(fā)現(xiàn)本文內(nèi)容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《基于BCEWithLogitsLoss樣本不均衡的處理方案》相關的同類信息!
  • 本頁收集關于基于BCEWithLogitsLoss樣本不均衡的處理方案的相關信息資訊供網(wǎng)民參考!
  • 企业400电话

    智能AI客服机器人
    15000

    在线订购

    合计11份范本:公司章程+合伙协议+出资协议+合作协议+股权转让协议+增资扩股协议+股权激励+股东会决议+董事会决议

    推薦文章