eigenfaces.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. """
  2. ===================================================
  3. Faces recognition example using eigenfaces and SVMs
  4. ===================================================
  5. The dataset used in this example is a preprocessed excerpt of the
  6. "Labeled Faces in the Wild", aka LFW_:
  7. http://vis-www.cs.umass.edu/lfw/lfw-funneled.tgz (233MB)
  8. .. _LFW: http://vis-www.cs.umass.edu/lfw/
  9. original source: http://scikit-learn.org/stable/auto_examples/applications/face_recognition.html
  10. """
  11. print __doc__
  12. from time import time
  13. import logging
  14. import pylab as pl
  15. import numpy as np
  16. from sklearn.cross_validation import train_test_split
  17. from sklearn.datasets import fetch_lfw_people
  18. from sklearn.grid_search import GridSearchCV
  19. from sklearn.metrics import classification_report
  20. from sklearn.metrics import confusion_matrix
  21. from sklearn.decomposition import RandomizedPCA
  22. from sklearn.svm import SVC
  23. # Display progress logs on stdout
  24. logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
  25. ###############################################################################
  26. # Download the data, if not already on disk and load it as numpy arrays
  27. lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)
  28. # introspect the images arrays to find the shapes (for plotting)
  29. n_samples, h, w = lfw_people.images.shape
  30. np.random.seed(42)
  31. print n_samples, h, w
  32. # for machine learning we use the data directly (as relative pixel
  33. # position info is ignored by this model)
  34. X = lfw_people.data
  35. n_features = X.shape[1]
  36. # the label to predict is the id of the person
  37. y = lfw_people.target
  38. target_names = lfw_people.target_names
  39. n_classes = target_names.shape[0]
  40. print "Total dataset size:"
  41. print "n_samples: %d" % n_samples
  42. print "n_features: %d" % n_features
  43. print "n_classes: %d" % n_classes
  44. ###############################################################################
  45. # Split into a training and testing set
  46. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
  47. ###############################################################################
  48. # Compute a PCA (eigenfaces) on the face dataset (treated as unlabeled
  49. # dataset): unsupervised feature extraction / dimensionality reduction
  50. n_components = 150
  51. print "Extracting the top %d eigenfaces from %d faces" % (n_components, X_train.shape[0])
  52. t0 = time()
  53. pca = RandomizedPCA(n_components=n_components, whiten=True).fit(X_train)
  54. print "done in %0.3fs" % (time() - t0)
  55. print pca.explained_variance_ratio_
  56. eigenfaces = pca.components_.reshape((n_components, h, w))
  57. # print len(pca.components_[10])
  58. print "Projecting the input data on the eigenfaces orthonormal basis"
  59. t0 = time()
  60. X_train_pca = pca.transform(X_train)
  61. X_test_pca = pca.transform(X_test)
  62. print "done in %0.3fs" % (time() - t0)
  63. ###############################################################################
  64. # Train a SVM classification model
  65. print "Fitting the classifier to the training set"
  66. t0 = time()
  67. param_grid = {
  68. 'C': [1e3, 5e3, 1e4, 5e4, 1e5],
  69. 'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1],
  70. }
  71. # for sklearn version 0.16 or prior, the class_weight parameter value is 'auto'
  72. clf = GridSearchCV(SVC(kernel='rbf', class_weight='balanced'), param_grid)
  73. clf = clf.fit(X_train_pca, y_train)
  74. print "done in %0.3fs" % (time() - t0)
  75. print "Best estimator found by grid search:"
  76. print clf.best_estimator_
  77. ###############################################################################
  78. # Quantitative evaluation of the model quality on the test set
  79. print "Predicting the people names on the testing set"
  80. t0 = time()
  81. y_pred = clf.predict(X_test_pca)
  82. print "done in %0.3fs" % (time() - t0)
  83. print classification_report(y_test, y_pred, target_names=target_names)
  84. print confusion_matrix(y_test, y_pred, labels=range(n_classes))
  85. ###############################################################################
  86. # Qualitative evaluation of the predictions using matplotlib
  87. def plot_gallery(images, titles, h, w, n_row=3, n_col=4):
  88. """Helper function to plot a gallery of portraits"""
  89. pl.figure(figsize=(1.8 * n_col, 2.4 * n_row))
  90. pl.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35)
  91. for i in range(n_row * n_col):
  92. pl.subplot(n_row, n_col, i + 1)
  93. pl.imshow(images[i].reshape((h, w)), cmap=pl.cm.gray)
  94. pl.title(titles[i], size=12)
  95. pl.xticks(())
  96. pl.yticks(())
  97. # plot the result of the prediction on a portion of the test set
  98. def title(y_pred, y_test, target_names, i):
  99. pred_name = target_names[y_pred[i]].rsplit(' ', 1)[-1]
  100. true_name = target_names[y_test[i]].rsplit(' ', 1)[-1]
  101. return 'predicted: %s\ntrue: %s' % (pred_name, true_name)
  102. prediction_titles = [title(y_pred, y_test, target_names, i)
  103. for i in range(y_pred.shape[0])]
  104. plot_gallery(X_test, prediction_titles, h, w)
  105. # plot the gallery of the most significative eigenfaces
  106. eigenface_titles = ["eigenface %d" % i for i in range(eigenfaces.shape[0])]
  107. plot_gallery(eigenfaces, eigenface_titles, h, w)
  108. pl.show()