計算預測值
在實務上,我們常會用已擬合的羅吉斯迴歸來估計機率,並為這些估計建立信賴區間。使用 wells 資料集與模型 'switch ~ arsenic',假設你有未參與訓練樣本的新觀測 wells_test,並希望預測是否會轉用最近的安全水井的機率。
你將使用 .predict() 方法來完成這件事。
請注意,.predict() 會接受幾個參數:
exog:新的觀測值(測試資料集)。transform = True:將擬合時的公式y ~ x套用到資料。
如果未指定 exog,則會對訓練資料集計算機率。
模型 wells_fit 以及資料集 wells 和 wells_test 已預先載入至工作區。
本練習屬於課程
Generalized Linear Models in Python
練習說明
- 使用已擬合的模型
wells_fit,對測試資料wells_test計算預測,並存成prediction。 - 將
prediction加到現有的資料框wells_test,並將欄位命名為prediction。 - 使用
print()顯示wells_test的前 5 列,並只呈現switch、arsenic與prediction欄位。請使用 pandas 的head()函式只檢視前 5 列。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Compute predictions for the test sample wells_test and save as prediction
prediction = ____.predict(exog = ____)
# Add prediction to the existing data frame wells_test and assign column name prediction
____[____] = ____
# Examine the first 5 computed predictions
print(____[[____, ____, ____]].head())