scikit-learn/examples/decomposition/plot_sparse_pca.py

45 lines
1.3 KiB
Python
Raw Normal View History

2011-06-14 03:31:27 +08:00
"""
========================================
Sparse PCA for digits feature extraction
========================================
:ref:`SparsePCA` extracting the first 12 components out of the subset of
the digits dataset containing only the digit 3.
"""
print __doc__
2011-06-15 07:34:49 +08:00
# Authors: Vlad Niculae, Alexandre Gramfort
# License: BSD
2011-06-12 22:55:26 +08:00
import numpy as np
2011-06-15 07:34:49 +08:00
import pylab as pl
2011-06-12 22:55:26 +08:00
from scikits.learn.decomposition import SparsePCA
from scikits.learn.datasets import load_digits
2011-06-15 07:34:49 +08:00
###############################################################################
# Load data and fit the model
2011-06-12 22:55:26 +08:00
rows, cols = 4, 3
digits = load_digits()
threes = digits.data[digits.target == 3]
2011-06-15 07:34:49 +08:00
threes -= threes.mean(axis=0) # XXX: use preprocessors
model = SparsePCA(n_components=rows * cols, alpha=5)
2011-06-12 22:55:26 +08:00
model.fit(threes)
span = np.max(np.abs(model.components_))
2011-06-15 07:34:49 +08:00
###############################################################################
# Plot sparse components
fig = pl.figure(figsize=(1.2 * cols, 1.4 * rows))
2011-06-12 22:55:26 +08:00
for i, comp in enumerate(model.components_):
2011-06-15 07:34:49 +08:00
pl.subplot(rows, cols, i + 1)
pl.imshow(np.reshape(comp, (8, 8)), interpolation='nearest',
vmin=-span, vmax=span, cmap=pl.cm.PuOr)
pl.xticks(())
pl.yticks(())
2011-06-25 22:35:33 +08:00
2011-06-15 07:34:49 +08:00
pl.subplots_adjust(0.01, 0.15, 0.99, 0.99, 0.04, 0.)
2011-06-14 03:31:27 +08:00
cax = fig.add_axes([0.1, 0.06, 0.8, 0.04])
2011-06-15 07:34:49 +08:00
pl.colorbar(cax=cax, orientation='horizontal')
pl.show()