All Revision Notes

COM6005 Statistical Modeling · Module 2a

Simulation, Variable Types & Probability Functions

COM6005 · Module 2a · Source: Module_2a_ProbFunction_L02_complete.pdf (27 slides)

Contents · 8 sections

🎯 本講重點 (Learning outcomes)

  • 用 np.random.choice 做 simulation:replace=True/False、指定 probability p=、np.random.seed()。
  • 分辨四種 variable type:Nominal、Ordinal(categorical)同 Interval、Ratio(numerical)。
  • 知道常見情境對應嘅 distribution:Poisson、Geometric、Normal、Exponential、Weibull、Pareto。
  • 由 frequency table / histogram 理解 distribution、density(面積 = 1)同 cumulative frequency。
  • 分清 PMF / CMF(discrete)同 PDF / CDF(continuous),並識用 scipy.stats 計。

⭐ 考試必溫 Top-5

  1. PMF / CMF / PDF / CDF 對照表(slide 23):邊個 discrete、邊個 continuous、輸出係咩、總和/面積 = 1。
  2. Continuous variable:P(X = 某一點) = 0;PDF 嘅值係 density 唔係 probability;probability = 曲線下面積。
  3. Nominal / Ordinal / Interval / Ratio 嘅定義同例子(例如 temperature °C = interval;weight = ratio;Likert = ordinal)。
  4. replace=True vs replace=False;seed 嘅用途;train/test split 70/30 嘅寫法。
  5. stats.binom.pmf(5,10,0.5) = 0.2461、binom.cdf(5,10,0.5) = 0.6230、norm.pdf(0) = 0.3989、norm.cdf(0) = 0.5 嘅意思。

1. Simulation:用 random number generator

Simulation = 用電腦產生 random numbers 去模擬現實中嘅隨機現象,例如抽樣、擲硬幣、包剪揼。Slides 2–6 全部用 np.random.choice()。

1.1 replace=True vs replace=False(slide 3)

import numpy as np
np.random.choice(range(1, 11), size=10, replace=True)   # 抽完放返 → 數字可以重複
np.random.choice(range(1, 11), size=10, replace=False)  # 抽完唔放返 → 數字唔會重複(等於一個 permutation)
⭐ 考試重點

What is the difference? The numbers will not be repeated when replace=False(sampling without replacement)。replace=True = sampling with replacement,同一個數可以出現多次。注意 range(1, 11) 係 1 到 10(Python 唔包尾)。

1.2 實際應用(slide 4)

  • 由 40 個學生(編號 1–40)隨機揀 10 個做 interview:np.random.choice(range(1, 41), size=10, replace=False)(唔可以揀同一個人兩次 → 一定要 False)。
  • 將數據隨機分做 training data (70%) 同 test data (30%):數據 label 由 0 到 99(Python index always begins with 0):np.random.choice(range(0, 100), size=70, replace=False) → 得到 training 嘅 index list,其餘 30 個就係 test。
import numpy as np
import pandas as pd
df = pd.DataFrame({"x": np.arange(100)})
train_idx = np.random.choice(range(0, 100), size=70, replace=False)
train = df.iloc[train_idx]
test = df.drop(index=train_idx)          # 剩低嘅 30 行
print(len(train), len(test))             # 70 30

1.3 Scissor, Rock, Paper(slide 5)

Result = np.random.choice(["S", "R", "P"], size=10000)        # 預設每樣機會均等 (1/3)
Prob_S = len(Result[Result == 'S']) / 10000                    # 約 0.333
# 指定真實 underlying probabilities,控制出現率
Result = np.random.choice(["S", "R", "P"], p=[0.25, 0.5, 0.25], size=10000)
print((Result == "R").mean())                                  # 約 0.5
💡 直覺理解

玩 10,000 次之後,「S」嘅相對頻率會好接近真實 probability(1/3 或 0.25)——呢個就係 Law of Large Numbers:simulation 次數越多,empirical proportion 越接近理論 probability。p= 嘅數加埋一定要等於 1。

