scikit-learn/examples/linear_model/plot_omp.py

83 lines
2.2 KiB
Python
Raw Normal View History

2011-07-25 18:57:42 +08:00
"""
===========================
Orthogonal Matching Pursuit
===========================
Using orthogonal matching pursuit for recovering a sparse signal from a noisy
measurement encoded with a dictionary
"""
print(__doc__)
2011-07-25 18:57:42 +08:00
import matplotlib.pyplot as plt
2011-07-25 18:57:42 +08:00
import numpy as np
2013-07-26 00:57:38 +08:00
from sklearn.linear_model import OrthogonalMatchingPursuit
from sklearn.linear_model import OrthogonalMatchingPursuitCV
from sklearn.datasets import make_sparse_coded_signal
2011-07-25 18:57:42 +08:00
2011-07-29 06:28:00 +08:00
n_components, n_features = 512, 100
2012-11-28 22:03:43 +08:00
n_nonzero_coefs = 17
2011-07-25 18:57:42 +08:00
2011-07-29 06:28:00 +08:00
# generate the data
###################
2011-07-29 18:01:11 +08:00
2013-07-26 00:57:38 +08:00
# y = Xw
2012-11-28 22:03:43 +08:00
# |x|_0 = n_nonzero_coefs
2011-07-29 18:01:11 +08:00
2013-07-26 00:57:38 +08:00
y, X, w = make_sparse_coded_signal(n_samples=1,
n_components=n_components,
n_features=n_features,
2012-11-28 22:03:43 +08:00
n_nonzero_coefs=n_nonzero_coefs,
random_state=0)
2011-07-25 18:57:42 +08:00
2013-07-26 00:57:38 +08:00
idx, = w.nonzero()
2011-07-25 18:57:42 +08:00
2011-07-29 06:28:00 +08:00
# distort the clean signal
##########################
2011-07-31 23:28:57 +08:00
y_noisy = y + 0.05 * np.random.randn(len(y))
2011-07-25 18:57:42 +08:00
# plot the sparse signal
########################
plt.figure(figsize=(7, 7))
plt.subplot(4, 1, 1)
plt.xlim(0, 512)
plt.title("Sparse signal")
plt.stem(idx, w[idx])
2011-07-25 18:57:42 +08:00
# plot the noise-free reconstruction
####################################
2013-07-26 00:57:38 +08:00
omp = OrthogonalMatchingPursuit(n_nonzero_coefs=n_nonzero_coefs)
omp.fit(X, y)
coef = omp.coef_
idx_r, = coef.nonzero()
plt.subplot(4, 1, 2)
plt.xlim(0, 512)
plt.title("Recovered signal from noise-free measurements")
plt.stem(idx_r, coef[idx_r])
2011-07-25 18:57:42 +08:00
# plot the noisy reconstruction
###############################
2013-07-26 00:57:38 +08:00
omp.fit(X, y_noisy)
coef = omp.coef_
idx_r, = coef.nonzero()
plt.subplot(4, 1, 3)
plt.xlim(0, 512)
plt.title("Recovered signal from noisy measurements")
plt.stem(idx_r, coef[idx_r])
2013-07-26 00:57:38 +08:00
# plot the noisy reconstruction with number of non-zeros set by CV
##################################################################
omp_cv = OrthogonalMatchingPursuitCV()
omp_cv.fit(X, y_noisy)
coef = omp_cv.coef_
idx_r, = coef.nonzero()
plt.subplot(4, 1, 4)
plt.xlim(0, 512)
plt.title("Recovered signal from noisy measurements with CV")
plt.stem(idx_r, coef[idx_r])
2011-07-25 18:57:42 +08:00
plt.subplots_adjust(0.06, 0.04, 0.94, 0.90, 0.20, 0.38)
plt.suptitle('Sparse signal recovery with Orthogonal Matching Pursuit',
fontsize=16)
plt.show()