python - 蟒蛇 | 散点图不显示
问题描述
我正在对我的数据集执行 PCA,我可以获得正确的结果。但是当我试图可视化 PCA 时,它没有显示。这是我的尝试:
#Import dataset
dataset = pd.read_csv('Data.csv', names=['0','1','2','3','target'],header=0)
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
#PCA
from sklearn.decomposition import PCA
pca = PCA(n_components = 2)
X = pca.fit_transform(X)
principalDf = pd.DataFrame(data = X, columns = ['principal component 1',
'principal component 2'])
finalDf = pd.concat([principalDf, dataset['target']], axis = 1)
#Visualizing
fig = plt.figure(figsize = (8,8))
ax = fig.add_subplot(1,1,1)
ax.set_xlabel('Principal Component 1', fontsize = 15)
ax.set_ylabel('Principal Component 2', fontsize = 15)
ax.set_title('2 component PCA', fontsize = 20)
targets = ['1', '2', '3', '4']
colors = ['r', 'g', 'b', 'hotpink']
for target, color in zip(targets,colors):
indicesToKeep = finalDf['target'] == target
ax.scatter(finalDf.loc[indicesToKeep, 'principal component 1']
, finalDf.loc[indicesToKeep, 'principal component 2']
, c = color
, s = 50)
ax.legend(targets)
ax.grid()
解决方案
您正在索引您finalDf
以获取 DataFrame 的切片,其中列值与 listtarget
中的单个相同。target
targets = ['1', '2', '3', '4']
由于您target
列中的值不是str
类型,而是数值类型,因此没有满足此条件的数据:
'1' != 1
'2' != 2
'3' != 3
'4' != 4
因此没有数据被绘制。
要获得您想要的切片,而不是targets = ['1', '2', '3', '4']
您应该使用数值作为目标:
targets = [1, 2, 3, 4]
推荐阅读
- python - 如何使用 pyclustering lib 计算 k-mediod 聚类的轮廓系数?
- android - Android Kitkat 上的内存分析,DDMS 上的堆大小?
- sql - SQL - 如何删除重复值
- vuejs2 - 在mounted中设置变量,但在设置变量后不会更改
- powershell - SCCM 未从 powershell 读取返回代码
- sql - 试图在没有否定记录的表中查找唯一记录
- apache-spark - 为什么在 main 方法之外创建的方法不能在 RDD 中运行?
- javascript - Monaco 编辑器 - 使用警告/错误图标自定义 linting 错误
- windows - closesocket 后的 Windows 套接字完成例程回调
- sql-server - OleDbDataReader 和 bulkcopy.WriteToServer 不写入表