-
Notifications
You must be signed in to change notification settings - Fork 0
/
animation.py
358 lines (311 loc) · 9.75 KB
/
animation.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
from math import pi
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import streamlit as st
import streamlit.components.v1 as components
import torch
import plotly.graph_objects as go
from torch.optim import SGD, Adam
from plotly.subplots import make_subplots
from optimal_pytorch.coin_betting.torch import Cocob, Regralizer, Recursive
plt.style.use("seaborn-white")
def plot_coherent(show=False):
"""
Plot coherent function.
"""
x = np.linspace(-1.5, 1.5, 250)
y = np.linspace(-1.5, 1.5, 250)
minimum = (0, 0)
X, Y = np.meshgrid(x, y)
Z = coherent([X, Y])
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(1, 1, 1)
ax.contour(X, Y, Z, 90, cmap="jet")
ax.set_title(
r"Coherent function, $f(x) = 3 + \sin(5\theta) + \cos(3\theta) * r^2(5/3-r)$"
)
ax.plot(*minimum, "gD")
if show:
plt.plot()
plt.show()
return fig, ax
def plot_rosenbrock(show=False):
"""
Plot Rosenbrock function.
"""
x = np.linspace(-2, 2, 250)
y = np.linspace(-1, 3, 250)
minimum = (1.0, 1.0)
X, Y = np.meshgrid(x, y)
Z = rosenbrock([X, Y])
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(1, 1, 1)
ax.contour(X, Y, Z, 90, cmap="jet")
ax.set_title("Rosenbrock function")
ax.plot(*minimum, "gD")
if show:
plt.plot()
plt.show()
return fig, ax
def plot_rastrigin(show=False):
"""
Plot Rastrigin function.
"""
x = np.linspace(-4.5, 4.5, 250)
y = np.linspace(-4.5, 4.5, 250)
minimum = (0, 0)
X, Y = np.meshgrid(x, y)
Z = rastrigin([X, Y])
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(1, 1, 1)
ax.contour(X, Y, Z, 20, cmap="jet")
ax.set_title("Rastrigin function")
ax.plot(*minimum, "gD")
if show:
plt.plot()
plt.show()
return fig, ax
def coherent(tensor):
"""
Compute coherent function.
"""
x, y = tensor
lib = torch if isinstance(x, torch.Tensor) else np
r = lib.sqrt(x ** 2 + y ** 2)
if lib == np:
theta = np.arctan2(y, x)
else:
theta = torch.atan2(y, x)
return (3 + lib.sin(5 * theta) + lib.cos(3 * theta)) * r ** 2 * (5 / 3 - r)
def rastrigin(tensor):
"""
Compute Rastrigin function.
https://en.wikipedia.org/wiki/Test_functions_for_optimization
"""
x, y = tensor
lib = torch if isinstance(x, torch.Tensor) else np
A = 10
f = A * 2 + (x ** 2 - A * lib.cos(x * pi * 2)) + (y ** 2 - A * lib.cos(y * pi * 2))
return f
def rosenbrock(tensor):
"""
Compute Rosenbrock function.
# https://en.wikipedia.org/wiki/Test_functions_for_optimization
"""
x, y = tensor
return (1 - x) ** 2 + 100 * (y - x ** 2) ** 2
def draw(i, X, Y, pathline, point):
"""
Draw the optimization path.
"""
x = X[i]
y = Y[i]
pathline[0].set_data(X[: i + 1], Y[: i + 1])
point[0].set_data(x, y)
return pathline[0], point[0]
@st.cache(suppress_st_warning=True)
def plotly_rastrigin():
"""
Plot Rastrigin function with plotly.
"""
x = np.linspace(-4.5, 4.5, 250)
y = np.linspace(-4.5, 4.5, 250)
X, Y = np.meshgrid(x, y)
Z = rastrigin([X, Y])
fig = make_subplots(
rows=1, cols=1, specs=[[{"is_3d": True}]], subplot_titles=["Rastrigin function"]
)
fig.add_trace(go.Surface(x=X, y=Y, z=Z), 1, 1)
fig.update_traces(
contours_z=dict(
show=True, usecolormap=True, highlightcolor="limegreen", project_z=True
)
)
fig.update_layout(autosize=False, width=800, height=800)
return fig
@st.cache(suppress_st_warning=True)
def plotly_rosenbrock():
"""
Plot Rosenbrock function with plotly.
"""
x = np.linspace(-2, 2, 250)
y = np.linspace(-1, 3, 250)
X, Y = np.meshgrid(x, y)
Z = rosenbrock([X, Y])
fig = make_subplots(
rows=1,
cols=1,
specs=[[{"is_3d": True}]],
subplot_titles=["Rosenbrock function"],
)
fig.add_trace(go.Surface(x=X, y=Y, z=Z), 1, 1)
fig.update_traces(
contours_z=dict(
show=True, usecolormap=True, highlightcolor="limegreen", project_z=True
)
)
fig.update_layout(autosize=False, width=800, height=800)
return fig
@st.cache(suppress_st_warning=True)
def plotly_coherent():
"""
Plot coherent function with plotly.
"""
x = np.linspace(-1.5, 1.5, 250)
y = np.linspace(-1.5, 1.5, 250)
X, Y = np.meshgrid(x, y)
Z = coherent([X, Y])
fig = make_subplots(
rows=1, cols=1, specs=[[{"is_3d": True}]], subplot_titles=["Coherent function"]
)
fig.add_trace(go.Surface(x=X, y=Y, z=Z), 1, 1)
fig.update_traces(
contours_z=dict(
show=True, usecolormap=True, highlightcolor="limegreen", project_z=True
),
showlegend=False,
)
fig.update_layout(autosize=False, width=800, height=800)
return fig
def execute_steps(func, initial_state, optimizer_class, optimizer_config, num_iter=500):
"""Run the optimizer."""
x = torch.Tensor(initial_state).requires_grad_(True)
optimizer = optimizer_class([x], **optimizer_config)
steps = np.zeros((2, num_iter + 1))
steps[:, 0] = np.array(initial_state)
for i in range(1, num_iter + 1):
optimizer.zero_grad()
f = func(x)
f.backward(create_graph=True, retain_graph=True)
torch.nn.utils.clip_grad_norm_(x, 1.0)
optimizer.step()
steps[:, i] = x.detach().numpy()
return steps
def frame_selector_ui():
"""Streamlit UI."""
st.sidebar.markdown("# Parameters")
fun_select = st.sidebar.radio(
"Function to optimize:",
("Rosenbrock", "Rastrigin", "Coherent"),
)
iterations = st.sidebar.slider("iterations:", 500, 1000, step=100)
# The user can pick which type of object to search for.
algo = st.sidebar.selectbox(
"Which algo?", ["SGD", "Adam", "Cocob", "Regralizer", "Recursive"], 0
)
params = {}
if algo in ["Cocob", "Recursive"]:
# Choose initial wealth
eps = st.sidebar.slider("Choose initial wealth:", 0.1, 10.0, step=0.1)
params["eps"] = eps
else:
lr = st.sidebar.slider("Learning rate:", 0.1, 1.0, value=0.1, step=0.1)
params["lr"] = lr
if algo == "SGD":
momentum = st.sidebar.selectbox("Momentum:", [0, 0.9, 0.99])
params["momentum"] = momentum
return fun_select, algo, params, iterations
def animate_function(fig, ax, steps, n_frames=100):
"""
A simple way to produce an animation with Streamlit.
"""
X = steps[0, :]
Y = steps[1, :]
pathline = ax.plot(X[0], Y[0], color="r", lw=1)
point = ax.plot(X[0], Y[0], "ro")
point_ani = animation.FuncAnimation(
fig,
draw,
frames=n_frames,
fargs=(X, Y, pathline, point),
interval=100,
blit=True,
repeat=False,
)
# video rendering
with st.spinner("Wait for it..."):
with open("myvideo.html", "w") as f:
print(point_ani.to_html5_video(), file=f)
st.success("Done!")
st.markdown("Green point is the minimum:")
with open("myvideo.html", "r") as HtmlFile:
source_code = HtmlFile.read()
components.html(source_code, height=900, width=900)
def run_the_app(function, selected_algo, selected_params, iterations):
"""
Streamlit core function.
"""
# create figure
if function == "Rosenbrock":
fig, ax = plot_rosenbrock()
initial_state = (-2.0, 2.0)
elif function == "Rastrigin":
fig, ax = plot_rastrigin()
initial_state = (-2.0, 3.5)
elif function == "Coherent":
fig, ax = plot_coherent()
initial_state = (0.9, 0.3)
else:
st.error("Please select a different function.")
return
if selected_algo is None:
st.error("Please select a different algorithm.")
return
optimizers = {
"Cocob": Cocob,
"SGD": SGD,
"Adam": Adam,
"Regralizer": Regralizer,
"Recursive": Recursive,
}
functions = {
"Rosenbrock": rosenbrock,
"Rastrigin": rastrigin,
"Coherent": coherent,
}
# run the algorithm
optimizer = optimizers[selected_algo]
function = functions[function]
tot_iter = iterations
steps = execute_steps(
function, initial_state, optimizer, selected_params, num_iter=tot_iter
)
# function animation
animate_function(fig, ax, steps)
if __name__ == "__main__":
st.title("Coin Betting algorithms visualized")
# Add a selector for the app mode on the sidebar.
st.sidebar.title("Command line:")
app_mode = st.sidebar.selectbox(
"Choose the app mode", ["Show instructions", "Run optimizers"]
)
if app_mode == "Show instructions":
description = st.markdown(
"In this app we compare coin-betting optimizers with SGD and Adam on non-convex \
functions notoriously difficult to optimize.\n\
To visualize the possible functions please use the buttons on the left."
)
st.sidebar.success('To continue select "Run optimizers".')
images = {
"Rastrigin": plotly_rastrigin(),
"Rosenbrock": plotly_rosenbrock(),
"Coherent": plotly_coherent(),
}
fun = st.sidebar.radio(
"Function:",
("Rosenbrock", "Rastrigin", "Coherent"),
)
im = st.empty()
figure = images[fun]
im.write(figure)
elif app_mode == "Run optimizers":
st.write("Choose the options on the left.")
(
loss_function,
algorithm,
hyperparams,
time_horizon,
) = frame_selector_ui()
if st.sidebar.button("Run!"):
run_the_app(loss_function, algorithm, hyperparams, time_horizon)