pytorch | transpose、permute、view、contiguous、is_contiguous、reshape
生活随笔
收集整理的這篇文章主要介紹了
pytorch | transpose、permute、view、contiguous、is_contiguous、reshape
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
- transpose、contiguous、view
結果:
?
其中:is_contiguous函數是判斷一個變量是否內存連續,連續返回True,不連續返回False
- torch.reshape()
結果:?
- 查看變量的內存地址:id()函數
?結果:
transpose、permute異同點
transpose:交換維度?
torch.manual_seed(1) a = torch.randn(2, 3) print(a) b = a.transpose(0, 1) print(b) print('=====================') a1 = torch.randn(2, 3, 4) print(a1) b1 = a1.transpose(1, 2) print(b1)結果:
permute:排列、置換維度,比transpose更靈活,適用于多維度
a1 = torch.from_numpy(np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]])) print(a1) b1 = a1.permute(1, 0, 2) # 原本是2*3*3,將第1維和第2維交換,結果變為3*2*3 print(b1) c1 = a1.permute(1, 2, 0) # 原本是2*3*3,第1維變為第3維,第2維變為第1維,第3維變為第2維,結果是:3*3*2 print(c1)結果:
雖然都是維度變化,但transpose只能選擇兩個維度進行交換,permute則可以多維交換。
看函數原型也能看出:
def transpose(self, dim0: _int, dim1: _int) -> Tensor: ... def permute(self, dims: _size) -> Tensor: ...?
總結
以上是生活随笔為你收集整理的pytorch | transpose、permute、view、contiguous、is_contiguous、reshape的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 理解 | 理解a: float=10
- 下一篇: 问题 | list(set(list))