-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsparsity2.py
More file actions
58 lines (45 loc) · 1.43 KB
/
sparsity2.py
File metadata and controls
58 lines (45 loc) · 1.43 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
"""
File: sparsity2.py
By Peter Caven, peter@sparseinference.com
Description:
Another sparse recovery test function for the Stepping Stone Search Algorithm.
"""
import numpy
from numpy import *
from random import sample
from numpy.random import normal
from sss import Optimize
# Construct a random test instance:
rows,cols = 50,100
A = normal(size=(rows,cols))
x = zeros(cols)
nonZeroCount = cols//4
x[sample(range(cols), nonZeroCount)] = abs(normal(size=nonZeroCount))
b = dot(A,x)
L1 = sum(abs(x))
def Sparsity(x):
"""
Use this if we know the L1 norm of 'x'.
"""
y = dot(A,x) - b
return dot(y,y) + abs(sum(x) - L1)
def SparsityZero(x):
"""
Use this if we know nothing about 'x'.
"""
y = dot(A,x) - b
return dot(y,y) + (1.5 * sum(abs(x)))
optimum = Optimize( Sparsity,
dimensions = cols,
lowerDomain = 0.0,
upperDomain = 5.0,
constrainToDomain = True,
maxMutations = 3,
maxIndexes = 3,
gamma = 0.99999,
minImprovements = 3,
popSize = 20,
maxIterations = 5000000,
targetLoss = 0.001)
print(f"\nFound Solution (sum(|x|)={sum(abs(optimum.rep))}):\n{optimum.rep}")
print(f"\nTrue Solution (sum(|x|)={sum(abs(x))}):\n{x}")