我正在用 Python 進行主成分分析 (PCA)。出于理解原因,我想自己實作它。為此,我根據給定的協方差矩陣創建隨機資料,以便我可以使用不同的值以及主成分的行為方式。所以這個腳本只是為了理解和澄清PCA。
我的理解是,主成分(它們是協方差矩陣的特征向量)總是相互正交。維基百科的下圖也是這么說的:

來自維基百科的圖片描述(
我的 Python 腳本:
from matplotlib import pyplot as plt
import numpy as np
from sklearn.decomposition import PCA
def normalize(data: np.array, mean=None, std=None):
"""
Normalize a pandas dataframe with respect to their stochastical moment. If mean and/or std is not passed they are
calculated beforeheand.
:param data: Data to be normalized
:param mean: A mean value (optional)
:param std: A standard deviation (optional)
:return: normalized dataframe, mean value(s), standard deviation(s)
"""
if mean is None:
mean = data.mean(axis=0).reshape(1, -1)
if std is None:
std = data.std(axis=0).reshape(1, -1)
res = data - mean / std
return res, mean, std
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
datacount = 1000
# create data based on given covariance matrix
cov = np.array([[1, 0.85], [0.85, 1]])
rand1 = np.random.multivariate_normal([1, 3], cov, datacount)
# normalize, calculate covariance matrix and its eigenvectors and eigenvalues
rand1, mean, std = normalize(rand1)
cov = np.cov(rand1.T)
eig_values, eig_vectors = np.linalg.eig(cov)
# sort eig_values by importance and use this to also sort the vectors
idx = np.argsort(eig_values, axis=0)[::-1]
sorted_eig_vectors = eig_vectors[:, idx]
# plot data
plt.figure()
plt.scatter(rand1[:, 0], rand1[:, 1])
# set both axis limits to the maximum/minimum of the axis scalesv
ax = plt.gca()
xlimits = np.array(ax.get_xlim())
ylimits = np.array(ax.get_ylim())
axmax = np.max([np.max(xlimits), np.max(ylimits)])
axmin = np.min([np.min(xlimits), np.min(ylimits)])
ax.set_xlim([axmin, axmax])
ax.set_ylim([axmin, axmax])
# use PCA from sklearn for comparison
pca = PCA(n_components=2)
pca = pca.fit(rand1)
# Plot the eigenvectors
# Beware! Eigenvectors are oriented in rows in sklearn PCA and column-oriented in np.linalg.eig()!
for i in range(2):
plt.arrow(0, 0, pca.components_[0, i], pca.components_[1, i], color="g",
head_width=0.05, head_length=0.1)
for i in range(2):
plt.arrow(0, 0, eig_vectors[i, 0], eig_vectors[i, 1], color="r",
head_width=0.05, head_length=0.1)
# plt.annotate(text='', xy=(1, 1), xytext=(0, 0), arrowprops=dict(arrowstyle='<->'))
plt.grid()
plt.figure()
# Transform data to new subspace
eig_scores = np.dot(rand1, sorted_eig_vectors[:, :2]).T
# plot PCAs in subspace
plt.scatter(eig_scores[0], eig_scores[1])
# set both axis limits to the maximum/minimum of the axis scales
ax = plt.gca()
xlimits = np.array(ax.get_xlim())
ylimits = np.array(ax.get_ylim())
axmax = np.max([np.max(xlimits), np.max(ylimits)])
axmin = np.min([np.min(xlimits), np.min(ylimits)])
ax.set_xlim([axmin, axmax])
ax.set_ylim([axmin, axmax])
plt.grid()
plt.show()
# Are Eigenvectors orthogonal?
print(np.dot(eig_vectors[:, 0], eig_vectors[:, 1]) == 0) # yields True
print(np.dot(pca.components_[0, :], pca.components_[1, :]) == 0) # yields True
奇怪的是,最后兩行,我檢查兩種方法的特征向量是否正交,總是產生 True,表明向量實際上是正交的。
此外,資料到新子空間的轉換作業正常,結果如下:

我錯過了什么?我的期望是假的嗎?還是我的 Python 腳本中存在錯誤?
uj5u.com熱心網友回復:
你檢查過它們是正交的,它們是,但在圖中你說它們不是。向量是否正確繪制?他們是:
array([[ 0.707934 , -0.70627859],
[ 0.70627859, 0.707934 ]])
看圖好像是這樣。
問題是您正在嘗試測量顯示幕上的角度,其中兩個軸的比例不同。
只需添加 plt.axis('equal')
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/385779.html
標籤:Python 麻木的 matplotlib 个人电脑
