-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.py
63 lines (49 loc) · 1.66 KB
/
example.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
### IMPORTS
# Only "nelder_mead" is required for use
import nelder_mead as nm
# Additional imports used for demonstration + visualization
import numpy as np
import random
from matplotlib import cm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
### COST FUNCTION
# This will be minimized in this example
def cost(x,y):
return (pow(x,4) + pow(y,4) - 4*x*y)
### PLOT CONFIGURATION
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-2, 2, 0.25)
Y = np.arange(-2, 2, 0.25)
X, Y = np.meshgrid(X, Y)
Z = cost(X,Y)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
linewidth=0, antialiased=False, alpha=0.5)
ax.set_zlim(-2.0, 25.0)
fig.colorbar(surf, shrink=0.5, aspect=5)
color = "b"
### NELDER-MEAD EXAMPLE
# Randomly sample the cost function to provide a starting point for Nelder Mead method
# The number of initial points is equal to the dimensionality + 1
dimension = 2
points = []
for i in range (0, 3):
x = random.uniform(-2,2)
y = random.uniform(-2,2)
c = cost(x,y)
points.append(nm.Point([x,y],c))
ax.scatter(x,y,c, c=color)
# Initializing the Nelder-Mead model
model = nm.NelderMead(dimension,points)
# Iteratively minimizing cost
for i in range (0, 30):
# 1: Fetch a suggested next point from the model
point = model.get_next_point()
# 2 : Compute the result cost of the proposed point
point.cost = cost(point.coordinates[0],point.coordinates[1])
# 3 : Return the point with updated cost back to the model
model.set_next_point(point)
if (i > 5): color = "r"
ax.scatter(point.coordinates[0],point.coordinates[1],point.cost, c=color)
plt.show()