pytorch0.4学习过程中遇到不知名bug

仅为记录一下自己遇到的bug,方便以后查询。

在使用pytorch的自动求导功能过程中遇到的bug。
以下是能正确运行的代码

import torch

dtype = torch.float
device = torch.device("cpu")

N, D_in, H, D_out = 64, 1000, 100, 10

x = torch.randn(N, D_in, device=device, dtype=dtype)
y = torch.randn(N, D_out, device=device, dtype=dtype)

w1 = torch.randn(D_in, H, device=device, dtype=dtype, requires_grad=True)
w2 = torch.randn(H, D_out, device=device, dtype=dtype, requires_grad=True)

learning_rate = 1e-6
for t in range(500):
    y_pred = x.mm(w1).clamp(min=0).mm(w2)
    loss = (y_pred - y).pow(2).sum()
    if t%100==0:
        print(t, loss.item())
    loss.backward()
    with torch.no_grad():
        w1 -= learning_rate * w1.grad
        w2 -= learning_rate * w2.grad

        w1.grad.zero_()
        w2.grad.zero_()

以下是有问题的代码:

import torch

dtype = torch.float
device = torch.device("cpu")

N, D_in, H, D_out = 64, 1000, 100, 10

x = torch.randn(N, D_in, device=device, dtype=dtype)
y = torch.randn(N, D_out, device=device, dtype=dtype)

w1 = torch.randn(D_in, H, device=device, dtype=dtype, requires_grad=True)
w2 = torch.randn(H, D_out, device=device, dtype=dtype, requires_grad=True)

learning_rate = 1e-6
for t in range(500):
    y_pred = x.mm(w1).clamp(min=0).mm(w2)
    loss = (y_pred - y).pow(2).sum()
    if t%100==0:
        print(t, loss.item())
    loss.backward()
    with torch.no_grad():
        w1 = w1 - learning_rate * w1.grad
        w2 = w2 - learning_rate * w2.grad

        w1.grad.zero_()
        w2.grad.zero_()

以上代码一直报错,具体原因未知:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-16-00ba2e896408> in <module>()
     54 
     55         # Manually zero the gradients after updating weights
---> 56         w1.grad.zero_()
     57         w2.grad.zero_()

AttributeError: 'NoneType' object has no attribute 'zero_'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值