All Revision Notes

COM6005 Statistical Modeling · Module 2c

Normal Distribution, QQ-plot & Approximation

COM6005 · Module 2c · Source: Module_2c_NormalDist_Approximation_L02_Complete.pdf (16 slides)

Contents · 9 sections

🎯 本講重點 (Learning outcomes)

  • 用 boxplot、histogram、empirical CDF 睇數據分佈(plt.hist(..., cumulative=True, histtype='step'))。
  • 理解 residual(e=y−y^e = y - \hat y)同點解 normal residual 代表 model 已經冇得再改善 mean prediction。
  • 分清 norm.pdf(density)、norm.cdf(probability)、norm.ppf(quantile)、norm.rvs(random)。
  • 用 simulation + histogram、QQ-plot、stats.normaltest 檢查數據係咪 normal。
  • Normal approximation to Binomial(np≥10np \ge 10、n(1−p)≥10n(1-p) \ge 10;μ=np\mu = np、σ2=np(1−p)\sigma^2 = np(1-p))同 Poisson approximation to Binomial(n≥50n \ge 50、p≤0.1p \le 0.1;λ=np\lambda = np)。

⭐ 考試必溫 Top-5

  1. pdf → density;cdf → probability;ppf → quantile;rvs → random numbers(slide 6)。
  2. QQ-plot:如果數據 normal,點會貼近一條直線;亦用嚟檢查 regression residuals。
  3. normaltest:H0H_0 = data comes from a normal distribution;p-value > 0.05 → do not reject H0H_0。
  4. Normal approximation 條件同 parameters:np≥10np \ge 10、n(1−p)≥10n(1-p) \ge 10;μ=np\mu = np、σ2=np(1−p)\sigma^2 = np(1-p)。
  5. Poisson approximation 條件同 parameter:n large、p small(n≥50n \ge 50、p≤0.1p \le 0.1 或 np≤10np \le 10);λ=np\lambda = np。

1. Revision:Boxplot、Histogram、Empirical CDF

Slide 2:如果數據冇 missing values (NA),plt.hist 加 histtype='step'(同 cumulative=True)就可以畫出 empirical cumulative distribution function。

import pandas as pd
import matplotlib.pyplot as plt
d = pd.read_csv("bee_wax.txt", sep='\t')       # 蜂蠟熔點數據(tab 分隔)
y = d['Melting']
fig, axs = plt.subplots(1, 3, figsize=(15, 5))
axs[0].boxplot(y);                         axs[0].set_title('Boxplot')
axs[1].hist(y, bins='auto');               axs[1].set_title('Histogram')
axs[2].hist(y, bins=50, cumulative=True, histtype='step')   # Empirical CDF
axs[2].set_title('Cumulative Distribution')
plt.tight_layout(); plt.show()
💡 三幅圖各自睇咩
  • Boxplot:median、Q1、Q3(IQR)、outliers——快速睇 location 同 spread。
  • Histogram:分佈形狀(bell-shape?skewed?bimodal?)。
  • Empirical CDF:由 0 升到 n(或 1)嘅樓梯線;可以直接讀「有幾多比例 ≤ 某值」。
⚠️ 注意

有 NaN 嘅話 plt.hist 會出錯或者結果唔啱,先 y.dropna()(連返 COM6001 data cleaning)。

2. Normal distribution 同 residual 嘅關係

Slide 5 預告之後 regression 會研究 residual 嘅 histogram:

  • True height (target) = yy;Predicted height = y^\hat y (y_hat)
  • Residual (prediction error) = e=y−y^e = y - \hat y
  • 如果 residual is normally distributed with zero mean,即係佢純粹 random,model cannot be further optimized/improved for the mean prediction。
  • 好多量度數據嘅 histogram 都係 bell-shape:中間高、兩邊 tails 薄;residuals 嘅 histogram 好多時都似鐘形。
  • Linear regression 嘅統計方法正正建基於 error (residual) terms 係 bell-shape(normal)呢個理論。
💡 直覺理解

如果 residual 仲有 pattern(例如全部偏正、或者跟 X 有曲線關係),代表 model 仲有「可以學」嘅嘢未學到;如果 residual 就好似 random noise(normal、mean 0),model 已經榨乾咗數據入面嘅系統性資訊。

3. scipy.stats.norm:pdf、cdf、ppf、rvs

