Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
DataScienceUWL
GitHub Repository: DataScienceUWL/DS775
Path: blob/main/Lessons/Lesson 07 - Global Optimization 2/scripts/bumpy_contours.py
871 views
1
import numpy as np
2
import matplotlib.pyplot as plt
3
import seaborn as sns
4
sns.set_style("darkgrid")
5
6
# define objective function and show a contour plot
7
8
def f(xy):
9
obj = 0.2 + sum(xy**2 - 0.1*np.cos(6*np.pi*xy))
10
return obj
11
12
# compute on mesh for plotting
13
numx = 101
14
numy = 101
15
x = np.linspace(-1.0, 1.0, numx)
16
y = np.linspace(-1.0, 1.0, numy)
17
xx,yy=np.meshgrid(x,y)
18
z = np.zeros((numx,numy))
19
for i in range(numx):
20
for j in range(numy):
21
z[i,j] = f(np.array([xx[i,j],yy[i,j]]))
22
23
# Create a contour plot
24
plt.figure(figsize=(8,8))
25
# Plot contours
26
contours = plt.contour(xx,yy,z,30)
27
# Label contours
28
plt.clabel(contours, inline=1, fontsize=8)
29
# Add some text to the plot
30
plt.title('Non-Convex Function')
31
plt.xlabel('x')
32
plt.ylabel('y');
33