-
Notifications
You must be signed in to change notification settings - Fork 0
/
optimization_function.py
393 lines (308 loc) · 14.4 KB
/
optimization_function.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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
import numpy as np
import scipy as sc
from tqdm import tqdm
class Optimizer:
def __init__(self, algorithm: str = 'SGD', alpha: float = 0.2, \
epsilon: float = None, beta1: float = None, type_of_optimization: str = 'min', \
beta2: float = None, dimention: int = 1):
self.epsilon_adam = epsilon
self.beta1_adam = beta1
self.beta2_adam = beta2
self.algorithm = algorithm
self.alpha = alpha
self.dimention = dimention
self.bias_vector = np.abs(np.random.randn(self.dimention, 1))
self.m_adam = np.abs(np.random.randn(self.dimention, 1))
self.m_hat_adam = np.abs(np.random.randn(self.dimention, 1))
self.v_adam = np.abs(np.random.randn(self.dimention, 1))
self.v_hat_adam = np.abs(np.random.randn(self.dimention, 1))
if type_of_optimization == 'min':
self.type_of_optimization = -1
elif type_of_optimization == 'max':
self.type_of_optimization = 1
else:
raise Exception('Please correctly enter the type of optimization!')
if self.algorithm == 'SGD':
self.fit = self.SGD
elif self.algorithm == 'ADAM':
self.fit = self.ADAM
elif self.algorithm == 'RMSprop':
self.fit = self.RMSprop
else:
raise Exception('Please use a correct optimizer')
def SGD(self, parameter, derivatives, t):
parameter = parameter + self.type_of_optimization * self.alpha * derivatives
return parameter
def ADAM(self, parameter, derivatives, t):
self.m_adam = self.beta1_adam * self.m_adam + (1 - self.beta1_adam) * derivatives
self.v_adam = self.beta2_adam * self.v_adam + (1 - self.beta2_adam) * derivatives ** 2
self.m_hat_adam = self.m_adam / (1 - self.beta1_adam ** (t + 1))
self.v_hat_adam = self.v_adam / (1 - self.beta2_adam ** (t + 1))
parameter = parameter + self.type_of_optimization * self.alpha * self.m_hat_adam / (
np.sqrt(self.v_hat_adam) + self.epsilon_adam)
return parameter
def RMSprop(self, parameter, derivatives, t):
self.m_adam = self.beta1_adam * self.m_adam + (1 - self.beta1_adam) * derivatives ** 2
parameter = parameter + self.type_of_optimization * self.alpha * derivatives / (
np.sqrt(self.m_adam) + self.epsilon_adam)
return parameter
##================================================================================================
##================================================================================================
##================================================================================================
class Convex_problems_dual_ascend():
def __init__(self, problem_type: int = 1, learning_rate: float = 0.05, algorithm: str = 'SGD',
tolerance: float = 1e-12):
self.tolerance = tolerance
self.problem_type = problem_type
self.old_opt = np.inf
self.learning_rate = learning_rate
self.algorithm = algorithm
# =================================================================
def loss_f(self):
self.P = np.eye(self.n)
F = self.x.T @ self.P @ self.x
dF_dx = (self.P + self.P.T) @ self.x
return F, dF_dx
# =======================================================================
def linear_constraint(self):
R = (self.A @ self.x - self.b)
dR_dx = self.A.T
aug = R.T @ R
adug_dx = 2 * self.A.T @ R
return R, dR_dx, aug, adug_dx
# ============================================================
def lagrangian(self):
self.opt, dF_dx = self.loss_f()
lin_cons, dR_dx, _, _ = self.linear_constraint()
L = self.opt + self.y.T @ lin_cons
dL_dx = dF_dx + dR_dx @ self.y
dL_dy = lin_cons
return L, dL_dx, dL_dy
# ============================================================
def augmented_lagrangian(self):
self.rho = 0.01
self.opt, dF_dx = self.loss_f()
lin_cons, dR_dx, aug, adug_dx = self.linear_constraint()
L = self.opt + self.y.T @ lin_cons + (self.rho / 2) * aug
dL_dx = dF_dx + dR_dx @ self.y + (self.rho / 2) * adug_dx
dL_dy = lin_cons
return L.ravel(), dL_dx, dL_dy
# ===========================================================================
def Dual_Ascent(self, A: np.ndarray = np.eye(1), b: np.ndarray = np.eye(1), tolerance: float = 1e-12):
self.tolerance = tolerance
m, n = A.shape # m is the number of linear constraints
m2, n2 = b.shape
if m > n:
raise Exception('Overdetermined Problem!')
if m != m2:
raise Exception('The number of parameters and equation is not consistent!')
if n2 != 1:
raise Exception('Currently the algorithms is not suitable for multi-output problems!')
self.y = np.random.randn(m, 1)
self.x = np.random.randn(n, 1)
self.A = A
self.b = b
self.m = m
self.n = n
self.iterations = 20000
variable_optimizer = Optimizer(algorithm=self.algorithm, alpha=self.learning_rate, type_of_optimization='min')
lagrange_optimizer = Optimizer(algorithm=self.algorithm, alpha=self.learning_rate, type_of_optimization='max')
for itr in tqdm(range(self.iterations)):
L, dl_dx, dl_dy = self.lagrangian()
L, dl_dx, dl_dy = self.augmented_lagrangian()
self.x = variable_optimizer.fit(self.x, dl_dx, itr // 1000)
self.y = lagrange_optimizer.fit(self.y, dl_dy, itr // 1000)
tol = np.abs(self.opt - self.old_opt)
self.old_opt = self.opt
if tol < self.tolerance:
print('Optimum values acheived!')
break
if itr == self.iterations - 1:
print('Optimization terminated due to the maximum iteration!')
print(f'norm of constraint Error= : {((self.A @ self.x - self.b) ** 2).sum()}')
print(f'the value of loss function= : {self.opt}')
return self.x, self.opt
# ===============================================================================================
# if __name__=='__main__':
# A = np.random.rand(10,12)
# b = np.random.rand(10,1)
# D = Convex_problems_dual_ascend(problem_type = 1, learning_rate=0.05, algorithm='SGD')
# val,opt = D.Dual_Ascent(A=A, b=b)
# val
# =================================================================================
# =================================================================================
# =================================================================================
class ADMM:
def __init__(self, problem_type: int = 1, learning_rate: float = 0.05, algorithm: str = 'SGD',
tolerance: float = 1e-12, iterations: int = 20000):
self.tolerance = tolerance
self.problem_type = problem_type
self.old_opt = np.inf
self.learning_rate = learning_rate
self.algorithm = algorithm
self.iterations = iterations
# =================================================================
def loss_f(self):
self.P1 = np.eye(self.n1)
self.P2 = np.eye(self.n2)
F1 = self.x.T @ self.P1 @ self.x
F2 = self.z.T @ self.P2 @ self.z
dF_dx = (self.P1 + self.P1.T) @ self.x
dF_dz = (self.P2 + self.P2.T) @ self.z
F = F1 + F2
return F, dF_dx, dF_dz
# =======================================================================
def linear_constraint(self):
R = self.A @ self.x + self.B @ self.z - self.c
aug = R.T @ R
dR_dx = self.A.T
dR_dz = self.B.T
adug_dx = 2 * dR_dx @ R
adug_dz = 2 * dR_dz @ R
return R, aug, dR_dx, dR_dz, adug_dx, adug_dz
# ============================================================
def augmented_lagrangian(self):
self.rho = 0.01
F, dF_dx, dF_dz = self.loss_f()
R, aug, dR_dx, dR_dz, adug_dx, adug_dz = self.linear_constraint()
Cons = self.y.T @ R
L = F + Cons + (self.rho / 2) * aug
dL_dx = dF_dx + dR_dx @ self.y + (self.rho / 2) * adug_dx
dL_dz = dF_dz + dR_dz @ self.y + (self.rho / 2) * adug_dz
dL_dy = R
self.opt = F + (self.rho / 2) * aug
return L, dL_dx, dL_dz, dL_dy
# ===========================================================================
def ADMM_dual_ascent(self, A: np.ndarray = np.eye(1), B: np.ndarray = np.eye(1), c: np.ndarray = np.eye(1)):
p1, n1 = A.shape
p2, n2 = B.shape
p3, n3 = c.shape
if p1 == p2 == p3:
self.p = p1
else:
raise Exception('The matrices of linear constraint are not consistent!')
self.n1 = n1
self.n2 = n2
self.y = np.random.randn(self.p, 1)
self.x = np.random.randn(n1, 1)
self.z = np.random.randn(n2, 1)
self.A = A
self.B = B
self.c = c
variable_optimizer_x = Optimizer(algorithm=self.algorithm, alpha=self.learning_rate, type_of_optimization='min')
variable_optimizer_z = Optimizer(algorithm=self.algorithm, alpha=self.learning_rate, type_of_optimization='min')
lagrange_optimizer = Optimizer(algorithm=self.algorithm, alpha=self.learning_rate, type_of_optimization='max')
for itr in tqdm(range(self.iterations)):
L, dl_dx, dl_dz, dl_dy = self.augmented_lagrangian()
self.x = variable_optimizer_x.fit(self.x, dl_dx, itr // 1000)
self.z = variable_optimizer_z.fit(self.z, dl_dz, itr // 1000)
self.y = lagrange_optimizer.fit(self.y, dl_dy, itr // 1000)
tol = np.abs(self.opt - self.old_opt)
self.old_opt = self.opt
if tol < self.tolerance:
print('Optimum values acheived!')
break
if itr == self.iterations - 1:
print('Optimization terminated due to the maximum iteration!')
print(f'norm of constraint Error= : {((self.A @ self.x + self.B @ self.z - self.c) ** 2).sum()}')
print(f'the value of loss function= : {self.opt}')
return self.x, self.opt
# if __name__=='__main__':
# A = np.random.rand(10,12)
# B = np.random.rand(10, 4)
# c = np.random.rand(10,1)
# D = ADMM(problem_type = 1, learning_rate=0.05, algorithm='SGD')
# val,opt = D.ADMM_dual_ascent(A=A,B=B, c=c)
# val
# =================================================================================
# =================================================================================
# =================================================================================
class Linear_quadratic_programming:
def __init__(self, problem_type: int = 1, learning_rate: float = 0.05, algorithm: str = 'SGD',
tolerance: float = 1e-12, iterations: int = 20000):
self.tolerance = tolerance
self.problem_type = problem_type
self.old_opt = np.inf
self.learning_rate = learning_rate
self.algorithm = algorithm
self.iterations = iterations
# =================================================================
def loss_f(self):
self.P = np.eye(self.n)
self.q = -0.1 * np.ones((self.n,))
self.r = 5
F = (1 / 2) * self.x.T @ self.P @ self.x + self.q.T @ self.x + self.r
dF_dx = (1 / 2) * (self.P + self.P.T) @ self.q
return F, dF_dx
# =======================================================================
def linear_constraint(self):
R = self.A @ self.x - self.b
aug = R.T @ R
dR_dx = self.A.T
adug_dx = 2 * dR_dx @ R
return R, aug, dR_dx, adug_dx
# ============================================================
def augmented_lagrangian(self):
self.rho = 0.01
F, dF_dx = self.loss_f()
R, aug, dR_dx, adug_dx = self.linear_constraint()
L = None
dL_dz = None
dL_dy = None
dL_dx = dF_dx + dR_dx @ self.y + (self.rho / 2) * adug_dx
dL_dy = R
self.opt = F + (self.rho / 2) * aug
return L, dL_dx, dL_dz, dL_dy
# ===========================================================================
def LQR(self, A: np.ndarray = np.eye(1), b: np.ndarray = np.eye(1)):
"""
The standard form quadratic program (QP) is
minimize (1/2)xTP x + qT x
subject to Ax = b, x ≥ 0, (5.3)
with variable x ∈ Rn; we assume that P ∈ Sn
+. When P = 0, this reduces to the standard form linear program (LP).
"""
m1, n = A.shape
m2, n2 = b.shape
if m1 == m2:
self.m = m1
else:
raise Exception('The matrices of linear constraint are not consistent!')
if n != 1:
raise Exception('Select a correct array b!')
else:
self.n = n
if self.m > self.n:
raise Exception('over specified optimization problem!')
self.z = np.random.randn(self.n, 1)
self.x = np.random.randn(self.n, 1)
self.u = np.random.randn(self.n, 1)
self.A = A
self.b = b
variable_optimizer_x = Optimizer(algorithm=self.algorithm, alpha=self.learning_rate, type_of_optimization='min')
for itr in tqdm(range(self.iterations)):
L, dl_dx, dl_dz, dl_dy = self.augmented_lagrangian()
self.x = variable_optimizer_x.fit(self.x, dl_dx, itr // 1000)
# self.z = variable_optimizer_z.fit(self.z, dl_dz, itr // 1000)
# self.y = lagrange_optimizer.fit(self.y, dl_dy, itr//1000)
tol = np.abs(self.opt - self.old_opt)
self.old_opt = self.opt
if tol < self.tolerance:
print('Optimum values acheived!')
break
if itr == self.iterations - 1:
print('Optimization terminated due to the maximum iteration!')
print(f'norm of constraint Error= : {((self.A @ self.x + self.B @ self.z - self.c) ** 2).sum()}')
print(f'the value of loss function= : {self.opt}')
return self.x, self.opt
if __name__ == '__main__':
n = 7 # the number of variables x
m = 3 # the number of equality constraints
p = 2 # the number of inequality
d = 1
A = np.random.rand(10, 12)
B = np.random.rand(10, 4)
c = np.random.rand(10, 1)
D = Linear_quadratic_programming(problem_type=1, learning_rate=0.05, algorithm='SGD')
val, opt = D.ADMM_dual_ascent(A=A, B=B, c=c)
val