Sample Test Function
A common way for sampling a two-dimensional function is to first generate a uniform sample along each variable, x and y, then use these two uniform samples to create a grid of samples, called a mesh grid.
This is not a two-dimensional array across the input space; instead, it is two two-dimensional arrays that, when used together, define a grid across the two input variables.
This is achieved by duplicating the entire x sample array for each y sample point and similarly duplicating the entire y sample array for each x sample point.
This can be achieved using the meshgrid() NumPy function; for example:
…
define range for input
r_min, r_max = -5.0, 5.0
sample input range uniformly at 0.1 increments
xaxis = arange(r_min, r_max, 0.1)
yaxis = arange(r_min, r_max, 0.1)
create a mesh from the axis
x, y = meshgrid(xaxis, yaxis)
summarize some of the input domain
print(x[:5, :5])
We can then evaluate each pair of points using our objective function.
…
compute targets
results = objective(x, y)
summarize some of the results
print(results[:5, :5])
Finally, we can review the mapping of some of the inputs to their corresponding output values.
…
create a mapping of some inputs to some results
for i in range(5):
print(‘f(%.3f, %.3f) = %.3f’ % (x[i,0], y[i,0], results[i,0]))
The example below demonstrates how we can create a uniform sample grid across the two-dimensional input space and objective function.
sample 2d objective function
from numpy import arange
from numpy import meshgrid
objective function
def objective(x, y):
return x2.0 + y2.0
define range for input
r_min, r_max = -5.0, 5.0
sample input range uniformly at 0.1 increments
xaxis = arange(r_min, r_max, 0.1)
yaxis = arange(r_min, r_max, 0.1)
create a mesh from the axis
x, y = meshgrid(xaxis, yaxis)
summarize some of the input domain
print(x[:5, :5])
compute targets
results = objective(x, y)
summarize some of the results
print(results[:5, :5])
create a mapping of some inputs to some results
for i in range(5):
print(‘f(%.3f, %.3f) = %.3f’ % (x[i,0], y[i,0], results[i,0]))
Running the example first summarizes some points in the mesh grid, then the objective function evaluation for some points.
Finally, we enumerate coordinates in the two-dimensional input space and their corresponding function evaluation.
[[-5. -4.9 -4.8 -4.7 -4.6]
[-5. -4.9 -4.8 -4.7 -4.6]
[-5. -4.9 -4.8 -4.7 -4.6]
[-5. -4.9 -4.8 -4.7 -4.6]
[-5. -4.9 -4.8 -4.7 -4.6]]
[[50. 49.01 48.04 47.09 46.16]
[49.01 48.02 47.05 46.1 45.17]
[48.04 47.05 46.08 45.13 44.2 ]
[47.09 46.1 45.13 44.18 43.25]
[46.16 45.17 44.2 43.25 42.32]]
f(-5.000, -5.000) = 50.000
f(-5.000, -4.900) = 49.010
f(-5.000, -4.800) = 48.040
f(-5.000, -4.700) = 47.090
f(-5.000, -4.600) = 46.160