pytorch nn.LogSoftmax

本文详细解析了PyTorch中的LogSoftmax函数,对比了其与Softmax函数的区别,阐述了LogSoftmax在神经网络输出层的应用,以及如何通过加入log函数来优化数值稳定性。

应用

# softmax层
# m = nn.Softmax(dim=1)
# input = torch.randn(2, 3)
# output = m(input)

m = nn.LogSoftmax()
input = torch.randn(2, 3)
output = m(input)
import torch
input=torch.randn(2,2)
input # 每一行代表一个样本,每一列代表该样本属于某一类
---------------------------
tensor([[-0.3549,  1.1395],
        [ 2.1887,  1.0817]])
---------------------------
soft = torch.nn.Softmax(dim=1) # 横向计算softmax
logsoft = torch.nn.LogSoftmax(dim=1) # 横向计算softmax
soft(input) # 将输出转化为概率
---------------------------
tensor([[0.1833, 0.8167],
        [0.7516, 0.2484]])
---------------------------
logsoft(input) # 等价于torch.log(soft_input(input))
-----------------------------
tensor([[-1.6968, -0.2024],
        [-0.2856, -1.3926]])
-----------------------------


API

LogSoftmax(xi)=log(exp(xi)∑jexp(xj))LogSoftmax(x_i)=log(\frac{exp(x_i)}{\sum_jexp(x_j)})LogSoftmax(xi)=log(jexp(xj)exp(xi))
在softmax层外加了log函数

CLASS torch.nn.LogSoftmax(dim: Optional[int] = None)

参考

https://pytorch.org/docs/stable/generated/torch.nn.LogSoftmax.html?highlight=nn%20logsoftmax#torch.nn.LogSoftmax

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值