เราสามารถใช้ torch.add() เพื่อทำการเพิ่มองค์ประกอบบนเทนเซอร์ใน PyTorch เพิ่มองค์ประกอบที่เกี่ยวข้องของเทนเซอร์ เราสามารถเพิ่มสเกลาร์หรือเทนเซอร์ให้กับเทนเซอร์ตัวอื่นได้ เราสามารถเพิ่มเทนเซอร์ที่มีมิติเท่ากันหรือต่างกันก็ได้ มิติของเทนเซอร์สุดท้ายจะเท่ากับมิติของเทนเซอร์มิติที่สูงกว่า
ขั้นตอน
-
นำเข้าไลบรารีที่จำเป็น ในตัวอย่าง Python ทั้งหมดต่อไปนี้ ไลบรารี Python ที่จำเป็นคือ ไฟฉาย . ตรวจสอบให้แน่ใจว่าคุณได้ติดตั้งแล้ว
-
กำหนดเทนเซอร์ PyTorch สองตัวขึ้นไปและพิมพ์ออกมา หากคุณต้องการเพิ่มปริมาณสเกลาร์ ให้กำหนด
-
เพิ่มเมตริกซ์ตั้งแต่สองตัวขึ้นไปโดยใช้ torch.add() และกำหนดค่าให้กับตัวแปรใหม่ คุณยังสามารถเพิ่มปริมาณสเกลาร์ให้กับเทนเซอร์ได้อีกด้วย การเพิ่มเทนเซอร์โดยใช้วิธีนี้จะไม่ทำให้เทนเซอร์เดิมเปลี่ยนแปลง
-
พิมพ์เทนเซอร์สุดท้าย
ตัวอย่างที่ 1
โปรแกรม Python ต่อไปนี้แสดงวิธีการเพิ่มปริมาณสเกลาร์ให้กับ atensor เราเห็นสามวิธีในการทำงานเดียวกัน
# Python program to perform element-wise Addition
# import the required library
import torch
# Create a tensor
t = torch.Tensor([1,2,3,2])
print("Original Tensor t:\n", t)
# Add a scalar value to a tensor
v = torch.add(t, 10)
print("Element-wise addition result:\n", v)
# Same operation can also be done as below
t1 = torch.Tensor([10])
w = torch.add(t, t1)
print("Element-wise addition result:\n", w)
# Other way to perform the above operation
t2 = torch.Tensor([10,10,10,10])
x = torch.add(t, t2)
print("Element-wise addition result:\n", x) ผลลัพธ์
Original Tensor t: tensor([1., 2., 3., 2.]) Element-wise addition result: tensor([11., 12., 13., 12.]) Element-wise addition result: tensor([11., 12., 13., 12.]) Element-wise addition result: tensor([11., 12., 13., 12.])
ตัวอย่างที่ 2
โปรแกรม Python ต่อไปนี้แสดงวิธีการเพิ่มเทนเซอร์ 1D และ 2D
# Import the library
import torch
# Create a 2-D tensor
T1 = torch.Tensor([[1,2],[4,5]])
# Create a 1-D tensor
T2 = torch.Tensor([10]) # also t2 = torch.Tensor([10,10])
print("T1:\n", T1)
print("T2:\n", T2)
# Add 1-D tensor to 2-D tensor
v = torch.add(T1, T2)
print("Element-wise addition result:\n", v) ผลลัพธ์
T1: tensor([[1., 2.], [4., 5.]]) T2: tensor([10.]) Element-wise addition result: tensor([[11., 12.], [14., 15.]])
ตัวอย่างที่ 3
โปรแกรมต่อไปนี้แสดงวิธีการเพิ่มเทนเซอร์ 2 มิติ
# Import the library
import torch
# create two 2-D tensors
T1 = torch.Tensor([[1,2],[3,4]])
T2 = torch.Tensor([[0,3],[4,1]])
print("T1:\n", T1)
print("T2:\n", T2)
# Add the above two 2-D tensors
v = torch.add(T1,T2)
print("Element-wise addition result:\n", v) ผลลัพธ์
T1: tensor([[1., 2.], [3., 4.]]) T2: tensor([[0., 3.], [4., 1.]]) Element-wise addition result: tensor([[1., 5.], [7., 5.]])