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
。
本文作者:StubbornHuang
版权声明:本文为站长原创文章,如果转载请注明原文链接!
原文标题:Pytorch – reshape和view的用法和区别
原文链接:https://www.stubbornhuang.com/2442/
发布于:2022年12月09日 9:58:05
修改于:2023年06月21日 17:44:35
当前分类随机文章推荐
- Pytorch - pad_sequence、pack_padded_sequence、pack_sequence、pad_packed_sequence参数详解与使用 阅读1634次,点赞0次
- Pytorch - 一文搞懂如何使用Pytorch构建与训练自定义深度学习网络(数据集自定义与加载,模型训练,模型测试,模型保存与加载) 阅读1380次,点赞2次
- Pytorch - 用Pytorch实现ResNet 阅读1022次,点赞0次
- Pytorch - torch.optim优化器 阅读1167次,点赞0次
- Pytorch - 模型微调时删除原有模型中的某一层的方法 阅读3323次,点赞0次
- Pytorch - 检测CUDA、cuDNN以及GPU版本的Pytorch是否安装成功、GPU显存测试 阅读4839次,点赞1次
- Pytorch – 使用torch.matmul()替换torch.einsum('bhxyd,md->bhxym',(a,b))算子模式 阅读1678次,点赞0次
- Pytorch - transpose和permute函数的区别和用法 阅读1795次,点赞0次
- 深度学习 - 我的深度学习项目代码文件组织结构 阅读1845次,点赞3次
- Pytorch - 多GPU训练方式nn.DataParallel与nn.parallel.DistributedDataParallel的区别 阅读1522次,点赞0次
全站随机文章推荐
- OnnxRuntime - C++捕获OnnxRuntime中的异常 阅读82次,点赞0次
- ThreeJS - FBXLoader: TGA loader not found, creating placeholder texture for ... 阅读1066次,点赞0次
- 资源分享 - Game Programming Gems 4 英文高清PDF下载 阅读2641次,点赞1次
- 资源分享 - 深入应用C++ 11代码优化与工程级应用(祁宇著)PDF下载 阅读6897次,点赞1次
- WordPress - 为文章添加自定义字段,在文章编辑页面增加编辑面板 阅读198次,点赞0次
- 资源分享 - C++程序设计语言(第4部分 标准库),原书第4版 高清PDF下载 阅读3424次,点赞2次
- 资源分享 - Practical Linear Algebra - A Geometry Toolbox , Fourth Edition 英文高清PDF下载 阅读1754次,点赞0次
- 资源分享 - Graphics Shaders - Theory and Practice (Second Edition) 英文高清PDF下载 阅读2665次,点赞0次
- Python - 配置Yolov5出现ImportError: cannot import name 'PILLOW_VERSION' from 'PIL'错误 阅读1735次,点赞0次
- Python - 爬取直播吧首页重要赛事赛程信息 阅读645次,点赞0次
评论
169