⭐ 四個 function(slide 6)
Function用途例子(身高 N(170,72)N(170, 7^2))
norm.pdfdensity(唔係直接嘅 probability,要積分先得 prob)pdf(175):數值約喺 175 附近嘅 proportion(密度)
norm.cdfprobability(cumulative)cdf(175):proportion of data ≤175\le 175
norm.ppfquantile(cdf 嘅反函數)ppf(0.95):95% 嘅人矮過呢個高度
norm.rvsrandom numbers(simulation)rvs(170, 7, 1000):1000 個模擬身高

3.1 Standardization 同查表(補充,Module 3 會大量用)

Z=X−μσ∼N(0,1),P(X≤x)=Φ ⁣(x−μσ)Z = \frac{X-\mu}{\sigma} \sim N(0,1), \qquad P(X\le x) = \Phi\!\left(\frac{x-\mu}{\sigma}\right)
⭐ Worked example

身高 X∼N(μ=170,σ=7)X \sim N(\mu = 170, \sigma = 7)。求 P(X≤177)P(X \le 177)、P(X>177)P(X > 177)、P(166.5≤X≤173.5)P(166.5 \le X \le 173.5)。

  1. Standardize:z=(177−170)/7=1z = (177-170)/7 = 1
  2. 查 standard normal table:Φ(1)=0.8413\Phi(1) = 0.8413 → P(X≤177)=0.8413P(X \le 177) = 0.8413(norm.cdf(177, 170, 7))
  3. P(X>177)=1−0.8413=0.1587P(X > 177) = 1 - 0.8413 = 0.1587
  4. z1=(166.5−170)/7=−0.5, z2=(173.5−170)/7=0.5z_1 = (166.5-170)/7 = -0.5,\ z_2 = (173.5-170)/7 = 0.5 → Φ(0.5)−Φ(−0.5)=0.6915−0.3085=0.3829\Phi(0.5)-\Phi(-0.5) = 0.6915 - 0.3085 = 0.3829

反方向(quantile):norm.ppf(0.975) = 1.96 → 97.5% 嘅 ZZ 值 ≤1.96\le 1.96,Module 3 嘅 95% CI 就用佢。

4. Simulation of normal distribution

Slide 7:Simulation = 用電腦整一啲睇落似真實 normally-distributed data 嘅 random numbers。

  • scipy.stats.norm.rvs(5, 2, 1000):1000 個數,似 mean = 5、sd = 2 嘅 normal。
  • 可以 x = scipy.stats.norm.rvs(5, 2, 1000); plt.hist(x) 睇吓係咪鐘形。
  • 如果冇指定第一、二個 argument,預設 loc = 0、scale = 1(standard normal)。
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
np.random.seed(12345)                        # set random seed
ns = 1000                                    # simulation size
z = norm.rvs(loc=0, scale=1, size=ns)        # generate N(0,1) random numbers
plt.hist(z, bins='auto', density=True)       # histogram with density(面積 = 1)
x = np.arange(-3, 4, 0.1)                    # x-coordinates
plt.plot(x, norm.pdf(x, loc=0, scale=1))     # 疊上理論 normal density curve
plt.show()

Slide 8 結論:simulated data 嘅 histogram 同 normal density function curve(bell)配合得好好。

⚠️ 常見錯誤

要將 histogram 同 pdf 曲線比較,plt.hist 一定要加 density=True;否則 y 軸係 frequency(幾十至幾百),而 pdf 最高只有 0.3989,兩者 scale 對唔上。另外 scale 係 standard deviation,唔係 variance。

🖼️ 圖片內容

Slide 4 係分節標題頁(“Simulation of normal distribution”),只有圖片,冇額外文字。

5. Quantile-quantile plot (QQ-plot)

Slide 9 嘅問題:Does IQ data look normal? Does error look normal?

  • 可以將 histogram 同 normal density curve 疊埋比較(上一節)。
  • 更精確嘅做法:用比較抽象但更好嘅工具 QQ-plot。
  • If the data is normally distributed, QQ-plot should be close to a straight line.
  • 同一個 idea 適用於 regression 嘅 residuals:用 QQ-plot 檢查 error terms 嘅 normal assumption。
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
d = pd.read_csv("bee_wax.txt", delimiter='\t')
sm.qqplot(d['Melting'], fit=True, line="45")   # fit=True:先 standardize;line="45":畫 45° 參考線
plt.show()

Slide 12 嘅 QQ-plot(bee wax melting point):x 軸 Theoretical Quantiles(約 −2 至 2),y 軸 Sample Quantiles(約 62.8 至 64.4),啲點大致沿住紅色直線排列,只係右上尾端有少少偏離 → 數據大致符合 normal。

