1. 程式人生 > >三種方法實現PCA演算法(Python)

三種方法實現PCA演算法(Python)

  主成分分析,即Principal Component Analysis(PCA),是多元統計中的重要內容,也廣泛應用於機器學習和其它領域。它的主要作用是對高維資料進行降維。PCA把原先的n個特徵用數目更少的k個特徵取代,新特徵是舊特徵的線性組合,這些線性組合最大化樣本方差,儘量使新的k個特徵互不相關。關於PCA的更多介紹,請參考:https://en.wikipedia.org/wiki/Principal_component_analysis.

  PCA的主要演算法如下:

  • 組織資料形式,以便於模型使用;
  • 計算樣本每個特徵的平均值;
  • 每個樣本資料減去該特徵的平均值(歸一化處理);
  • 求協方差矩陣;
  • 找到協方差矩陣的特徵值和特徵向量;
  • 對特徵值和特徵向量重新排列(特徵值從大到小排列);
  • 對特徵值求取累計貢獻率;
  • 對累計貢獻率按照某個特定比例選取特徵向量集的子集合;
  • 對原始資料(第三步後)進行轉換。

  其中協方差矩陣的分解可以通過按對稱矩陣的特徵向量來,也可以通過分解矩陣的SVD來實現,而在Scikit-learn中,也是採用SVD來實現PCA演算法的。關於SVD的介紹及其原理,可以參考:矩陣的奇異值分解(SVD)(理論)

  本文將用三種方法來實現PCA演算法,一種是原始演算法,即上面所描述的演算法過程,具體的計算方法和過程,可以參考:A tutorial on Principal Components Analysis, Lindsay I Smith.

 一種是帶SVD的原始演算法,在Python的Numpy模組中已經實現了SVD演算法,並且將特徵值從大從小排列,省去了對特徵值和特徵向量重新排列這一步。最後一種方法是用Python的Scikit-learn模組實現的PCA類直接進行計算,來驗證前面兩種方法的正確性。

  用以上三種方法來實現PCA的完整的Python如下:

 1 import numpy as np
 2 from sklearn.decomposition import PCA
 3 import sys
 4 #returns choosing how many main factors
 5 def index_lst(lst, component=0, rate=0):
6 #component: numbers of main factors 7 #rate: rate of sum(main factors)/sum(all factors) 8 #rate range suggest: (0.8,1) 9 #if you choose rate parameter, return index = 0 or less than len(lst) 10 if component and rate: 11 print('Component and rate must choose only one!') 12 sys.exit(0) 13 if not component and not rate: 14 print('Invalid parameter for numbers of components!') 15 sys.exit(0) 16 elif component: 17 print('Choosing by component, components are %s......'%component) 18 return component 19 else: 20 print('Choosing by rate, rate is %s ......'%rate) 21 for i in range(1, len(lst)): 22 if sum(lst[:i])/sum(lst) >= rate: 23 return i 24 return 0 25 26 def main(): 27 # test data 28 mat = [[-1,-1,0,2,1],[2,0,0,-1,-1],[2,0,1,1,0]] 29 30 # simple transform of test data 31 Mat = np.array(mat, dtype='float64') 32 print('Before PCA transforMation, data is:\n', Mat) 33 print('\nMethod 1: PCA by original algorithm:') 34 p,n = np.shape(Mat) # shape of Mat 35 t = np.mean(Mat, 0) # mean of each column 36 37 # substract the mean of each column 38 for i in range(p): 39 for j in range(n): 40 Mat[i,j] = float(Mat[i,j]-t[j]) 41 42 # covariance Matrix 43 cov_Mat = np.dot(Mat.T, Mat)/(p-1) 44 45 # PCA by original algorithm 46 # eigvalues and eigenvectors of covariance Matrix with eigvalues descending 47 U,V = np.linalg.eigh(cov_Mat) 48 # Rearrange the eigenvectors and eigenvalues 49 U = U[::-1] 50 for i in range(n): 51 V[i,:] = V[i,:][::-1] 52 # choose eigenvalue by component or rate, not both of them euqal to 0 53 Index = index_lst(U, component=2) # choose how many main factors 54 if Index: 55 v = V[:,:Index] # subset of Unitary matrix 56 else: # improper rate choice may return Index=0 57 print('Invalid rate choice.\nPlease adjust the rate.') 58 print('Rate distribute follows:') 59 print([sum(U[:i])/sum(U) for i in range(1, len(U)+1)]) 60 sys.exit(0) 61 # data transformation 62 T1 = np.dot(Mat, v) 63 # print the transformed data 64 print('We choose %d main factors.'%Index) 65 print('After PCA transformation, data becomes:\n',T1) 66 67 # PCA by original algorithm using SVD 68 print('\nMethod 2: PCA by original algorithm using SVD:') 69 # u: Unitary matrix, eigenvectors in columns 70 # d: list of the singular values, sorted in descending order 71 u,d,v = np.linalg.svd(cov_Mat) 72 Index = index_lst(d, rate=0.95) # choose how many main factors 73 T2 = np.dot(Mat, u[:,:Index]) # transformed data 74 print('We choose %d main factors.'%Index) 75 print('After PCA transformation, data becomes:\n',T2) 76 77 # PCA by Scikit-learn 78 pca = PCA(n_components=2) # n_components can be integer or float in (0,1) 79 pca.fit(mat) # fit the model 80 print('\nMethod 3: PCA by Scikit-learn:') 81 print('After PCA transformation, data becomes:') 82 print(pca.fit_transform(mat)) # transformed data 83 84 main()

