pytorch 中的 reshape 和 view 有什么区别? [英] What's the difference between reshape and view in pytorch?

查看:14
本文介绍了pytorch 中的 reshape 和 view 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 numpy 中,我们使用 ndarray.reshape() 来重塑数组.

In numpy, we use ndarray.reshape() for reshaping an array.

我注意到在 pytorch 中,人们出于同样的目的使用 torch.view(...),但同时,还有一个 torch.reshape(...) 存在.

I noticed that in pytorch, people use torch.view(...) for the same purpose, but at the same time, there is also a torch.reshape(...) existing.

所以我想知道它们之间有什么区别以及何时应该使用它们中的任何一个?

So I am wondering what the differences are between them and when I should use either of them?

推荐答案

torch.view 已经存在很长时间了.它将返回一个具有新形状的张量.返回的张量将与原始张量共享底层数据.请参阅此处的文档.

torch.view has existed for a long time. It will return a tensor with the new shape. The returned tensor will share the underling data with the original tensor. See the documentation here.

另一方面,似乎torch.reshape 已经最近在 0.4 版中引入.根据文档,此方法将

On the other hand, it seems that torch.reshape has been introduced recently in version 0.4. According to the document, this method will

返回一个张量,其数据和元素数量与输入相同,但具有指定的形状.如果可能,返回的张量将是输入的视图.否则,它将是一个副本.连续输入和具有兼容步幅的输入可以在不复制的情况下重新整形,但您不应依赖于复制与查看行为.

Returns a tensor with the same data and number of elements as input, but with the specified shape. When possible, the returned tensor will be a view of input. Otherwise, it will be a copy. Contiguous inputs and inputs with compatible strides can be reshaped without copying, but you should not depend on the copying vs. viewing behavior.

这意味着 torch.reshape 可能会返回原始张量的副本或视图.您不能指望它返回视图或副本.根据开发者的说法:

It means that torch.reshape may return a copy or a view of the original tensor. You can not count on that to return a view or a copy. According to the developer:

如果您需要副本,请使用 clone() 如果您需要相同的存储,请使用 view().reshape() 的语义是它可能会或可能不会共享存储并且您事先不知道.

if you need a copy use clone() if you need the same storage use view(). The semantics of reshape() are that it may or may not share the storage and you don't know beforehand.

另一个区别是 reshape() 可以对连续和非连续张量进行操作,而 view() 只能对连续张量进行操作.另请参阅此处,了解contiguous 的含义.

Another difference is that reshape() can operate on both contiguous and non-contiguous tensor while view() can only operate on contiguous tensor. Also see here about the meaning of contiguous.

这篇关于pytorch 中的 reshape 和 view 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