機器學習--用PCA算法實現三維樣本降到二維


  對於維數比較多的數據,首先需要做的事就是在盡量保證數據本質的前提下將數據中的維數降低。降維是一種數據集預處理技術,往往在數據應用在其他算法之前使用,它可以去除掉數據的一些冗余信息和噪聲,使數據變得更加簡單高效,從而實現提升數據處理速度的目的,節省大量的時間和成本。降維也成為了應用非常廣泛的數據預處理方法。目前處理降維的技術有很多種,如SVD奇異值分解,主成分分析(PCA),因子分析(FA),獨立成分分析(ICA)等。

  以下是使用主成分分析(PCA)進行降維:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.datasets.samples_generator import make_blobs
from sklearn.decomposition import PCA

def show_scatter(data,nfigure,n_axe):
    num=data.shape[1]
    if num==2:
        fig.add_subplot(nfigure,1,n_axe)
        plt.scatter(data[:,0],data[:,1],marker='o')
    elif num==3:        
        fig.add_subplot(nfigure,1,n_axe,projection='3d')
        plt.scatter(data[:,0],data[:,1],data[:,2],marker='o')

def pca_components(component,X):
    if isinstance(component,str):
        pca_n=PCA(n_components=component,svd_solver='full')
        print(component)
    else:
        pca_n=PCA(n_components=component)
        print(component)
    newData_n=pca_n.fit_transform(X)
    print('主成分方差比例:',pca_n.explained_variance_ratio_)
    print('主成分方差:',pca_n.explained_variance_)
    return newData_n

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)

n_components=[2,0.95,0.99,'mle']


fig=plt.figure(figsize=(8,12) )

show_scatter(X,len(n_components)+1,n_axe=1)

for i,component in zip(range(len(n_components)),n_components):
    newData=pca_components(component,X)
    show_scatter(newData,len(n_components)+1,n_axe=i+2)

輸出結果:

2
主成分方差比例: [ 0.98318212  0.00850037]
主成分方差: [ 3.78521638  0.03272613]
0.95
主成分方差比例: [ 0.98318212]
主成分方差: [ 3.78521638]
0.99
主成分方差比例: [ 0.98318212  0.00850037]
主成分方差: [ 3.78521638  0.03272613]
mle
主成分方差比例: [ 0.98318212]
主成分方差: [ 3.78521638]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM