我认为这mlab.PCA
门课不适合你想做的事情。特别是,PCA
该类在找到特征向量之前重新调整数据:
a = self.center(a)
U, s, Vh = np.linalg.svd(a, full_matrices=False)
该center
方法除以sigma
:
def center(self, x):
'center the data using the mean and sigma from training set a'
return (x - self.mu)/self.sigma
这导致特征向量 ,pca.Wt
,如下所示:
[[-0.70710678 -0.70710678]
[-0.70710678 0.70710678]]
它们是垂直的,但与原始数据的主轴没有直接关系。它们是关于按摩数据的主轴。
也许直接编写你想要的代码可能更容易(不使用mlab.PCA
类):
import numpy as np
import matplotlib.pyplot as plt
N = 1000
xTrue = np.linspace(0, 1000, N)
yTrue = 3 * xTrue
xData = xTrue + np.random.normal(0, 100, N)
yData = yTrue + np.random.normal(0, 100, N)
xData = np.reshape(xData, (N, 1))
yData = np.reshape(yData, (N, 1))
data = np.hstack((xData, yData))
mu = data.mean(axis=0)
data = data - mu
# data = (data - mu)/data.std(axis=0) # Uncommenting this reproduces mlab.PCA results
eigenvectors, eigenvalues, V = np.linalg.svd(data.T, full_matrices=False)
projected_data = np.dot(data, eigenvectors)
sigma = projected_data.std(axis=0).mean()
print(eigenvectors)
fig, ax = plt.subplots()
ax.scatter(xData, yData)
for axis in eigenvectors:
start, end = mu, mu + sigma * axis
ax.annotate(
'', xy=end, xycoords='data',
xytext=start, textcoords='data',
arrowprops=dict(facecolor='red', width=2.0))
ax.set_aspect('equal')
plt.show()