<input>:1: UserWarning: The .grad attribute of a Tensor that is not a leaf Tensor is being accessed.

博客讲述了在最新版PyTorch中遇到的问题,即在将数据迁移到GPU上后,即使设置了requires_grad=True仍然无法解决问题。原因是旧版的Variable已经过时,现在应使用torch.nn.Parameter。作者提供了修正后的代码,通过将numpy数据转换为torch.nn.Parameter并直接分配到GPU上,成功解决了问题。
摘要由CSDN通过智能技术生成

今天遇到这个问题啊

结果出现这个错误
解决方法很简单
放到gpu上
我把数据放到gpu上 reguires_grad需要重新赋值为True

    self.w_1_p = self.w_1_p.to(device)
    self.w_2_p = self.w_2_p.to(device)
    self.w_3_p = self.w_3_p.to(device)
    self.fc_w = self.fc_w.to(device)

    self.w_1_p.requires_grad = True
    self.w_2_p.requires_grad = True
    self.w_3_p.requires_grad = True
    self.fc_w.requires_grad = True

经过上述并没有解决问题,就算强制设置叶子几点也失败
关键原因在于原来使用的Variable太老了 是之前0.x版本的pytorch
对于最新的pytorch直接使用在自定义参数 而且直接赋值在gpu上
具体代码如下

tmp = sio.loadmat(‘./tmp/afew/w_1.mat’)[‘w_1’]
# self.w_1_p = Variable(torch.from_numpy(tmp), requires_grad=True)
self.w_1_p=torch.nn.Parameter(torch.from_numpy(tmp).cuda())

    tmp = sio.loadmat('./tmp/afew/w_2.mat')['w_2']
    # self.w_2_p = Variable(torch.from_numpy(tmp), requires_grad=True)
    self.w_2_p = torch.nn.Parameter(torch.from_numpy(tmp).cuda())

    tmp = sio.loadmat('./tmp/afew/w_3.mat')['w_3']
    # self.w_3_p = Variable(torch.from_numpy(tmp), requires_grad=True)
    self.w_3_p = torch.nn.Parameter(torch.from_numpy(tmp).cuda())

    tmp = sio.loadmat('./tmp/afew/fc.mat')['theta']
    # self.fc_w = Variable(torch.from_numpy(tmp.astype(np.float64)), requires_grad=True)
    self.fc_w = torch.nn.Parameter(torch.from_numpy(tmp).cuda())

原始的代码都是numpy写的,torch 的gpu计算也有类似的,不需要转换

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值