微信公眾平臺(tái) 網(wǎng)站開(kāi)發(fā)seo產(chǎn)品是什么意思
在PyTorch中,movedim、transpose 和 permute這三個(gè)操作都可以用來(lái)重新排列張量(tensor)的維度,它們功能相似卻又有所不同。
movedim
🔗 torch.movedim
- 用途:將張量的一個(gè)或多個(gè)維度移動(dòng)到新的位置。
- 參數(shù):需要指定要移動(dòng)的維度和目標(biāo)位置。
- 特點(diǎn):
- 可以移動(dòng)單個(gè)或多個(gè)維度。
- 可以指定移動(dòng)后的維度順序。
- 移動(dòng)維度時(shí),不會(huì)改變其他維度的相對(duì)順序。
movedim 的重點(diǎn)是移動(dòng)維度到指定位置,而transpose的重點(diǎn)是交換兩個(gè)維度,這是它們之間最顯著的區(qū)別,此外movedim還可以移動(dòng)多個(gè)維度。
>>> x = torch.randint(1,100,(1,2,3,4))
>>> x
tensor([[[[58, 1, 62, 12],[65, 99, 20, 15],[95, 6, 54, 67]],[[92, 62, 97, 15],[17, 19, 70, 48],[17, 90, 76, 96]]]])
>>> x.shape
torch.Size([1, 2, 3, 4])
>>> ## 移動(dòng)單個(gè)維度
>>> x.movedim(0,3).shape # 把原tensor中的dim0移動(dòng)到dim3
torch.Size([2, 3, 4, 1])
>>> x.transpose(0,3).shape # 交換dim-0 和 dim-3
torch.Size([4, 2, 3, 1])
>>>
>>> ## 同時(shí)移動(dòng)多個(gè)維度
>>>> x.movedim((0,2),(1,3)).shape # 把原tensor中的dim0移動(dòng)到dim1, dim2移動(dòng)到dim3
torch.Size([2, 1, 4, 3])
>>> x.movedim((0,1),(1,2)).shape # 把原tensor中的dim0移動(dòng)到dim1, dim1移動(dòng)到dim2
torch.Size([3, 1, 2, 4])
總結(jié)
- movedim是把指定維度移動(dòng)到新的維度位置,其他未移動(dòng)的的維度保持相對(duì)位置不變。
- 對(duì)于 source_tensor.movedim(d1, d2):
- 如果 d1,d2 是連續(xù)的,則效果等同于 source_tensor.transpos(d1, d2)
- 如果 d1 < d2,則移動(dòng)后,原始維度中(d1, d2] 范圍內(nèi)的維度左移一位;
- 如果 d1 > d2,則移動(dòng)后,原始維度中(d1, d2] 范圍內(nèi)的維度右移一位;
transpose
🔗 torch.transpose
- 用途:交換張量的兩個(gè)維度。
- 參數(shù):需要指定要交換的兩個(gè)維度的索引。
- 特點(diǎn):
- 只能交換兩個(gè)維度。
- 對(duì)于2D張量,相當(dāng)于矩陣的轉(zhuǎn)置。
- 對(duì)于高維張量,只能進(jìn)行一次交換。
>>> x = torch.randint(2,300,(2,3,4))
>>> x
tensor([[[ 23, 266, 112, 126],[176, 290, 291, 134],[155, 214, 238, 208]],[[ 20, 270, 192, 254],[ 59, 120, 47, 5],[247, 173, 94, 28]]])
>>> x.transpose(0,2).shape
torch.Size([4, 3, 2])
>>> x.transpose(0,2)
tensor([[[ 23, 20],[176, 59],[155, 247]],[[266, 270],[290, 120],[214, 173]],[[112, 192],[291, 47],[238, 94]],[[126, 254],[134, 5],[208, 28]]])
總結(jié)
- torch.transpose 是用于交換兩個(gè)維度,且只能交換兩個(gè)維度。
- torch.permute 可以交換多個(gè)維度
permute
🔗torch.permute
- 用途:重新排列張量的所有維度。
- 參數(shù):需要提供一個(gè)維度索引的排列。
- 特點(diǎn):
- 可以重新排列所有維度的順序。
- 參數(shù)是一個(gè)包含所有維度索引的元組,且每個(gè)索引只能出現(xiàn)一次。
>>> x = torch.randint(2,300,(2,3,4))
>>> x
tensor([[[158, 169, 28, 85],[212, 14, 265, 119],[ 6, 201, 221, 145]],[[114, 209, 272, 232],[ 46, 179, 121, 296],[ 89, 76, 142, 185]]])
>>> x.shape
torch.Size([2, 3, 4])
>>> x.permute(2,0,1).shape # 表示:原tensor的dim2放到輸出tensor的dim0,dim0放到dim1,dim1放到dim2。
torch.Size([4, 2, 3])
異同點(diǎn)
相同點(diǎn):
- 都用于改變張量的維度順序。
- 都不會(huì)改變張量中的數(shù)據(jù),只是改變了數(shù)據(jù)的布局。
不同點(diǎn):
- transpose僅限于交換兩個(gè)維度,而movedim和permute可以處理多個(gè)維度。
- permute需要指定所有維度的排列順序,而movedim只需要指定要移動(dòng)的維度和目標(biāo)位置。
- movedim在移動(dòng)維度時(shí),其他維度的相對(duì)順序保持不變,而permute會(huì)根據(jù)提供的排列順序完全重新排列所有維度。