torch.mul() เมธอดใช้ในการคูณองค์ประกอบตามเทนเซอร์ใน PyTorch มันทวีคูณองค์ประกอบที่สอดคล้องกันของเทนเซอร์ เราสามารถคูณเมตริกซ์ตั้งแต่สองตัวขึ้นไปได้ เราสามารถคูณสเกลาร์และเทนเซอร์ได้ด้วย สามารถคูณเทนเซอร์ที่มีขนาดเท่ากันหรือต่างกันได้ มิติของเทนเซอร์สุดท้ายจะเท่ากับมิติของเทนเซอร์มิติที่สูงกว่า การคูณองค์ประกอบบนเทนเซอร์เรียกอีกอย่างว่า ผลิตภัณฑ์ Hadamard
ขั้นตอน
-
นำเข้าไลบรารีที่จำเป็น ในตัวอย่าง Python ทั้งหมดต่อไปนี้ ไลบรารี Python ที่จำเป็นคือ ไฟฉาย . ตรวจสอบให้แน่ใจว่าคุณได้ติดตั้งแล้ว
-
กำหนดเทนเซอร์ PyTorch สองตัวขึ้นไปและพิมพ์ออกมา หากคุณต้องการคูณปริมาณสเกลาร์ ให้นิยามมัน
-
คูณเมตริกซ์ตั้งแต่สองตัวขึ้นไปโดยใช้ torch.mul() และกำหนดค่าให้กับตัวแปรใหม่ คุณยังสามารถคูณปริมาณสเกลาร์และเทนเซอร์ได้อีกด้วย การคูณเทนเซอร์ด้วยวิธีนี้จะไม่ทำให้เทนเซอร์เดิมเปลี่ยนแปลง
-
พิมพ์เทนเซอร์สุดท้าย
ตัวอย่างที่ 1
โปรแกรมต่อไปนี้แสดงวิธีการคูณสเกลาร์กับเทนเซอร์ ผลลัพธ์เดียวกันนี้สามารถรับได้โดยใช้เทนเซอร์แทนสเกลาร์
# Python program to perform element--wise multiplication
# import the required library
import torch
# Create a tensor
t = torch.Tensor([2.05, 2.03, 3.8, 2.29])
print("Original Tensor t:\n", t)
# Multiply a scalar value to a tensor
v = torch.mul(t, 7)
print("Element-wise multiplication result:\n", v)
# Same result can also be obtained as below
t1 = torch.Tensor([7])
w = torch.mul(t, t1)
print("Element-wise multiplication result:\n", w)
# other way to do above operation
t2 = torch.Tensor([7,7,7,7])
x = torch.mul(t, t2)
print("Element-wise multiplication result:\n", x) ผลลัพธ์
Original Tensor t: tensor([2.0500, 2.0300, 3.8000, 2.2900]) Element-wise multiplication result: tensor([14.3500, 14.2100, 26.6000, 16.0300]) Element-wise multiplication result: tensor([14.3500, 14.2100, 26.6000, 16.0300]) Element-wise multiplication result: tensor([14.3500, 14.2100, 26.6000, 16.0300])
ตัวอย่างที่ 2
โปรแกรม Python ต่อไปนี้แสดงวิธีการคูณ 2D tensor กับ 1Dtensor
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)
# Multiply 1-D tensor with 2-D tensor
v = torch.mul(T1, T2) # v = torch.mul(T2,T1)
print("Element-wise multiplication result:\n", v) ผลลัพธ์
T1: tensor([[3., 2.], [7., 5.]]) T2: tensor([10., 8.]) Element-wise multiplication result: tensor([[30., 16.], [70., 40.]])
ตัวอย่างที่ 3
โปรแกรม Python ต่อไปนี้แสดงวิธีการคูณเทนเซอร์ 2D สองตัว
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)
# Multiply above two 2-D tensors
v = torch.mul(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([[ 0., 21.], [12., 36.]])