微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何创建 PyTorch 可变张量?

如何解决如何创建 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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?