計算與描述預測

Generalized Linear Models in Python

Ita Cirovic Donev

Data Science Consultant

計算預測

取得模型擬合後

  1. 原始 $x$ 的擬合值

模型擬合流程圖。

Generalized Linear Models in Python

計算預測

取得模型擬合後

  1. 原始 $x$ 的擬合值

  2. 新的 $x$ 值以取得預測值

模型擬合與計算預測的流程圖。

Generalized Linear Models in Python

計算預測

  • 馬蹄蟹模型 y ~ weight $$ \mu = \frac{\exp(-3.6947+1.8151 \times weight)}{1+\exp(-3.6947+1.8151 \times weight)} $$

  • 新量測:weight = 2.85

$$ \mu = \frac{\exp(-3.6947+1.8151 \times \color{blue}{2.85})}{1+\exp(-3.6947+1.8151 \times \color{blue}{2.85})} = 0.814 $$

Generalized Linear Models in Python

在 Python 中進行預測

  • 對資料集 new_data 計算模型預測
    # Compute model predictions
    model_GLM.predict(exog = new_data)
    
Generalized Linear Models in Python

從機率到類別

依機率門檻分離模型輸出。

Generalized Linear Models in Python

計算類別預測

# 從模型取出擬合機率
crab['fitted'] = model.fittedvalues.values
# 定義門檻值
cut_off = 0.4
# 計算類別預測
crab['pred_class'] = np.where(crab['fitted'] > cut_off, 1, 0)
Generalized Linear Models in Python

計算類別預測

# 計算各類別出現次數
crab['pred_class'].value_counts()
1    151
0     22
門檻 $\hat y=1$ $\hat y=0$
$\mu = 0.4$ 151 22
$\mu = 0.5$ 126 47
Generalized Linear Models in Python

混淆矩陣

空的混淆矩陣。

Generalized Linear Models in Python

混淆矩陣-真負類(TN)

在混淆矩陣中標示真負類。

Generalized Linear Models in Python

混淆矩陣-真正類(TP)

在混淆矩陣中標示真負類與真正類。

Generalized Linear Models in Python

混淆矩陣-假正類(FP)

在混淆矩陣中標示真負類、真正類與假正類。

Generalized Linear Models in Python

混淆矩陣-假負類(FN)

在混淆矩陣中標示真負類、真正類、假正類與假負類。

Generalized Linear Models in Python

在 Python 中建立混淆矩陣

print(pd.crosstab(y_actual, y_predicted, 
            rownames=['Actual'], colnames=['Predicted'], 
            margins = True))
Predicted   0    1  All
Actual                 
0          15   47   62
1           7  104  111
All        22  151  173
Generalized Linear Models in Python

一起來練習吧!

Generalized Linear Models in Python

Preparing Video For Download...