交叉熵损失CrossEntropyLoss

文章通过示例解释了在PyTorch中如何使用CrossEntropyLoss函数处理语义分割问题的多分类输出。当reduction设为none时,损失函数返回每个像素点的损失;设为mean,则返回所有像素的平均损失。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

交叉熵损失CrossEntropyLoss

语义分割网络输出tensor的尺寸为【B,C,H,W】,进行多分类,label的尺寸为【B,H,W】。
举例:三分类:output【1, 3,3, 3】,label【1, 3, 3】

验证

import torch

output = torch.tensor([[[[1, 1, 0],
                         [2, 0, 1],
                         [2, 1, 0]],
                        [[2, 0, 2],
                         [0, 0, 1],
                         [1, 1, 2]],
                        [[1, 1, 0],
                         [0, 0, 1],
                         [2, 0, 2]]]
                       ]).float()
label = torch.tensor([[[1, 1, 0],
                       [1, 0, 0],
                       [2, 2, 2]]]).long()

CrossEntropyLoss = torch.nn.CrossEntropyLoss(reduction='none')
loss = CrossEntropyLoss(output, label)
print(loss)
# result:
# tensor([[[0.5514, 1.8620, 2.2395],
#          [2.2395, 1.0986, 1.0986],
#          [0.8620, 1.8620, 0.7586]]])
import torch

output = torch.tensor([[[[1, 1, 0],
                         [2, 0, 1],
                         [2, 1, 0]],
                        [[2, 0, 2],
                         [0, 0, 1],
                         [1, 1, 2]],
                        [[1, 1, 0],
                         [0, 0, 1],
                         [2, 0, 2]]]
                       ]).float()
label = torch.tensor([[[1, 1, 0],
                       [1, 0, 0],
                       [2, 2, 2]]]).long()

CrossEntropyLoss = torch.nn.CrossEntropyLoss(reduction='mean')
loss = CrossEntropyLoss(output, label)
print(loss)
# result:
# tensor(1.3969)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值