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