PyTorch中CrossEntropyLoss、BCELoss、BCEWithLogitsLoss的理解

import torch

predict =torch.Tensor([[0.5796,0.4403,0.9087],[-1.5673,-0.3150,1.6660]])

#predict =torch.Tensor([[0.5796,0.4403],[-1.5673,-0.3150]])

print(predict)

target =torch.tensor([0,2])

target_bce =torch.Tensor([[1,0,0],[0,0,1]])

ce_loss=torch.nn.CrossEntropyLoss()

soft_max=torch.nn.Softmax(dim=-1)

sig_max=torch.nn.Sigmoid()

soft_out=soft_max(predict)

sig_out=sig_max(predict)

bce_loss=torch.nn.BCELoss()

bce_loss1=torch.nn.BCEWithLogitsLoss()

print(ce_loss(predict,target))

print(bce_loss(soft_out,target_bce))

print(bce_loss(sig_out,target_bce))

print(bce_loss1(predict,target_bce))

输出:

#predict:

**tensor([[ 0.5796, 0.4403, 0.9087],

-1.5673, -0.3150, 1.6660\]\])** #print(ce_loss(predict,target)): **tensor(0.6725)** #print(bce_loss(soft_out,target_bce)) **tensor(0.3950)** #print(bce_loss(sig_out,target_bce)) **tensor(0.5900)** print(bce_loss1(predict,target_bce)) **tensor(0.5900)** **结论:** **1.sigmoid激活+BCELoss等于BCEWithLogitsLoss** **2.BCEWithLogitsLoss和CrossEntropyLoss不一样,但都可以不加激活** **3.sigmoid激活+BCELoss和softmax激活+BCELoss有很大区别**

相关推荐
宝贝儿好6 小时前
【强化学习实战】第十一章:Gymnasium库的介绍和使用(1)、出租车游戏代码详解(Sarsa & Q learning)
人工智能·python·深度学习·算法·游戏·机器学习
如若1239 小时前
flash-attn 安装失败?从报错到成功的完整排雷指南(CUDA 12.8 + PyTorch 2.7)
人工智能·pytorch·python
阿_旭10 小时前
基于YOLO26深度学习的交警手势识别系统【python源码+Pyqt5界面+数据集+训练代码】
人工智能·python·深度学习·交警手势识别
EQUINOX110 小时前
卷积神经网络
人工智能·神经网络·cnn
love530love11 小时前
Windows 11 源码编译 vLLM 0.16 完全指南(CUDA 12.6 / PyTorch 2.7.1+cu126)
人工智能·pytorch·windows·python·深度学习·comfyui·vllm
有Li13 小时前
CIA-net:用于多模态MRI卵巢肿瘤分割的跨模态交互与聚合网络/文献速递-大模型与图像分割在医疗影像中应用
论文阅读·人工智能·深度学习·计算机视觉·文献
WeeJot嵌入式13 小时前
ICLR 2026低秩Transformer解决方案:多变量时间序列异常检测与定位的数学原理
人工智能·深度学习·transformer
工业甲酰苯胺15 小时前
制造业数字化转型:低代码核心系统技术解析与落地实践
人工智能·深度学习·低代码
卓律涤15 小时前
【工作篇】 Dell机架式服务器,采用RAID 5,怎么部署win系统
运维·服务器·单片机·嵌入式硬件·深度学习·程序人生·安全