Using callback
You want to find the two highest maxima of a profit function and you have decided to use callback to collect the optima found and then select the top two values.
First, you will complete the callback function. You will check if the value of the objective currently examined by basinhopping is accepted as optimum, and if so, you will append it to a list opt_values. Afterwards you will run basinhopping with the callback function you just defined.
basinhopping has been imported for you.
The initial guess, x0, kwargs, and profit, function have already been defined for you.
Este ejercicio forma parte del curso
Introduction to Optimization in Python
Instrucciones del ejercicio
- Fill in the
callbackfunction to check if thexcandidate examined in the current iteration is indeed deemed an optimum. - Append the value of the minimized objective to list
opt_values. - Run
basinhoppingwith the appropriate callback function and find the top two maxima.
Ejercicio interactivo práctico
Prueba este ejercicio y completa el código de muestra.
opt_values = []
def callback(x, f, accept):
# Check if the candidate is an optimum
if ____:
# Append the value of the minimized objective to list opt_values
opt_values.append(____)
# Run basinhopping to find top two maxima
result = basinhopping(lambda q: -profit(q), x0, callback=____, minimizer_kwargs=kwargs, niter=5, seed=3)
top2 = sorted(list(set([round(f, 2) for f in opt_values])), reverse=True)[:2]
top2 = [-f for f in top2]
print(f"{result.message}\nThe highest two values are {top2}")