ComeçarComece de graça

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 exercício faz parte do curso

Introduction to Optimization in Python

Ver curso

Instruções do exercício

  • Fill in the callback function to check if the x candidate examined in the current iteration is indeed deemed an optimum.
  • Append the value of the minimized objective to list opt_values.
  • Run basinhopping with the appropriate callback function and find the top two maxima.

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

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}")
Editar e executar o código