Graphing the Michalewicz Function Using Matplotlib

The Michalewicz function is an interesting math function that is sometimes used to test the effectiveness of numerical optimization algorithms.

The function can accept two or more input values. The function is tricky to minimize because there are several local minimum values and several flat areas which make the one global minimum value hard to find for optimization algorithms.

I graphed the Michalewicz function in with two variables, x and y; therefore the dimension of the function is 2, but the graph appears in 3D.

I used the matplotlib library. The code is:

# michalewicz_graph.py

from matplotlib import cm  # color map
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

X = np.linspace(0, 3.2, 50)    
Y = np.linspace(0, 3.2, 50)    
X, Y = np.meshgrid(X, Y)

# Michalewicz function
Z = -1 * ( (np.sin(X) * np.sin((1 * X**2) / np.pi)**20) + \
           (np.sin(Y) * np.sin((2 * Y**2) / np.pi)**20) )

fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, \
  rstride=1, cstride=1, cmap=cm.jet, \
  edgecolor='darkred', linewidth=0.1)

ax.set_xlabel('x', fontsize=10)
ax.set_ylabel('y', fontsize=10)
ax.set_zlabel('f(x,y)', fontsize=10)
ax.tick_params(axis='both', which='major',
  labelsize=6)
    
plt.show()

The program sets up X and Y values from 0 to 3.2 (just a bit more than pi) in 50 evenly-spaced intervals. Different ranges of X and Y give a very different overall graph.

The Michalewicz function has a free parameter m that controls the steepness of they valleys. Larger values of m make the function more difficult to optimize. The most common value for m is 10, which is what I used in the demo code.

For two variables, x and y, the global minimum value is approximately z = -1.8013 when x = 2.20319 and y = 1.57049.

Good fun.



The matplotlib library approximates a smooth surface by using many small straight lines to make facets. I’m not particularly a fan of animated movies, but I really like the artistic style that was used in “Sleeping Beauty” (1959). Unlike all previous animation, which used a very smooth curved style, SB used an angular style with some straight lines that I find very beautiful.


This entry was posted in Machine Learning. Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s