All Revision Notes

COM6005 Statistical Modeling · Module 4

Linear Regression

COM6005 · Module 4 · Source: L4_Linear_Regression_V2.pdf (46 slides)

Contents · 11 sections

🎯 本講重點 (Learning outcomes)

  • Simple linear regression Y=β0+β1X1+errorY=\beta_0+\beta_1X_1+\text{error}:適用條件、dependent / independent variable 嘅叫法。
  • OLS:最小化 SS(a,b)=∑(Yt−a−bXt)2SS(a,b)=\sum(Y_t-a-bX_t)^2;用 smf.ols('fuel~dlic', data).fit()、讀 model.summary()、model.params、model.predict()。
  • Matrix 解法:β^=(X′X)−1X′Y\hat\beta=(X'X)^{-1}X'Y,識用 3 點例子手計。
  • R2=1−RSS/TSSR^2 = 1 - RSS/TSS 嘅意思;TSS=ESS+RSSTSS = ESS + RSS。
  • Regression 幾時 fail:non-linearity、residuals 唔 i.i.d. normal;四幅 diagnostic plots 點讀。
  • Multiple linear regression、coefficient interpretation、train/test split、Bias / RMSE、in-sample vs out-of-sample、AIC / BIC。
  • (Optional)interval prediction、ANOVA F-test、coefficient t-test 同 standard error 公式。

⭐ 考試必溫 Top-5

  1. OLS 目標函數同 β^=(X′X)−1X′Y\hat\beta=(X'X)^{-1}X'Y;3 點 (1,2), (2,3), (3,5) → β^0=1/3, β^1=3/2\hat\beta_0 = 1/3,\ \hat\beta_1 = 3/2。
  2. 讀 summary:Y^=−227.3091+14.0984X\hat Y=-227.3091+14.0984X;slope 解讀(X 加 1 單位,Y 平均變幾多)、p-value、95% CI、R2=0.489R^2 = 0.489。
  3. R2=1−RSSTSSR^2 = 1-\dfrac{RSS}{TSS},TSS=ESS+RSSTSS = ESS + RSS;R2=1R^2 = 1 = perfect fit。
  4. Residual diagnostics:Residual vs Fitted(linearity、constant variance)、vs Index(independence)、Lag plot(autocorrelation)、QQ-plot(normality)。
  5. Big model in-sample RMSE 一定較細,但 out-of-sample 唔一定;用 test data RMSE / AIC / BIC(越低越好)揀 model。

1. Regression problem:Simple linear regression

Y=β0+β1X1+errorY = \beta_0 + \beta_1 X_1 + \text{error}

Slide 1:適合以下問題——

  • 只有 p=1p = 1 個 predictor;
  • X 同 Y 都係 numerical and continuous;
  • X、Y 嘅 scatter plot 理想上似一條直線。
YX
Dependent variable / response / predicted target
(statsmodels 叫 endogenous variable,endog)
Independent variable / predictor
(statsmodels 叫 exogenous variable,exog)

Slides 2–5 例子:美國 48 個州嘅 fuel consumption vs number of driving licenses(dlic;Module 1 slide 8 叫 %Driving License)。Slide 3 嘅 scatter plot 顯示 dlic 越高、fuel 越高,大致線性。

  • Problem:根據 X 同 Y 嘅數學關係,由 X 預測 Y。
  • Linear model:Y=a+bX+ErrorY = a + bX + \text{Error}(a = intercept,b = slope)。
  • Regression:由 training data 估計 a、b 嘅統計方法 → a^, b^\hat a,\ \hat b。新數據只知 X → 預測 Y^=a^+b^X\hat Y = \hat a + \hat b X。
  • Slide 5 嘅 prediction problem:如果新政策將 license 數目減至 50%,執行後 fuel consumption 會係幾多?

2. Problem Solving with Python:OLS

import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
import matplotlib.pyplot as plt
import seaborn as sns
fueldata = pd.read_csv("fueldata.csv")
plt.scatter(fueldata['dlic'], fueldata['fuel'])    # 先睇 scatter plot 係咪線性
plt.show()

Slide 7:Simple linear regression 搵 a^\hat a、b^\hat b 令 sum of squared errors 最細——OLS (Ordinary Least Squares):

SS(a,b)=∑t=1n(Yt−a−bXt)2SS(a,b) = \sum_{t=1}^{n}\left(Y_t - a - bX_t\right)^2
model = smf.ols('fuel~dlic', data=fueldata).fit()   # 'Y~X':左邊 dependent,右邊 independent
print(model.summary())
print(model.params)                                  # 睇 a-hat 同 b-hat

a^\hat a 讀做 “a-hat”,代表由數據估計出嚟嘅值。

💡 Simple regression 嘅 closed-form(補充,手計用)
b^=SXYSXX=∑(Xt−Xˉ)(Yt−Yˉ)∑(Xt−Xˉ)2,a^=Yˉ−b^ Xˉ\hat b = \frac{S_{XY}}{S_{XX}} = \frac{\sum (X_t-\bar X)(Y_t-\bar Y)}{\sum (X_t-\bar X)^2}, \qquad \hat a = \bar Y - \hat b\,\bar X

(由 ∂SS/∂a=0\partial SS/\partial a = 0、∂SS/∂b=0\partial SS/\partial b = 0 推出,即 Module 1 提過嘅 calculus:derivatives → minimum。)

2.1 讀 OLS Regression Results(slide 8)

項目值意思
Dep. VariablefuelY
No. Observations48n
Df Residuals / Df Model46 / 1n−2n - 2 / pp
R-squared / Adj. R-squared0.489 / 0.477dlic 解釋到 fuel 約 48.9% 嘅 variation
F-statistic / Prob (F)43.94 / 3.29e-08整個 model 顯著(ANOVA F-test)
AIC / BIC559.9 / 563.6model selection 用,越低越好
coefstd errtP>|t|[0.0250.975]
Intercept−227.3091121.862−1.8650.069−472.60417.986
dlic14.09842.1276.6290.0009.81718.380
Y^=−227.3091+14.0984 X\hat Y = -227.3091 + 14.0984\,X
⭐ Coefficient interpretation(考試必寫格式)
  • Slope 14.0984:dlic 每增加 1 單位(1 個百分點),預期 fuel consumption 平均增加約 14.10 單位。
  • Intercept −227.31:dlic=0\text{dlic} = 0 時嘅預測 fuel——負數冇實際意義,因為 dlic=0\text{dlic} = 0 遠超出數據範圍(extrapolation),intercept 只係令條線位置正確。
  • t=coef/std errt = \text{coef} / \text{std err}:14.0984 / 2.127 = 6.629;p-value ≈ 0.000 < 0.05 → reject H0:β1=0H_0: \beta_1 = 0 → dlic 對 fuel 有顯著線性關係。Intercept p=0.069>0.05p = 0.069 > 0.05 → 喺 5% 唔顯著。
  • 95% CI of slope:[9.817, 18.380],唔包 0 → 同 t-test 結論一致(Module 3:CI 唔包 null value ⇔ reject H0H_0)。手計:14.0984 ± 2.013 × 2.127 = 14.0984 ± 4.282(t46,0.975≈2.013t_{46,0.975} \approx 2.013)。
  • Simple regression 入面 F=t2F = t^2:6.6292≈43.946.629^2 \approx 43.94 ✔。

2.2 畫 fitted line 同 prediction(slides 9–10)

plt.scatter(fueldata['dlic'], fueldata['fuel'])
predicted_values = model.predict()                 # training data 嘅 fitted values
plt.plot(fueldata['dlic'], predicted_values)
plt.show()

newdata = pd.DataFrame({'dlic': [50]})             # test dataset:column 名要同 formula 一樣
prediction = model.predict(newdata)                # 477.61
newdata = pd.DataFrame({'dlic': [50, 55, 60]})
predictions = model.predict(newdata)               # 477.61, 548.10, 618.59
⭐ 手計 prediction

dlic=50\text{dlic} = 50:Y^=−227.3091+14.0984×50=−227.3091+704.92=477.61\hat Y = -227.3091 + 14.0984 \times 50 = -227.3091 + 704.92 = 477.61。
dlic=60\text{dlic} = 60:−227.3091+845.904=618.59-227.3091 + 845.904 = 618.59。

3. Step-by-step numerical example:Matrix OLS(slides 11–19)

3 個數據點:(1, 2)、(2, 3)、(3, 5)。Slide 12 嘅圖顯示 OLS line 穿過三點附近。

3.1 Derivation(slides 13–16)

Objective function(slide 14):選 β^\hat\beta 令 Sum of Squared Residuals 最細;column vector 嘅平方和 = inner product eTee^Te:

S(β^)=eTe=(y−Xβ^)T(y−Xβ^)=(yT−β^TXT)(y−Xβ^)=yTy−yTXβ^−β^TXTy+β^TXTXβ^=yTy−2β^TXTy+β^TXTXβ^\begin{aligned} S(\hat\beta) &= e^Te = (y - X\hat\beta)^T(y-X\hat\beta) \\ &= (y^T - \hat\beta^TX^T)(y - X\hat\beta) \\ &= y^Ty - y^TX\hat\beta - \hat\beta^TX^Ty + \hat\beta^TX^TX\hat\beta \\ &= y^Ty - 2\hat\beta^TX^Ty + \hat\beta^TX^TX\hat\beta \end{aligned}

(因為 yTXβ^y^TX\hat\beta 係 scalar,等於自己嘅 transpose β^TXTy\hat\beta^TX^Ty,兩個中間項可以合併。)

Matrix differentiation & first-order conditions(slide 15):兩條 matrix calculus rules——Linear rule ∂(ATβ)/∂β=A\partial(A^T\beta)/\partial\beta = A;Quadratic rule(A symmetric)∂(βTAβ)/∂β=2Aβ\partial(\beta^TA\beta)/\partial\beta = 2A\beta:

∂S∂β^=0−2XTy+2XTXβ^=0\frac{\partial S}{\partial\hat\beta} = 0 - 2X^Ty + 2X^TX\hat\beta = 0

Normal Equations(slide 16):

XTXβ^=XTy⟹β^=(XTX)−1XTyX^TX\hat\beta = X^Ty \quad\Longrightarrow\quad \hat\beta = (X^TX)^{-1}X^Ty

前提:design matrix X 有 full column rank(冇 perfect multicollinearity),咁 XTXX^TX 先可逆。

3.2 手計(slides 17–18)

⭐ 6 個步驟
  1. Define matrices: Y=[235]Y = \begin{bmatrix}2\\3\\5\end{bmatrix},X=[111213]X = \begin{bmatrix}1&1\\1&2\\1&3\end{bmatrix}(第一欄全 1 = intercept;第二欄 = independent variable)
  2. Transpose:XT=[111123]X^T = \begin{bmatrix}1&1&1\\1&2&3\end{bmatrix}
  3. XTXX^TX:[1+1+11+2+31+2+31+4+9]=[36614]\begin{bmatrix}1+1+1 & 1+2+3\\ 1+2+3 & 1+4+9\end{bmatrix} = \begin{bmatrix}3&6\\6&14\end{bmatrix}
  4. Invert(2×2:1ad−bc[d−b−ca]\frac{1}{ad-bc}\begin{bmatrix}d&-b\\-c&a\end{bmatrix}):determinant = 3×14 − 6×6 = 6; (XTX)−1=16[14−6−63]=[2.333−1−10.5](X^TX)^{-1} = \frac16\begin{bmatrix}14&-6\\-6&3\end{bmatrix} = \begin{bmatrix}2.333&-1\\-1&0.5\end{bmatrix}
  5. XTYX^TY:[2+3+52+6+15]=[1023]\begin{bmatrix}2+3+5\\2+6+15\end{bmatrix} = \begin{bmatrix}10\\23\end{bmatrix}
  6. Solve:β^=[2.333−1−10.5][1023]=[23.33−23−10+11.5]=[0.3331.5]\hat\beta = \begin{bmatrix}2.333&-1\\-1&0.5\end{bmatrix}\begin{bmatrix}10\\23\end{bmatrix} = \begin{bmatrix}23.33-23\\-10+11.5\end{bmatrix} = \begin{bmatrix}0.333\\1.5\end{bmatrix}

Intercept β^0=1/3\hat\beta_0 = 1/3,Slope β^1=3/2\hat\beta_1 = 3/2 → Y^=0.333+1.5X\hat Y = 0.333 + 1.5X。

💡 用 closed-form 驗證

Xˉ=2, Yˉ=10/3\bar X = 2,\ \bar Y = 10/3;SXY=(−1)(−4/3)+0+(1)(5/3)=3S_{XY} = (-1)(-4/3) + 0 + (1)(5/3) = 3;SXX=2S_{XX} = 2 → b^=1.5\hat b = 1.5,a^=10/3−1.5×2=1/3\hat a = 10/3 - 1.5 \times 2 = 1/3 ✔。

3.3 Python code(slide 19)

import numpy as np
import statsmodels.api as sm
x_data = np.array([1, 2, 3])
Y = np.array([2, 3, 5]).reshape(-1, 1)
X = np.column_stack((np.ones_like(x_data), x_data))   # design matrix:加一欄 1
XT = X.T
XTX = XT @ X
XTX_inv = np.linalg.inv(XTX)
XTY = XT @ Y
beta_hat = XTX_inv @ XTY
print(f"Intercept (Beta 0): {beta_hat[0][0]:.3f}")      # 0.333
print(f"Slope (Beta 1):     {beta_hat[1][0]:.3f}")      # 1.500
# 同 library 比較:endog = dependent,exog = independent(要自己加 constant 欄)
model = sm.OLS(endog=Y, exog=X).fit()
print(model.summary())
⚠️ 常見錯誤

sm.OLS(大寫,array API)唔會自動加 intercept,要自己加一欄 1(或 sm.add_constant(x));smf.ols(細寫,formula API)會自動加 Intercept。

4. R squared(slide 20)

R2R^2 係 0 至 1 之間嘅數,描述 Y 嘅 variation 有幾多比例被 model 解釋。

Total SS=Explained SS+Residual SS,R2=1−Residual SSTotal SS=1−RSSTSS\text{Total SS} = \text{Explained SS} + \text{Residual SS}, \qquad R^2 = 1 - \frac{\text{Residual SS}}{\text{Total SS}} = 1 - \frac{RSS}{TSS}
TSS=∑t=1n(Yt−Yˉ)2,RSS=∑t=1n(Yt−β^0−β^1X1t−⋯−β^pXpt)2=∑(True−Predicted)2TSS = \sum_{t=1}^{n}(Y_t-\bar Y)^2, \qquad RSS = \sum_{t=1}^{n}\left(Y_t - \hat\beta_0 - \hat\beta_1X_{1t} - \cdots - \hat\beta_pX_{pt}\right)^2 = \sum(\text{True} - \text{Predicted})^2

Explained / Regression SS (ESS):ESS=TSS−RSSESS = TSS - RSS。R2=1R^2 = 1 代表 perfect fit(RSS=0RSS = 0)。

⚠️ 留意

Slide 20 原文寫 “R squared: 1 means perfect fit. It implies that ESS = 0”——正確應該係 RSS(Residual SS)= 0(所有點都喺線上),ESS=TSSESS = TSS。考試要寫 RSS=0RSS = 0。

⭐ Worked example:3 點數據嘅 R2R^2
  1. Yˉ=10/3=3.333\bar Y = 10/3 = 3.333;TSS=(2−3.333)2+(3−3.333)2+(5−3.333)2=1.778+0.111+2.778=4.667TSS = (2-3.333)^2 + (3-3.333)^2 + (5-3.333)^2 = 1.778 + 0.111 + 2.778 = 4.667
  2. Fitted:Y^=1.833, 3.333, 4.833\hat Y = 1.833,\ 3.333,\ 4.833;residuals = 0.167, −0.333, 0.167
  3. RSS=0.0278+0.1111+0.0278=0.1667RSS = 0.0278 + 0.1111 + 0.0278 = 0.1667
  4. ESS=4.667−0.1667=4.5ESS = 4.667 - 0.1667 = 4.5
  5. R2=1−0.1667/4.667=0.964R^2 = 1 - 0.1667/4.667 = 0.964 → model 解釋 96.4% variation。
💡 Fuel 例子

R2=0.489R^2 = 0.489:dlic 只解釋到 fuel 大約一半嘅差異,其餘可能嚟自 income、tax 等其他因素 → 引出 multiple regression。

5. When does regression fail?(slides 21–22)

⭐ 失敗情況
  • Relationship does not look linear。
  • Error terms / residuals are not i.i.d. normal(independent and identically distributed):
    • Independent:check serial correlation → 改善:加 time series model component。
    • Identically distributed:Var(error) 應該 constant,唔應該跟 fitted values 或 time/index 改變 → 否則係 Heteroskedasticity(non-constant variance)→ time-varying variance model (GARCH)。
    • Normal:residuals Yt−a^−b^XtY_t-\hat a-\hat bX_t 應該 bell-shaped:QQ-plot(intuitive)同 Anderson-Darling test(rigorous,not discussed)→ 否則其他 model 可能更好。

5.1 Visual diagnostics check(slides 23–25)

resid = model.resid
fitted = model.fittedvalues
n = len(resid)
fig, axs = plt.subplots(2, 2, figsize=(10, 10))
axs[0, 0].scatter(fitted, resid);            axs[0, 0].axhline(0, color='red', lw=2)  # e(i) vs fit(i)
axs[0, 1].scatter(np.arange(n), resid);      axs[0, 1].axhline(0, color='red', lw=2)  # e(i) vs i
axs[1, 0].scatter(resid[:-1], resid[1:]);    axs[1, 0].axhline(0, color='red', lw=2)  # e(i) vs e(i-1)
sm.qqplot(resid, ax=axs[1, 1]);              axs[1, 1].set_title('Normal Q-Q')
plt.show()
plt.hist(resid, bins=20); plt.show()         # residual histogram
⭐ 四幅圖點讀(slide 25)
PlotCheck 咩理想問題 pattern
Top-left:Residuals vs FittedLinearity + homoscedasticity圍繞 0 嘅 random、均勻點雲曲線 / U 形 → non-linearity;漏斗 / cone 形 → heteroscedasticity
Top-right:Residuals vs Order/IndexIndependence(時間/次序)圍繞 0 隨機散佈Trends、cycles、clusters → 次序影響 error(time series)
Bottom-left:Lag plot eie_i vs ei−1e_{i-1}First-order autocorrelation(lag-1)冇結構、冇方向正斜線 → positive autocorrelation;負斜線 → negative
Bottom-right:Q-Q plotNormality of residuals貼住對角直線兩端偏離 / S 形 → skewness、heavy tails、outliers
Residual histogram (20 bins)Normality、symmetry、skewness以 0 為中心嘅鐘形偏斜、多峰

Slide 24 係 fuel model 嘅四幅 diagnostic plots:residual vs predicted fuel、vs index、vs lagged error 大致都係圍繞 0 嘅散點,冇明顯 pattern;QQ-plot 大致沿直線,但右上尾有幾個大 residual(約 180、250)偏離 → 可能有 outliers/少少 right skew。(Summary 嘅 Skew = 0.747、Prob(Omnibus) = 0.049 亦提示 residual 唔算完全 normal;Durbin-Watson = 1.645 接近 2,autocorrelation 唔嚴重。)

6. Multiple linear regression(slides 26–29)

Y=β0+β1X1+β2X2+⋯+βpXp+errorY = \beta_0 + \beta_1X_1 + \beta_2X_2 + \cdots + \beta_pX_p + \text{error}

Applicable if:

  • 所有 X 同 Y 都係 numerical and continuous;
  • p 相對 n 細(p>10p > 10 can be very problematic)。

Lecture 4 第二部分內容:basic ideas of regression for p>1p > 1、doing prediction using Python、selecting important predictors。

例子(slide 29):What affects the saving rate?savings.csv:50 個國家 1960–1970 數據(Belsley, Kuh & Welsch 1980, Regression Diagnostics)。

Variable意思
Y=srY = \text{sr}personal saving ÷ disposable income
X1=pop15X_1 = \text{pop15}% population under age 15
X2=pop75X_2 = \text{pop75}% population over age 75
X3=dpiX_3 = \text{dpi}per capita disposable income (US$)
X4=ddpiX_4 = \text{ddpi}% growth rate of dpi

7. Multiple regression with Python(slides 30–34)

要識:點寫 regression formula、計 coefficients、指定 training / test data。

SS(β)=∑t=1n(Yt−β0−β1X1t−β2X2t−⋯−βpXpt)2SS(\boldsymbol\beta) = \sum_{t=1}^{n}\left(Y_t - \beta_0 - \beta_1X_{1t} - \beta_2X_{2t} - \cdots - \beta_pX_{pt}\right)^2
model = smf.ols('sr~pop75+dpi', data=savings).fit()   # 多個 X 用 + 連接
print(model.summary())                                 # β-hat 喺 "coef" 欄

Slide 32 嘅 output:

coefstd errtP>|t|[0.0250.975]
Intercept7.05661.2905.4680.0004.4619.653
pop751.30500.7781.6780.100−0.2592.869
dpi−0.00030.001−0.3370.738−0.0020.002

R2=0.102R^2 = 0.102、Adj. R2=0.064R^2 = 0.064、F=2.680F = 2.680、Prob (F) = 0.0791、n=50n = 50、Df Residuals = 47、Df Model = 2、AIC = 291.5、BIC = 297.2。

⭐ Multiple regression 嘅 coefficient interpretation
sr^=7.0566+1.3050 pop75−0.0003 dpi\widehat{sr} = 7.0566 + 1.3050\,\text{pop75} - 0.0003\,\text{dpi}
  • pop75 = 1.3050:在 dpi 不變(holding other variables constant)下,75 歲以上人口比例每增加 1 個百分點,saving rate 平均增加約 1.305 個百分點。p=0.100>0.05p = 0.100 > 0.05 → 喺 5% 水平唔顯著;95% CI [−0.259, 2.869] 包 0,結論一致。
  • dpi = −0.0003:pop75 不變下,人均可支配收入每增加 US$1,saving rate 平均跌 0.0003(每增加 $1000 跌 0.3);p=0.738p = 0.738 → 完全唔顯著。
  • Overall F-test:p=0.0791>0.05p = 0.0791 > 0.05 → 喺 5% 水平唔能夠 reject “βpop75=βdpi=0\beta_{\text{pop75}} = \beta_{\text{dpi}} = 0”。
  • R2=0.102R^2 = 0.102:只解釋 10.2% variation,model 解釋力弱。
⚠️ 常見錯誤

Multiple regression 嘅 coefficient 一定要加「holding other variables constant」;同 simple regression 嘅 slope 唔同。Coefficient 大細亦受單位影響(dpi 係美元,所以 coef 好細),唔代表重要性。

7.1 Matrix notation(slide 33)

Y=[Y1Y2⋮Yn],X=[1X11X12⋯X1p1X21X22⋯X2p⋮⋮⋮⋮1Xn1Xn2⋯Xnp]Y = \begin{bmatrix}Y_1\\Y_2\\\vdots\\Y_n\end{bmatrix},\qquad X = \begin{bmatrix}1 & X_{11} & X_{12} & \cdots & X_{1p}\\ 1 & X_{21} & X_{22} & \cdots & X_{2p}\\ \vdots & \vdots & \vdots & & \vdots\\ 1 & X_{n1} & X_{n2} & \cdots & X_{np}\end{bmatrix}
SS(β)=(Y−Xβ)′(Y−Xβ)=Y′Y−2(Y′X)β+β′(X′X)βSS(\boldsymbol\beta) = (Y-X\boldsymbol\beta)'(Y-X\boldsymbol\beta) = Y'Y - 2(Y'X)\boldsymbol\beta + \boldsymbol\beta'(X'X)\boldsymbol\beta

Gradient = −2X′Y+2(X′X)β-2X'Y + 2(X'X)\boldsymbol\beta,設 = 0:

β^=(X′X)−1X′Y\hat{\boldsymbol\beta} = (X'X)^{-1}X'Y

第一欄全 1 係「for intercept」。Simple regression 只係 p = 1 嘅特例。

7.2 Prediction for new data(slide 34)

newdata = pd.DataFrame({'pop15': [30], 'pop75': [3], 'dpi': [2000], 'ddpi': [5]})
newdata = pd.DataFrame({'pop15': [30, 25], 'pop75': [3, 4],
                        'dpi': [2000, 2000], 'ddpi': [5, 5]})
predictions = model.get_prediction(newdata)   # 有 summary_frame,可出 interval
predictions = model.predict(newdata)          # point prediction

例:用 slide 32 model,pop75=3\text{pop75} = 3、dpi=2000\text{dpi} = 2000:sr^=7.0566+1.305(3)−0.0003(2000)=7.0566+3.915−0.6=10.37\widehat{sr} = 7.0566 + 1.305(3) - 0.0003(2000) = 7.0566 + 3.915 - 0.6 = 10.37(用四捨五入後嘅 coef;多出嚟嘅 columns 如 pop15、ddpi 會被 model 忽略)。

8. Measuring prediction ability(slides 35–39)

⭐ 步驟(slide 35)
  1. 將 full data split 做 training data 同 testing data,例如 70% vs 30%。
  2. 用 training data 做 ols。
  3. 假裝唔知 test data 嘅 Y,用 predict。
  4. 比較 actual 同 predicted:用 bias 同 mean squared error 量度 prediction accuracy。
  • 小心分清 in-sample prediction(training data)同 out-of-sample prediction(test data)。
  • Training data 係 model 見過嘅,用嚟訓練 model、得到 coefficients / parameters。
  • Model 嘅目的係應用喺 unseen data——只有 test data 係 unseen。
Bias=1m∑i=1m(y^i−yi),RMSE=1m∑i=1m(yi−y^i)2\text{Bias} = \frac1m\sum_{i=1}^{m}(\hat y_i - y_i), \qquad \text{RMSE} = \sqrt{\frac1m\sum_{i=1}^{m}(y_i-\hat y_i)^2}
savings_train = savings.iloc[:35]        # 頭 35 個國家做 training(70%)
savings_test = savings.iloc[35:50]       # 其餘 15 個做 test(30%)
model = smf.ols('sr~pop15+ddpi', data=savings_train).fit()
from sklearn.metrics import mean_squared_error
pre_val = model.predict(savings_test)
act_val = savings_test['sr']
bias = np.mean(pre_val - act_val)        # 正 = 系統性高估;負 = 系統性低估
rmse = np.sqrt(mean_squared_error(act_val, pre_val))
print("Bias:", bias)
print("RMSE:", rmse)                     # 亦可以用 MSE
💡 手計例子(補充)

Actual = 10, 12, 8;Predicted = 11, 11, 10。Errors (pred − act) = 1, −1, 2。Bias=2/3=0.667\text{Bias} = 2/3 = 0.667(平均高估);MSE=(1+1+4)/3=2MSE = (1 + 1 + 4)/3 = 2;RMSE=2=1.414RMSE = \sqrt{2} = 1.414。

8.1 Big model vs small model(slides 36–39)

⭐ Is a big model always better than a small model?(slide 38)
  • In-sample RMSE:YES(大 model 一定唔會差過細 model)——但冇用,只係 fit 咗見過嘅 data。
  • Out-of-sample RMSE:NO——大 model 可能 overfit,喺 unseen data 表現更差。
  • 點決定?AIC / BIC → Lower is better(佢哋會懲罰多餘 parameters)。
# Small model vs Big model(slide 39)
small_model = smf.ols('sr~pop15+ddpi', data=savings_train).fit()
big_model = smf.ols('sr~pop15+pop75+dpi+ddpi', data=savings_train).fit()
for name, m in [("small", small_model), ("big", big_model)]:
    in_rmse = np.sqrt(mean_squared_error(savings_train['sr'], m.predict(savings_train)))
    out_rmse = np.sqrt(mean_squared_error(savings_test['sr'], m.predict(savings_test)))
    print(f"{name}: AIC={m.aic:.1f}, BIC={m.bic:.1f}, In-RMSE={in_rmse:.4f}, Out-RMSE={out_rmse:.4f}")
⚠️ 常見錯誤

用 training data 嘅 R2R^2 / RMSE 去揀 model——加任何 variable(就算係 random noise)R2R^2 都只會升唔會跌。要睇 out-of-sample RMSE、Adj. R2R^2、AIC / BIC。Slide 39 冇顯示實際輸出數字,重點係概念:small model 嘅 out-of-sample RMSE 可以更低。

9. Optional topics(slides 40–46)

9.1 Interval prediction(slide 41)

newdata = pd.DataFrame({'dlic': [50]})          # simple regression 例子
predictions = model.get_prediction(newdata)
prediction_summary = predictions.summary_frame(alpha=0.05)
print(prediction_summary)
# mean_ci_lower/upper:population mean(平均 Y)嘅 CI
# obs_ci_lower/upper :future prediction / new data point 嘅 prediction interval(更闊)
💡 兩種 interval

CI of mean:「dlic=50\text{dlic} = 50 嘅州,平均 fuel 喺邊個範圍」;Prediction interval:「某一個 dlic=50\text{dlic} = 50 嘅州 fuel 喺邊」——要加埋個別 error 嘅 variance,所以更闊。

9.2 Is X helpful to predict Y?(slides 42–43)

ANOVA (F-statistic)T-tests
H0H_0所有 regression coefficients(intercept 除外)= 0:β1=β2=⋯=βp=0\beta_1=\beta_2=\cdots=\beta_p=0βj=0\beta_j = 0:第 j 個 predictor 對 Y 冇 effect(given other variables)
H1H_1至少一個 ≠0\ne 0βj≠0\beta_j \ne 0:XjX_j 同 Y 有顯著線性關係
測試咩整個 model 係咪比 intercept-only mean model 解釋顯著更多 variance個別 predictor 係咪顯著
⭐ ANOVA table(simple regression,slide 43)
Source of variationSum of squaresDegree of freedomMean squareF-ratio
RegressionSSR1MSR=SSR/1MSR = SSR/1MSR/MSEMSR/MSE
ErrorSSEn−2n - 2MSE=SSE/(n−2)MSE = SSE/(n-2)
TotalSSTn−1n - 1

F-test:比較 F-ratio 同 F1, n−2, 95%F_{1,\,n-2,\,95\%}(記法 Fnumerator, denominator, αF_{\text{numerator},\,\text{denominator},\,\alpha})。F-ratio 大過 critical value → reject H0H_0。

Slide 44 係 F-table(α=0.05\alpha = 0.05):column = Numerator DF(1–10),row = Denominator DF(1–50)。例如 F1,1=161.448F_{1,1} = 161.448、F1,3=10.128F_{1,3} = 10.128、F1,46=4.052F_{1,46} = 4.052、F2,47=3.195F_{2,47} = 3.195。

⭐ Worked example:Fuel model F-test

F=43.94F = 43.94,df=(1,46)df = (1, 46);查表 F1,46,0.05=4.052F_{1,46,0.05} = 4.052。43.94 > 4.052 → reject H0:β1=0H_0: \beta_1 = 0,dlic 有助預測 fuel(同 Prob(F) = 3.29e-08 一致)。

Savings model:F=2.680F = 2.680,df=(2,47)df = (2, 47);F2,47=3.195F_{2,47} = 3.195。2.680 < 3.195 → do not reject(同 Prob(F) = 0.0791 > 0.05 一致)。

9.3 Is the coefficient significantly different from zero?(slides 45–46)

統計估計同 prediction 通常會附上 standard error 量度準確度/不確定性。

σ^=1n−2 SS(a^,b^),S.E.(a^)=σ^1n+Xˉ2SXX,S.E.(b^)=σ^1SXX\hat\sigma = \sqrt{\frac{1}{n-2}\,SS(\hat a,\hat b)}, \qquad \text{S.E.}(\hat a) = \hat\sigma\sqrt{\frac1n + \frac{\bar X^2}{S_{XX}}}, \qquad \text{S.E.}(\hat b) = \hat\sigma\sqrt{\frac{1}{S_{XX}}}
SXX=∑t=1n(Xt−Xˉ)2,t=b^S.E.(b^)  compared with tn−2, 97.5%S_{XX} = \sum_{t=1}^{n}(X_t-\bar X)^2, \qquad t = \frac{\hat b}{\text{S.E.}(\hat b)} \ \text{ compared with } t_{n-2,\,97.5\%}

Slide 46 係 t-table(同 Module 3a 一樣,row ν\nu、column α\alpha)。

⭐ Worked example 1:3 點數據 (1,2), (2,3), (3,5)
  1. SS(a^,b^)=RSS=0.1667SS(\hat{a}, \hat{b}) = RSS = 0.1667;n−2=1n - 2 = 1 → σ^=0.1667/1=0.4082\hat\sigma = \sqrt{0.1667/1} = 0.4082
  2. SXX=(1−2)2+0+(3−2)2=2S_{XX} = (1-2)^2 + 0 + (3-2)^2 = 2
  3. SE(b^)=0.4082×1/2=0.2887SE(\hat{b}) = 0.4082 \times \sqrt{1/2} = 0.2887
  4. t=1.5/0.2887=t = 1.5 / 0.2887 = 5.196
  5. t1, 97.5%=12.706t_{1,\,97.5\%} = 12.706(ν=1\nu = 1,α=.025\alpha = .025)→ 5.196 < 12.706 → 唔能 reject β1=0\beta_1 = 0。只有 3 點,df=1df = 1,證據唔夠。
  6. SE(a^)=0.4082×1/3+4/2=0.4082×1.5275=0.6236SE(\hat{a}) = 0.4082 \times \sqrt{1/3 + 4/2} = 0.4082 \times 1.5275 = 0.6236
  7. ANOVA 驗證:SSR=4.5SSR = 4.5,MSE=0.1667/1MSE = 0.1667/1 → F=27=t2F = 27 = t^2(5.1962≈275.196^2 \approx 27);F1,1=161.448F_{1,1} = 161.448 → 同樣唔 reject。
⭐ Worked example 2:Module 1 廣告 vs Sales(n = 5)

X=172,156,167,145,150X = 172, 156, 167, 145, 150;Y=60,43,52,36,40Y = 60, 43, 52, 36, 40。

  1. Xˉ=158, Yˉ=46.2, SXX=514, SXY=434\bar X = 158,\ \bar Y = 46.2,\ S_{XX} = 514,\ S_{XY} = 434 → b^=0.8444, a^=−87.21\hat b = 0.8444,\ \hat a = -87.21
  2. TSS=376.8TSS = 376.8;RSS=10.35RSS = 10.35 → R2=1−10.35/376.8=0.973R^2 = 1 - 10.35/376.8 = 0.973
  3. σ^=10.35/3=1.857\hat\sigma = \sqrt{10.35/3} = 1.857;SE(b^)=1.857/514=0.0819SE(\hat{b}) = 1.857/\sqrt{514} = 0.0819
  4. t=0.8444/0.0819=t = 0.8444/0.0819 = 10.31;t3, 97.5%=3.182t_{3,\,97.5\%} = 3.182 → reject H0:β1=0H_0: \beta_1 = 0,廣告開支顯著影響 sales。
  5. 95% CI of slope:0.8444 ± 3.182 × 0.0819 = (0.584, 1.105)。
⚠️ 常見錯誤

Regression coefficient t-test 嘅 df=df = n−2n - 2(simple regression;multiple regression 係 n−p−1n - p - 1),唔係 n−1n - 1。two-sided 用 97.5% quantile。

自我測驗 Self-test

Q1. 用 matrix 方法計 (0, 1), (1, 3), (2, 2) 嘅 OLS line。

XTX=[3335]X^TX = \begin{bmatrix}3&3\\3&5\end{bmatrix},det = 15 − 9 = 6,(XTX)−1=16[5−3−33](X^TX)^{-1} = \frac16\begin{bmatrix}5&-3\\-3&3\end{bmatrix};XTY=[67]X^TY = \begin{bmatrix}6\\7\end{bmatrix};β^=16[30−21−18+21]=[1.50.5]\hat\beta = \frac16\begin{bmatrix}30-21\\-18+21\end{bmatrix} = \begin{bmatrix}1.5\\0.5\end{bmatrix} → Y^=1.5+0.5X\hat Y = 1.5 + 0.5X。

Q2. 繼續 Q1:計 TSS、RSS、R2R^2。

Yˉ=2\bar Y = 2;TSS=1+1+0=2TSS = 1 + 1 + 0 = 2。Fitted = 1.5, 2, 2.5;residuals = −0.5, 1, −0.5;RSS=0.25+1+0.25=1.5RSS = 0.25 + 1 + 0.25 = 1.5。R2=1−1.5/2=0.25R^2 = 1 - 1.5/2 = 0.25。

Q3. 某 output:coef of X = −2.35,std err = 0.80,n=25n = 25(simple regression)。做 two-sided t-test(α=0.05\alpha = 0.05)並解讀 coefficient。

t=−2.35/0.80=−2.94t = -2.35/0.80 = -2.94;df=23df = 23,t23,0.975=2.069t_{23,0.975} = 2.069。|−2.94| > 2.069 → reject H0:β1=0H_0: \beta_1 = 0。解讀:X 每增加 1 單位,Y 平均減少 2.35 單位。

Q4. Fuel model:dlic=65\text{dlic} = 65 時嘅預測?如果政策令 dlic 由 60 跌到 30,預測 fuel 變化?有咩問題?

dlic=65\text{dlic} = 65:−227.3091 + 14.0984 × 65 = 689.09。60 → 30:變化 = 14.0984 × (−30) = −422.95。問題:dlic=30\text{dlic} = 30 可能遠超出 training data 範圍(extrapolation),linear 關係未必成立;而且 regression 只顯示 association,唔一定係 causation。

Q5. Residual vs fitted plot 呈漏斗形(fitted 越大,residual 越散),代表咩問題?違反咩 assumption?

Heteroskedasticity(non-constant variance),違反 identically distributed(constant Var(error))assumption。可考慮 transformation(例如 log Y)或 GARCH 類 time-varying variance model。

Q6. Simple regression,n=22n = 22,SSR=120SSR = 120,SSE=200SSE = 200。完成 ANOVA table 並做 F-test(α=0.05\alpha = 0.05)。R2R^2 係幾多?

df:Regression 1、Error 20、Total 21。MSR=120MSR = 120;MSE=200/20=10MSE = 200/20 = 10;F=12F = 12。F1,20,0.05=4.351F_{1,20,0.05} = 4.351 → 12 > 4.351 → reject H0:β1=0H_0: \beta_1 = 0。SST=320SST = 320,R2=120/320=0.375R^2 = 120/320 = 0.375。

Q7. 點解 big model 嘅 in-sample RMSE 一定 ≤ small model,但 out-of-sample 唔一定?點樣揀?

OLS 喺 training data 上最小化 SS;多咗 parameters 最差都可以將佢哋設 0 得返 small model,所以 in-sample error 唔會更大。但多餘 parameters 會 fit 埋 noise(overfitting),喺 unseen test data 表現可能更差。揀 model:比較 out-of-sample RMSE,或 AIC / BIC(越低越好)。

Q8. 寫 Python:用 savings 頭 35 行 fit sr ~ pop15 + pop75,計 test set 嘅 bias 同 RMSE。

m = smf.ols('sr~pop15+pop75', data=savings.iloc[:35]).fit(); te = savings.iloc[35:50]; pred = m.predict(te); bias = np.mean(pred - te['sr']); rmse = np.sqrt(mean_squared_error(te['sr'], pred))

Q9. Savings output 中 pop75 coef = 1.305、p=0.100p = 0.100。用完整句子解讀,並講喺 α=0.05/0.10\alpha = 0.05 / 0.10 嘅結論。

喺 dpi 不變下,75 歲以上人口比例每增加 1 個百分點,saving rate 平均增加 1.305 個百分點。α=0.05\alpha = 0.05:p=0.100>0.05p = 0.100 > 0.05 → 唔顯著;α=0.10\alpha = 0.10:p=0.100p = 0.100 啱啱喺邊界(p 唔細過 0.10),嚴格嚟講都唔 reject。

一頁總結 Cheat sheet

⭐ 考前速記
  • Model:Y=β0+β1X+errorY=\beta_0+\beta_1X+\text{error};Y = dependent / response / endogenous;X = independent / predictor / exogenous。
  • OLS:min ∑(Yt−a−bXt)2\sum(Y_t-a-bX_t)^2;b^=SXY/SXX\hat b=S_{XY}/S_{XX},a^=Yˉ−b^Xˉ\hat a=\bar Y-\hat b\bar X;matrix:β^=(X′X)−1X′Y\hat\beta=(X'X)^{-1}X'Y(X 第一欄全 1)。
  • 3 點 (1,2),(2,3),(3,5):X′X=[36614]X'X=\begin{bmatrix}3&6\\6&14\end{bmatrix},det 6,X′Y=(10,23)′X'Y=(10,23)' → β^=(1/3, 3/2)\hat\beta=(1/3,\ 3/2)。
  • Python:smf.ols('y~x1+x2', data).fit()、.summary()、.params、.predict(newdata)、.get_prediction().summary_frame(alpha=0.05);sm.OLS(endog, exog) 要自己加 constant。
  • Fuel:Y^=−227.3091+14.0984X\hat Y=-227.3091+14.0984X,R2=0.489R^2 = 0.489,slope t=6.629t = 6.629,F=43.94=t2F = 43.94 = t^2;dlic=50\text{dlic} = 50 → 477.61。
  • Slope 解讀:X 加 1 單位,Y 平均變 β^\hat\beta(multiple:holding others constant);intercept 可能無實際意義(extrapolation)。
  • R2=1−RSS/TSSR^2=1-RSS/TSS;TSS=ESS+RSSTSS = ESS + RSS;R2=1  ⟺  RSS=0R^2 = 1 \iff RSS = 0。
  • Fail:non-linear;residuals 唔 independent(serial correlation)/唔 identical(heteroskedasticity → GARCH)/唔 normal(QQ-plot、Anderson-Darling)。
  • Diagnostics:resid vs fitted(曲線 = non-linear,漏斗 = heteroscedastic);vs index(trend = dependence);lag plot(斜線 = autocorrelation);QQ(直線 = normal);histogram。
  • Multiple regression:p 相對 n 細(p>10p > 10 有問題)。
  • Prediction ability:train/test(70/30);Bias=mean(pred−act)\text{Bias} = \text{mean}(\text{pred} - \text{act});RMSE=MSERMSE = \sqrt{MSE};in-sample 大 model 必勝,out-of-sample 唔一定;AIC / BIC 越低越好。
  • ANOVA:Regression df 1、Error df n−2n - 2、Total n−1n - 1;F=MSR/MSEF = MSR/MSE vs F1,n−2,95%F_{1,n-2,95\%};H0H_0:所有 slopes = 0。
  • σ^=SS/(n−2)\hat\sigma=\sqrt{SS/(n-2)};SE(b^)=σ^/SXXSE(\hat{b}) = \hat\sigma/\sqrt{S_{XX}};SE(a^)=σ^1/n+Xˉ2/SXXSE(\hat{a}) = \hat\sigma\sqrt{1/n+\bar X^2/S_{XX}};t=b^/SEt = \hat{b}/SE vs tn−2,97.5%t_{n-2,97.5\%}。