-
Notifications
You must be signed in to change notification settings - Fork 263
/
Optimize_my_LM2.m
108 lines (63 loc) · 1.81 KB
/
Optimize_my_LM2.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
function [a,resnorm]=Optimize_my_LM2(Loss_fun,a0,data,TolX,TolFun,MaxIter)
% author Zhang Xin
tao=1e-10;
xk=a0;
v=2;
Jacobi=Get_Jacobi(Loss_fun,xk,data);
Ek=Loss_fun(xk,data);
g=Jacobi'*Ek;
found=logical(norm(g)<=TolFun);
mou=tao*max(diag(Jacobi'*Jacobi));
k=0;
while (~found && k<MaxIter+1)
%delta_x=-(Jacobi'*Jacobi+mou*eye(size(a0,2)))\Jacobi'*Ek;
delta_x=-[Jacobi;sqrt(mou)*eye(size(a0,2))]\[Ek;zeros(size(a0,2),1)];
if (norm(delta_x)<=TolX*(norm(xk)+TolX))
found=true;
else
xk_new=xk+delta_x';
Ek=Loss_fun(xk,data);
Ek_new=Loss_fun(xk_new,data);
L0=delta_x'*Jacobi'*Ek;
L_delta=delta_x'*Jacobi'*Jacobi*delta_x;
rho=(Ek'*Ek-Ek_new'*Ek_new)/(-L0-L_delta);
if rho>0
fprintf('Iterations: %d, Residual: %d, Step: %d \n',k,Ek'*Ek,norm(delta_x));
k=k+1;
xk=xk_new;
Jacobi=Get_Jacobi(Loss_fun,xk,data);
Ek=Loss_fun(xk,data);
g=Jacobi'*Ek;
found=(norm(g)<=TolFun);
mou=mou*max([1/3,1-(2*rho-1)^3]);
v=2;
else
mou=mou*v;
v=2*v;
end
end
end
xk=xk+delta_x';
Ek=Loss_fun(xk,data);
fprintf('Iterations: %d, Residual: %d, Step: %d \n',k,Ek'*Ek,norm(delta_x));
a=xk;
resnorm=Ek'*Ek;
end
function Jacobi=Get_Jacobi(Loss_fun,xk,data)
scale=1e-4;
%Ek=Loss_fun(xk,data);
for i=1:length(xk)
x_temp1=xk;
x_temp2=xk;
if abs(x_temp1(i))>scale
delta=x_temp1(i)*scale;
else
delta=scale;
end
x_temp1(i)=x_temp1(i)+delta;
x_temp2(i)=x_temp2(i)-delta;
E_temp1=Loss_fun(x_temp1,data);
E_temp2=Loss_fun(x_temp2,data);
Jacobi(:,i)=(E_temp1-E_temp2)/delta/2;
end
end