Bắt đầu ngayBắt đầu miễn phí

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.

Bài tập này là một phần của khóa học

Introduction to Optimization in Python

Xem khóa học

Hướng dẫn bài tập

  • 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.

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

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}")
Chỉnh sửa và Chạy Mã