Để thực hiện chia theo phần tử (element-wise division) trên hai tensor trong PyTorch, ta dùng phương thức torch.div(). Nó chia mỗi phần tử của tensor đầu tiên cho phần tử tương ứng của tensor thứ hai. Cũng có thể chia tensor cho một scalar. Tensor có thể chia cho tensor cùng hoặc khác chiều. Chiều tensor kết quả sẽ bằng chiều tensor chiều cao hơn. Nếu chia tensor 1D cho tensor 2D, tensor kết quả sẽ là 2D.
Các bước
Nhập thư viện torch. Đảm bảo đã cài.
Định nghĩa hai hoặc nhiều tensor PyTorch và in ra. Nếu chia cho scalar, định nghĩa scalar.
Chia tensor cho tensor hoặc scalar bằng torch.div() gán vào biến mới. Phép chia này không thay đổi tensor gốc.
In tensor kết quả.
Ví dụ 1
import torch
t = torch.Tensor([2, 3, 5, 9])
print("Original Tensor t:\n", t)
# Chia tensor cho scalar 4
v = torch.div(t, 4)
print("Element-wise division result:\n", v)
# Cùng kết quả
t1 = torch.Tensor([4])
w = torch.div(t, t1)
print("Element-wise division result:\n", w)
# Cách khác
t2 = torch.Tensor([4, 4, 4, 4])
x = torch.div(t, t2)
print("Element-wise division result:\n", x)
Kết quả
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])
Ví dụ 2
Chia tensor 2D cho tensor 1D.
import torch
T1 = torch.Tensor([[3, 2], [7, 5]])
T2 = torch.Tensor([10, 8])
print("T1:\n", T1)
print("T2:\n", T2)
v = torch.div(T1, T2)
print("Element-wise division result:\n", v)
Kết quả
T1:
tensor([[3., 2.],
[7., 5.]])
T2:
tensor([10., 8.])
Element-wise division result:
tensor([[0.3000, 0.2500],
[0.7000, 0.6250]])
Ví dụ 3
Chia tensor 1D cho tensor 2D.
import torch
T1 = torch.Tensor([[8, 7], [4, 5]])
T2 = torch.Tensor([10, 5])
print("T1:\n", T1)
print("T2:\n", T2)
v = torch.div(T2, T1)
print("Division 1D tensor by 2D tensor result:\n", v)
Kết quả
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]])
Kết quả là tensor 2D.
Ví dụ 4
Chia tensor 2D cho tensor 2D.
import torch
T1 = torch.Tensor([[8, 7], [3, 4]])
T2 = torch.Tensor([[0, 3], [4, 9]])
print("T1:\n", T1)
print("T2:\n", T2)
v = torch.div(T1, T2)
print("Element-wise division result:\n", v)
Kết quả
T1:
tensor([[8., 7.],
[3., 4.]])
T2:
tensor([[0., 3.],
[4., 9.]])
Element-wise division result:
tensor([[inf, 2.3333],
[0.7500, 0.4444]])