[pytorch]极易犯错的问题

15 篇文章 0 订阅
6 篇文章 0 订阅

一 x.clone()

错误:

import torch
x = torch.randn(5)
print(x)
y = x.clone()
x =x*12

print(y)

tensor([-0.0455,  0.9827, -0.7915,  0.8110,  1.1524])
tensor([-0.0455,  0.9827, -0.7915,  0.8110,  1.1524])

正确:

import torch
x = torch.randn(5)
print(x)
y = x.clone()
z =x*12

print(z)

tensor([ 1.7743, -2.0879,  0.4297, -0.3849, -0.6147])
tensor([ 21.2920, -25.0553,   5.1562,  -4.6190,  -7.3768])
class A(nn.Module):
    def __init__(self):
        super().__init__()
        self.m = nn.Identity()  #nn.Linear(12, 12)

    def forward(self, x):
        print(f'old x:{x}')
        y = x  #==> .clone()
        x = self.m(x)*12
        print(f'new x:{x}')
        print(f'res y:{y}')

        return

A()(torch.randn(12))

old x:tensor([-0.0204,  0.5557,  2.1049, -1.2744, -1.0640,  1.2480, -2.2674, -0.6850,
         0.0507, -0.9022, -0.2756, -0.1572])
new x:tensor([ -0.2450,   6.6683,  25.2586, -15.2927, -12.7677,  14.9765, -27.2085,
         -8.2195,   0.6080, -10.8261,  -3.3074,  -1.8865])
res y:tensor([-0.0204,  0.5557,  2.1049, -1.2744, -1.0640,  1.2480, -2.2674, -0.6850,
         0.0507, -0.9022, -0.2756, -0.1572])

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

放飞自我的Coder

你的鼓励很棒棒哦~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值