執行以上程式碼,輸出結果為:

  這說明用以上三種方法來實現PCA都是可行的。這樣我們就能理解PCA的具體實現過程啦~~有興趣的讀者可以用其它語言實現一下哈~~

參考文獻:

  1. PCA 維基百科: https://en.wikipedia.org/wiki/Principal_component_analysis.
  2. 講解詳細又全面的PCA教程: A tutorial on Principal Components Analysis, Lindsay I Smith.
  3. 部落格:矩陣的奇異值分解(SVD)(理論):http://www.cnblogs.com/jclian91/p/8022426.html.
  4. 部落格:主成分分析PCA: https://www.cnblogs.com/zhangchaoyang/articles/2222048.html.
  5. Scikit-learn的PCA介紹:http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html.

相關推薦

方法實現PCA演算法Python

  主成分分析,即Principal Component Analysis(PCA),是多元統計中的重要內容,也廣泛應用於機器學習和其它領域。它的主要作用是對高維資料進行降維。PCA把原先的n個特徵用數目更少的k個特徵取代,新特徵是舊特徵的線性組合,這些線性組合最大化樣本方差,儘量使新的k個特徵互不相關。關於

實現Apriori演算法python

1 # coding: utf-8 2 3 # 利用python實現apriori演算法 4 5 # In[1]: 6 7 8 #匯入需要的庫 9 from numpy import * 10 11 12 # In[2]: 13 14 15

asp.net儲存過程使用方法存取資料庫記錄20070510

**********asp.net中儲存過程的應用***************後臺程式碼:using System;using System.Collections;using System.ComponentModel;using System.Data;using Sy

基於sklearn實現LogisticRegression演算法python

本文使用的資料型別是數值型,每一個樣本6個特徵表示,所用的資料如圖所示: 圖中A,B,C,D,E,F列表示六個特徵,G表示樣本標籤。每一行資料即為一個樣本的六個特徵和標籤。 實現LogisticRegression演算法的程式碼如下: from sklearn.li

Python C/S 網路程式設計方法實現天氣預報小程式

1. 首先明白下協議棧和庫的概念: 協議棧(Protocol Stack): 是指網路中各層協議的總和,其形象的反映了一個網路中檔案傳輸的過程:由上層協議到底層協議,再由底層協議到上層協議。 庫(Library):主要用來解析要使用的網路通訊協議,包含Python內建標準庫

刪除鏈表的倒數第N個節點方法實現

from ++ n+1 while end != bsp -- 結點 刪除鏈表的倒數第N個節點 給定一個鏈表,刪除鏈表的倒數第 n 個節點,並且返回鏈表的頭結點。 示例: 給定一個鏈表: 1->2->3->4->5, 和 n = 2. 當刪

url地址資料引數轉化JSON物件js方法實現

