Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

3-2 主成分分析(PCA) リスト3.3について #7

Open
achopari opened this issue Feb 4, 2021 · 2 comments
Open

3-2 主成分分析(PCA) リスト3.3について #7

achopari opened this issue Feb 4, 2021 · 2 comments
Labels

Comments

@achopari
Copy link

achopari commented Feb 4, 2021

3-2 主成分分析(PCA) リスト3.3について、
固有ベクトルの軸のプロットですが、少し傾きがおかしいので、
計算方法が誤っているのではないかと思い、投稿させていただきます。

標準化の逆変換は、x=μ+σx' となるのでsc.mean_を加算する必要はないと思います。
また固有ベクトルは列ベクトルなので第1成分は[:,0]で渡すと思います(はまる人が多いらしいですが)。

以下が修正案(の一つ)と思います。5倍の部分は線分の長さを左右に広げているだけです。
pca_point1 = sc.inverse_transform(5.*pca.components_[:,0])
pca_point2 = sc.inverse_transform(-5.*pca.components_[:,0])

たとえば、共分散行列のSxy^2を20から-20にして負の相関にしてみてください。
元の計算では固有ベクトルの軸がさらに変なところに引かれてしまうのですが、
修正案では20でも-20でも、もっともらしい場所になります。

@shimitaku
Copy link
Owner

@achopari

ご返信遅くなってしまい申し訳ありません。

ご指摘いただきありがとうございます。
おっしゃる通り、軸の傾きが間違っていました。

inverse_transformメソッド内で加算されているため、sc.mean_は不要でした。

参照:https://github.com/scikit-learn/scikit-learn/blob/95119c13a/sklearn/preprocessing/_data.py#L902

一方で、固有ベクトルについては、pca.components_[0]のままで正しいです。
scikit-learnのPCA.components_では、固有ベクトルに相当する主成分が行ベクトルで表現されています。

参照:https://github.com/scikit-learn/scikit-learn/blob/95119c13a/sklearn/decomposition/_pca.py#L211

ちなみに、numpyのlinalg.eigでは、固有ベクトルが列ベクトルとして表現されているようです。
np.linalg.eigを使用する場合は、ご指摘の通り、[:,0]で取り出します。
参照:https://numpy.org/doc/stable/reference/generated/numpy.linalg.eig.html

ご指摘いただいた点の修正コードは以下と致します。

pca_point1 = sc.inverse_transform(5.*pca.components_[0])
pca_point2 = sc.inverse_transform(-5.*pca.components_[0])
pca_point = np.c_[pca_point1, pca_point2]  

本Issueに誤植ラベルを付与し、他の読者の皆様への案内にさせてください。
今後ともどうぞよろしくお願い致します。

@achopari
Copy link
Author

achopari commented Feb 8, 2021

ご検討いただきありがとうございました。
また、私の固有ベクトルの誤解をご指摘
いただき、ありがとうございました。
「はまる人」とは自分のことでした。

大変わかりやすい入門書でした。
ますますのご活躍をお祈り申し上げます。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants