python部分三方库中softmax函数的使用
softmax函数,又称**归一化指数函数。**它是二分类函数sigmoid在多分类上的推广,目的是将多分类的结果以概率的形式展现出来。保证各个输入层(无论正负)通过softmax函数之后以不同的概率(均为整数)输出且和为1。
torch.nn.Function中的softmax
下面公式为该函数的计算实质,确保了概率的种种性质和概率与输入之间的映射关系。
y
i
=
Softmax
(
x
i
)
=
e
x
i
∑
j
e
x
j
y_i=\text{Softmax}(x_{i}) = \frac{e^{x_i}}{\sum_j e^{x_j}}
yi=Softmax(xi)=∑jexjexi
import torch
import torch.nn.functional as F
src=torch.Tensor([0.3,1,-0.9,2,1.3])
print(F.softmax(src))
输出
tensor([0.0869, 0.1750, 0.0262, 0.4757, 0.2362])
torch中的softmax
torch.softmax和torch.nn.functional.softmax是相同的效果,不过torch中需要对维度进行补充
import torch
import torch.nn.functional as F
src=torch.Tensor([0.3,1,-0.9,2,1.3])
print(torch.softmax(src,0))
输出
tensor([0.0869, 0.1750, 0.0262, 0.4757, 0.2362])
torch_geometric.utils中的softmax
该库是计算带有稀疏矩阵的softmax计算,这里传入参数是一个需要计算的张量(类似上面中输入张量)和一个索引张量,索引是稀疏矩阵中特有的。softmax中计算源代码如下。
out = src - scatter(src, index, dim=0, dim_size=N, reduce='max')[index]
out = out.exp()
out_sum = scatter(out, index, dim=0, dim_size=N, reduce='sum')[index]
out= out / (out_sum + 1e-16)
上述代码中N为index中最大值加一(默认计算)。下面对scatter函数进行实验
from torch_scatter import scatter
src = torch.randn(6, 3)
print(src)
index = torch.tensor([0, 1, 0, 1, 2, 1])
out = scatter(src, index, dim=0, reduce="sum")
print(out)
print(out.size())
tensor([[-0.5734, 1.3489, -1.6266],
[ 1.2066, -0.6000, -0.9497],
[-1.5092, 0.8770, 1.2036],
[ 0.5813, 0.2572, 2.7192],
[ 1.3273, 0.2899, -0.2035],
[ 0.6973, 2.9523, 0.3111]])
tensor([[-2.0826, 2.2259, -0.4230],
[ 2.4852, 2.6095, 2.0806],
[ 1.3273, 0.2899, -0.2035]])
torch.Size([3, 3])
scatter函数表示在dim维度上安装index的索引进行分组(index的长度一定要等于src的dim维度上长度),比如上面分为0,1,2三组,即在src的dim维度第0和2组数据为计算相加后的第0组,第1和3组数据为计算相加后的第1组,第4组数据为计算相加后的第2组。
import torch_geometric.utils as geo_utils
src=torch.Tensor([0.3,1,-0.9,2,1.3])
print(src)
index = torch.tensor([0, 1, 0, 1, 2])
out=geo_utils.softmax(src,index)
print(out)
print(out.size())
tensor([ 0.3000, 1.0000, -0.9000, 2.0000, 1.3000])
tensor([0.7685, 0.2689, 0.2315, 0.7311, 1.0000])
torch.Size([5])
因此稀疏矩阵下softmax函数表示在按照index分组下的按照之前的softmax算法一致。