ptorch F.softmax() 梯度信息为None

我在进行一个测试梯度实验的时候,发现,当原始变量流经F.softmax以后,原始变量的梯度就无法获得了,例子如下:

import torch.nn.functional as F
import torch


x = torch.randn(1,5,requires_grad=True)
print(x)
# x = F.softmax(x,dim=1)
# print(x)
l = 0
for i in range(5):
    l = l + x[0][i]

print(l)
l.backward()
print(x.grad)

如果x不经过F.softmax(),则会出现如下的梯度信息:

tensor([[ 1.4093, -0.2620,  0.6668, -0.3897,  1.4681]], requires_grad=True)
tensor(2.8925, grad_fn=<AddBackward0>)
tensor([[1., 1., 1., 1., 1.]])

如果经过了F.softmax(),则x的梯度信息就无法获得了,例子如下:

import torch.nn.functional as F
import torch


x = torch.randn(1,5,requires_grad=True)
print(x)
x = F.softmax(x,dim=1)
print(x)
l = 0
for i in range(5):
    l = l + x[0][i]

print(l)
l.backward()
print(x.grad)

此时的x的梯度为None:

tensor([[ 1.0408,  0.5212,  0.2902, -0.7637, -0.7276]], requires_grad=True)
tensor([[0.4163, 0.2476, 0.1965, 0.0685, 0.0710]], grad_fn=<SoftmaxBackward>)
tensor(1., grad_fn=<AddBackward0>)
None

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值