首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >sklearn.decomposition.PCA特征向量的简单图

sklearn.decomposition.PCA特征向量的简单图
EN

Stack Overflow用户
提问于 2016-06-22 19:20:15
回答 1查看 12.5K关注 0票数 5

我试图了解Principal Component Analysis是如何工作的,我正在sklearn.datasets.load_iris数据集上测试它。我理解每个步骤是如何工作的(例如标准化数据、协方差、特征值排序、使用K选择的维度将原始数据转换为新的轴)。

下一步是可视化这些eigenvectors在dataset上的投影位置(在PC1 vs. PC2 plot上,对吗?)

有人能解释如何在降维数据集的三维图上绘制PC1、PC2、PC3特征向量吗?

另外,我是否正确地绘制了这个2D版本?我不知道为什么我的第一个特征向量有更短的长度。我应该乘以特征值吗?

这里是我为实现这一目标所做的一些研究:

下面的PCA方法来自:https://plot.ly/ipython-notebooks/principal-component-analysis/#Shortcut---PCA-in-scikit-learn (尽管我不想使用plotly )。我想坚持使用pandas, numpy, sklearn, matplotlib, scipy, and seaborn)

我一直在遵循本教程来绘制特征向量,这看起来很简单:Basic example for PCA with matplotlib,但我似乎无法用数据复制结果。

我发现了这一点,但是对于我想要做的事情来说,这似乎太复杂了,我不想创建一个FancyArrowPatchplotting the eigenvector of covariance matrix using matplotlib and np.linalg

--我试图使我的代码尽可能简单地遵循其他教程:

代码语言:javascript
复制
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
from sklearn import decomposition
import seaborn as sns; sns.set_style("whitegrid", {'axes.grid' : False})

%matplotlib inline
np.random.seed(0)

# Iris dataset
DF_data = pd.DataFrame(load_iris().data, 
                       index = ["iris_%d" % i for i in range(load_iris().data.shape[0])],
                       columns = load_iris().feature_names)

Se_targets = pd.Series(load_iris().target, 
                       index = ["iris_%d" % i for i in range(load_iris().data.shape[0])], 
                       name = "Species")

# Scaling mean = 0, var = 1
DF_standard = pd.DataFrame(StandardScaler().fit_transform(DF_data), 
                           index = DF_data.index,
                           columns = DF_data.columns)

# Sklearn for Principal Componenet Analysis

# Dims
m = DF_standard.shape[1]
K = 2

# PCA (How I tend to set it up)
M_PCA = decomposition.PCA(n_components=m)
DF_PCA = pd.DataFrame(M_PCA.fit_transform(DF_standard), 
                columns=["PC%d" % k for k in range(1,m + 1)]).iloc[:,:K]


# Plot the eigenvectors
#https://stackoverflow.com/questions/18299523/basic-example-for-pca-with-matplotlib

# This is where stuff gets weird...
data = DF_standard

mu = data.mean(axis=0)
eigenvectors, eigenvalues = M_PCA.components_, M_PCA.explained_variance_ #eigenvectors, eigenvalues, V = np.linalg.svd(data.T, full_matrices=False)
projected_data = DF_PCA #np.dot(data, eigenvectors)

sigma = projected_data.std(axis=0).mean()

fig, ax = plt.subplots(figsize=(10,10))
ax.scatter(projected_data["PC1"], projected_data["PC2"])
for axis, color in zip(eigenvectors[:K], ["red","green"]):
#     start, end = mu, mu + sigma * axis ### leads to "ValueError: too many values to unpack (expected 2)"

    # So I tried this but I don't think it's correct
    start, end = (mu)[:K], (mu + sigma * axis)[:K] 
    ax.annotate('', xy=end,xytext=start, arrowprops=dict(facecolor=color, width=1.0))
    
ax.set_aspect('equal')
plt.show()

EN

回答 1

Stack Overflow用户

发布于 2016-06-22 20:02:50

我想你问错问题了。特征向量是主成分(PC1、PC2等)。因此,绘制PC1,PC2,PC3三维图中的特征向量就是简单地绘制该图的三个正交轴。

你可能想要可视化特征向量在你原来的坐标系中的样子。这是您的第二个链接:Basic example for PCA with matplotlib中讨论的内容。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37976564

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档