在sklearn中绘制PCA加载和加载(如R的autoplot)

时间:2022-08-22 23:51:23

I saw this tutorial in R w/ autoplot. They plotted the loadings and loading labels:

我在R w/ autoplot上看过这个教程。他们绘制了装载和装载标签:

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

在sklearn中绘制PCA加载和加载(如R的autoplot)https://cran.r-project.org/web/packages/ggfortify/vignettes/plot_pca.html

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

I prefer Python 3 w/ matplotlib, scikit-learn, and pandas for my data analysis. However, I don't know how to add these on?

我更喜欢Python 3 w/ matplotlib、scikit-learn和panda来进行数据分析。但是,我不知道如何添加这些?

How can you plot these vectors w/ matplotlib?

如何绘制这些向量w/ matplotlib?

I've been reading Recovering features names of explained_variance_ratio_ in PCA with sklearn but haven't figured it out yet

我一直在用sklearn阅读PCA中explained_variance_ratio_的恢复特性名称,但还没有弄清楚

Here's how I plot it in Python

这是我如何用Python绘制的

import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom sklearn.datasets import load_irisfrom sklearn.preprocessing import StandardScalerfrom sklearn import decompositionimport seaborn as sns; sns.set_style("whitegrid", {'axes.grid' : False})%matplotlib inlinenp.random.seed(0)# Iris datasetDF_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 = 1DF_standard = pd.DataFrame(StandardScaler().fit_transform(DF_data),                            index = DF_data.index,                           columns = DF_data.columns)# Sklearn for Principal Componenet Analysis# Dimsm = 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 classescolor_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)

在sklearn中绘制PCA加载和加载(如R的autoplot)

2 个解决方案

#1


4  

You could do something like the following by creating a biplot function. In this example I am using the iris data:

import numpy as npimport matplotlib.pyplot as pltfrom sklearn import datasetsfrom sklearn.decomposition import PCAimport pandas as pdfrom sklearn.preprocessing import StandardScaleriris = datasets.load_iris()X = iris.datay = iris.target#In general a good idea is to scale the datascaler = 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()

RESULT

结果

在sklearn中绘制PCA加载和加载(如R的autoplot)


#2


1  

I found the answer here by @teddyroland: https://github.com/teddyroland/python-biplot/blob/master/biplot.py

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

#1


4  

You could do something like the following by creating a biplot function. In this example I am using the iris data:

import numpy as npimport matplotlib.pyplot as pltfrom sklearn import datasetsfrom sklearn.decomposition import PCAimport pandas as pdfrom sklearn.preprocessing import StandardScaleriris = datasets.load_iris()X = iris.datay = iris.target#In general a good idea is to scale the datascaler = 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()

RESULT

结果

在sklearn中绘制PCA加载和加载(如R的autoplot)


#2


1  

I found the answer here by @teddyroland: https://github.com/teddyroland/python-biplot/blob/master/biplot.py

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