绘制PCA加载和sklearn中双图的加载(如R的自动绘图) [英] Plot PCA loadings and loading in biplot in sklearn (like R's autoplot)
问题描述
我在R
w/autoplot
中看到了本教程.他们绘制了载荷和载荷标签:
I saw this tutorial in R
w/ autoplot
. They plotted the loadings and loading labels:
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 3
w/matplotlib, scikit-learn, and pandas
进行数据分析.但是,我不知道如何添加这些内容?
I prefer Python 3
w/ matplotlib, scikit-learn, and pandas
for my data analysis. However, I don't know how to add these on?
如何使用matplotlib
绘制这些向量?
How can you plot these vectors w/ matplotlib
?
我一直在阅读恢复功能带有sklearn的PCA中的explained_variance_ratio_的名称,但尚未弄清
I've been reading Recovering features names of explained_variance_ratio_ in PCA with sklearn but haven't figured it out yet
这是我在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)
推荐答案
尝试使用"pca"库.这将绘制解释的方差,并创建一个双图.
Try the ‘pca’ library. This will plot the explained variance, and create a biplot.
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加载和sklearn中双图的加载(如R的自动绘图)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!