损失函数-BCEWithLogitsLoss
BCEWithLogitsLoss(predict,target) 和BCELoss(predict,target) 的区别:BCEWithLogitsLoss会对predict进行sigmoid处理;BCELoss不会对predict进行sigmoid处理;#%%import torchimport torch.nn as nn#%% mdBCEWithLogitsLoss损失函数#%% 产生p
·
BCEWithLogitsLoss(predict,target) 和BCELoss(predict,target) 的区别:
BCEWithLogitsLoss会对predict进行sigmoid处理;BCELoss不会对predict进行sigmoid处理;
#%%
import torch
import torch.nn as nn
#%% md
BCEWithLogitsLoss损失函数
#%% 产生predict,产生target
N = 2
C = 1
H = 2
W = 2
predict = torch.arange(8,dtype=torch.float32).view([N,C,H,W])
predict = torch.sigmoid(predict)
target = torch.arange(start=1,end=9,step=1,dtype=torch.float32).view([N,C,H,W])
target = torch.sigmoid(target)
print('predict:',predict)
print('target:',target)
#%% 利用pytorch计算BCEWithLogitsLoss
loss = torch.nn.BCEWithLogitsLoss()
print('Pytorch计算结果:BCEWithLogitsLoss:',loss(predict,target))
#%% 对predict做sigmoid+BCELoss
predict = torch.sigmoid(predict)
loss = torch.nn.BCELoss()
print('Pytorch计算结果:sigmoid+BCELoss:',loss(predict,target))
结果:
Pytorch计算结果:BCEWithLogitsLoss: tensor(0.3864)
Pytorch计算结果:sigmoid+BCELoss: tensor(0.3864)
更多推荐
已为社区贡献3条内容
所有评论(0)