1.4 Random seed(slide 6)

每次重新執行程式,random numbers 都唔同。如果想每次都得到同一組 random numbers(reproducible),就要 set seed:

np.random.seed(123)
sample = np.random.choice(range(1, 10), 5)   # 每次 run 都係同一組 5 個數
⚠️ 常見錯誤

Seed 唔係令結果「更隨機」或者「更準」,只係令結果可以重現(方便 debug、交功課、比較模型)。另外 np.random.choice(range(1, 10), 5) 預設 replace=True。

2. Different types of Variables

Slide 7 嘅樹狀圖:Data Types 分做 Categorical(= discrete value)同 Numerical(= continuous value);Categorical 再分 Ordinal 同 Nominal,Numerical 再分 Interval 同 Ratio。

Type大類定義(slides 8–10)例子
NominalCategoricalNamed variables;unordered, categorical and mutually exclusiveCountries(Afghanistan, Brazil, China);Yes/No(只有兩個值 → dichotomous / binary)
OrdinalCategoricalNamed variables that have a meaningful order;ordered, categorical and mutually exclusiveGrade A, A-, B+;BMI: Underweight/Normal/Overweight/Obese;Likert scale 1 = Strongly Disagree … 5 = Strongly Agree
IntervalNumericalMeaningful interval between data points but no meaningful zeroTemperature °C(0 °C 唔係「冇溫度」);Shoe size(EU size 0 不存在)
RatioNumericalMeaningful interval and a meaningful (true) zeroLength cm(0 cm = 冇長度);Weight kg

Interval 同 Ratio 喺 SPSS 統稱 ‘Scale’。

⭐ 考試重點:點樣分?
  1. 有冇數值意義(可以加減)?冇 → Categorical;有 → Numerical。
  2. Categorical:有冇次序?有 → Ordinal;冇 → Nominal。
  3. Numerical:0 係咪代表「冇」?係(true zero)→ Ratio;唔係 → Interval。

Ratio 嘅「比例」有意義:20 kg 係 10 kg 嘅兩倍;但 20 °C 唔可以話係 10 °C「兩倍熱」→ interval。

⚠️ 常見錯誤

Likert scale 用 1–5 編碼,但佢本質仍然係 ordinal:「Agree (4)」同「Neutral (3)」之間嘅距離唔一定等於「Neutral (3)」同「Disagree (2)」。數字 code 唔等於 numerical variable。

2.1 Example data(slides 11–12)

Slide 11 係教科書 Table 9.1 “Information for ten sold residential properties”:每一行(Property 1–10)係一個 observation / element,每一欄 x1x_1–x6x_6 係一個 variable。例如 Property 1:x1=Highx_1 = \text{High}、x2=NTx_2 = \text{NT}、x3=13x_3 = 13、x4=732x_4 = 732、x5=322x_5 = 322、x6=4399x_6 = 4399。

Variable意思Type
X1X_1Floor level (High, Medium, Low)Ordinal / Categorical
X2X_2District (Hong Kong Island, Kowloon, New Territories)Nominal / Categorical
X3X_3Age (in years)Ratio / quantitative / numerical
X4X_4Size (square feet)Ratio
X5X_5Sale price (in ten thousand dollars)Ratio
X6X_6Price per square feetRatio

Which are categorical and which are quantitative? X1X_1、X2X_2 categorical;X3X_3–X6X_6 quantitative(全部有 true zero → ratio)。

import pandas as pd
d = pd.DataFrame({"x1": ["High", "Low", "Low"], "x2": ["NT", "HK", "NT"], "x3": [13, 9.5, 13]})
# Ordinal:指定次序
d["x1"] = pd.Categorical(d["x1"], categories=["Low", "Medium", "High"], ordered=True)
# Nominal:冇次序
d["x2"] = d["x2"].astype("category")
print(d.dtypes)

3. Distributional properties of Variables

