目标检测 YOLOv5 - loss for objectness and classification

目标检测 YOLOv5 - loss for objectness and classification

flyfish

下面两句位于utils/loss.py的ComputeLoss类中

BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))

BCEWithLogitsLoss的公式是

ℓ ( x , y ) = L = { l 1 , … , l N } ⊤ , l n = − w n [ y n ⋅ log ⁡ σ ( x n ) + ( 1 − y n ) ⋅ log ⁡ ( 1 − σ ( x n ) ) ] , \ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad l_n = - w_n \left[ y_n \cdot \log \sigma(x_n) + (1 - y_n) \cdot \log (1 - \sigma(x_n)) \right], (x,y)=L={l1,,lN},ln=wn[ynlogσ(xn)+(1yn)log(1σ(xn))],

使用BCEWithLogitsLoss代码示例

import torch
target = torch.ones([10, 64], dtype=torch.float32)  # 64 classes, batch size = 10
output = torch.full([10, 64], 1.5)  # A prediction (logit)
pos_weight = torch.ones([64])  # All weights are equal to 1
criterion = torch.nn.BCEWithLogitsLoss(pos_weight=pos_weight)
loss=criterion(output, target)  # -log(sigmoid(1.5))
print(loss) #tensor(0.2014)

BCEWithLogitsLoss = Sigmoid + BCELoss

代码示例

import torch
target = torch.ones([10, 64], dtype=torch.float32)  # 64 classes, batch size = 10
output = torch.full([10, 64], 1.5)  # A prediction (logit)
a=torch.nn.Sigmoid()
criterion=torch.nn.BCELoss()
a=torch.nn.Sigmoid()
loss = criterion(a(output), target)
print(loss)#tensor(0.2014)

调用binary_cross_entropy的实现

import torch
import torch.nn.functional as F
target = torch.ones([10, 64], dtype=torch.float32,requires_grad=False)  # 64 classes, batch size = 10
output = torch.full([10, 64], 1.5,requires_grad=True)  # A prediction (logit)
a=torch.nn.Sigmoid()
loss = F.binary_cross_entropy(a(output), target)
loss.backward()
print(loss) #tensor(0.2014, grad_fn=<BinaryCrossEntropyBackward>)

推荐使用BCEWithLogitsLoss,而不是其他方式的实现,因为BCEWithLogitsLoss内部使用了log-sum-exp技巧
这里有是如何实现的log-sum-exp,包含整个推理过程 。

以一个实际的例子来理解BCEWithLogitsLoss内部的计算过程

sigmoid的公式是
Sigmoid ( x ) = σ ( x ) = 1 1 + exp ⁡ ( − x ) \text{Sigmoid}(x) = \sigma(x) = \frac{1}{1 + \exp(-x)} Sigmoid(x)=σ(x)=1+exp(x)1
BCELoss的公式是
ℓ ( x , y ) = L = { l 1 , … , l N } ⊤ , l n = − w n [ y n ⋅ log ⁡ x n + ( 1 − y n ) ⋅ log ⁡ ( 1 − x n ) ] \ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad l_n = - w_n \left[ y_n \cdot \log x_n + (1 - y_n) \cdot \log (1 - x_n) \right] (x,y)=L={l1,,lN},ln=wn[ynlogxn+(1yn)log(1xn)]
预测值分别是 0.7,0.2,0.1
类别标签分别是 1 , 0, 0
预测值经过sigmoid结果是0.6682, 0.5498, 0.5250
代入sigmoid公式

print(1 /(1+math.exp(-1 * 0.7)))
print(1 /(1+math.exp(-1 * 0.2)))
print(1 /(1+math.exp(-1 * 0.1)))

math.exp就是e的多少次方
e约等于2.718281828459045,上面第一个式子与print(1/(1+2.718281828459045 ** (-0.7)))相同

在经过BCELoss结果是0.648557191505494

代入BCELoss公式

from math import log
a=0.6682
b=0.5498
c=0.5250
print(((1 * log (a)+(1-1) * log (1-a))+(0 * log (b)+(1-0) * log (1-b))+(0 * log (c)+(1-0) * log (1-c))) /(-3))

最终得到的结果是0.648557191505494

上例如果用BCEWithLogitsLoss代码写是

import torch
pred=torch.tensor([0.7,0.2,0.1],dtype=torch.float)
target=torch.tensor([1,0,0],dtype=torch.float)
criterion = torch.nn.BCEWithLogitsLoss()
loss=criterion(pred, target)
print(loss)#tensor(0.6486)
### YOLOv5 PCLS Loss Explanation In the context of object detection, particularly within models like YOLOv5, the term `pcls` often refers to a combination of probability (p), confidence (c), and location (l) or sometimes class-specific elements. However, specifically addressing what is referred to as "pcls loss," it appears there might be some confusion with terminology directly used in YOLOv5 documentation or source code[^1]. The primary losses that are well-documented and integral parts of training YOLOv5 include box localization error, objectness score regression, and classification errors. For clarity on how these components contribute to the overall loss function: - **Box Localization Error**: This part focuses on improving bounding box predictions by minimizing differences between predicted boxes and ground truth labels. - **Objectness Score Regression**: Aims at predicting whether an anchor contains any object instance regardless of its category. - **Classification Errors**: Handles multi-class prediction accuracy when multiple classes exist within datasets[^2]. Given this understanding, if one were referring to aspects encompassed under 'pcls', they would likely involve all three aforementioned types combined into one cohesive mechanism designed for optimizing model performance during training phases. ### Usage Example Code Snippet Demonstrating Customization Around These Concepts Below demonstrates a simplified version focusing on customizing certain parameters related to these concepts but not explicitly labeled as "pcls": ```python from yolov5.models.experimental import attempt_load import torch model = attempt_load('yolov5s.pt') # Load pre-trained model weights for name, param in model.named_parameters(): if 'anchor' in name: print(f"Adjusting {name}...") # Modify specific layers associated with anchors which influence both l (location) and c (confidence) # Note: Direct manipulation should generally avoid altering core functionalities unless thoroughly understood. ``` This snippet provides insight into accessing and potentially adjusting parameters relevant to the concept described above without directly implementing something called "pcls loss."
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

二分掌柜的

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值