2010-09-06 22:30:29 +08:00
|
|
|
"""
|
2011-06-06 17:44:35 +08:00
|
|
|
=======================================================
|
2011-06-04 23:18:12 +08:00
|
|
|
Comparison of LDA and PCA 2D projection of Iris dataset
|
2011-06-06 17:44:35 +08:00
|
|
|
=======================================================
|
2010-09-11 19:04:43 +08:00
|
|
|
|
|
|
|
|
The Iris dataset represents 3 kind of Iris flowers (Setosa, Versicolour
|
|
|
|
|
and Virginica) with 4 attributes: sepal length, sepal width, petal length
|
|
|
|
|
and petal width.
|
|
|
|
|
|
|
|
|
|
Principal Component Analysis (PCA) applied to this data identifies the
|
|
|
|
|
combination of attributes (principal components, or directions in the
|
|
|
|
|
feature space) that account for the most variance in the data. Here we
|
|
|
|
|
plot the different samples on the 2 first principal components.
|
2011-06-04 23:18:12 +08:00
|
|
|
|
|
|
|
|
Linear Discriminant Analysis (LDA) tries to identify attributes that
|
|
|
|
|
account for the most variance *between classes*. In particular,
|
|
|
|
|
LDA, in constrast to PCA, is a supervised method, using known class labels.
|
2010-09-06 22:30:29 +08:00
|
|
|
"""
|
2010-11-02 18:38:06 +08:00
|
|
|
print __doc__
|
2010-09-06 22:30:29 +08:00
|
|
|
|
|
|
|
|
import pylab as pl
|
|
|
|
|
|
2011-09-02 17:00:02 +08:00
|
|
|
from sklearn import datasets
|
|
|
|
|
from sklearn.decomposition import PCA
|
|
|
|
|
from sklearn.lda import LDA
|
2010-09-06 22:30:29 +08:00
|
|
|
|
|
|
|
|
iris = datasets.load_iris()
|
|
|
|
|
|
|
|
|
|
X = iris.data
|
|
|
|
|
y = iris.target
|
|
|
|
|
target_names = iris.target_names
|
|
|
|
|
|
2010-12-11 03:04:51 +08:00
|
|
|
pca = PCA(n_components=2)
|
2010-09-06 22:30:29 +08:00
|
|
|
X_r = pca.fit(X).transform(X)
|
|
|
|
|
|
2011-03-11 20:59:16 +08:00
|
|
|
lda = LDA(n_components=2)
|
|
|
|
|
X_r2 = lda.fit(X, y).transform(X)
|
|
|
|
|
|
2010-09-07 00:23:02 +08:00
|
|
|
# Percentage of variance explained for each components
|
2011-04-01 22:29:49 +08:00
|
|
|
print 'explained variance ratio (first two components):', \
|
|
|
|
|
pca.explained_variance_ratio_
|
2010-09-07 00:23:02 +08:00
|
|
|
|
2010-09-06 22:30:29 +08:00
|
|
|
pl.figure()
|
|
|
|
|
for c, i, target_name in zip("rgb", [0, 1, 2], target_names):
|
2011-04-04 21:42:16 +08:00
|
|
|
pl.scatter(X_r[y == i, 0], X_r[y == i, 1], c=c, label=target_name)
|
2010-09-06 22:30:29 +08:00
|
|
|
pl.legend()
|
|
|
|
|
pl.title('PCA of IRIS dataset')
|
|
|
|
|
|
2011-04-09 05:30:46 +08:00
|
|
|
pl.figure()
|
2011-03-11 20:59:16 +08:00
|
|
|
for c, i, target_name in zip("rgb", [0, 1, 2], target_names):
|
2011-04-04 21:42:16 +08:00
|
|
|
pl.scatter(X_r2[y == i, 0], X_r2[y == i, 1], c=c, label=target_name)
|
2011-03-11 20:59:16 +08:00
|
|
|
pl.legend()
|
|
|
|
|
pl.title('LDA of IRIS dataset')
|
|
|
|
|
|
2010-09-06 22:30:29 +08:00
|
|
|
pl.show()
|