What is the difference between view() and unsqueeze() in Torch?(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() 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Torch 中的 view() 和 unsqueeze() 有什么区别?
基础教程推荐
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
