Pytorch中的contiguous 函式

2021-09-26 09:00:17 字數 788 閱讀 9365

這個函式主要是為了輔助pytorch中的一些其他函式,主要包含在pytorch中,有一些對tensor的操作不會真正改變tensor的內容,改變的僅僅是tensor中位元組位置的索引。這些操作有:
narrow(),view(),expand()和transpose()
在執行這幾個函式之前,需要先把variable進行.contiguous()操作。

這是因為:有些tensor並不是占用一整塊記憶體,而是由不同的資料塊組成,而tensor的view()操作依賴於記憶體是整塊的,這時只需要執行contiguous()這個函式,把tensor變成在記憶體中連續分布的形式。 

例如執行view操作之後,不會開闢新的記憶體空間來存放處理之後的資料,實際上新資料與原始資料共享同一塊記憶體。

而在呼叫contiguous()之後,pytorch會開闢一塊新的記憶體空間存放變換之後的資料,並會真正改變tensor的內容,按照變換之後的順序存放資料。

判斷是否contiguous用torch.tensor.is_contiguous()函式。

如果在需要呼叫contiguous()的地方呼叫contiguous(),執行時會提示你:

runtimeerror: input is not contiguous
這個時候,加上contiguous()就好。

Pytorch 中 torchvision的錯誤

在學習pytorch的時候,使用 torchvision的時候發生了乙個小小的問題 安裝都成功了,並且import torch也沒問題,但是在import torchvision的時候,出現了如下所示的錯誤資訊 dll load failed 找不到指定模組。首先,我們得知道torchvision在...

pytorch中的乘法

總結 按元素相乘用torch.mul,二維矩陣乘法用torch.mm,batch二維矩陣用torch.bmm,batch 廣播用torch.matmul if name main a torch.tensor 1 2,3 b torch.arange 0,12 reshape 4 3 c torch...

pytorch中index select 的用法

a torch.linspace 1,12,steps 12 view 3,4 print a b torch.index select a,0,torch.tensor 0,2 print b print a.index select 0,torch.tensor 0,2 c torch.inde...