赞
踩
记录一下训练过程中遇到的问题,由于这个问题我花了很长时间才解决,所以值得记录。
先给出结论:tensor转换成numpy后会丢失梯度,导致回传出现问题
由于原代码不容易理解,简单用个例子说明
- import torch
- from torch.autograd import Variable
-
- input=Variable(torch.tensor([1,2,3.]))
- input.requires_grad=True
- input_numpy=input.detach().numpy()
- x=input_numpy*2
- x_tensor=torch.from_numpy(x)
- output=x_tensor.sum()
- output.requires_grad=True # 没有会报错
- output.backward()
- print(input.grad)
>> None
心得:写代码的时候不知道为啥(可能是脑子抽了),把tensor转成numpy去计算了,实际上numpy能操作的tensor也可以,没必要转化,反而给自己留下了坑。
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。