Slide 13:唔同情境嘅數據有唔同嘅「形狀」,數學家用唔同 distribution 去描述:

情境DistributionType
Number of occurrence in a time period(每小時收幾多封 email)Poissondiscrete
Number of trials until the first successGeometricdiscrete
Biological measurements(身高、體重)Normalcontinuous
Time between two consecutive eventsExponentialcontinuous
Lifetime of bulb, small insectsWeibullcontinuous
IncomeParetocontinuous(右偏、長尾)

Poisson 例子嘅步驟(slide 13):

  1. Define a random variable X=number of emails received in an hourX = \text{number of emails received in an hour}
  2. Give distribution parameter = average number of emails received an hour(λ\lambda)
  3. 計 Prob(X=0)\text{Prob}(X = 0)、Prob(X=3)\text{Prob}(X = 3)、Prob(X=5)\text{Prob}(X = 5)…
💡 數字示範(自行假設 λ=3\lambda = 3 封/小時;公式見 Module 2b)

P(X=k)=λke−λk!P(X=k) = \dfrac{\lambda^k e^{-\lambda}}{k!},e−3≈0.0498e^{-3} \approx 0.0498:

  • P(X=0)=e−3≈0.0498P(X=0) = e^{-3} \approx 0.0498
  • P(X=3)=276e−3≈0.2240P(X=3) = \frac{27}{6}e^{-3} \approx 0.2240
  • P(X=5)=243120e−3≈0.1008P(X=5) = \frac{243}{120}e^{-3} \approx 0.1008

Python:stats.poisson.pmf([0, 3, 5], 3)

🖼️ 圖片內容

Slide 14 “Types of distributions” 係一張各種 distribution 形狀嘅 cheat-sheet 圖片(來源 DsciCheatsheet Facebook),文字擷取不到;請對照原 slide 第 14 頁。

4. Concepts of probability distribution:由 histogram 到 density

4.1 Categorical data(slide 15)

Distribution 可以用 bar chart 或 pie chart 描述;可以用 frequency(次數)或 proportion(比例)。

4.2 Continuous data(slides 16–17)

將 range 切成好多 bins / classes,數每個 bin 有幾多個,畫出嚟就係 histogram(bar chart 嘅 continuous 版本)。Slide 16 嘅 frequency table:

ClassFrequencyCumulative Freq
62.8–63.011
63.0–63.267
63.2–63.41219
63.4–63.61635
………
64.4–64.6158

Cumulative frequency = 由最細 class 加到而家嘅總和(1, 1+6 = 7, 7+12 = 19, 19+16 = 35 …),最後一個 = 總數 n=58n = 58。Slide 17 就係 histogram 同 cumulative frequency histogram 嘅圖。

4.3 Density(slide 18)

通常唔直接用 frequency,而係將 frequency 除以原本 histogram 嘅總面積 → 得到 density。除完之後,所有 bar 嘅面積加埋 = 1。

density of a bin=frequencyn×bin width\text{density of a bin} = \frac{\text{frequency}}{n \times \text{bin width}}
💡 Worked example

63.4–63.6 呢個 bin:frequency=16\text{frequency} = 16,n=58n = 58,bin width=0.2\text{bin width} = 0.2 → density=16/(58×0.2)≈1.379\text{density} = 16 / (58 \times 0.2) \approx 1.379。呢個 bar 嘅面積 =1.379×0.2=16/58≈0.276= 1.379 \times 0.2 = 16/58 \approx 0.276 = 落入呢個 bin 嘅比例。所以 面積 = 比例 = probability,所有面積加埋 = 1。注意 density(1.379)可以大過 1!

4.4 Normal density 同 CDF(slides 19–20)

Histogram 唔平滑;數學家定義咗平滑曲線去 approximate 佢。Normal distribution 係 bell-shape curve,由兩個 parameter 描述:μ\mu(mean,location)同 σ2\sigma^2(variance,dispersion / scale)。

