1. 程式人生 > >nn.Softmax()與nn.LogSoftmax()

nn.Softmax()與nn.LogSoftmax()

nn.Softmax()計算出來的值,其和為1,也就是輸出的是概率分佈,具體公式如下:

這保證輸出值都大於0,在0,1範圍內。

而nn.LogSoftmax()公式如下:

由於softmax輸出都是0-1之間的,因此logsofmax輸出的是小於0的數,

softmax求導:

logsofmax求導:

例子:

import torch.nn as nn
import torch
import numpy as np
layer1=nn.Softmax()
layer2=nn.LogSoftmax()

input=np.asarray([2,3])
input=Variable(torch.Tensor(input))

output1=layer1(input)
output2=layer2(input)
print('output1:',output1)
print('output2:',output2)

輸出:

output1: Variable containing:  0.2689  0.7311 [torch.FloatTensor of size 2]

output2: Variable containing: -1.3133 -0.3133 [torch.FloatTensor of size 2]