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有很大区别

相关推荐
phltxy几秒前
LangGraph智能租房助手实践
大数据·人工智能·python·深度学习·语言模型·langchain
OpenApi.cc6 分钟前
Mocode 开发文档平台
人工智能·深度学习·目标检测·自然语言处理·语音识别
大鹏的NLP博客29 分钟前
CMAD:基于紧凑表征学习与马氏距离统计判别的工业异常检测架构
人工智能·深度学习
lkforce1 小时前
Transformer架构下的详细计算流程模拟,精确到数字(单层单头)
人工智能·深度学习·ai·transformer
PNP Robotics9 小时前
多伦多大学机器人峰会|物理AI与具身智能落地新趋势
人工智能·深度学习·机器学习·机器人
_Jimmy_15 小时前
AI应用开发工程师面试题库
人工智能·python·深度学习·机器学习·知识图谱
烬羽17 小时前
递归老写崩?一个"退回"公式,把回溯题变成填空题
javascript·深度学习·算法
hongyucai18 小时前
torch具身常用算子
人工智能·深度学习
林泽毅18 小时前
PyTRIO快速入门(一):概念、推理与训练
人工智能·python·深度学习·机器学习·语言模型
学术小李19 小时前
基于Pytorch,如何用CUDA自己写算子?(一)
人工智能·pytorch·python