💡 點讀 QQ-plot
  • X 軸 = 如果數據真係 normal,第 i 細嘅值「應該」喺邊(theoretical quantile);Y 軸 = 實際第 i 細嘅值(sample quantile)。
  • 點貼住直線 → normal。
  • 兩端向外彎(S 形)→ heavy tails / outliers;一邊彎 → skewed。

6. Statistical test for normality

Slide 13:用 hypothesis test 正式檢驗:

from scipy import stats
# Null hypothesis: a sample comes from a normal distribution
res = stats.normaltest(d['Melting'])
print(res.statistic)
print(res.pvalue)
⭐ 點寫結論(slide 13)
  • H0H_0:sample comes from a normal distribution;H1H_1:not normal。
  • p-value > 0.05 → the null hypothesis is not rejected。
  • “We do not find enough evidence to claim that the data is not from Normal distribution.”
  • Weakly say:“The data can be considered to follow normal distribution.”
⚠️ 易混淆

Not rejecting H0H_0 ≠ proving H0H_0。所以 slide 用「weakly say」:只能話「冇證據話佢唔係 normal」,唔可以話「證明咗係 normal」。呢個邏輯喺 Module 3 Hypothesis testing 會再出現。

7. Approximation

7.1 Normal Approximation to the Binomial(slide 15)

當 trials 夠多而且 success rate 平衡,可以用 normal distribution approximate binomial。

⭐ 條件同 parameters
  • Condition:n is large and p is near 0.5 (not too close to 0 or 1)。
  • Rule of Thumb:Both np≥10np \ge 10 and n(1−p)≥10n(1-p) \ge 10(some sources use 5 instead of 10)。
  • Parameters:μ=np\mu = np,σ2=np(1−p)\sigma^2 = np(1-p)。
💡 Worked example(補充)

擲 100 次公平硬幣,求 head ≤55\le 55 次嘅 probability。

  1. 檢查條件:np=50≥10np = 50 \ge 10,n(1−p)=50≥10n(1-p) = 50 \ge 10 ✔
  2. μ=np=50\mu = np = 50,σ2=100×0.5×0.5=25\sigma^2 = 100 \times 0.5 \times 0.5 = 25 → σ=5\sigma = 5
  3. z=(55−50)/5=1z = (55-50)/5 = 1 → Φ(1)=0.8413\Phi(1) = 0.8413
  4. (進階:continuity correction 用 55.5 → z=1.1z = 1.1 → 0.8643;真正 binomial 答案 = 0.8644,可見 correction 令 approximation 更準。)
from scipy import stats
print(stats.binom.cdf(55, 100, 0.5))       # exact: 0.8644
print(stats.norm.cdf(55, 50, 5))           # approx: 0.8413
print(stats.norm.cdf(55.5, 50, 5))         # with continuity correction: 0.8643

7.2 Poisson Approximation to the Binomial(slide 16)

當事件罕見(rare events),可以用 Poisson approximate binomial。

⭐ 條件同 parameter
  • Condition:n is large and p is small。
  • Rule of Thumb:n≥50n \ge 50 and p≤0.1p \le 0.1,or when the expected value np≤10np \le 10。
  • Parameter:λ=np\lambda = np。
💡 Worked example(補充)

一批 200 件產品,每件次貨率 1%。求冇次貨嘅 probability,同最多 2 件次貨嘅 probability。

  1. 檢查:n=200≥50n = 200 \ge 50,p=0.01≤0.1p = 0.01 \le 0.1 ✔ → λ=np=2\lambda = np = 2
  2. P(X=0)≈e−2=0.1353P(X=0) \approx e^{-2} = 0.1353(exact binomial:0.99200=0.13400.99^{200} = 0.1340)
  3. P(X≤2)≈e−2(1+2+22/2)=5e−2=0.6767P(X\le 2) \approx e^{-2}(1 + 2 + 2^2/2) = 5e^{-2} = 0.6767(exact:0.6767)
Normal approx.Poisson approx.
幾時用n 大、p 接近 0.5n 大、p 細(rare events)
Rule of thumbnp≥10np \ge 10 且 n(1−p)≥10n(1-p) \ge 10n≥50n \ge 50 且 p≤0.1p \le 0.1(或 np≤10np \le 10)
Parametersμ=np\mu = np,σ2=np(1−p)\sigma^2 = np(1-p)λ=np\lambda = np
⚠️ 常見錯誤

