PyTorch中 tensor.detach() 和 tensor.data 的区别详解
PyTorch0.4中,.data仍保留,但建议使用.detach(),区别在于.data返回和x的相同数据tensor,但不会加入到x的计算历史里,且requires_grad=False,这样有些时候是不安全的,因为x.data不能被autograd追踪求微分。
.detach()返回相同数据的tensor,且requires_grad=False,但能通过in-place操作报告给autograd在进行反向传播的时候.
举例:
tensor.data
>>>a=torch.tensor([1,2,3.],requires_grad=True) >>>out=a.sigmoid() >>>c=out.data >>>c.zero_() tensor([0.,0.,0.]) >>>out#out的数值被c.zero_()修改 tensor([0.,0.,0.]) >>>out.sum().backward()#反向传播 >>>a.grad#这个结果很严重的错误,因为out已经改变了 tensor([0.,0.,0.])
tensor.detach()
>>>a=torch.tensor([1,2,3.],requires_grad=True) >>>out=a.sigmoid() >>>c=out.detach() >>>c.zero_() tensor([0.,0.,0.]) >>>out#out的值被c.zero_()修改!! tensor([0.,0.,0.]) >>>out.sum().backward()#需要原来out得值,但是已经被c.zero_()覆盖了,结果报错 RuntimeError:oneofthevariablesneededforgradient computationhasbeenmodifiedbyan
以上这篇PyTorch中tensor.detach()和tensor.data的区别详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。