-
Notifications
You must be signed in to change notification settings - Fork 0
/
leonomp2.py
177 lines (161 loc) · 5.85 KB
/
leonomp2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# -*- coding: utf-8 -*-
"""
this code is designed for the test of sparse coding
"""
from time import time
import numpy as np
from scipy import linalg
import matplotlib.pyplot as pl
def unsparse(v, idx, length):
x = np.zeros(length)
x[idx] = v
return x
def orthogonal_mp(D, x, m, eps=None):
residual = x
idx = []
if eps == None:
stopping_condition = lambda: len(idx) == m
else:
stopping_condition = lambda: np.inner(residual, residual) <= eps
while not stopping_condition():
lam = np.abs(np.dot(residual, D)).argmax()
idx.append(lam)
gamma,_,_,_ = linalg.lstsq(D[:, idx], x)
residual = x - np.dot(D[:, idx], gamma)
return gamma, idx
def cholesky_omp(D, x, m, eps=None):
if eps == None:
stopping_condition = lambda: it == m
else:
stopping_condition = lambda: np.inner(residual, residual) <= eps
alpha = np.dot(x,D)
it = 1
lam = np.abs(np.dot(x,D)).argmax()
idx = [lam]
L = np.ones((1,1))
gamma = linalg.lstsq(D[:,idx],x)[0]
residual = x - np.dot(D[:,idx],gamma)
while not stopping_condition():
lam = np.abs(np.dot(residual, D)).argmax()
w = linalg.solve_triangular(L, np.dot(D[:,idx].T, D[:,lam]),
lower=True, unit_diagonal=True)
L = np.r_[np.c_[L, np.zeros(len(L))],
np.atleast_2d(np.append(w, np.sqrt(1-np.dot(w.T, w))))]
idx.append(lam)
it +=1
Ltc = linalg.solve_triangular(L, alpha[idx], lower=True)
gamma = linalg.solve_triangular(L, Ltc, trans=1, lower=True)
residual = x - np.dot(D[:, idx], gamma)
return gamma, idx
def _batch_omp_step(G, alpha_0, m, eps_0=None, eps=None):
idx = []
L = np.ones((1,1))
alpha = alpha_0
eps_curr = eps_0
delta = 0
it = 0
if eps == None:
stopping_condition = lambda: it == m
else:
stopping_condition = lambda: eps_curr <=eps
while not stopping_condition():
lam = np.abs(alpha).argmax()
if len(idx) > 0:
w = linalg.solve_triangular(L, G[idx, lam],
lower = True, unit_diagonal=True)
L = np.r_[np.c_[L, np.zeros(len(L))],
np.atleast_2d(np.append(w, np.sqrt(1-np.inner(w,w))))]
idx.append(lam)
it +=1
Ltc = linalg.solve_triangular(L, alpha_0[idx], lower=True)
gamma = linalg.solve_triangular(L, Ltc, trans=1, lower=True)
beta = np.dot(G[:, idx], gamma)
alpha = alpha_0 - beta
if eps != None:
eps_curr += delta
delta = np.inner(gamma, beta[idx])
eps_curr -= delta
return gamma, idx
def batch_omp(D, x, m, eps=None):
Alpha = np.dot(D.T, x)
G = np.dot(D.T, D)
func = lambda a: unsparse(*_batch_omp_step(G, a, m), length=D.shape[1])
V = np.apply_along_axis(func, axis=0, arr=Alpha)
return V
def generate_dict(n_features, n_components):
D = np.random.randn(n_components, n_features)
D /= np.apply_along_axis(lambda x: np.sqrt(np.dot(x.T, x)), 0, D)
return D
def generate_data(D, sparsity):
n_features = D.shape[1]
x = np.zeros(n_features)
indices = np.random.randint(0, n_features, sparsity)
x[indices] = np.random.normal(0, 5, sparsity)
return (indices, x), np.dot(D, x)
def bench_plot():
np.random.seed(42)
n_features, n_components = 512, 1024
print "generating dictionary..."
D = generate_dict(n_features, n_components)
sparsities = np.arange(50, 200, 50)
print "generating signals..."
Y = np.zeros((n_components, len(sparsities)))
X = np.zeros((n_features, len(sparsities)))
for i, sp in enumerate(sparsities):
(_,X[:,i]), Y[:,i] = generate_data(D, sp)
print "precomputing..."
G = np.dot(D.T, D)
A = np.dot(D.T, Y)
naive, cholesky, batch = [], [], []
naive_er, cholesky_er, batch_er = [], [], []
for i in xrange(len(sparsities)):
print "sparsity:", sparsities[i]
t0 = time()
x, idx = orthogonal_mp(D, Y[:,i], sparsities[i])
naive.append(time() - t0)
naive_er.append(linalg.norm(X[:,i]-unsparse(x,idx,n_features)))
t0 = time()
x, idx = cholesky_omp(D, Y[:, i], sparsities[i])
cholesky.append(time() - t0)
cholesky_er.append(linalg.norm(X[:,i]-unsparse(x, idx, n_features)))
t0 = time()
x, idx = _batch_omp_step(G, A[:, i], sparsities[i])
batch.append(time() - t0)
batch_er.append(linalg.norm(X[:,i]-unsparse(x, idx, n_features)))
pl.figure(1)
pl.subplot(1,2,1)
pl.xlabel('sparsity level')
pl.ylabel('Time')
pl.plot(sparsities, naive, 'o-', label="Naive implementation")
pl.plot(sparsities, cholesky, 'o-', label="Cholesky implementation")
pl.plot(sparsities, batch, 'o-', label="Batch implementation")
pl.legend()
pl.subplot(1,2,2)
pl.xlabel('sparsity level')
pl.ylabel('Error')
pl.plot(sparsities, naive_er, 'o-', label="Naive implementation")
pl.plot(sparsities, cholesky_er, 'o-', label="Cholesky implementation")
pl.plot(sparsities, batch_er, 'o-', label="Batch implementation")
pl.show()
def plot_reconstruction():
np.random.seed(42)
D = generate_dict(n_features=512, n_components=100)
sparsity = 17
(indices, x), y = generate_data(D, sparsity)
pl.figure(2)
pl.subplot(3,1,1)
pl.title("sparse signal")
pl.stem(indices, x[indices])
y_noise = y + np.random.normal(0, 0.05, y.shape)
x_r, i_r = _batch_omp_step(np.dot(D.T, D), np.dot(D.T, y), sparsity)
pl.subplot(3,1,2)
pl.title("Recovered signal from noise-free measurements")
pl.stem(i_r, x_r)
x_r, i_r = _batch_omp_step(np.dot(D.T, D), np.dot(D.T, y_noise), sparsity)
pl.subplot(3,1,3)
pl.title("Recoverd signal from noisy measurements")
pl.stem(i_r, x_r)
pl.show()
if __name__=="__main__":
bench_plot()
plot_reconstruction()