如何使用 Python 在 SciPy 中找到標量函式的最小值?


求解標量函式的最小值是一個最佳化問題。最佳化問題有助於提高解決方案的質量,從而以更高的效能獲得更好的結果。最佳化問題還用於曲線擬合、根擬合等。

我們看一個示例 −

示例

import matplotlib.pyplot as plt
from scipy import optimize
import numpy as np
print("The function is defined")
def my_func(a):
   return a*2 + 20 * np.sin(a)
plt.plot(a, my_func(a))
print("Plotting the graph")
plt.show()
print(optimize.fmin_bfgs(my_func, 0))

輸出

Optimization terminated successfully.
   Current function value: -23.241676
   Iterations: 4
   Function evaluations: 18
   Gradient evaluations: 6
[-1.67096375]

說明

  • 匯入了所需的包。
  • 定義了一個生成資料的函式。
  • 使用 matplotlib 庫將此資料繪製到圖表上。
  • 接下來,透過將函式作為引數傳遞來使用“fmin_bgs”函式。
  • 此資料顯示在控制檯上。

更新時間:10-12-2020

132 次瀏覽

開啟您的 職業生涯

完成本課程即可獲得認證

開始
廣告
© . All rights reserved.