從零開始深度學(xué)習(xí)Pytorch筆記(5)——張量的索引與變換

前文傳送門:從零開始深度學(xué)習(xí)Pytorch筆記(1)——安裝Pytorch從零開始深度學(xué)習(xí)Pytorch筆記(2)——張量的創(chuàng)建(上)從零開始深度學(xué)習(xí)Pytorch筆記(3)——張量的創(chuàng)建(下)從零開始深度學(xué)習(xí)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的數(shù)據(jù)挑出來,返回一維張量
張量變換使用torch.reshape()變換變換張量的形狀torch.reshape(input, shape)參數(shù):input: 要變換的張量shape: 新張量的形狀
t?=?torch.randperm(10)
t1?=?torch.reshape(t,(2,5))
print(t,'\n',t1)

t1?=?torch.reshape(t,(-1,5))#?-1代表根據(jù)其他維度計算得到
print(t,'\n',t1)
當(dāng)張量在內(nèi)存中是連續(xù)時,新張量和input共享數(shù)據(jù)內(nèi)存t?=?torch.randperm(10)
t[0]?=?1024
print(t,'\n',t1)
print(id(t.data),id(t1.data))
#共享內(nèi)存,id相同
使用torch.transpose()變換交換張量的兩個維度torch.transpose(input,?dim0,?dim1)參數(shù):
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 維張量轉(zhuǎn)置,對于矩陣而言,等價于torch.transpose(input,0,1)torch.t(input)參數(shù):input:要變換的張量
x?=?torch.randn(3,2)
print(x)
torch.t(x)
使用torch.squeeze()變換壓縮長度為1的維度(軸)torch.squeeze(input,?dim=None,?out=None)參數(shù):dim: 若為None,移除所有長度為1的軸;若指定維度,當(dāng)且僅當(dāng)該軸長度為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()變換依據(jù)dim擴(kuò)展維度torch.unsqueeze(input,?dim,?out=None)參數(shù):dim:擴(kuò)展的維度
x?=?torch.tensor([1,?2,?3,?4,?5])
torch.unsqueeze(x,?0)
從中括號數(shù)量可以看出已經(jīng)從1維變成2維的了。torch.unsqueeze(x,?1)
歡迎關(guān)注公眾號學(xué)習(xí)之后的深度學(xué)習(xí)連載部分~
喜歡記得點再看哦,證明你來看過~評論
圖片
表情
