import numpy as np
import matplotlib . pyplot as plt
x0 = [2.5,0.5,2.2,1.9,3.1,2.3,2,1,1.5,1.1]
average1 = np.mean(x0)
print('x0的平均值是:{}'.format(average1))
y0 = [2.4,0.7,2.9,2.2,3,2.7,1.6,1.1,1.6,0.9]
average2 = np.mean(y0)
print('y0的平均值是:{}'.format(average2))
x1=x0-average1
y1=y0-average2
#print(x1,y1)
data=np.array([x1,y1])
data1=data.T
print('更新后x,y',data1)
cov0=np.cov(data)
print('协方差矩阵:',cov0)
eigenvalue,featurevector=np.linalg.eig(cov0)
print('eigenvalue=',eigenvalue)
print('featurevector=',featurevector)
if eigenvalue[0]>eigenvalue[1]:
t=np.array([[featurevector[0,0],featurevector[1,0]]])
else:
t=np.array([[featurevector[0,1],featurevector[1,1]]])
print('对应的特征向量',t)
v=t.T
final=data1.dot(v)
print('最终结果',final)
plt.xlabel('X')
plt.ylabel('Y')
plt.scatter(final,y0,c = 'm',marker = 'o')
plt.show()
x0的平均值是:1.81
y0的平均值是:1.9100000000000001
更新后x,y [[ 0.69 0.49]
[-1.31 -1.21]
[ 0.39 0.99]
[ 0.09 0.29]
[ 1.29 1.09]
[ 0.49 0.79]
[ 0.19 -0.31]
[-0.81 -0.81]
[-0.31 -0.31]
[-0.71 -1.01]]
协方差矩阵: [[0.61655556 0.61544444]
[0.61544444 0.71655556]]
eigenvalue= [0.0490834 1.28402771]
featurevector= [[-0.73517866 -0.6778734 ]
[ 0.6778734 -0.73517866]]
对应的特征向量 [[-0.6778734 -0.73517866]]
最终结果 [[-0.82797019]
[ 1.77758033]
[-0.99219749]
[-0.27421042]
[-1.67580142]
[-0.9129491 ]
[ 0.09910944]
[ 1.14457216]
[ 0.43804614]
[ 1.22382056]]