pytorch:with torch.no_grad:

觉得这位博主解释得不错:
link

但是目前存在的问题是:

x = torch.randn(n,d_in)
y = torch.randn(n,d_out)

w1 = torch.randn(d_in,H,requires_grad=True)
w2 = torch.randn(H,d_out,requires_grad=True)

lr = 1e-6

epoch = 500

for it in range(2):
    #forward pass
    y_pred = x.mm(w1).clamp(min=0).mm(w2) #output shape : n*d_out
    
    # compute loss
    loss = (y_pred-y).pow(2).sum()
#     print(it,loss)
    
    # backward pass
        #1.compute grad
    loss.backward()
    print('这是第{}次迭代,loss为{},w1.requires_grad:{},w2.requires_grad{}'.format(it+1,loss.item(),w1.requires_grad,w2.requires_grad))
    
        #2.upgrade weights of w1 and w2
    with torch.no_grad():
        w1 -= lr*w1.grad
        w2 = w2-lr*w2.grad
        print('w1.requires_grad:',w1.requires_grad)
        print('w2.requires_grad:',w2.requires_grad)

在这里插入图片描述
可以看到,当自减时,即用‘-=’时,w1经过更新,仍然有grad;但是如果是用常规等式减,w2经过更新,就不再有grad。
所以:
question1:为什么有上述区别?
question2:明明都已经with torch.no_grad了,为什么w1还是有grad?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值