norm.pdf(x,μ,σ)=1σ2π e−(x−μ)2/2σ2\text{norm.pdf}(x,\mu,\sigma) = \frac{1}{\sigma\sqrt{2\pi}}\, e^{-(x-\mu)^2/2\sigma^2}
norm.cdf(x,μ,σ)=∫−∞xnorm.pdf(s,μ,σ) ds\text{norm.cdf}(x,\mu,\sigma) = \int_{-\infty}^{x} \text{norm.pdf}(s,\mu,\sigma)\, ds

Histogram 可以有其他形狀,數學家就引入其他 distribution 去描述(細節略)。

🖼️ 圖片內容

Slides 17、20 係 histogram/cumulative histogram 同 probability density / cumulative density 嘅圖,文字擷取不到;請對照原 slide 第 17、20 頁。概念:PDF 係鐘形曲線;CDF 係由 0 升到 1 嘅 S 形曲線。

5. PMF、CMF、PDF、CDF

5.1 Discrete variable(slide 21)

  • PMF (Probability Mass Function):A function that gives the exact probability that a discrete random variable equals a specific value. The sum of all probabilities in a PMF always equals 1.
    例:XX = 擲硬幣得到嘅 heads 數目,PMF(3)=P(X=3)\text{PMF}(3) = P(X = 3)。公平骰子擲到 4 嘅機率 = 1/6。
  • CMF (Cumulative Mass Function):adds up all the probabilities from the smallest possible value up to a chosen value x;running total,最終 = 1。
    CMF(4)=P(X≤4)=PMF(4)+PMF(3)+PMF(2)+PMF(1)+PMF(0)\text{CMF}(4) = P(X\le 4) = \text{PMF}(4)+\text{PMF}(3)+\text{PMF}(2)+\text{PMF}(1)+\text{PMF}(0)
    例:骰子擲到 ≤3\le 3:1/6+1/6+1/6=1/21/6 + 1/6 + 1/6 = 1/2。

5.2 Continuous variable(slide 22)

  • PDF (Probability Density Function):describes the likelihood for a continuous random variable. The output is not a probability. Area under the curve across an interval gives the probability. Total area = 1. The probability of one exact single point is zero.
    例:Prob(height=176 cm)=0\text{Prob}(\text{height} = 176\text{ cm}) = 0;Prob(176 cm≤height≤177 cm)=0.12\text{Prob}(176\text{ cm} \le \text{height} \le 177\text{ cm}) = 0.12。
  • CDF (Cumulative Distribution Function):works for both continuous and discrete. Gives P(X≤x)P(X \le x). Starts at 0 and climbs to 1. For continuous variables, CDF = integral (running total area) of the PDF.
    例:Prob(height≤177 cm)\text{Prob}(\text{height} \le 177\text{ cm})。
⭐ 考試重點:Probability functions 對照表(slide 23)
FunctionVariable TypeWhat the Output MeansTotal Sum / Area
PMFDiscreteExact probability of a single valueSum equals 1
CMFDiscreteCumulative probability up to a valueReaches 1
PDFContinuousProbability density (not probability itself)Total area under curve equals 1
CDFBothCumulative probability up to a value (P≤xP \le x)Reaches 1

Slide 上紅色箭咀特別指住 PMF、PDF 同 “density (not probability itself)”——即係考 PMF vs PDF 嘅分別。

⚠️ 常見錯誤
  • 以為 norm.pdf(x) 係 probability:佢只係曲線高度,可以 >1> 1(例如 σ=0.1\sigma = 0.1 時 pdf(μ)≈3.99\text{pdf}(\mu) \approx 3.99)。
  • Continuous 嘅 P(X≤a)P(X \le a) 同 P(X<a)P(X < a) 一樣(因為單點機率 = 0);但 discrete 唔一樣:P(X≤5)≠P(X<5)=P(X≤4)P(X \le 5) \ne P(X < 5) = P(X \le 4)。
  • 計區間 probability 要用 CDF 相減:P(a≤X≤b)=F(b)−F(a)P(a\le X\le b) = F(b) - F(a)。

