3.5.5 把所有的东西放在一起: 面孔识别

展示使用主成分分析来降维和用执行向量机分类的面孔识别的例子。

3.5.5 把所有的东西放在一起: 面孔识别 - 图1

In [ ]:

  1. """
  2. Stripped-down version of the face recognition example by Olivier Grisel
  3. http://scikit-learn.org/dev/auto_examples/applications/face_recognition.html
  4. ## original shape of images: 50, 37
  5. """
  6. import numpy as np
  7. import pylab as pl
  8. from sklearn import cross_val, datasets, decomposition, svm
  9. # ..
  10. # .. load data ..
  11. lfw_people = datasets.fetch_lfw_people(min_faces_per_person=70, resize=0.4)
  12. perm = np.random.permutation(lfw_people.target.size)
  13. lfw_people.data = lfw_people.data[perm]
  14. lfw_people.target = lfw_people.target[perm]
  15. faces = np.reshape(lfw_people.data, (lfw_people.target.shape[0], -1))
  16. train, test = iter(cross_val.StratifiedKFold(lfw_people.target, k=4)).next()
  17. X_train, X_test = faces[train], faces[test]
  18. y_train, y_test = lfw_people.target[train], lfw_people.target[test]
  19. # ..
  20. # .. dimension reduction ..
  21. pca = decomposition.RandomizedPCA(n_components=150, whiten=True)
  22. pca.fit(X_train)
  23. X_train_pca = pca.transform(X_train)
  24. X_test_pca = pca.transform(X_test)
  25. # ..
  26. # .. classification ..
  27. clf = svm.SVC(C=5., gamma=0.001)
  28. clf.fit(X_train_pca, y_train)
  29. # ..
  30. # .. predict on new images ..
  31. for i in range(10):
  32. print lfw_people.target_names[clf.predict(X_test_pca[i])[0]]
  33. _ = pl.imshow(X_test[i].reshape(50, 37), cmap=pl.cm.gray)
  34. _ = raw_input()

完整代码: faces.py