梯度为0,张量依然更新

pytorch使用SGD优化器进行张量优化,张量的梯度为零的部分,依然会进行更新,而且似乎张量的更新并不是依据梯度,这是为什么?

代码如下:

Loss = nn.MSELoss()
user_emb = th.rand((2,3),dtype=th.float32,device='cuda',requires_grad=True)
optim = th.optim.SGD([{'params':user_emb, 'lr':1,'weight_decay':0.1,'momentum':0.}])
pre = user_emb[0].reshape(1,3)
optim.zero_grad()
target = th.ones((1,3),requires_grad=True).cuda()
target = target
loss = Loss(target,pre)
loss.backward()
print('原始的张量为:',user_emb)
print('张量的梯度为:',user_emb.grad)
optim.step()
print('更新后的张量为:',user_emb)

得到结果:

img

你好,我是有问必答小助手,非常抱歉,本次您提出的有问必答问题,技术专家团超时未为您做出解答


本次提问扣除的有问必答次数,将会以问答VIP体验卡(1次有问必答机会、商城购买实体图书享受95折优惠)的形式为您补发到账户。


因为有问必答VIP体验卡有效期仅有1天,您在需要使用的时候【私信】联系我,我会为您补发。