6. 用 scipy.stats 計 probability

6.1 Discrete:Binomial(slides 24–25)

import scipy.stats as stats
n = 10   # Number of trials
p = 0.5  # Probability of getting heads
pmf_exact_5 = stats.binom.pmf(5, n, p)   # P(X = 5)  → 0.2461
cmf_up_to_5 = stats.binom.cdf(5, n, p)   # P(X ≤ 5)  → 0.6230
print(f"PMF (Exactly 5 heads): {pmf_exact_5:.4f}")
print(f"CMF/CDF (5 heads or fewer): {cmf_up_to_5:.4f}")
⭐ 手計驗證

P(X=5)=(105)(0.5)5(0.5)5=252/1024≈0.2461P(X=5) = \binom{10}{5}(0.5)^5(0.5)^5 = 252/1024 \approx 0.2461

P(X≤5)=1+10+45+120+210+2521024=638/1024≈0.6230P(X\le 5) = \frac{1+10+45+120+210+252}{1024} = 638/1024 \approx 0.6230

延伸:P(X≥6)=1−0.6230=0.3770P(X\ge 6) = 1 - 0.6230 = 0.3770(= 1 - binom.cdf(5, 10, 0.5) 或 binom.sf(5, 10, 0.5))。

Slide 25 嘅 visualization:左邊用 axes[0].stem() 畫 PMF(每個整數一支棒);右邊用 axes[1].step(..., where="mid") 畫 CDF(樓梯形,因為 probability 喺整數之間保持不變)。

import numpy as np, matplotlib.pyplot as plt, scipy.stats as stats
n, p = 10, 0.5
x = np.arange(0, n + 1)
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
axes[0].stem(x, stats.binom.pmf(x, n, p), basefmt=" ")      # PMF:棒形
axes[1].step(x, stats.binom.cdf(x, n, p), where="mid", marker="o")  # CMF/CDF:樓梯形
plt.tight_layout(); plt.show()

6.2 Continuous:Standard normal(slides 26–27)

pdf_at_zero = stats.norm.pdf(0, loc=0, scale=1)     # 0.3989 —— 係 height,唔係 probability
cdf_up_to_zero = stats.norm.cdf(0, loc=0, scale=1)  # 0.5000 —— 對稱鐘形曲線左半邊面積

pdf(0)=1/2π≈0.3989\text{pdf}(0) = 1/\sqrt{2\pi} \approx 0.3989。Slide 27 用 fill_between 將 −3-3 到 0 嘅面積塗色,標示 “Area = P(−inf ≤ X ≤ 0)”(理論上應由 −∞-\infty 開始,用 −3-3 只係方便畫圖);右圖用 plot 畫平滑 S 形 CDF。

💡 直覺理解

Discrete 嘅 PMF 係「一支支棒」,棒嘅高度 = probability;Continuous 嘅 PDF 係「一條曲線」,面積先係 probability。CDF 喺 discrete 係樓梯形,喺 continuous 係平滑 S 形。

自我測驗 Self-test

Q1. 要由 0–999 編號嘅數據隨機抽 80% 做 training set,點寫?應該用 replace=True 定 False?

np.random.choice(range(0, 1000), size=800, replace=False)。一定要 replace=False,否則同一行可能被抽兩次,而有啲行會被遺漏。

Q2. 將以下歸類:(a) 血型 A/B/AB/O (b) 年份 (c) 收入 (d) 滿意度 1–5 (e) 考試名次 (f) 智商 IQ

(a) Nominal;(b) Interval(年份 0 唔代表「冇時間」);(c) Ratio;(d) Ordinal(Likert);(e) Ordinal;(f) 一般當 Interval(IQ 0 冇「冇智力」嘅意思)。

Q3. 一個 histogram bin 寬 5,frequency 12,總數 n=60n = 60。Density 係幾多?呢個 bin 嘅面積代表咩?

