開始使用免費開始

使用 `statsmodels` 做最小平方法

有幾個 Python 函式庫提供了便利且抽象化的介面,讓你不必每次都親自處理模型最佳化的所有細節。

在這個練習中,你會以更高層、一般化的流程,使用 statsmodels 來建立以最小平方法(最小化 RSS)為基礎的模型。

為了幫你開始,我們已經用 x_data, y_data = load_data() 載入資料,並用 df = pd.DataFrame(dict(x_column=x_data, y_column=y_data)) 將其存成一個 pandas DataFrame,欄位名稱為 x_columny_column

本練習屬於課程

Python 線性建模入門

檢視課程

練習說明

  • 建立模型 ols(),使用 formula="y_column ~ x_column"data=df,然後對資料呼叫 .fit()
  • 使用 model_fit.predict() 取得 y_model
  • 使用提供的函式 plot_data_with_model(),將 y_datay_model 疊圖比較。
  • model_fit.params 擷取模型參數 a0a1
  • 使用 compute_rss_and_plot_fit() 確認這些結果與以 numpy 實作的解析公式一致。

動手互動練習

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

# Pass data and `formula` into ols(), use and `.fit()` the model to the data
model_fit = ols(____="y_column ~ x_column", ____=df).____()

# Use .predict(df) to get y_model values, then over-plot y_data with y_model
y_model = model_fit.____(df)
fig = plot_data_with_model(x_data, ____, ____)

# Extract the a0, a1 values from model_fit.params
a0 = model_fit.____['Intercept']
a1 = model_fit.____['x_column']

# Visually verify that these parameters a0, a1 give the minimum RSS
fig, rss = compute_rss_and_plot_fit(a0, a1)
編輯並執行程式碼