【发布时间】:2020-06-25 02:51:20
【问题描述】:
我正在尝试将张量从 (3,3) 缩小到 (1, 1),但我想保留原始张量:
import torch
a = torch.rand(3, 3)
a_copy = a.clone()
a_copy.resize_(1, 1)
我的初始张量中需要requires_grad=True,但 PyTorch 禁止我尝试调整副本大小:
a = torch.rand(3, 3, requires_grad=True)
a_copy = a.clone()
a_copy.resize_(1, 1)
抛出错误:
Traceback (most recent call last):
File "pytorch_test.py", line 7, in <module>
a_copy.resize_(1, 1)
RuntimeError: cannot resize variables that require grad
克隆和分离
我也试过.clone() 和.detach():
a = torch.rand(3, 3, requires_grad=True)
a_copy = a.clone().detach()
with torch.no_grad():
a_copy.resize_(1, 1)
这会给出这个错误:
Traceback (most recent call last):
File "pytorch_test.py", line 14, in <module>
a_copy.resize_(1, 1)
RuntimeError: set_sizes_contiguous is not allowed on a Tensor created from .data or .detach().
If your intent is to change the metadata of a Tensor (such as sizes / strides / storage / storage_offset)
without autograd tracking the change, remove the .data / .detach() call and wrap the change in a `with torch.no_grad():` block.
For example, change:
x.data.set_(y)
to:
with torch.no_grad():
x.set_(y)
与no_grad()
因此,按照他们在错误消息中的说明,我删除了.detach() 并改用no_grad():
a = torch.rand(3, 3, requires_grad=True)
a_copy = a.clone()
with torch.no_grad():
a_copy.resize_(1, 1)
但它仍然给我一个关于 grad 的错误:
Traceback (most recent call last):
File "pytorch_test.py", line 21, in <module>
a_copy.resize_(1, 1)
RuntimeError: cannot resize variables that require grad
类似问题
我查看了Resize PyTorch Tensor,但该示例中的张量保留了所有原始值。 我还查看了Pytorch preferred way to copy a tensor,这是我用来复制张量的方法。
我使用的是 PyTorch 1.4.0 版
【问题讨论】:
-
您是否尝试过先分离再克隆:
a_copy = a.detach().clone()? -
@AndreasK。不...我刚刚尝试过,它有效