評價此頁

Tensor 檢視#

建立日期: 2020年2月28日 | 最後更新日期: 2025年2月26日

PyTorch 允許一個 tensor 成為現有 tensor 的一個 檢視 (View)。檢視 tensor 與其基 tensor 共享相同的底層資料。支援 檢視 (View) 避免了顯式的資料複製,從而使我們能夠進行快速且記憶體高效的重塑、切片和逐元素操作。

例如,要獲取現有 tensor t 的檢視,可以呼叫 t.view(...)

>>> t = torch.rand(4, 4)
>>> b = t.view(2, 8)
>>> t.storage().data_ptr() == b.storage().data_ptr()  # `t` and `b` share the same underlying data.
True
# Modifying view tensor changes base tensor as well.
>>> b[0][0] = 3.14
>>> t[0][0]
tensor(3.14)

由於檢視與其基 tensor 共享底層資料,因此如果您編輯檢視中的資料,它也會反映在基 tensor 中。

通常,PyTorch 操作會返回一個新 tensor 作為輸出,例如 add()。但在檢視操作的情況下,輸出是輸入 tensor 的檢視,以避免不必要的資料複製。建立檢視時不會發生資料移動,檢視 tensor 只是改變了解釋相同資料的方式。獲取連續 tensor 的檢視可能會產生一個非連續的 tensor。使用者應額外注意,連續性可能對效能有隱式影響。 transpose() 是一個常見的例子。

>>> base = torch.tensor([[0, 1],[2, 3]])
>>> base.is_contiguous()
True
>>> t = base.transpose(0, 1)  # `t` is a view of `base`. No data movement happened here.
# View tensors might be non-contiguous.
>>> t.is_contiguous()
False
# To get a contiguous tensor, call `.contiguous()` to enforce
# copying data when `t` is not contiguous.
>>> c = t.contiguous()

供參考,這是 PyTorch 中檢視操作的完整列表

注意

透過索引訪問 tensor 的內容時,PyTorch 遵循 Numpy 的行為,即基本索引返回檢視,而高階索引返回副本。透過基本或高階索引進行的賦值是就地進行的。有關更多示例,請參見 Numpy 索引文件

還需要提及一些具有特殊行為的操作

  • reshape()reshape_as()flatten() 可以返回檢視或新 tensor,使用者程式碼不應依賴於它是檢視還是新 tensor。

  • contiguous() 在輸入 tensor 已經連續時返回**自身**,否則透過複製資料返回一個新的連續 tensor。

有關 PyTorch 內部實現的更詳細的演練,請參閱 ezyang 關於 PyTorch Internals 的部落格文章