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()同點解 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(、;、)同 Poisson approximation to Binomial(、;)。
⭐ 考試必溫 Top-5
- pdf → density;cdf → probability;ppf → quantile;rvs → random numbers(slide 6)。
- QQ-plot:如果數據 normal,點會貼近一條直線;亦用嚟檢查 regression residuals。
normaltest: = data comes from a normal distribution;p-value > 0.05 → do not reject 。- Normal approximation 條件同 parameters:、;、。
- Poisson approximation 條件同 parameter:n large、p small(、 或 );。
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) = ;Predicted height = (y_hat)
- Residual (prediction error) =
- 如果 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 已經榨乾咗數據入面嘅系統性資訊。
Module 4 Linear regression 嘅 diagnostic plots(residual vs fitted、QQ-plot of residuals、residual histogram)就係用呢度嘅概念。
3. scipy.stats.norm:pdf、cdf、ppf、rvs
| Function | 用途 | 例子(身高 ) |
|---|---|---|
norm.pdf | density(唔係直接嘅 probability,要積分先得 prob) | pdf(175):數值約喺 175 附近嘅 proportion(密度) |
norm.cdf | probability(cumulative) | cdf(175):proportion of data |
norm.ppf | quantile(cdf 嘅反函數) | ppf(0.95):95% 嘅人矮過呢個高度 |
norm.rvs | random numbers(simulation) | rvs(170, 7, 1000):1000 個模擬身高 |
3.1 Standardization 同查表(補充,Module 3 會大量用)
身高 。求 、、。
- Standardize:
- 查 standard normal table: → (
norm.cdf(177, 170, 7)) - →
反方向(quantile):norm.ppf(0.975) = 1.96 → 97.5% 嘅 值 ,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。
- 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)
- :sample comes from a normal distribution;: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 ≠ proving 。所以 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。
- Condition:n is large and p is near 0.5 (not too close to 0 or 1)。
- Rule of Thumb:Both and (some sources use 5 instead of 10)。
- Parameters:,。
擲 100 次公平硬幣,求 head 次嘅 probability。
- 檢查條件:, ✔
- , →
- →
- (進階:continuity correction 用 55.5 → → 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.86437.2 Poisson Approximation to the Binomial(slide 16)
當事件罕見(rare events),可以用 Poisson approximate binomial。
- Condition:n is large and p is small。
- Rule of Thumb: and ,or when the expected value 。
- Parameter:。
一批 200 件產品,每件次貨率 1%。求冇次貨嘅 probability,同最多 2 件次貨嘅 probability。
- 檢查:, ✔ →
- (exact binomial:)
- (exact:0.6767)
| Normal approx. | Poisson approx. | |
|---|---|---|
| 幾時用 | n 大、p 接近 0.5 | n 大、p 細(rare events) |
| Rule of thumb | 且 | 且 (或 ) |
| Parameters | , |
Normal approximation 用嘅係 (variance),代入 norm.cdf 時要開方做 。例如 → ,唔係 25。
Slides 9、14 係標題/示意圖頁(Quantile-quantile plot 問題頁、“Approximation”),只有圖片。
自我測驗 Self-test
Q1. 寫出 norm.pdf、norm.cdf、norm.ppf、norm.rvs 各自代表咩。
pdf = density;cdf = probability ;ppf = quantile(cdf 嘅反函數);rvs = random numbers(simulation)。
Q2. 。求 同第 97.5 百分位數。
, → 。97.5th percentile (norm.ppf(0.975, 60, 8))。
Q3. stats.normaltest 得到 p-value = 0.32。點寫結論?
p-value → do not reject 。冇足夠證據話數據唔係 normal;可以 weakly say 數據可以視為 normal。
Q4. QQ-plot 啲點喺兩端明顯偏離直線(左下向下、右上向上)代表咩?
兩邊 tails 比 normal 厚(heavy tails / outliers 多),數據唔太符合 normal。
Q5. :可唔可以用 normal approximation?
→ 按 slide 嘅 rule of thumb(10)唔適合;如果用寬鬆標準(5),、 都 → 勉強可以。考試跟 slide:答唔適合(或說明兩種標準)。
Q6. 、,求 P(X = 3) 嘅 Poisson approximation。
:。
Q7. 點解 residual 係 normal 而且 mean 0 代表 model 冇得再改善 mean prediction?
因為 residual 只係純 random noise,冇系統性 pattern 可以再被 X 解釋;如果仲有 pattern(例如 或跟 X 有關),代表 model 漏咗資訊。
Q8. 寫 code:模擬 1000 個 ,畫 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 ;normal + mean 0 → random → model 冇得再改善 mean prediction;regression 理論建基於 normal error。
- pdf = density|cdf = probability|ppf = quantile|rvs = random。預設 loc = 0、scale = 1(scale = SD)。
- ;、、。
- Histogram vs pdf:
density=True。 - QQ-plot(
sm.qqplot(x, fit=True, line="45")):normal → 近直線;亦用嚟查 residuals。 stats.normaltest: = normal;p > 0.05 → not rejected → “weakly” normal。- Normal approx. to Binomial:、(或 5);,。
- Poisson approx. to Binomial:、(或 );。