栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

PyTorch学习笔记(三):Tensor变换

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

PyTorch学习笔记(三):Tensor变换

view/reshape
a = torch.rand(4,1,28,28)
print(a.shape)                     # torch.Size([4, 1, 28, 28])
print(a.view(4, 28*28).shape)      # torch.Size([4, 784])
print(a.reshape(4, 28*28).shape)   # torch.Size([4, 784])
print(a.view(4, -1).shape)         # torch.Size([4, 784])
print(a.reshape(4, -1).shape)      # torch.Size([4, 784])
squeeze/unsqueeze
a = torch.rand(4,1,28,28)
print(a.shape)                  # torch.Size([4, 1, 28, 28])
print(a.unsqueeze(0).shape)     # torch.Size([1, 4, 1, 28, 28])
print(a.unsqueeze(4).shape)     # torch.Size([4, 1, 28, 28, 1])
print(a.unsqueeze(-1).shape)    # torch.Size([4, 1, 28, 28, 1])
print(a.squeeze().shape)        # torch.Size([4, 28, 28])
print(a.squeeze(1).shape)       # torch.Size([4, 28, 28])
transpose/permute
a = torch.rand(10,3,32,32)
print(a.shape)                    # torch.Size([10, 3, 32, 32])
print(a.transpose(1,3).shape)     # torch.Size([10, 32, 32, 3])
print(a.permute(0,3,2,1).shape)   # torch.Size([10, 32, 32, 3])
expand/repeat
b = torch.randint(1, 10, (1, 3))
print(b)
print(b.shape)
print(b.storage())              # 数据存放形式
print(b.storage().data_ptr())   # 地址
# 输出
tensor([[7, 8, 9]])
torch.Size([1, 3])
 7
 8
 9
[torch.LongStorage of size 3]
2530665948608

# expand: broadcasting
b_1 = b.expand(3, 3)
print(b_1)
print(b_1.shape)
print(b_1.storage())
print(b_1.storage().data_ptr())
# 输出
tensor([[7, 8, 9],
        [7, 8, 9],
        [7, 8, 9]])
torch.Size([3, 3])
 7
 8
 9
[torch.LongStorage of size 3]
2530665948608

# repeat: memory copied
b_2 = b.repeat(3, 1)
print(b_2)
print(b_2.shape)
print(b_2.storage())
print(b_2.storage().data_ptr())
# 输出
tensor([[7, 8, 9],
        [7, 8, 9],
        [7, 8, 9]])
torch.Size([3, 3])
 7
 8
 9
 7
 8
 9
 7
 8
 9
[torch.LongStorage of size 9]
2530678187136
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/618774.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号