Torch 中的 view() 和 unsqueeze() 有什么区别? [英] What is the difference between view() and unsqueeze() in Torch?

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

问题描述

使用unsqueeze():

input = torch.Tensor(2, 4, 3) # input: 2 x 4 x 3print(input.unsqueeze(0).size()) # 打印 - torch.size([1, 2, 4, 3])

使用视图():

input = torch.Tensor(2, 4, 3) # input: 2 x 4 x 3打印(input.view(1, -1, -1, -1).size()) # 打印 - torch.size([1, 2, 4, 3])

根据文档,unsqueeze() 在作为参数给出的位置插入单例 dim,view() 创建一个具有与 相关联的不同存储维度的视图张量.

view() 的作用对我来说很清楚,但我无法将它与 unsqueeze() 区分开来.而且,我不明白什么时候用 view() 什么时候用 unsqueeze()?

任何有好的解释的帮助将不胜感激!

解决方案

view() 只能接受一个 -1 参数.

因此,如果您想添加单个维度,则需要提供所有维度作为参数.例如,如果 A 是一个 2x3x4 张量,要添加单例维度,您需要执行 A:view(2, 1, 3, 4).>

但是,有时在使用操作时,输入的维度是未知的.因此,我们不知道 A 是 2x3x4,但我们仍然想插入一个单例维度.当使用小批量张量时,这种情况经常发生,其中最后一个维度通常是未知的.在这些情况下,nn.Unsqueeze 很有用,它让我们在编写代码时无需明确意识到其他维度即可插入维度.

Use of unsqueeze():

input = torch.Tensor(2, 4, 3) # input: 2 x 4 x 3
print(input.unsqueeze(0).size()) # prints - torch.size([1, 2, 4, 3])

Use of view():

input = torch.Tensor(2, 4, 3) # input: 2 x 4 x 3
print(input.view(1, -1, -1, -1).size()) # prints - torch.size([1, 2, 4, 3])

According to documentation, unsqueeze() inserts singleton dim at position given as parameter and view() creates a view with different dimensions of the storage associated with tensor.

What view() does is clear to me, but I am unable to distinguish it from unsqueeze(). Moreover, I don't understand when to use view() and when to use unsqueeze()?

Any help with good explanation would be appreciated!

解决方案

view() can only take a single -1 argument.

So, if you want to add a singleton dimension, you would need to provide all the dimensions as arguments. For e.g., if A is a 2x3x4 tensor, to add a singleton dimension, you would need to do A:view(2, 1, 3, 4).

However, sometimes, the dimensionality of the input is unknown when the operation is being used. Thus, we dont know that A is 2x3x4, but we would still like to insert a singleton dimension. This happens a lot when using minibatches of tensors, where the last dimension is usually unknown. In these cases, the nn.Unsqueeze is useful and lets us insert the dimension without explicitly being aware of the other dimensions when writing the code.

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

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