先看函數參數:
torch.flatten(input, start_dim=0, end_dim=-1)
input: 一個 tensor,即要被“推平”的 tensor。
start_dim: “推平”的起始維度。
end_dim: “推平”的結束維度。
首先如果按照 start_dim 和 end_dim 的默認值,那么這個函數會把 input 推平成一個 shape 為 [n][n] 的tensor,其中 nn 即 input 中元素個數。
如果我們要自己設定起始維度和結束維度呢?
我們要先來看一下 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 函數實現的。
到此這篇關于Python torch.flatten()函數案例詳解的文章就介紹到這了,更多相關Python torch.flatten()函數內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- Python入門教程2. 字符串基本操作【運算、格式化輸出、常用函數】
- Python中使用pprint函數進行格式化輸出的教程
- python中re.findall函數實例用法
- Python函數基礎
- Python之基礎函數案例詳解
- Python 函數簡單易理解版
- python機器學習高數篇之函數極限與導數
- python中super()函數的理解與基本使用
- Python如何使用print()函數輸出格式化字符串
- python中map()函數使用方法詳解
- python之多種方式傳遞函數方法案例講解
- Python類的高級函數詳解
- 10個有用的Python字符串函數小結
- python imread函數詳解
- 關于Python OS模塊常用文件/目錄函數詳解
- python用函數創造字典的實例講解
- Python常見的函數及格式化輸出