torch.nn.functional.softmax相关

softmax相关

核心引用:知乎链接
softmax

import torch.nn.functional as F
import torch
truth = torch.tensor([[1, 0, 0]], dtype=torch.float)
predicted1 = torch.tensor([[0.5, 0.4, 0.1]], dtype=torch.float)
print(truth.softmax(0))	#dim=0,每一列的概率之和为1
print(truth.softmax(1)) #dim=1,每一行的概率之和为1
print(F.log_softmax(predicted1, 1))
print(truth.log_softmax(-1))

输出为

tensor([[1., 1., 1.]])
tensor([[0.5761, 0.2119, 0.2119]])
tensor([[-0.9459, -1.0459, -1.3459]])
tensor([[-0.5514, -1.5514, -1.5514]])

第一行:按照列计算只有一个数据,所以计算后每列的只有1个1。
第二行:

\[\begin{aligned} \frac{e^{1}}{e^{1}+e^{0}+e^{0}} &=\frac{e}{e+2}=0.5017 \\ \frac{e^{0}}{e^{1}+e^{0}+e^{0}} &=\frac{1}{e+2}=0.2491 \\ \frac{e^{0}}{e^{1}+e^{0}+e^{0}} &=\frac{1}{e+2}=0.2491 \end{aligned} \]

第四行:

\[\ln (0.5017)=-0.68975 \]

\[\ln (0.2491)=-1.38990 \]

\[\ln (0.2491)=-1.38990 \]

涉及到了log_softmax函数,可以看看这个链接
大概就是取了个对数(等待补全)

posted @ 2021-04-16 22:14  小康要好好学习  阅读(476)  评论(0编辑  收藏  举报