-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompressedsensing.py
More file actions
executable file
·101 lines (76 loc) · 2.02 KB
/
compressedsensing.py
File metadata and controls
executable file
·101 lines (76 loc) · 2.02 KB
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
import cvxpy as cp
import numpy as np
import matplotlib.pyplot as plt
import random
from tqdm import tqdm
def main():
tree_list = []
with open("wonderland-tree.txt", "r") as f:
for line in f:
tree_list += [int(c) for c in line.strip()]
x = np.array(tree_list)
n = x.size
print("Sparsity: %f" % (x.sum() / n))
"""
A = np.random.normal(size=(n, n))
b = A[:700] @ x
x_rec = recover(b, A[:700])
print("x_700 is close enough to x: %r" % np.allclose(x, x_rec))
r_min = bin_search(A, x, n) # 614
print("r_min: %d" % r_min)
norms = []
for i in tqdm(range(-10, 3)):
x_rec = recover(A[:r_min + i] @ x, A[:r_min + i])
norms.append(np.linalg.norm(x - x_rec, ord=1))
print(norms)
fig, ax = plt.subplots()
ax.set_title("L1-norm versus Compression Index")
ax.set_ylabel("L1-norm of Difference between recovered x and x")
ax.set_xlabel("Compressed Dimension relative to r*")
ax.plot(range(-10, 3), norms)
plt.show()
rps = []
for p in np.arange(0.011, 0.021, 0.001):
print("\n\np: ", p)
rs = []
for i in range(5):
A = np.zeros((n, n))
for i in range(n):
for j in range(n):
prob = random.random()
if prob <= p / 2:
A[i, j] = - 1
elif prob <= p:
A[i, j] = 1
r_min = bin_search(A, x, n)
rs.append(r_min)
r_hat = sum(rs) / len(rs) # 628.0
print(r_hat)
rps.append(r_hat)
print("rps: ", rps)
fig, ax = plt.subplots()
ax.set_title("Average Minimum r for Probability p")
ax.set_ylabel("Minimum r")
ax.set_xlabel("p")
ax.plot(rps)
plt.show()
"""
def recover(b, A):
x = cp.Variable(1200)
constraints = [A @ x == b]
obj = cp.Minimize(cp.atoms.norm1(x))
prob = cp.Problem(obj, constraints)
prob.solve()
return x.value
def bin_search(A, x, n):
l, r = 0, 1200
while l + 1 < r:
m = int((r + l) / 2)
x_rec = recover(A[:m] @ x, A[:m])
if np.linalg.norm(x - x_rec, ord=1) < 0.001:
r = m
else:
l = m
return r
if __name__ == "__main__":
main()