示例:Python機器學習之PCA主成分分析提取特徵臉

一、目的:通過Sklearn自帶的人臉數據集模擬PCA提取特徵臉的方法

 

二、環境:

1、安裝:Jupyter NoteBook (編寫Python的IDE)

2、安裝:pip install Pillow

 

三、實現:

1、引用資源:

import matplotlib.pyplot as plt
from sklearn.datasets import fetch_lfw_people

分別是matplotlib python中用於繪圖的類庫和人臉數據集

2、查看數據集

faces = fetch_lfw_people()
faces.data.shape

查看數據結構:

(869, 2914)
869條信息,2914個特徵點
faces.images.shape

轉換成平面:images是將我們的數據集以一個二維平面可視化的角度展現出來

(869, 62, 47)

是62*47的圖像平面

3、 隨機獲取36張臉

import numpy as np

random_indexs = np.random.permutation(len(faces.data))
X = faces.data[random_indexs]
example_faces = X[:36,:]
example_faces.shape
(36, 2914)

4、繪製這些人臉

def plot_digits(data):
    fig,axes = plt.subplots(6,6,figsize=(10,10),
    subplot_kw={'xticks':[],'yticks':[]},
    gridspec_kw=dict(hspace=0.1,wspace=0.1))
    for i,ax in enumerate(axes.flat):
        ax.imshow(data[i].reshape(62,47),cmap='bone')

plot_digits(example_faces)

繪製結果:

5、讀取臉對應的人名:

faces.target_names

array(['Alex Barros', 'Arminio Fraga', 'Audrey Sauret', 'Bison Dele',
       'Bob Beauprez', 'Bob Graham', 'Bob Huggins', 'Colin Montgomerie',
       'Curtis Strange', 'Daniela Cicarelli', 'Darren Clarke',
       'David Caruso', 'Dawn Staley', 'Edmund Stoiber',
       'Edward James Olmos', 'Eve Ensler', 'Felipe Perez Roque',
       'Fernando Leon de Aranoa', 'George HW Bush', 'George W Bush',
       'Gerhard Schroeder', 'Gideon Black', 'Gloria Macapagal Arroyo',
       'Gordon Brown', 'Guido Westerwelle', 'Heath Ledger',
       'Heather Whitestone McCallum', 'Herta Daeubler-Gmelin',
       'Igor Ivanov', 'JK Rowling', 'Jane Fonda', 'Jimmy Szymanski',
       'John Howard', 'John Manley', 'Juan Ignacio Chela',
       'Justin Guarini', 'Larry Ellison', 'Li Peng', 'Marc Grossman',
       'Michael Schumacher', 'Mike Tyson', 'Mstislav Rostropovich',
       'Nelson Mandela', 'Paul Lo Duca', 'Paul ONeill',
       'Pervez Musharraf', 'Richard Shelby', 'Robert Fico',
       'Robert Vowler', 'Shannyn Sossamon', 'Tara Dawn Christensen',
       'Tiger Woods', 'Tommy Haas', 'Will Smith'], dtype='<U27')

 

獲取總人數數:len(faces.target_names)

54

說明一共有54張不同的臉

6、使用隨機的方式來求解出PCA
 

%%time
X,y = faces.data,faces.target
from sklearn.decomposition import PCA
pca = PCA(svd_solver='randomized')
pca.fit(X)

pca.components_.shape
結果:(869, 2914)

 7、繪製特徵臉

通過以上方法可以提取特徵臉 

 四、特徵臉介紹

1、特徵臉的生成:

一組特徵臉可以通過在一大組描述不同人臉的圖像上進行主成分分析(PCA)獲得。任意一張人臉圖像都可以被認爲是這些標準臉的組合。例如,一張人臉圖像可能是特徵臉1的10%,加上特徵臉2的55%,在減去特徵臉3的3%。值得注意的是,它不需要太多的特徵臉來獲得大多數臉的近似組合。另外,由於人臉是通過一系列向量(每個特徵臉一個比例值)而不是數字圖像進行保存,可以節省很多存儲空間。

2、特徵臉的應用:

特徵臉的最直接的應用就是人臉識別。在這個需求下,特徵臉相比其他手段在效率方面比較有優勢,因爲特徵臉的計算速度非常快,短時間就可以處理大量人臉。但是,特徵臉在實際使用時有個問題,就是在不同的光照條件和成像角度時,會導致識別率大幅下降。因此,使用特徵臉需限制使用者在統一的光照條件下使用正面圖像進行識別

 

Github下載地址:https://github.com/HeBianGu/Python-sklearn.git

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章