當我們用get方法提交表單時,在url上會顯示出請求的引數組成的字串,例如:http://localhost:3000/index.html?phone=12345678901&pwd=123123,在伺服器端我們要獲取其中的引數來進行操作,這種情況下,就要對請求過來的網址進行拆解了。下面將用3種方法

常用的排序演算法--python實現

1. 選擇排序,時間複雜度O(n^2),演算法不穩定。     思路:(1)迴圈整個陣列 arr,選出最大的數,將它放在空陣列 new_arr 的第一個位置。                (2)將剛

方法實現整型數值交換

int 異或 交換 實現 整型 數值交換 臨時 變量 a+b 臨時變量法: int a = 5; int b = 4; int temp = 0; temp = a; a = b; b = temp; 異或法: int a = 5; int b = 6; a = a^b;

leetCode 1號題詳解, 兩數之和的key , python3方法實現

原題如下 給定一個整數陣列和一個目標值,找出陣列中和為目標值的兩個數。 你可以假設每個輸入只對應一種答案,且同樣的元素不能被重複利用。 示例: 給定 nums = [2, 7, 11, 15], target = 9 因為 nums[0] + nums[1] = 2 + 7 = 9 所以

方法實現strlen函式

      我們知道,strlen函式是計算字串長度的函式,那麼要實現strlen函式主要就是得到字串長度,那麼 怎樣才能得到字串長度呢?如果是整形的陣列,我們可以通過下標來尋找,可是這是字串,我們就要了解字串了。       &nbs

使用HOG+卡方距離的方法實現圖片檢索python

在上一篇的文章中,使用HOG特徵提取了圖片的特徵,本篇文章則加上卡方距離的方法實現相似圖片的檢索。 前言 使用150張圖片,包括airplane、beach、desert、island和sea_ice各50張圖片進行測試。 第一步,獲取圖片特徵 獲取

數組合並演算法Python實現

合併兩個有序陣列(列表) 函式功能:傳入兩個有序列表,返回一個合併好的(有序)列表 引數 :兩個有序列表 思路:將長度短的列表的每個元素依次比較(先比較兩個list的長度,參len(list1) >= len(list2),如果 list2 的某個值大於等於 list1 中

robotframework使用python自定義“關鍵字”的兩方法:匯入庫LIB和匯入模組py檔案

1、匯入庫,需要把檔案做成包的形式 常見放置在,python主目錄的  \Lib\site-packages下 __init__.py 好處是:適合大規模的開發,包有多人負責,分模組開發,無限擴充套件檔案數量 缺點是:統一歸檔相對麻煩 2、匯入檔案,直

方法實現java呼叫Restful介面

1,基本介紹 Restful介面的呼叫,前端一般使用ajax呼叫,後端可以使用的方法比較多,   本次介紹三種:     1.HttpURLConnection實現     2.HttpClient實現     3.Spring的RestTemplat

android方法實現監聽事件

Android實現監聽事件的四種方式(匿名內部內實現,外部類實現,介面實現,繫結到標籤) 1. 使用匿名內部類的方式實現監聽事件 使用方法: 首先為要實現監聽的物件繫結監聽器,例如為一個Button物件繫結一個監聽器botton.setOnClickListener();。

斐波那契數列-java程式設計:方法實現斐波那契數列

題目要求:編寫程式在控制檯輸出斐波那契數列前20項,每輸出5個數換行 //java程式設計:三種方法實現斐波那契數列 //其一方法: public class Demo2 { // 定義三個變數方法

Android方法實現按鈕點選事件

0.我們都知道Java在開發介面的時候,需要使用監聽事件,只有在寫過監聽事件之後才能夠完整的使用軟體,比如說,我們在寫了一個button之後,想點選button,然後在文字標籤中變換字型該怎麼做呢?那麼我們就需要對button這個view進行新增監聽事件,新增完監聽事件之後,

java程式設計:方法實現斐波那契數列

題目要求:編寫程式在控制檯輸出斐波那契數列前20項,每輸出5個數換行 方法一:public class Fibonacci1{ //定義三個變數方法public static void main(String[] args) {int a=1, b=1, c=0;Syst

方法實現呼叫Restful介面

1 package com.taozhiye.controller; 2 3 import org.apache.http.HttpEntity; 4 import org.apache.http.HttpResponse; 5 import org.apache.http.NameVa