BCEloss

import torch

# 自定义数据
gt = torch.randint(1,10,(4,)).float()/10
pred = torch.randint(1,10,(4,)).float()/10


# 自定义BCEloss
def BCELoss( pred, target):
    output = - target * torch.log(pred) - (1.0 - target) * torch.log(1.0 - pred)
    return output

# 调用API
BCE = torch.nn.BCELoss(reduction="mean")

loss0 = BCELoss(pred,gt).mean()
loss1 = BCE(pred,gt)

# 打印损失
print(loss0,loss1)
tensor(0.7794) tensor(0.7794)

注意,自定义的BCE在计算之后要加 .mean() , 或者要与调用API时的reduction的参数一致

你可能感兴趣的:(笔记,pytorch)