PyTorch笔记--Softmax函数求导
softmax是非线性激活函数的一种。它将神经元的输出变换到(0,1)的区间内。

需要注意的是
对应的是分子中的指数项,而与分母是无关的。
下面对
进行求导,
这里分为两种情况。
j==i

另一种情况是
j!=i

就是要注意对
求导时,S的分子的指数项哪一项,刚好是
还是别的项,这将直接影响求导的最终结果。

下面使用程序演示;
>>> import torch >>> import torch.nn.functional as F >>> import torch.autograd >>> x = torch.rand(5) >>> x.requires_grad_() >>> S = F.softmax(x, dim=0) >>> S tensor([0.3098, 0.1383, 0.1354, 0.1614, 0.2551], grad_fn=<SoftmaxBackward>) >>> torch.autograd.grad(S[0], x, retain_graph = True) (tensor([ 0.2138, -0.0428, -0.0420, -0.0500, -0.0790]),) >>> torch.autograd.grad(S[1], x, retain_graph = True) (tensor([-0.0428, 0.1192, -0.0187, -0.0223, -0.0353]),) >>> torch.autograd.grad(S[2], x, retain_graph = True) (tensor([-0.0420, -0.0187, 0.1171, -0.0219, -0.0345]),) >>> torch.autograd.grad(S[3], x, retain_graph = True) (tensor([-0.0500, -0.0223, -0.0219, 0.1354, -0.0412]),) >>> torch.autograd.grad(S[4], x) (tensor([-0.0790, -0.0353, -0.0345, -0.0412, 0.1900]),)
其中
torch.autograd.grad(S[0], x, retain_graph = True)
她的含义是S[0]对x进行求导。
我们知道S[0]对x[0]的偏导结果是S[0]*(1-S[0])=0.3098*(1-0.3098)=0.2138
S[0]对x[1]的偏导结果是-S[0]*S[1]=-0.3098*0.1383=-0.0428
S[0]对x[2]的偏导结果是-S[0]*S[2]=-0.3098*0.1354=-0.0420
S[0]对x[3]的偏导结果是-S[0]*S[3]=-0.3098*0.1614=-0.0500
S[0]对x[4]的偏导结果是-S[0]*S[4]=-0.3098*0.2551=-0.0790
所以
(tensor([ 0.2138, -0.0428, -0.0420, -0.0500, -0.0790]),)
就是最后的结果。
其他的同理。

浙公网安备 33010602011771号