【问题标题】:Plot PCA loadings and loading in biplot in sklearn (like R's autoplot)在 sklearn 中绘制 PCA 加载和双图加载(如 R 的自动绘图)
【发布时间】:2017-01-06 02:43:03
【问题描述】:

我在Rautoplot 看到了这个教程。他们绘制了载荷和载荷标签:

autoplot(prcomp(df), data = iris, colour = 'Species',
         loadings = TRUE, loadings.colour = 'blue',
         loadings.label = TRUE, loadings.label.size = 3)

https://cran.r-project.org/web/packages/ggfortify/vignettes/plot_pca.html

我更喜欢 Python 3matplotlib, scikit-learn, and pandas 进行数据分析。但是,我不知道如何添加这些?

如何用matplotlib 绘制这些向量?

我一直在阅读Recovering features names of explained_variance_ratio_ in PCA with sklearn,但还没有弄清楚

这是我在Python 中绘制它的方式

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)
Mod_PCA = decomposition.PCA(n_components=m)
DF_PCA = pd.DataFrame(Mod_PCA.fit_transform(DF_standard), 
                      columns=["PC%d" % k for k in range(1,m + 1)]).iloc[:,:K]
# Color classes
color_list = [{0:"r",1:"g",2:"b"}[x] for x in Se_targets]

fig, ax = plt.subplots()
ax.scatter(x=DF_PCA["PC1"], y=DF_PCA["PC2"], color=color_list)

【问题讨论】:

    标签: python scikit-learn pca dimensionality-reduction biplot


    【解决方案1】:

    试试“pca”库。这将绘制解释方差,并创建双图。

    pip install pca
    
    from pca import pca
    
    # Initialize to reduce the data up to the number of componentes that explains 95% of the variance.
    model = pca(n_components=0.95)
    
    # Or reduce the data towards 2 PCs
    model = pca(n_components=2)
    
    # Fit transform
    results = model.fit_transform(X)
    
    # Plot explained variance
    fig, ax = model.plot()
    
    # Scatter first 2 PCs
    fig, ax = model.scatter()
    
    # Make biplot with the number of features
    fig, ax = model.biplot(n_feat=4)
    

    【讨论】:

    • 选择这个作为新的答案。好多了。谢谢!
    • 是否有可能将其推广到所有距离矩阵而不仅仅是欧几里得距离?带主坐标分析
    • PCA 基于正交线性变换。将其推广到其他距离矩阵可能并不那么简单。我建议使用其他方法,例如 MDS、UMAP。
    • 有没有办法根据原始 X 数据框中的列名向 n_feat 添加标签?我真的很喜欢这个,但很想重命名向量的标签。谢谢!
    • 这是可能的,fit_transform() 函数包含可以使用的参数“col_labels”。
    【解决方案2】:

    您可以通过创建biplot 函数来执行以下操作。

    好文章在这里:https://towardsdatascience.com/pca-clearly-explained-how-when-why-to-use-it-and-feature-importance-a-guide-in-python-7c274582c37e?source=friends_link&sk=65bf5440e444c24aff192fedf9f8b64f

    在本例中,我使用的是虹膜数据:

    import numpy as np
    import matplotlib.pyplot as plt
    from sklearn import datasets
    from sklearn.decomposition import PCA
    import pandas as pd
    from sklearn.preprocessing import StandardScaler
    
    iris = datasets.load_iris()
    X = iris.data
    y = iris.target
    
    # In general, it's a good idea to scale the data prior to PCA.
    scaler = StandardScaler()
    scaler.fit(X)
    X=scaler.transform(X)    
    pca = PCA()
    x_new = pca.fit_transform(X)
    
    def myplot(score,coeff,labels=None):
        xs = score[:,0]
        ys = score[:,1]
        n = coeff.shape[0]
        scalex = 1.0/(xs.max() - xs.min())
        scaley = 1.0/(ys.max() - ys.min())
        plt.scatter(xs * scalex,ys * scaley, c = y)
        for i in range(n):
            plt.arrow(0, 0, coeff[i,0], coeff[i,1],color = 'r',alpha = 0.5)
            if labels is None:
                plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, "Var"+str(i+1), color = 'g', ha = 'center', va = 'center')
            else:
                plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, labels[i], color = 'g', ha = 'center', va = 'center')
        plt.xlim(-1,1)
        plt.ylim(-1,1)
        plt.xlabel("PC{}".format(1))
        plt.ylabel("PC{}".format(2))
        plt.grid()
    
    #Call the function. Use only the 2 PCs.
    myplot(x_new[:,0:2],np.transpose(pca.components_[0:2, :]))
    plt.show()
    

    结果


    【讨论】:

    • 哇!这段代码非常简单易懂。我制作了一个非常复杂且不完整的版本。谢谢你复活这个。把我的答案换成你的。
    • 很高兴我能帮上忙 :)
    • 这是一个不错的功能。但是,当您使用 1/(max-min) 时,您会失去对单位的跟踪。你会怎么称呼这张图表中的单位?我不知道如何正确命名它。 “按每台 PC 的最大范围归一化”对我来说听起来不是很吸引人。
    • 正确。 score 是投影特征,coeff 是特征向量的元素
    • 我还在这里提供了有关术语的更多信息:stackoverflow.com/a/47371788/5025009
    【解决方案3】:

    我在这里找到了@teddyroland 的答案:https://github.com/teddyroland/python-biplot/blob/master/biplot.py

    【讨论】:

    • 完美!正是我想要的
    猜你喜欢
    • 2019-03-09
    • 2021-05-02
    • 2016-06-11
    • 2020-08-19
    • 2022-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多