pytorch 加权CE_loss实现(语义分割中的类不平衡使用)

加权CE_loss和BCE_loss稍有不同

1.标签为long类型,BCE标签为float类型

2.当reduction为mean时计算每个像素点的损失的平均,BCE除以像素数得到平均值,CE除以像素对应的权重之和得到平均值。

参数配置torch.nn.CrossEntropyLoss(weight=None,size_average=None,ignore_index=-100,reduce=None,reduction='mean',label_smoothing=0.0)

增加加权的CE_loss代码实现

python 复制代码
# 总之, CrossEntropyLoss() = softmax + log + NLLLoss() = log_softmax + NLLLoss(), 具体等价应用如下:
import torch
import torch.nn as nn
import torch.nn.functional as F
import random
import numpy as np

class CrossEntropyLoss2d(nn.Module):
    def __init__(self, weight=None):
      super(CrossEntropyLoss2d, self).__init__()
       self.nll_loss = nn.CrossEntropyLoss(weight, reduction='mean')
    def forward(self, preds, targets):
        return self.nll_loss(preds, targets)

语义分割类别计算

python 复制代码
class CE_w_loss(nn.Module):
    def __init__(self,ignore_index=255):
        super(CE_w_loss, self).__init__()
        self.ignore_index = ignore_index
        # self.CE = nn.CrossEntropyLoss(ignore_index=self.ignore_index)
    def forward(self, outputs, targets):
        class_num = outputs.shape[1]
        # print("class_num :",class_num )
        # # 计算每个类别在整个 batch 中的像素数占比
        class_pixel_counts = torch.bincount(targets.flatten(), minlength=class_num)  # 假设有class_num个类别
        class_pixel_proportions = class_pixel_counts.float() / torch.numel(targets)
        # # 根据类别占比计算权重
        class_weights = 1.0 / (torch.log(1.02 + class_pixel_proportions)).double()  # 使用对数变换平衡权重
        # # print("class_weights :",class_weights)
        #
        # 定义交叉熵损失函数,并使用动态计算的类别权重
        criterion = nn.CrossEntropyLoss(ignore_index=self.ignore_index,weight= class_weights)

        # 计算损失
        loss = criterion(outputs, targets)
        print(loss.item())  # 打印损失值
        return loss

    np.random.seed(666)
    pred = np.ones((2, 5, 256,256))
    seg = np.ones((2, 5, 256, 256)) # 灰度
    label = np.ones((2, 256, 256))  # 灰度

    pred = torch.from_numpy(pred)
    seg = torch.from_numpy(seg).int()  # 灰度
    label = torch.from_numpy(label).long()
     ce = CE_w_loss()
    loss = ce(pred, label)
    print("loss:",loss.item())

报错

Weight=torch.from_numpy(np.array([0.1, 0.8, 1.0, 1.0])).float() 报错

Weight=torch.from_numpy(np.array([0.1, 0.8, 1.0, 1.0])).double() 正确

参考:[1]https://blog.csdn.net/CSDN_of_ding/article/details/111515226

2\] \[3\]

相关推荐
腾视科技12 分钟前
让安全驾驶有“AI”相伴|腾视科技DMS视频监控一体机,守护每一次出行
人工智能·科技·安全
蓝桉~MLGT27 分钟前
Python学习历程——字符串相关操作及正则表达式
python·学习·正则表达式
一晌小贪欢28 分钟前
Python爬虫第5课:正则表达式与数据清洗技术
爬虫·python·正则表达式·网络爬虫·python爬虫·python3·网页爬虫
桃子叔叔31 分钟前
从0到1讲解大模型中的关键步骤(一)分词、词性标注、命名实体识别
人工智能·大模型·多模态
ARM+FPGA+AI工业主板定制专家1 小时前
【JETSON+FPGA+GMSL】实测分享 | 如何实现激光雷达与摄像头高精度时间同步?
人工智能·数码相机·机器学习·fpga开发·机器人·自动驾驶
Nina_7171 小时前
Google提示词白皮书总结(2)
人工智能·python
fakerth1 小时前
【OpenHarmony】AI引擎模块架构
人工智能·架构·openharmony
Lynnxiaowen1 小时前
今天我们继续学习python3编程之python基础
linux·运维·python·学习
综合热讯1 小时前
湖南粒界教育科技有限公司:专注影视技能培养,AI辅助教学提升学员就业竞争力
人工智能·科技
ImAlex1 小时前
实测PaddleOCR-VL:文心4.5最强衍生模型如何重构文档处理效率
人工智能·aigc