日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

pytorch | transpose、permute、view、contiguous、is_contiguous、reshape

發(fā)布時(shí)間:2024/4/14 编程问答 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 pytorch | transpose、permute、view、contiguous、is_contiguous、reshape 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
  • transpose、contiguous、view
a = torch.randn(2,3) #隨機(jī)產(chǎn)生的2*3的tensor,內(nèi)存是連續(xù)的,所以打印出“真” if a.is_contiguous():print("真") else:print("假") a = a.transpose(0,1)#經(jīng)過(guò)transpose,維度變換后,內(nèi)存不連續(xù)了,所以打印出“假” if a.is_contiguous():print("真") else:print("假") a = a.contiguous()#contiguous函數(shù)將不連續(xù)內(nèi)存變?yōu)檫B續(xù)內(nèi)存,所以打印出“真” if a.is_contiguous():print("真") else:print("假") a = a.view(1,6)#變換維度,但是內(nèi)存依然連續(xù),所以打印出“真“,view遇到不連續(xù)的會(huì)報(bào)錯(cuò),只有連續(xù)的才不會(huì)報(bào)錯(cuò) if a.is_contiguous():print("真") else:print("假")

結(jié)果:

?

其中:is_contiguous函數(shù)是判斷一個(gè)變量是否內(nèi)存連續(xù),連續(xù)返回True,不連續(xù)返回False


  • torch.reshape()
a = torch.randn(2,3) #隨機(jī)產(chǎn)生的2*3的tensor,內(nèi)存是連續(xù)的,所以打印出“真” if a.is_contiguous():print("真") else:print("假") a = a.transpose(0,1)#經(jīng)過(guò)transpose,維度變換后,內(nèi)存不連續(xù)了,所以打印出“假” if a.is_contiguous():print("真") else:print("假") a = torch.reshape(a,(1,6))#reshape相當(dāng)于將contiguous和view進(jìn)行了合并,無(wú)論之前是連續(xù)還是不連續(xù),最終都是連續(xù)的,且不會(huì)報(bào)錯(cuò) if a.is_contiguous():print("真") else:print("假")

結(jié)果:?


  • 查看變量的內(nèi)存地址:id()函數(shù)
a = torch.randn(2,3) print(id(a))

?結(jié)果:


transpose、permute異同點(diǎn)

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)

結(jié)果:

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維交換,結(jié)果變?yōu)?*2*3 print(b1) c1 = a1.permute(1, 2, 0) # 原本是2*3*3,第1維變?yōu)榈?維,第2維變?yōu)榈?維,第3維變?yōu)榈?維,結(jié)果是:3*3*2 print(c1)

結(jié)果:

雖然都是維度變化,但transpose只能選擇兩個(gè)維度進(jìn)行交換,permute則可以多維交換。

看函數(shù)原型也能看出:

def transpose(self, dim0: _int, dim1: _int) -> Tensor: ... def permute(self, dims: _size) -> Tensor: ...

?

總結(jié)

以上是生活随笔為你收集整理的pytorch | transpose、permute、view、contiguous、is_contiguous、reshape的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。