NJU1healer的个人博客分享 http://blog.sciencenet.cn/u/NJU1healer

博文

Pytorch中的Squeeze()和Unsqueeze()函数

已有 10485 次阅读 2020-9-24 19:37 |个人分类:Python|系统分类:科研笔记

1. unsqueeze()

该函数用来增加某个维度。在PyTorch中维度是从0开始的。

import torch

a = torch.arange(0, 9)

print(a)

结果:

tensor([0, 1, 2, 3, 4, 5, 6, 7, 8])

利用view()改变tensor的形状。值得注意的是view不会修改自身的数据,返回的新tensor与源tensor共享内存;同时必须保证前后元素总数一致。

a = a.view(3, 3)

print(f"a:{a} \n shape:{a.shape}")

结果:

a:tensor([[0, 1, 2],

        [3, 4, 5],

        [6, 7, 8]]) 

 shape:torch.Size([3, 3])

在第一个维度(即维度序号为0)前增加一个维度。

a = a.unsqueeze(0)

print(f"a:{a}\nshape:{a.shape}")

结果:


a:tensor([[[0, 1, 2],

         [3, 4, 5],

         [6, 7, 8]]])

shape:torch.Size([1, 3, 3])

同理,可在其他位置添加维度,在这里就不举例了。

2. squeeze()

该函数用来减少某个维度。

print(f"1.   a:{a}\nshape:{a.shape}")

a = a.unsqueeze(0)

a = a.unsqueeze(2)

print(f"2.   a:{a}\nshape:{a.shape}")

a = a.squeeze(2)

print(f"3.   a:{a}\nshape:{a.shape}")

结果:

1.   a:tensor([[0, 1, 2],

        [3, 4, 5],

        [6, 7, 8]])

shape:torch.Size([3, 3])

2.   a:tensor([[[[0, 1, 2]],


         [[3, 4, 5]],


         [[6, 7, 8]]]])

shape:torch.Size([1, 3, 1, 3])

3.   a:tensor([[[0, 1, 2],

         [3, 4, 5],

         [6, 7, 8]]])

shape:torch.Size([1, 3, 3])

更多实例参考博客https://www.cnblogs.com/chen-hw/p/11678949.html

点滴分享,福泽你我!Add oil!



https://wap.sciencenet.cn/blog-3428464-1251944.html

上一篇:Python的Tqdm模块—进度条配置
下一篇:PyTorch中permute的用法
收藏 IP: 103.149.249.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

全部作者的其他最新博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-3-28 17:20

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部