公式:
注意事项1:
0 值进行softmax后还应是0的问题:
x = torch.tensor([[0,1],[2,3]]).type(dtype=torch.float32)
x
Out[92]:
tensor([[0., 1.],
[2., 3.]])
对这个张量应用softmax
得到:
Out[93]:
tensor([[0.2689, 0.7311],
[0.2689, 0.7311]])
但我希望0 值softmax
后应该是0啊。
改写:
x = torch.tensor([[0,1],[2,3]]).type(dtype=torch.float32)
F.softmax(torch.where(x>0, x, -9e10*torch.ones_like(x)),dim=1)
Out[103]:
tensor([[0.0000, 1.0000],
[0.2689, 0.7311]])
也就是在softmax之前,将0用极小负值替换。
注意事项2
超界:
可以看出,但x极大时候,softmax
分子分母会超出计算机运算界限,如何处理,需要在softmax
之前减去张量最大值。
x = torch.tensor([[1000000,1216464],[1541212,22454578]]).type(dtype=torch.float32)
F.softmax(x-x.max(), dim=1)
Out[111]:
tensor([[0., 1.],
[0., 1.]])