python – 调整PyTorch Tensor的大小

weixin_38062902 2019-09-12 12:20:59
我目前正在使用tensor.resize()函数将张量大小调整为新形状t = t.resize(1,2,3). 这给了我一个弃用警告: non-inplace resize is deprecated 因此,我想切换到tensor.resize_()函数,这似乎是适当的就地替换.但是,这让我有了一个 cannot resize variables that require grad 错误.我可以回过头来 from torch.autograd._functions import Resize Resize.apply(t, (1, 2, 3)) 这是tensor.resize()的作用,以避免弃用警告.这似乎不是一个合适的解决方案,而是对我来说是一个黑客攻击.在这种情况下,如何正确使用tensor.resize_()?
...全文
1310 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_38091479 2019-09-12
  • 打赏
  • 举报
回复
您可以选择使用tensor.reshape或torch.reshape,如下所示: # 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 can be resolved by using `tensor.reshape` 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]])

433

社区成员

发帖
与我相关
我的任务
社区描述
其他技术讨论专区
其他 技术论坛(原bbs)
社区管理员
  • 其他技术讨论专区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