导读 | log_softmax 是计算损失的时候常用的一个函数,那么这个函数的内部到底是怎么做到的呢?这里详细的解释一下。 |
写代码前,回忆一下log_softmax的公式 − l o g e x p ( p j ) ∑ i e x p ( p i ) -log\frac{exp(p_j)}{\sum_{i}exp(p_i)} −log∑iexp(pi)exp(pj)
代码
'''自己实现log_softmax 函数 (1)使用torch.exp()函数计算各个logit的e次幂 (2)使用torch.sum()函数计算求和 (3)使用torch.log对比例求对数 可以发现,二者最终的结果是相同的 ''' import torch as t import torch.nn.functional as F logit = t.tensor([0.1,0.1,0.1,0.7]) a = t.exp(logit) print("a=",a) b = t.sum(a,dim=0,keepdim=True) print("b=",b) c=t.log(a/b) print(c) print(F.log_softmax(logit))
执行结果:
二者是相同的。所以以后想用的话,可以直接使用log_softmax()函数即可,就不用再分开搞了。
原文来自:https://blog.51cto.com/lawsonabs/4848368
本文地址:https://www.linuxprobe.com/pytorch-log_softmax.html编辑:xiangping wu,审核员:逄增宝
Linux命令大全:https://www.linuxcool.com/
Linux系统大全:https://www.linuxdown.com/
红帽认证RHCE考试心得:https://www.rhce.net/