Normal approximation 用嘅係 σ2\sigma^2(variance)=np(1−p)= np(1-p),代入 norm.cdf 時要開方做 σ\sigma。例如 n=100,p=0.5n = 100, p = 0.5 → σ=5\sigma = 5,唔係 25。

🖼️ 圖片內容

Slides 9、14 係標題/示意圖頁(Quantile-quantile plot 問題頁、“Approximation”),只有圖片。

自我測驗 Self-test

Q1. 寫出 norm.pdf、norm.cdf、norm.ppf、norm.rvs 各自代表咩。

pdf = density;cdf = probability P(X≤x)P(X \le x);ppf = quantile(cdf 嘅反函數);rvs = random numbers(simulation)。

Q2. X∼N(60,82)X \sim N(60, 8^2)。求 P(X>72)P(X > 72) 同第 97.5 百分位數。

z=(72−60)/8=1.5z = (72 - 60)/8 = 1.5,Φ(1.5)=0.9332\Phi(1.5) = 0.9332 → P(X>72)=0.0668P(X > 72) = 0.0668。97.5th percentile =60+1.96×8=75.68= 60 + 1.96 \times 8 = 75.68(norm.ppf(0.975, 60, 8))。

Q3. stats.normaltest 得到 p-value = 0.32。點寫結論?

p-value 0.32>α=0.050.32 > \alpha = 0.05 → do not reject H0H_0。冇足夠證據話數據唔係 normal;可以 weakly say 數據可以視為 normal。

Q4. QQ-plot 啲點喺兩端明顯偏離直線(左下向下、右上向上)代表咩?

兩邊 tails 比 normal 厚(heavy tails / outliers 多),數據唔太符合 normal。

Q5. Binomial(n=40,p=0.2)\text{Binomial}(n = 40, p = 0.2):可唔可以用 normal approximation?

np=8<10np = 8 < 10 → 按 slide 嘅 rule of thumb(10)唔適合;如果用寬鬆標準(5),np=8np = 8、n(1−p)=32n(1-p) = 32 都 ≥5\ge 5 → 勉強可以。考試跟 slide:答唔適合(或說明兩種標準)。

Q6. n=500n = 500、p=0.004p = 0.004,求 P(X = 3) 嘅 Poisson approximation。

λ=np=2\lambda = np = 2:P(X=3)≈23e−2/3!=8×0.1353/6≈0.1804P(X=3) \approx 2^3 e^{-2}/3! = 8 \times 0.1353/6 \approx 0.1804。

Q7. 點解 residual 係 normal 而且 mean 0 代表 model 冇得再改善 mean prediction?

因為 residual 只係純 random noise,冇系統性 pattern 可以再被 X 解釋;如果仲有 pattern(例如 mean≠0\text{mean} \ne 0 或跟 X 有關),代表 model 漏咗資訊。

Q8. 寫 code:模擬 1000 個 N(5,22)N(5, 2^2),畫 density histogram 並疊上理論曲線。

x = norm.rvs(5, 2, 1000); plt.hist(x, bins='auto', density=True); g = np.linspace(-2, 12, 200); plt.plot(g, norm.pdf(g, 5, 2)); plt.show()

一頁總結 Cheat sheet

⭐ 考前速記
  • ECDF:plt.hist(y, bins=50, cumulative=True, histtype='step')(數據要冇 NA)。
  • Residual e=y−y^e = y-\hat y;normal + mean 0 → random → model 冇得再改善 mean prediction;regression 理論建基於 normal error。
  • pdf = density|cdf = probability|ppf = quantile|rvs = random。預設 loc = 0、scale = 1(scale = SD)。
  • Z=(X−μ)/σZ=(X-\mu)/\sigma;Φ(1)=0.8413\Phi(1) = 0.8413、Φ(1.96)=0.975\Phi(1.96) = 0.975、Φ(0)=0.5\Phi(0) = 0.5。
  • Histogram vs pdf:density=True。
  • QQ-plot(sm.qqplot(x, fit=True, line="45")):normal → 近直線;亦用嚟查 residuals。
  • stats.normaltest:H0H_0 = normal;p > 0.05 → not rejected → “weakly” normal。
  • Normal approx. to Binomial:np≥10np \ge 10、n(1−p)≥10n(1-p) \ge 10(或 5);μ=np\mu = np,σ2=np(1−p)\sigma^2 = np(1-p)。
  • Poisson approx. to Binomial:n≥50n \ge 50、p≤0.1p \le 0.1(或 np≤10np \le 10);λ=np\lambda = np。