本文作者: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 - 多GPU训练方式nn.DataParallel与nn.parallel.DistributedDataParallel的区别 阅读924次,点赞0次
- Pytorch - torch.nn.Module的parameters()和named_parameters() 阅读599次,点赞0次
- Pytorch - torch.chunk参数详解与使用 阅读1127次,点赞0次
- Pytorch - 梯度累积/梯度累加trick,在显存有限的情况下使用更大batch_size训练模型 阅读403次,点赞0次
- Pytorch - reshape和view的用法和区别 阅读356次,点赞0次
- Pytorch - torch.distributed.init_process_group函数详解 阅读624次,点赞0次
- Pytorch - 使用torch.matmul()替换torch.einsum('nctw,cd->ndtw',(a,b))算子模式 阅读2277次,点赞1次
- Pytorch - 没有使用with torch.no_grad()造成测试网络时显存爆炸的问题 阅读578次,点赞0次
- Pytorch - 使用torch.onnx.export将Pytorch模型导出为ONNX模型 阅读6993次,点赞0次
- Pytorch - 模型保存与加载以及如何在已保存的模型的基础上继续训练模型 阅读561次,点赞0次
全站随机文章推荐
- 并发与并行的概念和区别 阅读245次,点赞0次
- Python - 不依赖第三方库对类对象进行json序列化与反序列化 阅读1437次,点赞0次
- human3.6m : Download(数据集下载) 阅读26326次,点赞39次
- 资源分享 - Vulkan Cookbook - Work through recipes to unlock the full potential of the next generation graphics API-Vulkan 英文高清PDF下载 阅读2346次,点赞0次
- C++11 - 委托机制的实现TinyDelegate 阅读1482次,点赞0次
- Duilib - RichEdit控件发送textchanged消息 阅读1376次,点赞0次
- C++ - std::map正向遍历与反向遍历的几种方式 阅读4507次,点赞3次
- 资源分享 - Image Content Retargeting - Maintaining Color, Tone, and Spatial Consistency 英文高清PDF下载 阅读1379次,点赞0次
- Centos7 - frp内网穿透,访问内网web服务/访问内网websocket服务 阅读3003次,点赞1次
- Youtube运营 - Youtube中如何删除频道 阅读325次,点赞0次
评论
169