開始使用免費開始

計算 VIF

如同你在影片中學到的,檢查多重共線性最常用的診斷指標之一是變異膨脹因子(variance inflation factor,VIF),會對每個解釋變數各自計算。

回想影片中的經驗法則閾值:VIF 的門檻是 2.5。也就是說,若某變數的 VIF 高於 2.5,你就應該考慮多重共線性已經影響到你擬合的模型。

先前已擬合的 modelcrab 資料集都已預先載入到工作空間。

本練習屬於課程

Generalized Linear Models in Python

檢視課程

練習說明

  • statsmodels 匯入 variance_inflation_factor
  • crab 資料集中選取 weightwidthcolor,並存成 X。在 X 中加入名為 Intercept、值為 1 的欄位。
  • 使用 pandasDataFrame() 函式建立一個空的 vif 資料框,並在 Variables 欄位中加入 X 的欄名。
  • 對每個變數使用 variance_inflation_factor() 函式計算 VIF,並以欄名 VIF 儲存在 vif 資料框中。

動手互動練習

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

# Import functions
from statsmodels.stats.outliers_influence import ____

# Get variables for which to compute VIF and add intercept term
X = ____[[____, ____, ____]]
X[____] = 1

# Compute and view VIF
vif = pd.____
vif["variables"] = X.____
vif["VIF"] = [____(X.values, i) for i in range(X.shape[1])]

# View results using print
____(____)
編輯並執行程式碼