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()
