-
Notifications
You must be signed in to change notification settings - Fork 0
/
BFGScomparison.m
265 lines (207 loc) · 6.57 KB
/
BFGScomparison.m
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
clc; clear; close all;
%% BFGS vs Newton comparison
% steps
n = 1000;
% convergence
nsol = zeros(4,1);
% tolerance
tol = 1e-10;
% switch case for function to be optimized
optcase = 3;
%% Define function to be optimized (searched for minimum)
% https://en.wikipedia.org/wiki/Test_functions_for_optimization
% some of these are really hard to optimize
switch optcase
case 1
nv = 2;
vars = sym('x',[nv 1]);
% sphere -> opt = 0
truesol = zeros(nv,1);
fsym = vars'*vars;
case 2
vars = sym('x',[2 1]);
% Himmelblau's function (benchmark) -> opt = 0
truesol = [3 2; -2.805118 3.131312; -3.779310 -3.283186; 3.584428 -1.848126]';
fsym = (vars(1)^2 + vars(2)-11)^2 + (vars(1)+vars(2)^2-7)^2;
nv = length(vars);
case 3
vars = sym('x',[2 1]);
% Three-hump camel function -> opt = 0
truesol = [0;0];
fsym = 2*vars(1)^2-1.05*vars(1)^4+vars(1)^6/6 +vars(1)*vars(2)+vars(2)^2;
nv = length(vars);
case 4
% restrigin function -> opt = 0
nv = 2;
vars = sym('x',[nv 1]);
fsym = 10*nv;
for i = 1:nv
fsym = fsym + (vars(i)^2 - 10*cos(2*pi*vars(i)));
end
truesol = zeros(nv,1);
case 5
% beale function
nv = 2;
vars = sym('x',[nv 1]);
truesol = [3;0.5];
fsym = (1.5-vars(1)+vars(1)*vars(2))^2 + (2.25 - vars(1) + vars(1)*vars(2)^2)^2 + (2.625 - vars(1) + vars(1)*vars(2)^3)^2;
case 6
% rosenbrock function
nv = 3;
vars = sym('x',[nv 1]);
truesol = ones(nv,1);
fsym = 0;
for i = 1:nv-1
fsym = fsym + 100*(vars(i+1)-vars(i)^2)^2 + (1-vars(i))^2;
end
end
f = matlabFunction(fsym,'vars',{vars});
%%
rng('shuffle')
% gradient
gradfsym = gradient(fsym,vars);
gradf = matlabFunction(gradfsym,'vars',{vars});
gradnum = @(x) fordiff(f,x);
% hessians
Hsym = hessian(fsym,vars);
Hsinv = inv(Hsym);
H = matlabFunction(Hsym,'vars',{vars});
Hinv = matlabFunction(Hsinv,'vars',{vars});
% solution steps
sol = zeros(nv,4,n+1);
init = 3 + rand(nv,1).*(-6);
for i = 1:4
sol(:,i,1) = init;
end
% initialize BFGS matrices and variables
Hb = zeros(nv,nv,4,n+1);
hinit = randn(nv);
for i = 1:2
Hb(:,:,i,1) = hinit'*hinit;%0.5 * eye(nv);
end
sb = zeros(nv,4,n);
yb = zeros(nv,4,n);
alpha = zeros(4,n);
%% Iterations
% Need to check for both computed gradient (with forward diff) and symbolic one
% BFGS + symbolic gradient
for i = 1:n
% LineSearch with symbolic gradient, get both xk+1 and alphak+1
[xk1, ak1] = linsearch_computed(f,gradf,Hb(:,:,1,i),sol(:,1,i));
sol(:,1,i+1) = xk1;
alpha(1,i) = ak1;
nsol(1) = nsol(1)+1;
if norm(gradf(xk1)) <= tol
break
end
yb(:,1,i) = gradf(sol(:,1,i+1)) - gradf(sol(:,1,i));
sb(:,1,i) = sol(:,1,i+1) - sol(:,1,i);
Hb(:,:,1,i+1) = BFGSiteration(Hb(:,:,1,i),sb(:,1,i),yb(:,1,i));
end
%%
% BFGS + computed gradient
for i = 1:n
% LineSearch with numeric gradient, get both xk+1 and alphak+1
[xk1, ak1] = linsearch_computed(f,gradnum,Hb(:,:,2,i),sol(:,2,i));
sol(:,2,i+1) = xk1;
alpha(2,i) = ak1;
nsol(2) = nsol(2)+1;
if norm(gradnum(xk1)) <= tol
break
end
yb(:,2,i) = gradf(sol(:,2,i+1)) - gradf(sol(:,2,i));
sb(:,2,i) = sol(:,2,i+1) - sol(:,2,i);
Hb(:,:,2,i+1) = BFGSiteration(Hb(:,:,2,i),sb(:,2,i),yb(:,2,i));
end
%%
% Newton + computed gradient
for i = 1:n
% LineSearch with numeric gradient, get both xk+1 and alphak+1
[xk1, ak1] = linsearch_computed(f,gradnum,Hinv(sol(:,3,i)),sol(:,3,i));
sol(:,3,i+1) = xk1;
alpha(3,i) = ak1;
nsol(3) = nsol(3)+1;
if norm(gradnum(xk1)) <= tol
break
end
end
%%
% Newton + symbolic gradient
for i = 1:n
% LineSearch with symbolic gradient, get both xk+1 and alphak+1
[xk1, ak1] = linsearch_computed(f,gradf,Hinv(sol(:,4,i)),sol(:,4,i));
sol(:,4,i+1) = xk1;
alpha(4,i) = ak1;
nsol(4) = nsol(4)+1;
if norm(gradnum(xk1)) <= tol
break
end
end
%% Plots (only if nv=2, else pretty hard to visualize)
names = {'BFGS + symbolic gradient', 'BFGS + numeric gradient','Newton + numeric gradient','Newton + symbolic gradient'};
colors = jet(4);
if nv == 2
[X, Y] = meshgrid(-6:0.05:6);
lx = size(X,1);
Z = zeros(lx);
for i = 1:lx
for j = 1:lx
Z(i,j) = log10(f([X(i,j);Y(i,j)]));
end
end
figure
contour(X,Y,Z,35,'HandleVisibility','off')
hold on
plot(truesol(1,:),truesol(2,:),'b*','LineWidth',3,'HandleVisibility','off')
for i = 1:4
plot(squeeze(sol(1,i,1:nsol(i))),squeeze(sol(2,i,1:nsol(i))),'Color',colors(i,:),'Marker','o'...
,'MarkerSize',5,'DisplayName',names{i})
scatter(squeeze(sol(1,i,[nsol(i)])),squeeze(sol(2,i,[nsol(i)])),80,colors(i,:),"filled",'Marker',"square",'HandleVisibility','off')
end
scatter(init(1),init(2),80,'green','filled','Marker','diamond','DisplayName','init')
xlim([-5 5])
ylim([-5 5])
xlabel('X')
ylabel('Y')
title("Trajectories of solutions on level-sets of optimized function")
legend
cb = colorbar;
ylabel(cb,'Log Magnitude')
figure
ZZ = zeros(lx,lx);
for i = 1:lx
for j = 1:lx
ZZ(i,j) = log(norm(gradnum([X(i,j);Y(i,j)])));
end
end
gradcf = contour(X,Y,ZZ,50,'HandleVisibility','off');
hold on
for i = 1:4
plot(squeeze(sol(1,i,1:nsol(i))),squeeze(sol(2,i,1:nsol(i))),'Color',colors(i,:),'Marker','o'...
,'MarkerSize',5,'DisplayName',names{i})
scatter(squeeze(sol(1,i,[nsol(i):nsol(i)])),squeeze(sol(2,i,[nsol(i):nsol(i)])),80,colors(i,:),'Marker',"square",'HandleVisibility','off')
end
scatter(init(1),init(2),80,'green','filled','Marker','diamond','DisplayName','init')
xlim([-5 5])
ylim([-5 5])
xlabel('X')
ylabel('Y')
cb1 = colorbar;
ylabel(cb1,'Log Magnitude')
legend
title("Trajectories of solutions on level-sets of the norm of the gradient")
end
%%
for j = 1:size(truesol,2)
figure
hold on
for i = 1:4
plot(1:nsol(i),cellfun(@(x) norm(x),num2cell(squeeze(sol(:,i,1:nsol(i))-truesol(:,j)),1)),'Color',colors(i,:),'DisplayName',names{i})
end
set(gca, 'YScale', 'log')
set(gca, 'XScale', 'log')
legend
xlabel('# of Iterations')
ylabel("log(||x-x_{opt}||^2)")
title("Distance from solution [" + num2str(truesol(1,j)) + ", " + num2str(truesol(1,j)) +"]")
end