python,sklearn实现PCA

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/littlle_yan/article/details/82954343

本文使用的数据类型是数值型,每一个样本7个特征表示,所用的数据如图所示:

图中A,B,C,D,E,F,G列表示六个特征,H表示样本标签。每一行数据即为一个样本的六个特征和标签。

实现PCA算法的代码如下:

from sklearn.decomposition import PCA as sklearnPCA
from matplotlib import pyplot as plt
import csv
from sklearn import preprocessing

data=[]
traffic_feature=[]
traffic_target=[]
csv_file = csv.reader(open('7packSize.csv'))
for content in csv_file:
    content=list(map(float,content))
    if len(content)!=0:
        data.append(content)
        traffic_feature.append(content[0:7])
        traffic_target.append(content[-1])
min_max_scaler = preprocessing.MinMaxScaler()
traffic_feature = min_max_scaler.fit_transform(traffic_feature)
print('data=',data)
print('traffic_feature=',traffic_feature)
print('traffic_target=',traffic_target)
sklearn_pca = sklearnPCA(n_components=2)
sklearn_transf = sklearn_pca.fit_transform(traffic_feature)

plt.plot(sklearn_transf[0:99148,0],sklearn_transf[0:99148,1], 'o', markersize=3, color='blue', alpha=0.5, label='class0')
plt.plot(sklearn_transf[99148:,0], sklearn_transf[99148:,1], '^', markersize=3, color='red', alpha=0.5, label='class1')

plt.xlabel('x')
plt.ylabel('y')
plt.xlim([-1,1])
plt.ylim([-1,1])
plt.legend()
plt.title('picture')


plt.show()

运行结果如图所示:

猜你喜欢

转载自blog.csdn.net/littlle_yan/article/details/82954343