pytorch tensor(.data,.clone(),.detach())区别

clone()是不内存共享的。
clone()得到的Tensor不仅拷贝了原始的value,而且会计算梯度传播信息,copy_()只拷贝数值。对b处理,grad会返回到a身上。但是b 不会有 grad 属性。

b = a.clone()#a经过克隆得到b,
c = (b ** 2).mean()#
c.backward()
print('a_grad:', a.grad)#但是梯度传播没有因此中断
a_grad: tensor([ 0.4000,  0.8000,  1.2000,  1.6000,  2.0000])
1
So if you want to copy a tensor and detach from the computation graph you should be using
y = x.clone().detach()
Since it is the cleanest and most readable way. With all other version there is some hidden logic and it is also not 100% clear what happens to the computation graph and gradient propagation.

x.data 与 x.detach() 返回的 tensor 有相同的地方, 也有不同的地方:
相同:
都和 x 共享同一块数据
都和 x 的 计算历史无关
requires_grad = False
不同:
y=x.data 在某些情况下不安全, 某些情况, 指的就是 上述 inplace operation 的第二种情况

detach用法:
如果我们有两个网络 A,B , 两个关系是这样的 y=A(x),z=B(y) 现在我们想用 z.backward() 来为 B 网络的参数来求梯度,但是又不想求 A 网络参数的梯度。
#y=A(x), z=B(y) 求B中参数的梯度,不求A中参数的梯度
#第一种方法
y = A(x)
z = B(y.detach())
z.backward()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值