開始使用免費開始

使用 Scipy 進行最佳化

你可以用 numpy 撰寫解析解,求得最小 RSS 的解。但對更複雜的模型,往往無法得到解析式,因此我們需要改用其他方法。

在這個練習中,你會使用 scipy.optimize,用一種更通用的方式來解同一個最佳化問題。

在此過程中,你會看到該方法額外回傳的數值,幫助我們回答「最佳解有多好」。為了方便和新的 scipy 方法比較,我們會沿用上一個練習的量測資料與參數設定。

本練習屬於課程

Python 線性建模入門

檢視課程

練習說明

  • 定義函式 model_func(x, a0, a1),對給定的陣列 x 回傳 a0 + a1*x
  • 使用 scipyoptimize.curve_fit() 來計算 a0a1 的最佳值。
  • param_opt 拆包,將模型參數儲存為 a0 = param_opt[0]a1 = param_opt[1]
  • 使用預先定義的函式 compute_rss_and_plot_fit 來測試並驗證你的答案。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Define a model function needed as input to scipy
def model_func(x, a0, a1):
    return ____ + (____*x)

# Load the measured data you want to model
x_data, y_data  = load_data()

# call curve_fit, passing in the model function and data; then unpack the results
param_opt, param_cov = optimize.curve_fit(____, x_data, y_data)
a0 = param_opt[0]  # a0 is the intercept in y = a0 + a1*x
a1 = param_opt[1]  # a1 is the slope     in y = a0 + a1*x

# test that these parameters result in a model that fits the data
fig, rss = compute_rss_and_plot_fit(____, ____)
編輯並執行程式碼