COM6005 Statistical Modeling · Module 5
Logistic Regression
COM6005 · Module 5 · Source: Lecture_5_Logistic_Regression_L02.pdf (19 slides)
Contents · 10 sections
🎯 本講重點 (Learning outcomes)
- 明白 Generalized linear model 嘅角度:先認清 Y 係咩類型;binary Y 用 Logistic regression。
- 解釋點解 linear regression 唔適合 binary Y:左邊 probability 喺 ,右邊 喺 ,所以要 transform。
- 識用 logit / logistic function,由 計 ,再用 threshold 0.5 做 classification。
- 比較 OLS(linear regression)同 MLE(logistic regression),明白 likelihood 嘅意思。
- 識睇同寫 Python:
smf.mnlogit、predict()、idxmax(axis=1)、confusion_matrix。 - 識計 Misclassification rate,分清 in-sample 同 out-of-sample prediction。
⭐ 考試必溫 Top-5
- 點解要 transform: 但 ,兩邊 range 唔夾。
- 預測三步: → → 即 就 classify 做 1(slide 10:,)。
- OLS minimize sum of squared errors;categorical Y 嘅 error 唔可以用減數定義,所以 logistic regression 改為 maximize likelihood(MLE)。
- 3 個 categories → 3 個「one vs not」logistic models(Red / Blue / Green)。
- Misclassification rate = 分錯數目 / 總數 = 分啱比例;slide 18:。評估 model 要用 out-of-sample(test data)。
1. 點解需要 Logistic regression?(slides 1–4)
Module 4 嘅 model 係:
Slide 2 講明:linear regression fails if Y is not continuous。Generalized linear regression 可以處理唔同類型嘅 Y,而本講集中講 Binomial,即 Logistic regression。Slide 2 嘅提醒:要 predict / classify,第一步係認清 Y 屬於邊種類型。
Binomial:Y 只有兩個可能值,例如 0/1、Yes/No、Healthy/Cancer、Good debt/Bad debt、Hungry/Not hungry、Rain/Not Rain。
ExamLogistic regression 嘅 target 唔係直接 predict 類別,而係 model 類別嘅 probability,例如 。Slide 1 嘅例子:
| Prediction | |
|---|---|
| 1 | Hungry |
| 0 | Not hungry |
| 0.2 | Not hungry |
1.1 Range 唔夾(slides 3–4)
Binomial data 本身係 categorical,唔可以直接寫成 。改為 model「getting 1 嘅 probability」就有數字,但係 range 仍然有問題:
| Data | Parameter | L.H.S. range | (R.H.S.)range |
|---|---|---|---|
| Rain / No |
如果硬寫 ,右邊可以計到 1.7 或者 −0.3,但 probability 一定喺 。 is arbitrary, probability is restricted to ,所以要 transform。
1.2 多過兩個類別點算?(slide 3)
ExamBinomial 只考慮 2 個 outcomes。如果要 predict ,slide 嘅做法係每個類別 fit 一個 model:
| Model | Y 嘅兩個 outcomes |
|---|---|
| Logistic regression model 1 | Red vs not Red |
| Logistic regression model 2 | Blue vs not Blue |
| Logistic regression model 3 | Green vs not Green |
將多類別問題拆做幾條 Yes/No 問題:「係咪 Red?」「係咪 Blue?」「係咪 Green?」。k 個 categories 就要 k 個 models。
Module 4b 嘅 dummy variables 係處理 categorical X,k 個 categories 用 個 dummies;呢度講嘅係 categorical Y,slide 3 嘅 3 個 categories 用 3 個 models。
2. Logit 同 Logistic function(slides 3、5、6)
Slide 3 指出 係透過 logistic function 連去 probability。Slide 6 有兩幅圖,係同一個關係嘅正反兩面:
| Logit function | Logistic function | |
|---|---|---|
| Input | ||
| Output | Probability | |
| Formula | ||
| 圖形(slide 6) | P = 0.5 時穿過 0,接近 0 同 1 時急速趨向 | S 形曲線,由 0 慢慢升到 1,中間最斜 |
將 寫出嚟,就可以反解 P:
幾個數值幫你感受 logit 點樣將 拉開:
| P | 0.01 | 0.1 | 0.2 | 0.5 | 0.7 | 0.9 | 0.99 |
|---|---|---|---|---|---|---|---|
| −4.595 | −2.197 | −1.386 | 0 | 0.847 | 2.197 | 4.595 |
可以係任何數字。Logistic function 就好似一個「壓縮器」,將任何數字壓入 ,所以計出嚟嘅一定係合法 probability。Slide 3 亦提到,呢個 function 喺其他 machine learning methods 都會用到。
3. 預測同分類(slides 5、10)
Logistic regression 係 statistical method of obtaining 。計到 之後,對新 data 就跟以下步驟做 classification:
Step 1:對 計 :
Step 2:計 probability:
Step 3(decision rule,default threshold = 0.5):如果 ,即 ,就 classify 。
例:,未過 0.5,所以 claim 聽日唔會落雨。
點解 同 係同一件事?
ExamSlide 10 例題:,新 data ,求 。
因為 ,所以 classify 做 。準確啲計,。
多一題(自編,唔係 slide 內容):。
| x | Classification | ||
|---|---|---|---|
| 2 | −1 | 0.2689 | 0 |
| 4 | 0 | 0.5000 | 剛好喺 threshold;slide 嘅 rule 要 ,所以唔算 1 |
| 6 | 1 | 0.7311 | 1 |
唔係 probability。 或者 都係正常數值,一定要過埋 logistic function 先得到 P。
由 可知, 加 1 會令 log-odds 加 ,即 odds 乘以 ,但 P 本身唔係加固定數值。Slide 只講到用 計 P 同做分類。
4. 點樣 fit model:OLS vs MLE(slides 7–9)
| Linear regression | Logistic regression | |
|---|---|---|
| Method | Ordinary Least Squares (OLS) | Maximum Likelihood Estimation (MLE) |
| Objective | Minimize the sum of squared errors | Maximize the likelihood |
| Slide 7 圖 | Size vs Weight:一條直線穿過散開嘅數據點 | Is Obese / Is Not Obese vs Weight:數據點只喺兩條水平線,model 係 S 形曲線;圖中亦有幾條灰色虛線 S-curve |
4.1 點解唔用 squared error?(slide 8)
Categorical Y 嘅 error 或 residual 唔可以用減數定義:Engineering − Humanity = ???;Cloudy − Sunny = ???。所以 sum of squared errors 要換成另一樣嘢,就係 likelihood。
4.2 Likelihood(slide 8)
Roughly speaking,likelihood 就係「觀察到你實際觀察到嘅結果」嘅 probability。Likelihood 同 probability 成正比,所以 代表 。
注意係 based on actual observations,將每一個 observation 嘅 probability 乘埋一齊。其中 。Statistician 就係 maximize the likelihood 去搵 unknown parameters。
Slide 寫 ,嚴格嚟講呢條只適用於 。當 ,個 probability 應該係 。下面例題就係咁計。
自編例題:三個 observations ,。邊個 嘅 likelihood 較高?
| Observation | : | : |
|---|---|---|
| , | 0.5 | |
| , | 0.5 | |
| , | 0.5 | |
| Likelihood |
喺呢兩個選擇之間, 嘅 likelihood 較高,即係佢令實際數據更加「有可能出現」,所以 MLE 會較鍾意佢。真正嘅 MLE 就係喺所有可能嘅 入面搵最高嗰個。
可以將幾條灰色 S-curve 想像成候選 ,每條都計到一個 likelihood,揀最高嗰條。
4.3 Numerical analysis(slide 9)
Numerical analysis 係一類方法,用重複步驟 approximately 搵 max / min 同解方程。Computer 加 numerical analysis 可以解好多 without explicit solutions 嘅難題,例如解 。Slide 列明詳細方法係 Out-of-syllabus,知道概念就夠。
Module 4 嘅 OLS 有 closed form:。Slide 9 喺 MLE 之後講 numerical analysis,就係因為 maximize 呢個 likelihood 要靠電腦反覆計算(.fit() 幫你做晒)。
5. South African Heart Disease data(slides 11–12)
例子嚟自 Rousseauw et al, 1983, South African Medical Journal。Slide 11 寫 Training data:。
| Column | 意思 |
|---|---|
sbp | Systolic 收縮壓 blood pressure(mm Hg) |
tobacco | Cumulative tobacco use(kg) |
ldl | Low-density lipoprotein cholesterol 低密度脂蛋白膽固醇 |
adiposity | Adiposity 肥胖 / obesity measure |
famhist | Family history of ischemic 缺血性的 heart disease(Absent / Present,或 coded 0 / 1) |
typea | Type-A behavior score(12–84);例如 highly competitive、stressed、impatient、perfectionist、time-pressured |
obesity | Body mass index (BMI) measure |
alcohol | Current alcohol consumption |
age | Age at onset / age in years |
chd | Coronary heart disease diagnosis:response variable(0 / negative 或 1 / positive) |
Slide 12 列出嘅 10 個 columns 已經包括 response chd,而 slide 13 嘅 formula 用 9 個 predictors。所以 predictors 數目係 9,slide 嘅「」應該係指 columns 總數。
6. Python:Fit model(slides 13–14)
ExamSlides 用 statsmodels 入面嘅 mnlogit,formula 寫法同 Module 4 嘅 smf.ols 一樣,Y ~ X1 + X2 + ...。
import pandas as pd
import numpy as np
import statsmodels.formula.api as smf
from sklearn.metrics import confusion_matrix
heart = pd.read_csv("SAheart.txt", sep=' ')
# 將 target class variable 轉做 integer codes(0, 1)
heart['chd'] = heart['chd'].astype('category').cat.codes
model = smf.mnlogit('chd ~ sbp+tobacco+ldl+adiposity+typea+obesity+alcohol+age+famhist', data=heart).fit()
print(model.summary())
- Slide 13 寫 package 係 “statsmodels.formulas.api”,正確名稱係 slide 14 code 用嘅
statsmodels.formula.api,冇 “s”。Function 要全細階寫smf.mnlogit,唔係 mnLogit。 - Slide 14 嘅
sep=' ‘收尾係彎引號,直接 copy 會 SyntaxError,上面已改做sep=' '。 - Slides 只有 code,冇 show
summary()嘅 output,所以呢度冇列 SAheart 嘅結果數字。
famhist 係 categorical X。Formula 會自動轉 dummy(Module 4b 嘅 規則),所以 output 會見到 famhist[T.Present],baseline 係 Absent。astype('category') 就係 COM6001 pandas 同 Module 4b 用過嗰個。
7. Python:Predict(slides 15–16)
# predict on new data
newdata = pd.DataFrame({
'const': [1],
'sbp': [114],
'tobacco': [4.08],
'ldl': [4.59],
'adiposity': [14.6],
'typea': [62],
'obesity': [23.11],
'alcohol': [6.72],
'age': [58],
'famhist': ['Present']
})
pred_probs = model.predict(newdata) # 每個 class 一個 column
print(pred_probs)
pred_classes = pred_probs.idxmax(axis=1) # index of first occurrence of max
# axis=0, return row index; axis=1, return column index
print(pred_classes)
model.predict(newdata):output probabilities,一個 row 一個 observation,一個 column 一個 class。pred_probs.idxmax(axis=1):每個 row 揀 probability 最大嗰個 column,output predicted class。兩個 classes 時,就等於 threshold 0.5。
- Slide 15 用
result.predict,slide 16 用model.predict。兩者一樣,只係變數名唔同;跟 slide 14 就係model。 - Formula API 會自己加 Intercept,
'const'呢個 column 其實用唔著,不過放咗亦唔會出錯。 - Binary Y 亦可以用
smf.logit,coefficients 同mnlogit一樣,但predict()回傳 Series,只得 ,idxmax(axis=1)會 ValueError。Slides 用mnlogit,跟住佢就得。
8. Misclassification rate(slides 17–19)
Exam評估 classification model 嘅步驟(slide 17):
- 將 full data 分做 training data 同 testing data(unseen),例如 70% vs 30%。
- 將
mnlogitapply 落 training data。 - 扮唔知 test data 嘅 Y,apply
predict()。 - 將 predicted class 同 actual class 比較。
Slide 17 特別提醒要小心 in-sample prediction 同 out-sample prediction 嘅分別:前者用嚟 fit model 嘅 data,後者係 model 未見過嘅 data。
| Predicted class | Actual class | |
|---|---|---|
| High risk | Low risk | |
| High risk | 50 | 6 |
| Low risk | 8 | 35 |
對角線係分啱,對角線以外係分錯。兩條 formula 結果一樣。
# Check the out-sample misclassification rate
heart_train = heart.iloc[0:323]
heart_test = heart.iloc[323:]
model = smf.mnlogit('chd ~ sbp+tobacco+ldl+adiposity+typea+obesity+alcohol+age+famhist', data=heart_train).fit()
print(model.summary())
predicted_class = model.predict(heart_test).idxmax(axis=1)
actual_class = heart_test['chd']
misclassification = confusion_matrix(actual_class, predicted_class)
error_rate = 1 - np.trace(misclassification) / np.sum(misclassification)
print('Out-of-sample performance:')
print(misclassification)
print(f'Error Rate: {error_rate}')
逐句拆解 slide 19:
| Code | 意思 |
|---|---|
iloc[0:323] / iloc[323:] | 頭 323 個 rows 做 training,其餘 139 個 rows 做 testing,約 70% vs 30%(323/462 ≈ 69.9%) |
np.trace(...) | 對角線總和,即分啱嘅數目 |
np.sum(...) | 所有格總和,即 test data 總數 |
1 - trace/sum | 就係 slide 18 第二條 formula |
Slide 18 嘅 table:row = Predicted,column = Actual。sklearn 嘅 confusion_matrix(actual, predicted):row = Actual,column = Predicted。Misclassification rate 唔受影響,因為對角線一樣,但讀「邊格係邊種錯」時要小心。
Slide 19 用 iloc 直接切頭同尾,唔係 random split。如果 data 本身有排序,train 同 test 嘅分佈就會唔同。實際做 project 時要留意呢點。
Module 4 用 out-of-sample RMSE 評估 numeric prediction;呢度 Y 係類別,所以改用 misclassification rate,但 train / test 嘅諗法一樣。COM6004 Classification 同樣係 predict 類別,可以將 Logistic regression 同 Decision Tree 放埋一齊比較。
自我測驗 Self-test
Q1. 點解唔可以直接寫 ?
因為 probability 一定喺 ,但 可以係 入面任何數。所以要用 logit / logistic function transform,將兩邊 range 夾返。
Q2. 。求 、 同 predicted class。
;;(亦即 ),所以 predict 。
Q3. 同一個 model,x 要大過幾多先會 classify 做 1?
要 :,即 。
Q4. 證明 。
。
Q5. 嘅 係幾多?
。係負數,同 一致。
Q6. Y 有 4 種顏色,跟 slide 3 嘅方法要 fit 幾多個 logistic regression models?
4 個:每種顏色一個「該顏色 vs not 該顏色」model。
Q7. 比較 OLS 同 MLE;點解 logistic regression 唔用 OLS?
OLS minimize sum of squared errors;MLE maximize likelihood 。Categorical Y 嘅 error 唔可以用減數定義(Cloudy − Sunny = ???),所以 squared error 要由 likelihood 取代。
Q8. Predicted High:actual High 40、actual Low 10;Predicted Low:actual High 5、actual Low 45。求 misclassification rate。
分錯 = 10 + 5 = 15,總數 = 100,rate = 15/100 = 0.15。亦可以用 。
Q9. pred_probs.idxmax(axis=1) 做咩?如果係 axis=0 呢?
axis=1:每個 row 搵最大值所屬嘅 column index,即每個 observation 嘅 predicted class。axis=0:每個 column 搵最大值所屬嘅 row index。
Q10. Training data 嘅 error rate 好低,test data 嘅 error rate 好高,代表咩?
Model 喺 in-sample 表現好,但 out-of-sample 差,即對 unseen data 預測能力弱,可能係 overfitting。評估應該睇 out-of-sample 嗰個數字。
一頁總結 Cheat sheet
- Binary Y → Logistic regression,model 嘅係 probability。、 → 要 transform。
- 3 個 categories → 3 個 models:Red / not Red、Blue / not Blue、Green / not Green。
- ();()。
- 預測: → P → → class 1。例:,。
- OLS:min sum of squared errors。MLE:max ;由 numerical analysis 計(詳細方法 out-of-syllabus)。
- Code:
smf.mnlogit('y ~ x1+x2', data=df).fit()→.summary()→.predict(new)→.idxmax(axis=1)。 - Misclassification = 分錯 / 總數 = ;slide 18:14/99 ≈ 0.141。
- 70 / 30 split;評估睇 out-of-sample。
confusion_matrix(actual, predicted):row = actual、column = predicted。