Лабораторная 3.2 Оптимизация

 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
from scipy.optimize import minimize_scalar
def get_step_point(x, h, i):
x = copy(x)
x[i] += h
return x
def exploring_search(f, x0, e=1e-5):
def f_opt(h):
return f(get_step_point(x, h, i))
x = x0
while True:
for i in range(len(x)):
xp = x
x = get_step_point(x, minimize_scalar(f_opt).x, i)
if sum(x-xp)*1.0/len(x) < e:
break
return x
def pattern_search(f, x0, e=1e-3, l=2.0):
step = 0
while True:
step += 1
x1 = x0
x2 = exploring_search(f, x0)
x3 = x1 + l*(x2-x1)
x4 = exploring_search(f, x3)
if np.linalg.norm((x2 - x4))/len(x0) < e:
break
else:
x0 = x2
return x2, f(x2), step
n = 2
scale = 100
start_point = [39.33561727, 38.77636387]
print f(start_point), start_point
print pattern_search(f, x0=start_point)
from scipy.optimize import minimize_scalar
def f(x, a = 250, b = 2, f0 = 300):
return sum([a*(x[i]**2 - x[i+1])**2 + b*(x[i] - 1)**2 for i in range(0, len(x)-1)]) + f0
def Grad(x, a = 350, b = 2):
return np.array([2*a*x[0], a + b*x[1]*2 - 2*b])
def GradSearch(x, nm ='Bounded', eps = 0.0005, max_step = 100, steps = 0):
result = minimize_scalar(lambda alpha: f(x - alpha*Grad(x)), bounds = (-max_step, max_step), method = nm)
new_x = x - result.x*Grad(x)
print x, f(x), f(new_x)
if f(x) - f(new_x) < eps:
return (f(x), x, steps)
return GradSearch(new_x, nm, steps = steps + 1)
print GradSearch(start_point, nm = 'Bounded')
print GradSearch(start_point, nm = 'Golden')