如何在 PyTorch 中對張量執行元素級乘法?
torch.mul() 方法用於在 PyTorch 中對張量執行元素級乘法。它將張量的對應元素相乘。我們可以將兩個或多個張量相乘。我們還可以將標量和張量相乘。還可以將維度相同或不同的張量相乘。最終張量的維度將與更高維度張量的維度相同。張量的元素級乘法也稱為哈達瑪積。
步驟
匯入所需的庫。在以下所有 Python 示例中,所需的 Python 庫都是 torch。請確保您已安裝它。
定義兩個或多個 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 張量與 1D 張量相乘。
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.]])
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP