从零开始深度学习Pytorch笔记(5)——张量的索引与变换

小黄用python

共 1631字,需浏览 4分钟

 · 2020-01-19

0ac5f713b9c3b4f9f1b0518cdda4833a.webp889b35608fc061f8f8fbedde501111bd.webp前文传送门:从零开始深度学习Pytorch笔记(1)——安装Pytorch从零开始深度学习Pytorch笔记(2)——张量的创建(上)从零开始深度学习Pytorch笔记(3)——张量的创建(下)从零开始深度学习Pytorch笔记(4)——张量的拼接与切分
在该系列的上一篇,我们介绍了更多Pytorch中的张量的拼接与切分,本文研究张量的索引与变换。张量的索引

import torch
使用torch.masked_select()索引
torch.masked_select(input, mask, out=None)
其中:
input: 要索引的张量mask: 与input同形状的布尔类型张量
t = torch.randint(0,12,size=(4,3))
mask = t.ge(6#ge是greater than or equal ,gt是greater than , le   lt 
t_select = torch.masked_select(t,mask)
print(t,'\n',mask,'\n',t_select)#将大于等于6的数据挑出来,返回一维张量
b9b114bad4006dd4d451d98c5d2a334f.webp张量变换
使用torch.reshape()变换变换张量的形状torch.reshape(input, shape)参数:input: 要变换的张量shape: 新张量的形状
t = torch.randperm(10)
t1 = torch.reshape(t,(2,5))
print(t,'\n',t1)
cfd7e6565756b0c2ea1f52840d153a1f.webp
t1 = torch.reshape(t,(-1,5))# -1代表根据其他维度计算得到
print(t,'\n',t1)
d53efdf020207fa0c51b9b9a149b208e.webp当张量在内存中是连续时,新张量和input共享数据内存
t = torch.randperm(10)
t[0] = 1024
print(t,'\n',t1)
print(id(t.data),id(t1.data))
#共享内存,id相同
b8f386602d188892089c895a947ae834.webp使用torch.transpose()变换交换张量的两个维度
torch.transpose(input, dim0, dim1)
参数:
input:要变换的张量dim0:要交换的维度dim1:要交换的维度
t = torch.rand((4,3,2))
t1 = torch.transpose(t,dim0=0,dim1=1)#交换他们的第0,1维度
print(t.shape,t1.shape)
a3875c500fbbba1794c36b175bbd757d.webp使用torch.t()变换2 维张量转置,对于矩阵而言,等价于torch.transpose(input,0,1)
torch.t(input)
参数:input:要变换的张量
x = torch.randn(3,2)
print(x)
torch.t(x)
c6ab98a3d979e5b04ea0e49872f78ffc.webp使用torch.squeeze()变换压缩长度为1的维度(轴)
torch.squeeze(input, dim=None, out=None)
参数:dim: 若为None,移除所有长度为1的轴;若指定维度,当且仅当该轴长度为1时,可以被移除。
t = torch.rand((1,2,1,1))
t1 = torch.squeeze(t)
t2 = torch.squeeze(t,dim=0)
t3 = torch.squeeze(t,dim=1)#指定的轴长度不为1,不能移除
print(t.shape,'\n',t1.shape,t2.shape,t3.shape)
ac50d6f8cb0841bc4a33bd20ee18d89f.webp使用torch.unsqueeze()变换依据dim扩展维度
torch.unsqueeze(input, dim, out=None)
参数:dim:扩展的维度
x = torch.tensor([12345])
torch.unsqueeze(x, 0)
20f0103a741425bf054427ce92de9775.webp从中括号数量可以看出已经从1维变成2维的了。
torch.unsqueeze(x, 1)
044a13ddc956db247e614549aab2b762.webp欢迎关注公众号学习之后的深度学习连载部分~29ef171bd2efd5601324b21351989805.webp喜欢记得点再看哦,证明你来看过~
浏览 21
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报