二元資料與羅吉斯迴歸

Generalized Linear Models in Python

Ita Cirovic Donev

Data Science Consultant

二元反應資料

  • 二分類反應 $\rightarrow \large{\texttt{\color{#079EA1}{0},\color{#ED715F}{1}}}$

範例:

  • 信用評分 $\rightarrow \texttt{\color{#ED715F}{"Default"}/\color{#079EA1}{"Non-Default"}}$
  • 測驗通過 $\rightarrow \texttt{\color{#079EA1}{"Pass"}/\color{#ED715F}{"Fail"}}$
  • 詐欺偵測 $\rightarrow \texttt{\color{#ED715F}{"Fraud"}/\color{#079EA1}{"No-Fraud"}}$
  • 產品選擇 $\rightarrow \texttt{\color{#2485F2}{"Product ABC"}/\color{#F2AC30}{"Product XYZ"}}$
Generalized Linear Models in Python

二元資料

未分組

  • 單一次事件
  • 擲 1 次硬幣
  • 兩種可能結果:0/1
  • $Bernoulli(p)$ 或
  • $Binomial(n=1,p)$

已分組

  • 多次事件
  • 擲多次硬幣
  • 給定 $n$ 次試驗中的成功次數
  • $Binomial(n,p)$
Generalized Linear Models in Python

羅吉斯函式

讀書時數與測驗通過/未通過反應(0/1)的散佈圖

Generalized Linear Models in Python

羅吉斯函式

讀書時數與測驗通過/未通過反應(0/1)的散佈圖

  • 測驗結果:$PASS=1$ 或 $FAIL=0$

  • 想要建模

$P(y=1)=\beta_0 + \beta_1x_1$

$P(\text{Pass})=\beta_0 + \beta_1 \times \text{Hours of study}$

Generalized Linear Models in Python

羅吉斯函式

對讀書時數與測驗通過/未通過(0/1)資料進行羅吉斯擬合的圖

  • 測驗結果:$PASS=1$ 或 $FAIL=0$

  • 想要建模

$P(y=1)=\beta_0 + \beta_1x_1$

$P(\text{Pass})=\beta_0 + \beta_1 \times \text{Hours of study}$

  • 使用羅吉斯函式

$f(z) = \frac{1}{(1+\exp(-z))}$

Generalized Linear Models in Python

勝算與勝算比

       

$$ ODDS = \frac{\text{事件發生}}{\text{事件未發生}} $$

       

$$ \text{勝算比} = \frac{odds 1}{odds 2} $$

Generalized Linear Models in Python

勝算範例

  • 4 場比賽 依序為 3 勝 1 敗

  • 勝算為 3 比 1 以 3 個勝利盒在分子、1 個失敗盒在分母來視覺化計算勝算。

Generalized Linear Models in Python

勝算與機率

  $$ \text{odds} \neq \text{probability} $$

  $$ \text{odds} = \frac{\text{probability}}{1-\text{probability}} $$

  $$ \text{probability} = \frac{\text{odds}}{1+\text{odds}} $$

Generalized Linear Models in Python

從機率模型到羅吉斯迴歸

 

步驟 1:機率模型

$E(y)=\mu=P(y=1)=\beta_0 + \beta_1x_1$

 

步驟 2:羅吉斯函式

$f(z) = \large{\frac{1}{(1+\exp(-z))}}$

 

步驟 3:套用羅吉斯函式 $\rightarrow$ 反羅吉斯(INVERSE-LOGIT)

$\mu = \large{\frac{1}{1+\exp(-(\beta_0+\beta_1x_1))}} = \large{\frac{\exp(\beta_0+\beta_1x_1)}{1+\exp(\beta_0+\beta_1x_1)}}$

$1-\mu = \large{\frac{1}{1+\exp(\beta_0+\beta_1x_1)}}$

Generalized Linear Models in Python

從機率模型到羅吉斯迴歸

 

  • 機率 $\rightarrow$ 勝算 $$ ODDS=\frac{\mu}{1-\mu} = exp{(\beta_0+\beta_1x_1)} $$  
  • 對數轉換 $\rightarrow \color{#CF5383}{\text{羅吉斯迴歸}}$

  $$ LOGIT(\mu)=log(\frac{\mu}{1-\mu}) = \beta_0+\beta_1x_1 $$

Generalized Linear Models in Python

在 Python 進行羅吉斯迴歸

函式 - glm()

model_GLM = glm(formula = 'y ~ x',                        
                data = my_data, 
                family = sm.families.Binomial()).fit

輸入

y = [0,1,1,0,...]
y = ['No','Yes','Yes',...]
y = ['Fail','Pass','Pass',...]
Generalized Linear Models in Python

一起來練習吧!

Generalized Linear Models in Python

Preparing Video For Download...