改编自菊厂的AI数学基础实验
import numpy as np
from scipy.linalg import eig
import matplotlib.pyplot as plt
A = [
[1,2],
[2,1]
]
evals,evacs = eig(A)
print(evals, "\n", evacs) # [ 3.+0.j -1.+0.j] [[ 0.70710678 -0.70710678] [ 0.70710678 0.70710678]]
evacs = evacs[:, 0],evacs[:, 1] # 转换成了tuple 类型的 array
print(evacs, type(evacs)) # (array([0.70710678, 0.70710678]), array([-0.70710678, 0.70710678])) <class 'tuple'>
fig, ax = plt.subplots() # 返回fig 整个图像 ax 坐标轴和所画的图 对象
for spine in ['left', 'bottom']: # 让坐标轴经过原点
ax.spines[spine].set_position('zero')
ax.grid(alpha=0.4) # 画出网格
xmin, xmax = -3, 3
ymin, ymax = -3, 3
ax.set(xlim=(xmin, xmax), ylim=(ymin, ymax)) # 设置坐标轴范围
for v in evacs: # 画出特征向量
ax.annotate("", xy=v, xytext=(0, 0), arrowprops=dict(facecolor='blue', shrink=0,alpha=0.6, width=0.5))
x = np.linspace(xmin,xmax,2) # 画出特征空间
for v in evacs:
print(v, type(v))
a = v[1]/v[0] # 延特征向量方向的单位向量
print(a)
ax.plot(x, a*x,'r-', linewidth=0.4)
plt.show()