Python torch.flatten()函數(shù)案例詳解
先看函數(shù)參數(shù):
torch.flatten(input, start_dim=0, end_dim=-1)
input: 一個(gè) tensor,即要被“推平”的 tensor。
start_dim: “推平”的起始維度。
end_dim: “推平”的結(jié)束維度。
首先如果按照 start_dim 和 end_dim 的默認(rèn)值,那么這個(gè)函數(shù)會(huì)把 input 推平成一個(gè) shape 為 [n][n] 的tensor,其中 nn 即 input 中元素個(gè)數(shù)。
如果我們要自己設(shè)定起始維度和結(jié)束維度呢?
我們要先來(lái)看一下 tensor 中的 shape 是怎么樣的:
t = torch.tensor([[[1, 2, 2, 1], [3, 4, 4, 3], [1, 2, 3, 4]], [[5, 6, 6, 5], [7, 8, 8, 7], [5, 6, 7, 8]]]) print(t, t.shape) 運(yùn)行結(jié)果: tensor([[[1, 2, 2, 1], [3, 4, 4, 3], [1, 2, 3, 4]], [[5, 6, 6, 5], [7, 8, 8, 7], [5, 6, 7, 8]]]) torch.Size([2, 3, 4])
我們可以看到,最外層的方括號(hào)內(nèi)含兩個(gè)元素,因此 shape 的第一個(gè)值是 2;類似地,第二層方括號(hào)里面含三個(gè)元素,shape 的第二個(gè)值就是 3;最內(nèi)層方括號(hào)里含四個(gè)元素,shape 的第二個(gè)值就是 4。
示例代碼:
x = torch.flatten(t, start_dim=1) print(x, x.shape) y = torch.flatten(t, start_dim=0, end_dim=1) print(y, y.shape) 運(yùn)行結(jié)果: tensor([[1, 2, 2, 1, 3, 4, 4, 3, 1, 2, 3, 4], [5, 6, 6, 5, 7, 8, 8, 7, 5, 6, 7, 8]]) torch.Size([2, 12]) tensor([[1, 2, 2, 1], [3, 4, 4, 3], [1, 2, 3, 4], [5, 6, 6, 5], [7, 8, 8, 7], [5, 6, 7, 8]]) torch.Size([6, 4])
可以看到,當(dāng) start_dim = 11 而 end_dim = −1−1 時(shí),它把第 11 個(gè)維度到最后一個(gè)維度全部推平合并了。而當(dāng) start_dim = 00 而 end_dim = 11 時(shí),它把第 00 個(gè)維度到第 11 個(gè)維度全部推平合并了。pytorch中的 torch.nn.Flatten 類和 torch.Tensor.flatten 方法其實(shí)都是基于上面的 torch.flatten 函數(shù)實(shí)現(xiàn)的。
到此這篇關(guān)于Python torch.flatten()函數(shù)案例詳解的文章就介紹到這了,更多相關(guān)Python torch.flatten()函數(shù)內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信