SciPy 教程-SciPy 线性代数

SciPy 建立在 ATLAS LAPACK 和 BLAS 库之上,提供了非常快速的线性代数功能。线性代数例程接受二维数组对象,并且输出也是二维数组。如果我们想要更快的计算速度,那么我们必须在这方面深入研究。
通过输入以下 SciPy 函数可以解决线性代数问题:
linalg.solve()
线性方程
linalg.solve 用于求解线性方程 a x + b y = Z 的未知 x, y 值。
x + 3y + 10z = 10
2x + 12y + 7z = 18
5x + 8y + 8z = 30
这里我们将使用 linalg.solve 命令来更快地求解上述线性方程。
import numpy as np
from scipy import linalg
# We are trying to solve a linear algebra system which can be given as
# x + 3y +10z = 10
# 2x + 12y + 7z = 18
# 5x + 8y + 8z = 30
# Creating input array
a = np.array([[1, 3, 10], [2, 12, 7], [5, 8, 8]])
# Solution Array
b = np.array([[10], [18], [30]])
# Solve the linear algebra
x = linalg.solve(a, b)
# Print results
print(x)
# Checking Results
print("\n Checking results, Vectors must be zeros")
print(a.dot(X) - b)
输出:
[[4.55393586]
[0.51311953]
[0.39067055]]
Checking results, Vectors must be zeros
[[0.]
[0.]
[0.]]
在上述程序中,我们声明了 a 和 b 作为变量,其中 a 存储方程的系数,b 存储等式右边的值。变量 x 存储评估的解。
求行列式
使用 linalg.det() 函数可以找到方阵的行列式。线性代数中的行列式 A 通常表示为 |A|。它接受一个矩阵并返回一个标量值。
考虑以下示例:
from scipy import linalg
import numpy as np
#Declaring the numpy array
A = np.array([[5,9],[8,4]])
#Passing the values to the det function
x = linalg.det(A)
#printing the result
print(x)
输出:
-52
特征值和特征向量
在线性代数中,寻找特征值和特征向量问题是最常见的问题。我们可以使用 linalg.eig() 函数找到方阵 (A) 的特征值 (?) 和相应的特征向量 (v)。考虑以下示例:
Av = λv
#importing the scipy and numpy packages
from scipy import linalg
import numpy as np
#Declaring the numpy array
a = np.array([[3,2],[4,6]])
#Passing the values to the eig function
l, v = linalg.eig(a)
#printing the result for eigenvalues
print(l)
#printing the result for eigenvectors
print(v)
输出:
[-0.37228132+0.j 5.37228132+0.j]
[[-0.82456484 -0.41597356]
[ 0.56576746 -0.90937671]]
SciPy svd
svd 代表 奇异值分解。矩阵 A 的奇异值分解是 A 分解为三个矩阵的乘积 A = UDVT 的形式,其中 U 和 V 的列是正交的,D 是对角线上具有实数正值的矩阵。