使用 callback
你想找出利潤函式的兩個最高極大值,並決定使用 callback 收集找到的極值,再從中挑出最大兩個。
首先,完成 callback 函式。你需要檢查 basinhopping 目前評估的目標值是否被接受為極值;如果是,將它加入清單 opt_values。接著,使用你剛定義的 callback 函式來執行 basinhopping。
basinhopping 已為你匯入。
初始猜測 x0、kwargs,以及 profit 函式都已經替你定義好了。
本練習屬於課程
Python 最佳化入門
練習說明
- 在
callback函式中,檢查本次迭代所評估的候選解x是否確實被視為極值。 - 將最小化目標的值附加到清單
opt_values。 - 使用適當的 callback 函式執行
basinhopping,並找出最高的兩個極大值。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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}")