PyTorch中 tensor.detach() 和 tensor.data 的区别详解

yipeiwu_com6年前Python基础

PyTorch0.4中,.data 仍保留,但建议使用 .detach(), 区别在于 .data 返回和 x 的相同数据 tensor, 但不会加入到x的计算历史里,且require s_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: one of the variables needed for gradient
computation has been modified by an

以上这篇PyTorch中 tensor.detach() 和 tensor.data 的区别详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Django中使用第三方登录的示例代码

Django中使用第三方登录的示例代码

OAuth2.0是什么  OAuth的英文全称是Open Authorization,它是一种开放授权协议。OAuth目前共有2个版本,2007年12月的1.0版(之后有一个修...

总结用Pdb库调试Python的方式及常用的命令

用Pdb调试有多种方式 使用 Pdb调试 Python的程序的方式主要是下面的三种!下面逐一介绍 命令行加-m参数 命令行启动目标程序,加上-m参数,这样调用 testPdb.py的...

Python定时发送消息的脚本:每天跟你女朋友说晚安

Python定时发送消息的脚本:每天跟你女朋友说晚安

首先 你要有个女朋友 效果: 需要安装几个包 pip install wxpy pip install wechat_sender pip install request...

对python中assert、isinstance的用法详解

1. assert 函数说明: Assert statements are a convenient way to insert debugging assertions into a...

Python 使用folium绘制leaflet地图的实现方法

Python 使用folium绘制leaflet地图的实现方法

leaflet为R语言提供了API很好用,这次尝试用Python使用leaflet,需要folium 安装folium pip install folium 一个小例子 imp...