调整 PyTorch 张量大小

14

我目前正在使用 tensor.resize() 函数将张量调整为新的形状 t = t.resize(1, 2, 3)

这会给我一个弃用警告:

非就地调整大小已被弃用

因此,我想切换到 tensor.resize_() 函数,它似乎是适当的就地替换。然而,这让我遇到了一个

无法调整需要梯度的变量

错误。 我可以退回到

from torch.autograd._functions import Resize
Resize.apply(t, (1, 2, 3))

这就是为了避免过时警告而使用的tensor.resize()的作用。但我认为这似乎不是一个合适的解决方案,而是一个hack。 在这种情况下,应该如何正确使用tensor.resize_()呢?


你确定要使用resize张量,而不是reshape吗?如果你想调整它的大小,那么使用resize会有哪些优势,而用切片操作又不能实现什么呢? - MBT
我认为你说得有道理。实际上,既然你提到了,我意识到我可能一开始就应该使用reshape。以下是操作前后的t.size()输出:torch.Size([16, 512, 8, 10, 2])和torch.Size([16, 512, 8, 20])。 - LL_
是的,我认为你可以直接使用viewreshape(从版本0.4.0开始)。 - MBT
3个回答

13
你可以选择使用 tensor.reshape(new_shape)torch.reshape(tensor, new_shape),例如:
# a `Variable` tensor
In [15]: ten = torch.randn(6, requires_grad=True)

# this would throw RuntimeError error
In [16]: ten.resize_(2, 3)
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-16-094491c46baa> in <module>()
----> 1 ten.resize_(2, 3)

RuntimeError: cannot resize variables that require grad
以上的 RuntimeError 可以通过使用 tensor.reshape(new_shape) 来解决或避免。
In [17]: ten.reshape(2, 3)
Out[17]: 
tensor([[-0.2185, -0.6335, -0.0041],
        [-1.0147, -1.6359,  0.6965]])

# yet another way of changing tensor shape
In [18]: torch.reshape(ten, (2, 3))
Out[18]: 
tensor([[-0.2185, -0.6335, -0.0041],
        [-1.0147, -1.6359,  0.6965]])

1
正如评论中@blue-phoenox所提到的,我尝试实现的确实是重塑(reshape)而不是调整大小(resize)。我实现了这里建议的解决方案,它运行得非常好! - LL_
1
附带说明:我使用了tensor.reshape()函数,因为它更易读! - LL_

1

Please can you try something like:

import torch
x = torch.tensor([[1, 2], [3, 4], [5, 6]])
print(":::",x.resize_(2, 2))
print("::::",x.resize_(3, 3))

0

如果您不想更改数据,只需使用t = t.contiguous().view(1, 2, 3)

如果不是这种情况,就会破坏t的梯度计算图的就地resize_操作。
如果您不在意,只需使用t = t.data.resize_(1,2,3)即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接