【问题标题】:Resize PyTorch Tensor调整 PyTorch 张量的大小
【发布时间】:2018-11-16 00:00:37
【问题描述】:

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

这给了我一个弃用警告:

不推荐使用非就地调整大小

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

无法调整需要 grad 的变量的大小

错误。 我可以退回到

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

这是 tensor.resize() 为避免弃用警告所做的。 这似乎不是一个合适的解决方案,而是对我来说是一种黑客行为。 在这种情况下如何正确使用tensor.resize_()?

【问题讨论】:

  • 您确定要使用调整张量大小而不是重塑形状吗?如果你想调整它的大小,有什么可以通过调整大小归档的,还有什么是使用切片操作无法实现的?
  • 我认为你说得有道理。实际上,既然您提到它,我意识到我可能应该首先使用 reshape 。这是t.size()在操作前后的输出:torch.Size([16, 512, 8, 10, 2]) 和torch.Size([16, 512, 8, 20])
  • 是的,所以我认为您可以使用 view 或 reshape(从 0.4.0 版本开始)。

标签: python runtime-error pytorch tensor deprecation-warning


【解决方案1】:

您可以选择使用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

使用tensor.reshape(new_shape)可以解决或避免上述RuntimeError

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]])

【讨论】:

  • 正如@blue-phoenox 在 cmets 中已经指出的那样,我试图实现的确实是重塑而不是调整大小。我实施了这里建议的解决方案,效果很好!
  • 附带说明:我使用了tensor.reshape() 函数,因为它更易于阅读!
【解决方案2】:

请您尝试以下方法:

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

【讨论】:

    【解决方案3】:

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

    如果不是这样,就地 resize_ 操作将破坏 t 的 grad 计算图。
    如果你没关系,就用t = t.data.resize_(1,2,3)。

    【讨论】:

      猜你喜欢
      • 2020-02-28
      • 1970-01-01
      • 2015-06-08
      • 1970-01-01
      • 1970-01-01
      • 2019-04-21
      • 2020-08-31
      • 1970-01-01
      • 2020-06-25
      相关资源
      最近更新 更多