Python线性代数中计算向量沿指定轴的范数
在Python NumPy中,使用LA.norm()方法可以返回线性代数中矩阵或向量的范数。第一个参数x是输入数组。如果axis为None,除非ord为None,否则x必须是一维或二维的。如果axis和ord都为None,则返回x.ravel的2范数。第二个参数ord是范数的阶数,inf表示NumPy的inf对象,默认为None。
第三个参数axis,如果为整数,则指定沿其计算向量范数的x轴。如果axis是一个2元组,则它指定保存二维矩阵的轴,并计算这些矩阵的矩阵范数。如果axis为None,则返回向量范数(当x是一维时)或矩阵范数(当x是二维时)。默认为None。
第四个参数keepdims,如果设置为True,则对准其进行归一化的轴将作为大小为一的维度保留在结果中。使用此选项,结果将针对原始x正确广播。
步骤
首先,导入所需的库:
import numpy as np from numpy import linalg as LA
创建一个数组:
arr = np.array([[ -4, -3, -2], [-1, 0, 1], [2, 3, 4] ])
显示数组:
print("Our Array...\n",arr)检查维度:
print("\nDimensions of our Array...\n",arr.ndim)获取数据类型:
print("\nDatatype of our Array object...\n",arr.dtype)获取形状:
print("\nShape of our Array object...\n",arr.shape)在Python NumPy中,使用LA.norm()方法可以返回线性代数中矩阵或向量的范数:
print("\nResult...\n",LA.norm(arr, np.inf))示例
import numpy as np
from numpy import linalg as LA
# Create an array
arr = np.array([[ -4, -3, -2],
[-1, 0, 1],
[2, 3, 4] ])
# Display the array
print("Our Array...\n",arr)
# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)
# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)
# Get the Shape
print("\nShape of our Array object...\n",arr.shape)
# To return the Norm of the matrix or vector in Linear Algebra, use the LA.norm() method in Python Numpy
print("\nResult...\n",LA.norm(arr, np.inf))输出
Our Array... [[-4 -3 -2] [-1 0 1] [ 2 3 4]] Dimensions of our Array... 2 Datatype of our Array object... int64 Shape of our Array object... (3, 3) Result... 9.0
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP