溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python中torch.flatten()函數(shù)怎么用

發(fā)布時間:2021-08-30 13:45:08 來源:億速云 閱讀:153 作者:小新 欄目:開發(fā)技術

這篇文章主要介紹Python中torch.flatten()函數(shù)怎么用,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

先看函數(shù)參數(shù):

torch.flatten(input, start_dim=0, end_dim=-1)

input: 一個 tensor,即要被“推平”的 tensor。

start_dim: “推平”的起始維度。

end_dim: “推平”的結束維度。

首先如果按照 start_dim 和 end_dim 的默認值,那么這個函數(shù)會把 input 推平成一個 shape 為 [n][n] 的tensor,其中 nn 即 input 中元素個數(shù)。

如果我們要自己設定起始維度和結束維度呢?

我們要先來看一下 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)
 
運行結果:
 
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])

我們可以看到,最外層的方括號內含兩個元素,因此 shape 的第一個值是 2;類似地,第二層方括號里面含三個元素,shape 的第二個值就是 3;最內層方括號里含四個元素,shape 的第二個值就是 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)
 
 
運行結果:
 
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])

可以看到,當 start_dim = 11 而 end_dim = ?1?1 時,它把第 11 個維度到最后一個維度全部推平合并了。而當 start_dim = 00 而 end_dim = 11 時,它把第 00 個維度到第 11 個維度全部推平合并了。pytorch中的 torch.nn.Flatten 類和 torch.Tensor.flatten 方法其實都是基于上面的 torch.flatten 函數(shù)實現(xiàn)的。

以上是“Python中torch.flatten()函數(shù)怎么用”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI