如何調整 PyTorch 中的張量的尺寸?
要調整 PyTorch 張量的尺寸,我們使用.view()方法。我們可以增加或減少張量的維度,但我們必須確保張量中元素的總數在調整前和調整後相等。
步驟
匯入所需的庫。在以下所有 Python 示例中,必需的 Python 庫都是torch。確保你已經安裝了它。
建立一個 PyTorch 張量並列印它。
使用.view()調整上述建立的張量,並將值分配給一個變數。.view()不會調整原始張量;它只提供一個具有新尺寸的檢視,就像它的名稱所暗示的那樣。
最後,在調整後列印張量。
示例 1
# Python program to resize a tensor in PyTorch # Import the library import torch # Create a tensor T = torch.Tensor([1, 2, 3, 4, 5, 6]) print(T) # Resize T to 2x3 x = T.view(2,3) print("Tensor after resize:\n",x) # Other way to resize T to 2x3 x = T.view(-1,3) print("Tensor after resize:\n",x) # Other way resize T to 2x3 x = T.view(2,-1) print("Tensor after resize:\n",x)
輸出
當你執行上述 Python 3 程式碼時,它將生成以下輸出
tensor([1., 2., 3., 4., 5., 6.]) Tensor after resize: tensor([[1., 2., 3.], [4., 5., 6.]]) Tensor after resize: tensor([[1., 2., 3.], [4., 5., 6.]]) Tensor after resize: tensor([[1., 2., 3.], [4., 5., 6.]])
示例 2
# Import the library import torch # Create a tensor shape 4x3 T = torch.Tensor([[1,2,3],[2,1,3],[2,3,5],[5,6,4]]) print(T) # Resize T to 3x4 x = T.view(-1,4) print("Tensor after resize:\n",x) # Other way to esize T to 3x4 x = T.view(3,-1) print("Tensor after resize:\n",x) # Resize T to 2x6 x = T.view(2,-1) print("Tensor after resize:\n",x)
輸出
當你執行上述 Python 3 程式碼時,它將生成以下輸出
tensor([[1., 2., 3.], [2., 1., 3.], [2., 3., 5.], [5., 6., 4.]]) Tensor after resize: tensor([[1., 2., 3., 2.], [1., 3., 2., 3.], [5., 5., 6., 4.]]) Tensor after resize: tensor([[1., 2., 3., 2.], [1., 3., 2., 3.], [5., 5., 6., 4.]]) Tensor after resize: tensor([[1., 2., 3., 2., 1., 3.], [2., 3., 5., 5., 6., 4.]])
廣告