-
Notifications
You must be signed in to change notification settings - Fork 5
/
dsy_numberical_optimization.py
330 lines (294 loc) · 12.2 KB
/
dsy_numberical_optimization.py
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 15 21:51:01 2022
@author: dsy
"""
import numpy as np
import numpy.linalg as LA
import time
# import pandas as pd
"""Welcome to dsy_numberical_optimization .To use this project,
you need to define your own targer funtion and optimizer with object "target_funtion" and "Optimizer".
Those two object are the most important object in this lib.
Here is a introduction for class "target_funtion"
class target_funtion args:
dimension:
type:list,if your target funtion is a map R_m to R_1 ,then your dimension=[1,m]
funtion:
type:funtion,you should pass your funtion in this arg,such as (lambda x:x.T*x)
grad_operator:
type:funtion,you should pass your grad_funtion in this arg,such as(lambda x:2x)
Hermite:
type:funtion,you should pass your Hermite_funtion in this arg
class Optimizer:
target_funtion:
type:target_funtion, your own target funtion.
Interpolate:
type:str ,choose one Interpolate,such as quadratic, cubic, or bisection.
alpha_logs:
type:bool,you can choose print step_length every step or not.
steps_logs:
type:bool,you can choose print target funtion's value every step or not.
require_time:
type:bool,you can choose print the time spent in the entire optimization process.
class line_search args:
target_funtion:
type:target_funtion
Interpolate:
type:str Interpolate,such as quadratic, cubic, or bisection.
"""
class target_function:
def __init__(self,dimension,function,grad_operator,Hessian= lambda x:0):
self.dimension=dimension
self.function=function
self.grad_operator=grad_operator
self.Hessian=Hessian
def get_value(self,x):
return self.function(x)
def get_grad(self,x):
return self.grad_operator(x)
def get_Hessian(self,x):
return self.Hessian(x)
def start_point(self):
rs = np.random.RandomState(1008)
sp=np.mat(rs.rand(self.dimension[0],self.dimension[1]))
return sp.T
class Optimizer:
def __init__(self,target_function,Interpolate="bisection",alpha_logs=False,steps_logs=False,Gly_logs=False,require_time=True,error_end=1e-6,constant_alpha=(False,1e-4)):
self.tf=target_function
self.Interpolate=Interpolate
self.error_end=error_end
self.alpha_logs=alpha_logs
self.steps_logs=steps_logs
self.require_time=require_time
self.Gly_logs=Gly_logs
self.ca=constant_alpha
def GD_optmize(self,start,Method="steepest_descent",A=np.mat([])):
x=start
if Method=="steepest_descent":
print("Method: steepest_descent")
ls=line_search(self.tf,self.Interpolate,self.alpha_logs)
if Method=="linear_conjugate_gradient":
print("Method: linear_conjugate_gradient")
print("waring: this method can only optmize funtion form like (0.5x.T*A*x-b.T*x)")
if Method=="FR_conjugate_gradient":
print("Method: FR_conjugate_gradient")
ls=line_search(self.tf,self.Interpolate,self.alpha_logs,c2=0.1)
if Method=="PR_conjugate_gradient":
print("Method: PR_conjugate_gradient")
ls=line_search(self.tf,self.Interpolate,self.alpha_logs,c2=0.1)
if Method=="HR_conjugate_gradient":
print("Method: HR_conjugate_gradient")
ls=line_search(self.tf,self.Interpolate,self.alpha_logs,c2=0.1)
if Method=="SR1":
print("Method: SR1")
if Method=="DFP":
print("Method: DFP")
if Method=="BFGS":
print("Method: BFGS")
if Method=="LS_Newton_CG":
print("Method: LS_Newton_CG")
ls=line_search(self.tf,self.Interpolate,self.alpha_logs,c2=0.1)
begin=time.time()
x_his=[]
fy_his=[]
for i in range(10000000000000):
x_his.append(i)
fy_his.append(float(self.tf.get_value(x)))
#########################################
if Method=="steepest_descent":
p=-self.tf.get_grad(x)
if self.ca[0]==True:
a=self.ca[1]*(2)**(-(i//20000))
# print("steplength={key}".format(key=a))
else:
a=ls.search(x,p)
########################################
if Method=="linear_conjugate_gradient":
if i==0:
r=self.tf.get_grad(x)
p=-r
else:
r_next=r+a*A*p
beta=float(r_next.T*r_next)/float(r.T*r)
p=-r_next+beta*p
r=r_next
a=float(r.T*r)/float(p.T*A*p)
##############################################
if Method=="FR_conjugate_gradient":
if i==0:
p=-self.tf.get_grad(x)
a=ls.search(x,p)
x_pre=x
else:
beta=float(self.tf.get_grad(x).T*self.tf.get_grad(x))/float(self.tf.get_grad(x_pre).T*self.tf.get_grad(x_pre))
p=-self.tf.get_grad(x)+beta*p
a=ls.search(x,p)
x_pre=x
##############################################
if Method=="PR_conjugate_gradient":
if i==0:
p=-self.tf.get_grad(x)
a=ls.search(x,p)
x_pre=x
else:
beta=float(self.tf.get_grad(x).T*(self.tf.get_grad(x)-self.tf.get_grad(x_pre)))/float(self.tf.get_grad(x_pre).T*self.tf.get_grad(x_pre))
if beta<0:beta=0
p=-self.tf.get_grad(x)+beta*p
a=ls.search(x,p)
x_pre=x
################################################
if Method=="HR_conjugate_gradient":
if i==0:
p=-self.tf.get_grad(x)
a=ls.search(x,p)
x_pre=x
else:
beta=float(self.tf.get_grad(x).T*(self.tf.get_grad(x)-self.tf.get_grad(x_pre)))/float((self.tf.get_grad(x)-self.tf.get_grad(x_pre)).T*p)
if beta<0:beta=0
p=-self.tf.get_grad(x)+beta*p
a=ls.search(x,p)
x_pre=x
####################################################
if Method=="SR1":
if i==0:
diag=np.ones(x.shape[0])
H_pre=np.mat(np.diag(diag))
a=H_pre
p=-self.tf.get_grad(x)
x_pre=x
else:
s_k=x-x_pre
y_k=self.tf.get_grad(x)-self.tf.get_grad(x_pre)
H=H_pre+((s_k-H_pre*y_k)*(s_k-H_pre*y_k).T)/((s_k-H_pre*y_k).T*y_k)
a=H
p=-self.tf.get_grad(x)
H_pre=H
x_pre=x
#####################################################
if Method=="DFP":
if i==0:
diag=np.ones(x.shape[0])
H_pre=np.mat(np.diag(diag))
a=H_pre
p=-self.tf.get_grad(x)
x_pre=x
else:
s_k=x-x_pre
y_k=self.tf.get_grad(x)-self.tf.get_grad(x_pre)
H=H_pre+((s_k*s_k.T)/(s_k.T*y_k))-(H_pre*y_k*y_k.T*H_pre)/(y_k.T*H_pre*y_k)
a=H
p=-self.tf.get_grad(x)
H_pre=H
x_pre=x
##########################################################
if Method=="BFGS":
if i==0:
diag=np.ones(x.shape[0])
H_pre=np.mat(np.diag(diag))
a=H_pre
p=-self.tf.get_grad(x)
x_pre=x
else:
s_k=x-x_pre
y_k=self.tf.get_grad(x)-self.tf.get_grad(x_pre)
H=H_pre+(float(1+((y_k.T*H_pre*y_k)/(s_k.T*y_k)))*((s_k*s_k.T)/(s_k.T*y_k)))-((s_k*y_k.T*H_pre+H_pre*y_k*s_k.T)/(s_k.T*y_k))
a=H
p=-self.tf.get_grad(x)
H_pre=H
x_pre=x
######################################
if Method=="LS_Newton_CG":
z=0
r=self.tf.get_grad(x)
d=-r
B=self.tf.Hessian(x)
erro=min([0.5,LA.norm(r,2)])*LA.norm(r,2)
p=Newton_CG_stepsearch(z,r,d,B,erro)
a=ls.search(x,p)
x=x+a*p
if self.steps_logs==True:
print("{index}th step funtion value:{value} ,x is".format(index=i,value=self.tf.get_value(x)))
print(x)
if(LA.norm(self.tf.get_grad(x),2)<self.error_end):break
if i>999888888: print("out of computing capacity")
end=time.time()
if self.steps_logs==True or self.require_time==True:
print("whole optmization take {time}s".format(time=end-begin))
# if self.Gly_logs==True:
# d={'step':x_his,'target_funtion':fy_his}
# data=pd.DataFrame(d)
# data.plot(x='step',y='target_funtion')
return x
class line_search:
def __init__(self,target_funtion,Interpolate,logs=False,c1=1e-4,c2=0.9):
self.tf=target_funtion
self.Interpolate=Interpolate
self.c1=c1
self.c2=c2
self.a_pre=0
self.logs=logs
def values(self,x,p,a):
return self.tf.get_value(x+p*a)
def derivative(self,x,p,a):
return p.T*self.tf.get_grad(x+p*a)
def zoom(self,a_l,a_h,x,p):
if self.Interpolate=="bisection":
Interpolate=bisection
if self.Interpolate=="quadratic":
Interpolate=quadratic
for i in range(205):
a=Interpolate(a_l,a_h,self.tf,x,p)
if ((self.values(x,p,a)>self.values(x,p,0)+self.c1*a*self.derivative(x,p,0)) or
(self.values(x,p,a)>=self.values(x,p,a_l))):
a_h=a
else:
if((self.derivative(x,p,a))>=self.c2*self.derivative(x,p,0)):
return a
if(self.derivative(x,p,a)*(a_h-a_l)>=0):
a_h=a_l
a_l=a
if i>200 :print("zoom error ")
def search(self,x,p):
a=1
a_pre=self.a_pre=0
for i in range(20000000000005):
if((self.values(x,p,a)>self.values(x,p,0)+self.c1*a*self.derivative(x,p,0)) or
(i>1 and self.values(x,p,a)>=self.values(x,p,a_pre))) :
a=self.zoom(a_pre,a,x,p)
if self.logs== True: print('step length: {alpha}'.format(alpha=a))
self.a_pre=a
return a
if ((self.derivative(x,p,a))>=self.c2*self.derivative(x,p,0)):
if self.logs== True: print('step length: {alpha}'.format(alpha=a))
self.a_pre=a
return a
if (self.derivative(x,p,a)>=0):
a=self.zoom(a,a_pre,x,p)
if self.logs== True: print('step length: {alpha}'.format(alpha=a))
self.a_pre=a
return a
if i>200 :print("alpha search error ")
def bisection(a_l,a_h,tf,x,p):
return (a_l+a_h)/2
def quadratic(a_l,a_h,tf,x,p):
a=a_l-((p.T*tf.get_grad(x+p*a_l))*(a_h-a_l)**2)/(2*(tf.get_value(x+p*a_h)-tf.get_value(x+p*a_l)-p.T*tf.get_grad(x+p*a_l)*(a_h-a_l)))
a=float(a)
return a
def Newton_CG_stepsearch(z,r_pre,d,B,error):
for i in range(1000):
if d.T*B*d <=0:
if i==0:
return d
else:
return z
a=float(r_pre.T*r_pre/(d.T*B*d))
z=z+a*d
r=r_pre+a*B*d
if LA.norm(r,2)<error:
return z
beta=float(r.T*r/(r_pre.T*r_pre))
d=-r+beta*d
r_pre=r
if i>900:
print("step error")