本文作者:StubbornHuang
版权声明:本文为站长原创文章,如果转载请注明原文链接!
原文标题:Pytorch – reshape和view的用法和区别
原文链接:https://www.stubbornhuang.com/2442/
发布于:2022年12月09日 9:58:05
修改于:2022年12月09日 9:58:05

1 torch.reshape
形式
torch.reshape(input, shape)
功能
返回一个与输入张量数据和元素数相同的,但是形状为shape的张量。
参数
- input:需要被重新定义形状的输入张量
- shape:新的形状
使用示例
import torch
if __name__ == '__main__':
a = torch.arange(0, 16)
print(a)
b = torch.reshape(a, shape=(4, 4))
print(b)
输出
tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
2 torch.view
形式
Tensor.view(*shape)
功能
返回一个新的张量,其数据与自张量相同,但形状不同。
返回的张量与输入向量共享相同的数据,具有相同数量的元素,但是可能拥有不同的形状。
参数
- shape:需要修改的形状
使用示例
import torch
if __name__ == '__main__':
a = torch.arange(0, 16)
print(a)
b = a.view(4, 4)
print(b)
输出
tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
3 reshape和view二者的区别
Pytorch的reshape
和view
这两个函数的作用是一模一样,但是两者还是有区别的。
在Pytorch的关于view的官方文档有这么一段话
When it is unclear whether a
view()
can be performed, it is advisable to usereshape()
, which returns a view if the shapes are compatible, and copies (equivalent to callingcontiguous()
) otherwise.
意思是当你搞不清是不是可以使用view
时,那么建议使用reshape
。
区别:
view
只能用在contiguous的张量上,但是reshape
没有这个限制;-
如果在
view
之前使用了transpose
或者permute
等操作,那么需要接一个.contiguous()
操作返回一个contiguous copy,才能使用view
算子。 -
view
输出的Tensor与输入Tensor共享内存。
简单的说,tensor.reshape
可以看做是tensor.contiguous().view
,所以尽可能的使用reshape
,而不是view
。
当前分类随机文章推荐
- Pytorch - nn.Transformer、nn.TransformerEncoderLayer、nn.TransformerEncoder、nn.TransformerDecoder、nn.TransformerDecoder参数详解 阅读1356次,点赞1次
- Pytorch - torch.nn.Conv1d参数详解与使用 阅读1150次,点赞0次
- Pytorch - 梯度累积/梯度累加trick,在显存有限的情况下使用更大batch_size训练模型 阅读122次,点赞0次
- Pytorch – 使用torch.matmul()替换torch.einsum('bhxyd,md->bhxym',(a,b))算子模式 阅读781次,点赞0次
- Pytorch - transpose和permute函数的区别和用法 阅读967次,点赞0次
- Pytorch - torch.cat参数详解与使用 阅读921次,点赞1次
- Pytorch - reshape和view的用法和区别 阅读85次,点赞0次
- Pytorch - 没有使用with torch.no_grad()造成测试网络时显存爆炸的问题 阅读290次,点赞0次
- Python - list/numpy/pytorch tensor相互转换 阅读1461次,点赞0次
- Pytorch - 使用opencv-python解码视频文件并将视频帧转换为Pytorch tensor作为网络模型输入数据 阅读2145次,点赞0次
全站随机文章推荐
- 资源分享 - Game Programming Gems 3 英文高清PDF下载 阅读1913次,点赞0次
- 资源分享 - 3D Engine Design for Virtual Globes 英文高清PDF下载 阅读1639次,点赞0次
- C++ - GBK编码下的全角字符转半角字符 阅读1365次,点赞0次
- Github - 如何进行Pull requests 阅读513次,点赞0次
- 资源分享 - Game Programming Patterns 英文高清PDF下载 阅读1371次,点赞0次
- 书籍翻译 – Fundamentals of Computer Graphics, Fourth Edition,第5章 Linear Algebra中文翻译 阅读1295次,点赞4次
- 资源分享 - 机器学习 (西瓜书) 周志华著PDF下载 阅读28072次,点赞30次
- 资源分享 - Practical Linear Algebra - A Geometry Toolbox , Third Edition 英文高清PDF下载 阅读880次,点赞0次
- Modern OpenGL从零开始 - 从茫茫多的OpenGL第三方库讲起 阅读3310次,点赞1次
- 资源分享 - Game Programming Gems 2 英文高清PDF下载 阅读1741次,点赞0次
评论
164