如何在PyTorch中對張量進行逐元素除法?


在PyTorch中對兩個張量進行逐元素除法,可以使用**torch.div()**方法。它將第一個輸入張量的每個元素除以第二個張量的對應元素。我們也可以用一個標量除以一個張量。可以使用相同或不同維度的張量相除。最終張量的維度將與維度較高的張量相同。如果我們用一個一維張量除以一個二維張量,那麼最終張量將是一個二維張量。

步驟

  • 匯入所需的庫。在以下所有Python示例中,所需的Python庫是**torch**。確保你已經安裝了它。

  • 定義兩個或多個PyTorch張量並列印它們。如果要將張量除以標量,請定義一個標量。

  • 使用**torch.div()**將張量除以另一個張量或標量,並將值賦給一個新的變數。使用此方法除以張量不會對原始張量進行任何更改。

  • 列印最終張量。

示例1

# Python program to perform element-wise division
# import the required library
import torch

# Create a tensor
t = torch.Tensor([2, 3, 5, 9])
print("Original Tensor t:\n", t)

# Divide a tensor by a scalar 4
v = torch.div(t, 4)
print("Element-wise division result:\n", v)

# Same result can also be obtained as below
t1 = torch.Tensor([4])
w = torch.div(t, t1)
print("Element-wise division result:\n", w)

# other way to do above operation
t2 = torch.Tensor([4,4,4,4])
x = torch.div(t, t2)
print("Element-wise division result:\n", x)

輸出

Original Tensor t:
   tensor([2., 3., 5., 9.])
Element-wise division result:
   tensor([0.5000, 0.7500, 1.2500, 2.2500])
Element-wise division result:
   tensor([0.5000, 0.7500, 1.2500, 2.2500])
Element-wise division result:
   tensor([0.5000, 0.7500, 1.2500, 2.2500])

示例2

下面的Python程式演示瞭如何將一個二維張量除以一個一維張量。

# import the required library
import torch

# Create a 2D tensor
T1 = torch.Tensor([[3,2],[7,5]])

# Create a 1-D tensor
T2 = torch.Tensor([10, 8])
print("T1:\n", T1)
print("T2:\n", T2)

# Divide 2-D tensor by 1-D tensor
v = torch.div(T1, T2)
print("Element-wise division result:\n", v)

輸出

T1:
tensor([[3., 2.],
         [7., 5.]])
T2:
tensor([10., 8.])
Element-wise division result:
tensor([[0.3000, 0.2500],
         [0.7000, 0.6250]])

示例3

下面的Python程式演示瞭如何將一個一維張量除以一個二維張量。

# Python program to dive a 1D tensor by a 2D tensor
# import the required 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)

# Divide 1-D tensor by 2-D tensor
v = torch.div(T2, T1)
print("Division 1D tensor by 2D tensor result:\n", v)

輸出

T1:
tensor([[8., 7.],
         [4., 5.]])
T2:
tensor([10., 5.])
Division 1D tensor by 2D tensor result:
tensor([[1.2500, 0.7143],
         [2.5000, 1.0000]])

您可以注意到最終張量是一個二維張量。

示例4

下面的Python程式演示瞭如何將一個二維張量除以一個二維張量。

# import necessary library
import torch

# Create two 2-D tensors
T1 = torch.Tensor([[8,7],[3,4]])
T2 = torch.Tensor([[0,3],[4,9]])

# Print the above tensors
print("T1:\n", T1)
print("T2:\n", T2)

# Divide T1 by T2
v = torch.div(T1,T2)
print("Element-wise division result:\n", v)

輸出

T1:
tensor([[8., 7.],
         [3., 4.]])
T2:
tensor([[0., 3.],
         [4., 9.]])
Element-wise division result:
tensor([[ inf, 2.3333],
         [0.7500, 0.4444]])

更新於:2021年11月6日

5K+ 瀏覽量

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.