如何在 PyTorch 中執行張量的逐元素減法?
要對張量執行逐元素減法,我們可以使用 PyTorch 的 **torch.sub()** 方法。張量的對應元素將被相減。我們可以從另一個張量中減去標量或張量。我們可以從具有相同或不同維度的張量中減去張量。最終張量的維度將與高維張量的維度相同。
步驟
匯入所需的庫。在以下所有 Python 示例中,所需的 Python 庫是 **torch**。確保您已安裝它。
定義兩個或多個 PyTorch 張量並列印它們。如果要減去標量,請定義它。
使用 **torch.sub()** 從另一個張量中減去標量或張量,並將值賦給一個新變數。您也可以從張量中減去標量。使用此方法減去張量不會對原始張量進行任何更改。
列印最終張量。
示例 1
這裡,我們將有一個 Python 3 程式從張量中減去標量。我們將看到三種不同的方法來執行相同的任務。
# Python program to perform element-wise subtraction # import the required library import torch # Create a tensor t = torch.Tensor([1.5, 2.03, 3.8, 2.9]) print("Original Tensor t:\n", t) # Subtract a scalar value to a tensor v = torch.sub(t, 5.60) print("Element-wise subtraction result:\n", v) # Same result can also be obtained as below t1 = torch.Tensor([5.60]) w = torch.sub(t, t1) print("Element-wise subtraction result:\n", w) # Other way to do above operation t2 = torch.Tensor([5.60,5.60,5.60,5.60]) x = torch.sub(t, t2) print("Element-wise subtraction result:\n", x)
輸出
Original Tensor t: tensor([1.5000, 2.0300, 3.8000, 2.9000]) Element-wise subtraction result: tensor([-4.1000, -3.5700, -1.8000, -2.7000]) Element-wise subtraction result: tensor([-4.1000, -3.5700, -1.8000, -2.7000]) Element-wise subtraction result: tensor([-4.1000, -3.5700, -1.8000, -2.7000])
示例 2
以下程式演示如何從二維張量中減去一維張量。
# Import necessary library import torch # Create a 2D tensor T1 = torch.Tensor([[8,7],[4,5]]) # Create a 1-D tensor T2 = torch.Tensor([10, 5]) print("T1:\n", T1) print("T2:\n", T2) # Subtract 1-D tensor from 2-D tensor v = torch.sub(T1, T2) print("Element-wise subtraction result:\n", v)
輸出
T1: tensor([[8., 7.], [4., 5.]]) T2: tensor([10., 5.]) Element-wise subtraction result: tensor([[-2., 2.], [-6., 0.]])
示例 3
以下程式演示如何從一維張量中減去二維張量。
# Python program to subtract 2D tensor from 1D tensor # Import the library import torch # Create a 2D tensor T1 = torch.Tensor([[1,2],[4,5]]) # Create a 1-D tensor T2 = torch.Tensor([10, 5]) print("T1:\n", T1) print("T2:\n", T2) # Subtract 2-D tensor from 1-D tensor v = torch.sub(T2, T1) print("Element-wise subtraction result:\n", v)
輸出
T1: tensor([[1., 2.], [4., 5.]]) T2: tensor([10., 5.]) Element-wise subtraction result: tensor([[9., 3.], [6., 0.]])
您可以注意到最終張量是二維張量。
示例 4
以下程式演示如何從二維張量中減去二維張量。
# import the library import torch # Create two 2-D tensors T1 = torch.Tensor([[8,7],[3,4]]) T2 = torch.Tensor([[0,3],[4,9]]) print("T1:\n", T1) print("T2:\n", T2) # Subtract above two 2-D tensors v = torch.sub(T1,T2) print("Element-wise subtraction result:\n", v)
輸出
T1: tensor([[8., 7.], [3., 4.]]) T2: tensor([[0., 3.], [4., 9.]]) Element-wise subtraction result: tensor([[ 8., 4.], [-1., -5.]])
廣告