数据的特征P,如果要是比样本容量还要多的话,必须进行降维处理,否则就是curse of dimensionality维数灾难
# -*-encoding: utf-8 -*-
"""
@version: 3.6
@time: 2018/4/1 14:46
@author: SunnyYang
@title:
@file: pcaTest.py
"""
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#%matplotlib inline 既然是IPython的内置magic函数,那么在Pycharm中是不会支持的。
from sklearn.datasets.samples_generator import make_blobs #是用来聚类的
# X为样本特征,Y为样本簇类别, 共1000个样本,每个样本3个特征,共4个簇,每个簇的中心点 每个类别的方差cluster_std random_state官方解释是随机生成器的种子 shuffle洗乱,默认值true center_box中心确定之后的数据边界默认是-10,10
X, Y = make_blobs(n_samples=10000, n_features=3, centers=[[3,3, 3], [0,0,0], [1,1,1], [2,2,2]], cluster_std=[0.2, 0.1, 0.2, 0.2],
random_state =9,shuffle=True,center_box=(-10,10))
fig = plt.figure() #建立空白图,也可在建立的时候指定图的大小:fig = plt.figure(figure.size=(4,2))
#plt.subplot(231) plt.subplot(232) plt.subplot(233) ...plt.subplot(236) 就是将画布分成两行三列,依次是第一个,第二个,第三个。。到第六个 最后plt.show()即可画出图形
#ax = Axes3D(fig) 将画布画在三维空间中
ax = Axes3D(fig, rect=[0, 0, 1, 1], elev=30, azim=20)
print(X)
plt.scatter(X[:, 0], X[:, 1], X[:, 2],marker='o') #AttributeError: 'NoneType' object has no attribute 'sqrt'
plt.show()
#在不降维的情况下对数据进行投影
from sklearn.decomposition import PCA
pca = PCA(n_components=3)
pca.fit(X)
print(pca.explained_variance_ratio_)
print(pca.explained_variance_)
#从三维降到二维
pca = PCA(n_components=2) #保留的主成分数,也就是样本的特征数 赋值为int,比如n_components=2,将把原始数据降到2维度。
pca.fit(X)
# print(pca.explained_variance_ratio_)
# print(pca.explained_variance_)
# print('8888888888888888888888888888888888888888888')
#降维后的图形展示k
X_new = pca.transform(X)
plt.scatter(X_new[:, 0], X_new[:, 1],marker='o')
plt.show()
输出:
[[ 2.38526096 2.1109917 2.23765695]
[ 0.05761939 -0.0117989 -0.03393958]
[ 3.08207073 3.19904227 3.08774759]
...,
[ 3.13804869 2.86955308 2.86443838]
降成二维时:
[ 0.98318212 0.00850037]
[ 3.78483785 0.03272285]
.....
参见:https://mp.weixin.qq.com/s/OxNj9fWaEMh8SuQiK52HWg