PyTorch – 如何計算向量或矩陣的範數?
要計算向量或矩陣的範數,我們可以使用 **torch.linalg.norm()** 方法。它返回一個包含計算出的範數的新張量。它接受向量、矩陣、矩陣批次以及矩陣批次的輸入。
向量是一維 PyTorch 張量,而矩陣是二維 PyTorch 張量。它支援 **float、double、cfloat** 和 **cdouble** 資料型別的輸入。我們可以沿著不同的維度計算矩陣或矩陣批次的範數。例如,我們可以沿著維度 0 或維度 1 計算矩陣的範數。
語法
torch.linalg.norm(A)
A 是向量、矩陣或矩陣批次。向量是一維 PyTorch 張量,矩陣是二維 PyTorch 張量。
步驟
我們可以使用以下步驟來計算向量或矩陣的範數:
匯入所需的庫。在以下所有示例中,所需的 Python 庫是 **torch**。確保您已安裝它。
import torch
定義向量或矩陣。這裡,我們定義一個大小為 3×3 的隨機數矩陣(二維張量)。
A = torch.randn(3,3)
使用 torch.linalg.norm(A) 計算向量或矩陣的範數。A 是向量、矩陣或矩陣批次。可以選擇將此值分配給一個新的變數。
norm_A = torch.linalg.norm(A)
列印計算出的範數
print("Norm:", norm_A)示例 1
在此程式中,我們計算向量的範數。
# import required library
import torch
# create a vector/ 1D tensor
v = torch.randn(3)
# print the above created vector
print("Vector:
", v)
# computet the norm of the vector
n = torch.linalg.norm(v)
print("Norm:
", n)輸出
Vector: tensor([-0.3792, -1.1512, 0.2590]) Norm: tensor(1.2394)
示例 2
在此程式中,我們計算矩陣的範數。
# import required library
import torch
# create a 3x4 matrix
mat = torch.randn(3,3)
# print the above created matrix
print("Matrix:
", mat)
# compute the norm of the matrix
nor = torch.linalg.norm(mat)
# print the computed determinants
print("Norm:
", nor)輸出
Matrix: tensor([[ 0.2376, 0.5451, -0.2423], [-0.2320, -0.2493, 1.3164], [-0.0265, -0.9278, -0.8413]]) Norm: tensor(1.9572)
示例 3
在此程式中,我們沿著不同的維度計算矩陣的範數。
# Python program to compute the norm of a matrix
# import torch library
import torch
# create a 3x3 matrix
mat = torch.tensor([[1.,2.,3.],[4.,5.,6.]])
# print the above created matrix
print("Matrix:
", mat)
# compute the norm of the matrix in dim 0
nor0 = torch.linalg.norm(mat, dim = 0)
# print the computed norm
print("Norm in 0 dim:
", nor0)
# compute the norm of the matrix in dim 1
nor1 = torch.linalg.norm(mat, dim = 1)
# print the computed norm
print("Norm in 1 dim:
", nor1)輸出
Matrix: tensor([[1., 2., 3.], [4., 5., 6.]]) Norm in 0 dim: tensor([4.1231, 5.3852, 6.7082]) Norm in 1 dim: tensor([3.7417, 8.7750])
示例 4
在此程式中,我們計算複數矩陣的範數。
# import required library
import torch
# create a 3x4 matrix
mat = torch.randn(3,4, dtype = torch.cfloat)
# print the above created matrix
print("Matrix:
", mat)
# compute the norm of the matrix
nor = torch.linalg.norm(mat)
# print the computed norm
print("Norm:
", nor)
# compute the norm of the matrix in dim 0
nor0 = torch.linalg.norm(mat, dim = 0)
# print the computed norm
print("Norm in 0 dim:
", nor0)
# compute the norm of the matrix in dim 1
nor1 = torch.linalg.norm(mat, dim = 1)
# print the computed norm
print("Norm in 1 dim:
", nor1)輸出
Matrix: tensor([[-0.2689+0.1693j, -1.5259-0.5821j, -0.2348-0.0016j, -0.9439+0.0868j], [-1.1065-0.5374j, 0.4492-0.0664j, 0.1469+1.0838j, -0.1163+0.2847j], [ 0.7928-1.0270j, 0.9414+1.0902j, 0.5717+0.9329j, -0.1108+0.2115j]]) Norm: tensor(3.4270) Norm in 0 dim: tensor([1.8159, 2.2244, 1.5648, 1.0247]) Norm in 1 dim: tensor([1.9292, 1.7350, 2.2388])
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP