特征脸
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_lfw_people
faces = fetch_lfw_people()
faces.keys()
dict_keys(['data', 'images', 'target', 'target_names', 'DESCR'])
faces.data.shape
(13233, 2914)
faces.target_names
array(['AJ Cook', 'AJ Lamas', 'Aaron Eckhart', ..., 'Zumrati Juma',
'Zurab Tsereteli', 'Zydrunas Ilgauskas'], dtype='<U35')
faces.images.shape
(13233, 62, 47)
random_indexes = np.random.permutation(len(faces.data))
X = faces.data[random_indexes]
example_faces = X[:36,:]
example_faces.shape
(36, 2914)
def plot_faces(faces):
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(faces[i].reshape(62, 47), cmap='bone')
plt.show()
plot_faces(example_faces)
特征脸
%%time
from sklearn.decomposition import PCA
pca = PCA(svd_solver='randomized')
pca.fit(X)
Wall time: 33.3 s
PCA(copy=True, iterated_power='auto', n_components=None, random_state=None,
svd_solver='randomized', tol=0.0, whiten=False) # 随机的方式求解, 没有指定主成分n,都要
pca.components_.shape # 所有的主成分
(2914, 2914)
plot_faces(pca.components_[:36,:]) # 前面比较笼统, 人脸就是大概这个位置,每一个脸都是特征脸的,线性组合
网友评论