如何解决如何创建 PyTorch 可变张量?
我正在尝试创建一个张量的副本,如果原始更改,则该副本将更改。
r = torch.tensor(1.0,requires_grad=True)
p = r.clone()
print('before')
print(r)
print(p)
r = r*5
print('after')
print(r)
print(p)
>>>
before
tensor(1.,requires_grad=True)
tensor(1.)
after
tensor(5.,grad_fn=<MulBackward0>)
tensor(1.)
我尝试使用 clone()
、detach()
,甚至只是简单的 p=r
,但没有任何效果。
更新。
试过view
:
r = torch.tensor(1.0,requires_grad=True)
p = r.view(1)
print('before')
print(r)
print(p)
r = r*5
print('after')
print(r)
print(p)
>>>before
tensor(1.,requires_grad=True)
tensor([1.],grad_fn=<ViewBackward>)
after
tensor(5.,grad_fn=<MulBackward0>)
tensor([1.],grad_fn=<ViewBackward>)
解决方法
你要找的是一个视图(它是张量的浅拷贝),numpy也遵循这个,下面包含你想要的
test = torch.tensor([100])
test_copy = test.view(1)
print(test,test_copy) # tensor([100]) tensor([100])
test[0] = 200
test,test_copy # (tensor([200]),tensor([200]))
编辑:进行了一些更改并发现了问题
r = torch.tensor(1.0,requires_grad=True) # Remove requires_grad if you really dont need it
p = r.view(1)
print('before')
print(r)
print(p)
with torch.no_grad(): # Had to use this if not wont be able to do math ops cause gradients are being tracked
# Problem here was that you redeclared a new variable of r so you wiped out the previous reference to the tensor
r.mul_(5) # Simple calculations
print('after')
print(r)
print(p)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。