Visualize 1D Function Optimization-2

Sample the Test Function
The first thing we might want to do with a new function is define an input range of interest and sample the domain of interest using a uniform grid.

This sample will provide the basis for generating a plot later.

In this case, we will define a domain of interest around the optima of x=0.0 from x=-5.0 to x=5.0 and sample a grid of values in this range with 0.1 increments, such as -5.0, -4.9, -4.8, etc.

…

…

define range for input

r_min, r_max = -5.0, 5.0

sample input range uniformly at 0.1 increments

inputs = arange(r_min, r_max, 0.1)

summarize some of the input domain

print(inputs[:5])
We can then evaluate each of the x values in our sample.

…

…

compute targets

results = objective(inputs)

summarize some of the results

print(results[:5])
Finally, we can check some of the input and their corresponding outputs.

…

create a mapping of some inputs to some results

for i in range(5):
print(‘f(%.3f) = %.3f’ % (inputs[i], results[i]))
Tying this together, the complete example of sampling the input space and evaluating all points in the sample is listed below.

sample 1d objective function

from numpy import arange

objective function

def objective(x):
return x**2.0

define range for input

r_min, r_max = -5.0, 5.0

sample input range uniformly at 0.1 increments

inputs = arange(r_min, r_max, 0.1)

summarize some of the input domain

print(inputs[:5])

compute targets

results = objective(inputs)

summarize some of the results

print(results[:5])

create a mapping of some inputs to some results

for i in range(5):
print(‘f(%.3f) = %.3f’ % (inputs[i], results[i]))
Running the example first generates a uniform sample of input points as we expected.

The input points are then evaluated using the objective function and finally, we can see a simple mapping of inputs to outputs of the objective function.

[-5. -4.9 -4.8 -4.7 -4.6]
[25. 24.01 23.04 22.09 21.16]
f(-5.000) = 25.000
f(-4.900) = 24.010
f(-4.800) = 23.040
f(-4.700) = 22.090
f(-4.600) = 21.160