栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

pytorch中的BCELoss与BCEWithLogitsLoss实现

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

pytorch中的BCELoss与BCEWithLogitsLoss实现

pytorch中的BCELoss与BCEWithLogitsLoss计算交叉采用的对数函数的底为自然对数e,下面代码是直接调用函数和代码实现。
import torch
import torch.nn as nn

input = torch.FloatTensor([[ -0.4089,  -1.2471,  0.5907],
        [ -0.4897, -0.8267,  -0.7349],
        [ 0.5241,  -0.1246, -0.4751]])
print(input)
target = torch.FloatTensor([[0, 1, 1],
                            [0, 0, 1],
                            [1, 0, 1]])

m = nn.Sigmoid()
sigmoid_res = m(input)
loss = nn.BCELoss()
# 公式为-1/n * (累加(y*lnx + (1-y)* ln(1-x)))
res = loss(sigmoid_res, target)
print(res)

#BCEWithLogitsLoss就是把Sigmoid-BCELoss合成一步。
loss1 = nn.BCEWithLogitsLoss()
res1 = loss1(input, target)
print(res1) #tensor(0.7193)

res2 = torch.Tensor([0.0])
for i in range(3):
    for j in range(3):
        print(i,j,res2)
        res2 += target[i,j] * torch.log(sigmoid_res[i,j]) + (1-target[i,j]) * torch.log(1-sigmoid_res[i,j])
res2 = -1 * res2 / 9
print('res2', res2)

运行结果:

 参考文献:

1.pytorch中的BCELoss与BCEWithLogitsLoss

2.交叉熵(Cross-Entropy)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/966238.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号