使用Python绘制PCA结果,包括散点图的原始数据
作为练习,我对iris数据进行了PCA。这是我的密码:使用Python绘制PCA结果,包括散点图的原始数据,python,numpy,matplotlib,scikit-learn,pca,Python,Numpy,Matplotlib,Scikit Learn,Pca,作为练习,我对iris数据进行了PCA。这是我的密码: #!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt from matplotlib import style style.use("ggplot") from sklearn.cluster import KMeans from sklearn.preprocessing import Standar
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use("ggplot")
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA # as sklearnPCA
import pandas as pd
#=================
df = pd.read_csv('iris.csv');
# Split the 1st 4 columns comprising values
# and the last column that has species
X = df.ix[:,0:4].values
y = df.ix[:,4].values
X_std = StandardScaler().fit_transform(X); # standardization of data
# Fit the model with X_std and apply the dimensionality reduction on X_std.
pca = PCA(n_components=2) # 2 PCA components;
Y_pca = pca.fit_transform(X_std)
# How to plot my results???? I am struck here!
请告知如何绘制我的原始虹膜数据和使用散点图导出的PCA。以下是我认为您可以可视化它的方式。我将把PC1放在X轴上,PC2放在Y轴上,并根据其类别为每个点上色。代码如下:
#first we need to map colors on labels
dfcolor = pd.DataFrame([['setosa','red'],['versicolor','blue'],['virginica','yellow']],columns=['Species','Color'])
mergeddf = pd.merge(df,dfcolor)
#Then we do the graph
plt.scatter(Y_pca[:,0],Y_pca[:,1],color=mergeddf['Color'])
plt.show()
这是我认为你可以想象的方式。我将把PC1放在X轴上,PC2放在Y轴上,并根据其类别为每个点上色。代码如下:
#first we need to map colors on labels
dfcolor = pd.DataFrame([['setosa','red'],['versicolor','blue'],['virginica','yellow']],columns=['Species','Color'])
mergeddf = pd.merge(df,dfcolor)
#Then we do the graph
plt.scatter(Y_pca[:,0],Y_pca[:,1],color=mergeddf['Color'])
plt.show()
请格式化你的帖子!你还没看过吗?请格式化你的帖子!你没看过吗?