-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathexample.py
More file actions
82 lines (64 loc) · 1.92 KB
/
example.py
File metadata and controls
82 lines (64 loc) · 1.92 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
# min (1/2) x'Q'x - q'x
import numpy as np
import matplotlib.pyplot as plt
import aa
dim = 100
mems = [5, 10, 20, 50]
N = int(1e4)
np.random.seed(1234)
Q = np.random.randn(dim, dim)
Q = 0.1 * Q.T.dot(Q)
q = np.random.randn(dim)
x_0 = np.random.randn(dim)
x_star = np.linalg.solve(Q, q)
step = 1.0 / np.max(np.linalg.eigvals(Q))
f = lambda x: 0.5 * x.T @ Q @ x - q.T @ x
f_star = f(x_star)
print('f^* = ', f_star)
print('No acceleration')
results = {}
fs = []
x = x_0.copy()
for i in range(N):
x_prev = np.copy(x)
x -= step * (Q.dot(x) - q)
fs.append(f(x) - f_star)
if i % 1000 == 0:
print('i: ', i,' f - f^*: ', np.abs(f(x) - f_star))
results['No accel'] = fs
RELAXATION = 1.0
for mem in mems:
print('Type-I acceleration, mem:', mem)
fs = []
x = x_0.copy()
aa_wrk = aa.AndersonAccelerator(dim, mem, type1=True, regularization=1e-8,
relaxation=RELAXATION, verbosity=1,
max_weight_norm=1e6)
for i in range(N):
if i > 0: aa_wrk.apply(x, x_prev)
x_prev = np.copy(x)
x -= step * (Q.dot(x) - q)
aa_wrk.safeguard(x, x_prev)
fs.append(f(x) - f_star)
if i % 1000 == 0:
print('i: ', i,' f - f^*: ', np.abs(f(x) - f_star))
results[f'AA-I {mem}'] = fs
print('Type-II acceleration, mem:', mem)
fs = []
x = x_0.copy()
aa_wrk = aa.AndersonAccelerator(dim, mem, type1=False, regularization=1e-12,
relaxation=RELAXATION, verbosity=1,
max_weight_norm=1e6)
for i in range(N):
if i > 0: aa_wrk.apply(x, x_prev)
x_prev = np.copy(x)
x -= step * (Q.dot(x) - q)
aa_wrk.safeguard(x, x_prev)
fs.append(f(x) - f_star)
if i % 1000 == 0:
print('i: ', i,' f - f^*: ', np.abs(f(x) - f_star))
results[f'AA-II {mem}'] = fs
for k,v in results.items():
plt.semilogy(v, label=k)
plt.legend()
plt.show()