Density=12/(60×5)=0.04\text{Density} = 12 / (60 \times 5) = 0.04。面積 =0.04×5=0.2= 0.04 \times 5 = 0.2 = 有 20% 數據落入呢個 bin。

Q4. 點解 Prob(height=176 cm)=0\text{Prob}(\text{height} = 176\text{ cm}) = 0,但 norm.pdf(176, 170, 7) 唔係 0?

Continuous variable 單一點嘅面積(寬度 0)= 0,所以 probability = 0。PDF 嘅值係曲線高度(density),代表該點附近嘅「密度」,要乘埋一段寬度(積分)先變成 probability。

Q5. X∼Binomial(n=10,p=0.5)X \sim \text{Binomial}(n = 10, p = 0.5)。用 CDF 表達 P(3≤X≤5)P(3 \le X \le 5),並計數值。

P(3≤X≤5)=F(5)−F(2)=638/1024−(1+10+45)/1024=638/1024−56/1024=582/1024≈0.5684P(3 \le X \le 5) = F(5) - F(2) = 638/1024 - (1 + 10 + 45)/1024 = 638/1024 - 56/1024 = 582/1024 \approx 0.5684。Python:stats.binom.cdf(5,10,0.5) - stats.binom.cdf(2,10,0.5)。

Q6. 骰子:CMF(4)\text{CMF}(4) 係幾多?PMF(7)\text{PMF}(7) 呢?

CMF(4)=P(X≤4)=4/6=2/3\text{CMF}(4) = P(X \le 4) = 4/6 = 2/3。PMF(7)=0\text{PMF}(7) = 0(骰子冇 7)。

Q7. 以下每個情境最適合邊個 distribution:(a) 一個網站每分鐘嘅 visit 數 (b) 燈泡壽命 (c) 擲骰直至第一次出 6 嘅次數 (d) 成年男性身高 (e) 兩架巴士之間嘅等候時間 (f) 個人收入

(a) Poisson (b) Weibull (c) Geometric (d) Normal (e) Exponential (f) Pareto。

Q8. np.random.choice(["S","R","P"], p=[0.25,0.5,0.25], size=10000) 之後,(Result=="R").mean() 大約係幾多?加 np.random.seed(1) 有咩作用?

約 0.5(Law of Large Numbers)。Seed 令每次執行得到相同嘅 random numbers,結果可重現;唔會改變 probability。

一頁總結 Cheat sheet

⭐ 考前速記
  • np.random.choice(a, size, replace, p):replace=False → 唔重複;p 指定各結果機率;np.random.seed() → 可重現。
  • Train/test 70/30:np.random.choice(range(0,100), size=70, replace=False);Python index 由 0 開始。
  • Categorical(discrete):Nominal(冇次序;binary = dichotomous)、Ordinal(有次序;Likert)。
  • Numerical(continuous):Interval(冇 true zero:°C、鞋碼)、Ratio(有 true zero:cm、kg);SPSS 叫 Scale。
  • Poisson = 時段內次數;Geometric = 第一次成功要幾多次;Normal = 生物量度;Exponential = 事件間隔;Weibull = 壽命;Pareto = 收入。
  • Density=freq/(n×bin width)\text{Density} = \text{freq} / (n \times \text{bin width});所有 bar 面積 = 1。
  • Normal:f(x)=1σ2πe−(x−μ)2/2σ2f(x)=\frac{1}{\sigma\sqrt{2\pi}}e^{-(x-\mu)^2/2\sigma^2};μ\mu = location,σ2\sigma^2 = scale。
  • PMF(discrete,exact prob,sum = 1);CMF(discrete,running total → 1);PDF(continuous,density 唔係 prob,面積 = 1,單點 = 0);CDF(both,P(X≤x)P(X \le x),0 → 1)。
  • binom.pmf(5,10,.5)=0.2461;binom.cdf(5,10,.5)=0.6230;norm.pdf(0)=0.3989;norm.cdf(0)=0.5。