使用 sklearn 和 panda 进行主成分分析

Principal component analysis using sklearn and panda

我已尝试在此处 (PCA-tutorial) 重现 PCA 教程的结果,但我遇到了一些问题。

  1. 据我了解,我正在按照应有的步骤应用 PCA。但是我的结果与教程中的结果不相似(或者它们可能相似但我无法正确解释它们?)。使用 n_components=4 我得到下图 n_components4。我可能在某处遗漏了一些东西,我还添加了到目前为止的代码。

  2. 我的第二个问题是关于在图中标注点,我有标签,我希望每个点都有相应的标签。我尝试了一些方法,但到目前为止没有成功。

我也添加了数据集,我把它保存为 CSV:

,Cheese,Carcass meat,Other meat,Fish,Fats and oils,Sugars,Fresh potatoes,Fresh Veg,Other Veg,Processed potatoes,Processed Veg,Fresh fruit,Cereals,Beverages,Soft drinks,Alcoholic drinks,Confectionery England,105,245,685,147,193,156,720,253,488,198,360,1102,1472,57,1374,375,54 Wales,103,227,803,160,235,175,874,265,570,203,365,1137,1582,73,1256,475,64 Scotland,103,242,750,122,184,147,566,171,418,220,337,957,1462,53,1572,458,62 NIreland,66,267,586,93,209,139,1033,143,355,187,334,674,1494,47,1506,135,41

那么对这两个问题有什么想法吗?

`

import pandas as pd

import matplotlib.pyplot as plt

from sklearn import decomposition

demo_df = pd.read_csv('uk_food_data.csv')
demo_df.set_index('Unnamed: 0', inplace=True)

target_names = demo_df.index
tran_ne = demo_df.T

pca = decomposition.PCA(n_components=4)
comps = pca.fit(tran_ne).transform(tran_ne)
plt.scatter(comps[0,:], comps[1, :])

plt.title("PCA Analysis UK Food");
plt.xlabel("PC1");
plt.ylabel("PC2");
plt.grid();
plt.savefig('PCA_UK_Food.png', dpi=125)

`

你可以试试这个。

import pandas as pd

import matplotlib.pyplot as plt

from sklearn import decomposition

# use your data file path here
demo_df = pd.read_csv(file_path)
demo_df.set_index('Unnamed: 0', inplace=True)

target_names = demo_df.index.values
tran_ne = demo_df.values

pca = decomposition.PCA(n_components=4)
pcomp = pca.fit_transform(tran_ne)
pcomp1 = pcomp[:,0]

fig, ax = plt.subplots()
ax.scatter(x=pcomp1[0], y=0, c='r', label=target_names[0])
ax.scatter(x=pcomp1[1], y=0, c='g', label=target_names[1])
ax.scatter(x=pcomp1[2], y=0, c='b', label=target_names[2])
ax.scatter(x=pcomp1[3], y=0, c='k', label=target_names[3])
ax.legend(loc='best')