返回Python线性代数中轴1上向量的范数

返回Python线性代数中轴1上向量的范数

要返回线性代数中矩阵或向量的范数,在Python的Numpy库中使用LA.norm()方法。第一个参数x是一个输入数组。如果axis为None,则x必须是1维或2维的,除非ord为None。如果axis和ord都为None,则返回x.ravel的二范数。第二个参数ord是范数的阶数。inf表示numpy的inf对象。默认为None。

第三个参数axis是一个整数,指定沿该轴计算向量范数的x。如果axis是一个二元组,则指定保存2维矩阵的轴,并计算这些矩阵的矩阵范数。如果axis为None,则返回一个向量范数(当x是1维时)或矩阵范数(当x是2维时)。默认为None。

第四个参数keepdims,如果设置为True,则在结果中保留被范数计算过的轴作为尺寸为1的维度。使用此选项,结果将与原始的x正确地广播。

步骤

首先,导入所需的库-

import numpy as np
from numpy import linalg as LA

创建一个数组 –

arr = np.array([[ 1, 2, 3], [-1, 1, 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中的LA.norm()方法。 Numpy –

print("\nResult...\n",LA.norm(arr, axis = 1))

示例

import numpy as np
from numpy import linalg as LA

# Create an array
arr = np.array([[ 1, 2, 3],[-1, 1, 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, axis = 1))

输出

Our Array...
   [[ 1 2 3]
   [-1 1 4]]

Dimensions of our Array...
2

Datatype of our Array object...
int64

Shape of our Array object...
(2, 3)

Result...
   [3.74165739 4.24264069]

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程