In [23]:
%matplotlib inline
import matplotlib.pyplot as plt
Here we'll take a look at a simple facial recognition example. This uses a dataset available within scikit-learn consisting of a subset of the Labeled Faces in the Wild data. Note that this is a relatively large download (~200MB) so it may take a while to execute.
In [24]:
from sklearn import datasets
lfw_people = datasets.fetch_lfw_people(min_faces_per_person=70, resize=0.4,
data_home='datasets')
lfw_people.data.shape
Out[24]:
Let's visualize these faces to see what we're working with:
In [25]:
fig = plt.figure(figsize=(8, 6))
# plot several images
for i in range(15):
ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[])
ax.imshow(lfw_people.images[i], cmap=plt.cm.bone)
We'll perform a Support Vector classification of the images. We'll do a typical train-test split on the images to make this happen:
In [26]:
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(lfw_people.data, lfw_people.target, random_state=0)
print X_train.shape, X_test.shape
1850 dimensions is a lot for SVM. We can use PCA to reduce these 1850 features to a manageable
size, while maintaining most of the information in the dataset. Here it is useful to use a variant
of PCA called RandomizedPCA
, which is an approximation of PCA that can be much faster for large
datasets. The interface is the same as the normal PCA we saw earlier:
In [27]:
from sklearn import decomposition
pca = decomposition.RandomizedPCA(n_components=50, whiten=True)
pca.fit(X_train)
Out[27]:
One interesting part of PCA is that it computes the "mean" face, which can be interesting to examine:
In [28]:
plt.imshow(pca.mean_.reshape((50, 37)), cmap=plt.cm.bone)
Out[28]:
The principal components measure deviations about this mean along orthogonal axes. It is also interesting to visualize these principal components:
In [29]:
print pca.components_.shape
In [30]:
plt.plot(pca.explained_variance_)
plt.xlabel('n_components')
plt.ylabel('explained variance')
Out[30]:
In [31]:
fig = plt.figure(figsize=(16, 6))
for i in range(30):
ax = fig.add_subplot(3, 10, i + 1, xticks=[], yticks=[])
ax.imshow(pca.components_[i].reshape((50, 37)), cmap=plt.cm.bone)
The components ("eigenfaces") are ordered by their importance from top-left to bottom-right. We see that the first few components seem to primarily take care of lighting conditions; the remaining components pull out certain identifying features: the nose, eyes, eyebrows, etc.
With this projection computed, we can now project our original training and test data onto the PCA basis:
In [32]:
X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)
In [33]:
print X_train_pca.shape
print X_test_pca.shape
These projected components correspond to factors in a linear combination of component images such that the combination approaches the original face.
Now we'll perform support-vector-machine classification on this reduced dataset:
In [34]:
from sklearn import svm
clf = svm.SVC(C=5., gamma=0.001)
clf.fit(X_train_pca, y_train)
Out[34]:
Finally, we can evaluate how well this classification did. First, we might plot a few of the test-cases with the labels learned from the training set:
In [35]:
fig = plt.figure(figsize=(8, 6))
for i in range(15):
ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[])
ax.imshow(X_test[i].reshape((50, 37)), cmap=plt.cm.bone)
y_pred = clf.predict(X_test_pca[i])[0]
color = 'black' if y_pred == y_test[i] else 'red'
ax.set_title(lfw_people.target_names[y_pred], fontsize='small', color=color)
The classifier is correct on an impressive number of images given the simplicity of its learning model! Using a linear classifier on 150 features derived from the pixel-level data, the algorithm correctly identifies a large number of the people in the images.
Again, we can
quantify this effectiveness using one of several measures from the sklearn.metrics
module. First we can do the classification report, which shows the precision,
recall and other measures of the "goodness" of the classification:
In [36]:
from sklearn import metrics
y_pred = clf.predict(X_test_pca)
print(metrics.classification_report(y_test, y_pred, target_names=lfw_people.target_names))
Another interesting metric is the confusion matrix, which indicates how often any two items are mixed-up. The confusion matrix of a perfect classifier would only have nonzero entries on the diagonal, with zeros on the off-diagonal.
In [37]:
print(metrics.confusion_matrix(y_test, y_pred))
In [38]:
print(metrics.f1_score(y_test, y_pred))
Above we used PCA as a pre-processing step before applying our support vector machine classifier.
Plugging the output of one estimator directly into the input of a second estimator is a commonly
used pattern; for this reason scikit-learn provides a Pipeline
object which automates this
process. The above problem can be re-expressed as a pipeline as follows:
In [39]:
from sklearn.pipeline import Pipeline
In [40]:
pipeline = Pipeline([('pca', decomposition.RandomizedPCA(n_components=150, whiten=True)),
('svm', svm.LinearSVC(C=1.0))])
In [41]:
pipeline.fit(X_train, y_train)
Out[41]:
In [42]:
y_pred = pipeline.predict(X_test)
In [43]:
print metrics.confusion_matrix(y_pred, y_test)
The results are not identical because we used the randomized version of the PCA -- because the projection varies slightly each time, the results vary slightly as well.
In [44]:
print(metrics.f1_score(y_test, y_pred))
In [44]: