從零開始深度學習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的數據挑出來,返回一維張量

張量的變換使用torch.reshape()變換變換張量的形狀torch.reshape(input, shape)
參數:input: 要變換的張量
shape: 新張量的形狀

t = torch.randperm(10)
t1 = torch.reshape(t,(2,5))
print(t,'\n',t1)
t1 = torch.reshape(t,(-1,5))# -1代表根據其他維度計算得到print(t,'\n',t1)

當張量在內存中是連續時,新張量和input共享數據內存

t = torch.randperm(10)
t[0] = 1024
print(t,'\n',t1)
print(id(t.data),id(t1.data))#共享內存,id相同

使用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)

使用torch.t()變換2 維張量轉置,對於矩陣而言,等價於

torch.transpose(input,0,1)
torch.t(input)#參數:input:要變換的張量
x = torch.randn(3,2)
print(x)
torch.t(x)

使用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)

使用torch.unsqueeze()變換依據dim擴展維度torch.unsqueeze(input, dim, out=None)參數:dim:擴展的維度

x = torch.tensor([1, 2, 3, 4, 5])
torch.unsqueeze(x, 0)#從中括號數量可以看出已經從1維變成2維的了。
torch.unsqueeze(x, 1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章