主成分分析是非监督的机器学习算法,主要用于数据的降维处理。主要解决如何找到让样本间间距最大的轴。使得样本间方差最大。用梯度上升法来求最大解,实现过程如下。
import numpy as np
import matplotlib.pyplot as plt
X=np.empty((100,2))
X[:,0]=np.random.uniform(0.,100.,size=100)
X[:,1]=0.75*X[:,0]+3.+np.random.normal(0,10.,size=100)
plt.scatter(X[:,0],X[:,1])
plt.show()
def demean(X):#均值归0化
return X-np.mean(X,axis=0)#对矩阵在行方向求均值
X_demean=demean(X)
plt.scatter(X_demean[:,0],X_demean[:,1])
plt.show()
def f(w,X):
return np.sum((X.dot(w)**2))/len(X)
def df_math(w,X):
return X.T.dot(X.dot(w)*2./len(X)
def direction(w):
return w/np.linalg.norm(w)#化成单位向量
def graident_ascent(df,X,initial_w,eta,n_iters=1e4,epsilon=1e-8)
w=direction(initial_w)
cur_iter=0
while cur_iter<n_iters:
gradient=df(w,X)
last_w=w
w=w+eta*gradient
w=direction(w)
if(abs(f(w,X)-f(last_w,X))<epsilon):
break
cur_iter+=1
return w
initial_w=np.random.random(X.shape[1])
eta=0.001
w=gradient_ascent(df_math,X_demean,initial_w,eta)
plt.scatter(X_demean[:,0],X_demean[:,1])
plt.plot([0,w[0]*30],[0,w[1]*30],color='r')
plt.show()
这里找出的即第一主成分,当维度很大的时候,会有多个主成分。