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、指定 probabilityp=、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
- PMF / CMF / PDF / CDF 對照表(slide 23):邊個 discrete、邊個 continuous、輸出係咩、總和/面積 = 1。
- Continuous variable:P(X = 某一點) = 0;PDF 嘅值係 density 唔係 probability;probability = 曲線下面積。
- Nominal / Ordinal / Interval / Ratio 嘅定義同例子(例如 temperature °C = interval;weight = ratio;Likert = ordinal)。
replace=Truevsreplace=False;seed 嘅用途;train/test split 70/30 嘅寫法。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) | 例子 |
|---|---|---|---|
| Nominal | Categorical | Named variables;unordered, categorical and mutually exclusive | Countries(Afghanistan, Brazil, China);Yes/No(只有兩個值 → dichotomous / binary) |
| Ordinal | Categorical | Named variables that have a meaningful order;ordered, categorical and mutually exclusive | Grade A, A-, B+;BMI: Underweight/Normal/Overweight/Obese;Likert scale 1 = Strongly Disagree … 5 = Strongly Agree |
| Interval | Numerical | Meaningful interval between data points but no meaningful zero | Temperature °C(0 °C 唔係「冇溫度」);Shoe size(EU size 0 不存在) |
| Ratio | Numerical | Meaningful interval and a meaningful (true) zero | Length cm(0 cm = 冇長度);Weight kg |
Interval 同 Ratio 喺 SPSS 統稱 ‘Scale’。
- 有冇數值意義(可以加減)?冇 → Categorical;有 → Numerical。
- Categorical:有冇次序?有 → Ordinal;冇 → Nominal。
- 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,每一欄 – 係一個 variable。例如 Property 1:、、、、、。
| Variable | 意思 | Type |
|---|---|---|
| Floor level (High, Medium, Low) | Ordinal / Categorical | |
| District (Hong Kong Island, Kowloon, New Territories) | Nominal / Categorical | |
| Age (in years) | Ratio / quantitative / numerical | |
| Size (square feet) | Ratio | |
| Sale price (in ten thousand dollars) | Ratio | |
| Price per square feet | Ratio |
Which are categorical and which are quantitative? 、 categorical;– 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)
COM6004 Chapter 2 (Data) 嘅 attribute types(nominal / ordinal / interval / ratio)同呢度一模一樣,而且會講每種 type 容許嘅運算( / / / )。COM6001 pandas 嘅 category dtype 就係用嚟存 categorical data。
3. Distributional properties of Variables
Slide 13:唔同情境嘅數據有唔同嘅「形狀」,數學家用唔同 distribution 去描述:
| 情境 | Distribution | Type |
|---|---|---|
| Number of occurrence in a time period(每小時收幾多封 email) | Poisson | discrete |
| Number of trials until the first success | Geometric | discrete |
| Biological measurements(身高、體重) | Normal | continuous |
| Time between two consecutive events | Exponential | continuous |
| Lifetime of bulb, small insects | Weibull | continuous |
| Income | Pareto | continuous(右偏、長尾) |
Poisson 例子嘅步驟(slide 13):
- Define a random variable
- Give distribution parameter = average number of emails received an hour()
- 計 、、…
,:
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:
| Class | Frequency | Cumulative Freq |
|---|---|---|
| 62.8–63.0 | 1 | 1 |
| 63.0–63.2 | 6 | 7 |
| 63.2–63.4 | 12 | 19 |
| 63.4–63.6 | 16 | 35 |
| … | … | … |
| 64.4–64.6 | 1 | 58 |
Cumulative frequency = 由最細 class 加到而家嘅總和(1, 1+6 = 7, 7+12 = 19, 19+16 = 35 …),最後一個 = 總數 。Slide 17 就係 histogram 同 cumulative frequency histogram 嘅圖。
4.3 Density(slide 18)
通常唔直接用 frequency,而係將 frequency 除以原本 histogram 嘅總面積 → 得到 density。除完之後,所有 bar 嘅面積加埋 = 1。
63.4–63.6 呢個 bin:,, → 。呢個 bar 嘅面積 = 落入呢個 bin 嘅比例。所以 面積 = 比例 = probability,所有面積加埋 = 1。注意 density(1.379)可以大過 1!
4.4 Normal density 同 CDF(slides 19–20)
Histogram 唔平滑;數學家定義咗平滑曲線去 approximate 佢。Normal distribution 係 bell-shape curve,由兩個 parameter 描述:(mean,location)同 (variance,dispersion / scale)。
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.
例: = 擲硬幣得到嘅 heads 數目,。公平骰子擲到 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。
例:骰子擲到 :。
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.
例:;。 - CDF (Cumulative Distribution Function):works for both continuous and discrete. Gives . Starts at 0 and climbs to 1. For continuous variables, CDF = integral (running total area) of the PDF.
例:。
| Function | Variable Type | What the Output Means | Total Sum / Area |
|---|---|---|---|
| PMF | Discrete | Exact probability of a single value | Sum equals 1 |
| CMF | Discrete | Cumulative probability up to a value | Reaches 1 |
| Continuous | Probability density (not probability itself) | Total area under curve equals 1 | |
| CDF | Both | Cumulative probability up to a value () | Reaches 1 |
Slide 上紅色箭咀特別指住 PMF、PDF 同 “density (not probability itself)”——即係考 PMF vs PDF 嘅分別。
- 以為
norm.pdf(x)係 probability:佢只係曲線高度,可以 (例如 時 )。 - Continuous 嘅 同 一樣(因為單點機率 = 0);但 discrete 唔一樣:。
- 計區間 probability 要用 CDF 相減:。
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}")
延伸:(= 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 —— 對稱鐘形曲線左半邊面積
。Slide 27 用 fill_between 將 到 0 嘅面積塗色,標示 “Area = P(−inf ≤ X ≤ 0)”(理論上應由 開始,用 只係方便畫圖);右圖用 plot 畫平滑 S 形 CDF。
Discrete 嘅 PMF 係「一支支棒」,棒嘅高度 = probability;Continuous 嘅 PDF 係「一條曲線」,面積先係 probability。CDF 喺 discrete 係樓梯形,喺 continuous 係平滑 S 形。
COM6004 Chapter 3 Data Visualization 嘅 histogram、cumulative distribution 同呢度一樣;COM6004 Chapter 4/5 嘅 Naïve Bayes 亦會用到 PMF(categorical attributes)同 normal PDF(continuous attributes)。
自我測驗 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,總數 。Density 係幾多?呢個 bin 嘅面積代表咩?
。面積 = 有 20% 數據落入呢個 bin。
Q4. 點解 ,但 norm.pdf(176, 170, 7) 唔係 0?
Continuous variable 單一點嘅面積(寬度 0)= 0,所以 probability = 0。PDF 嘅值係曲線高度(density),代表該點附近嘅「密度」,要乘埋一段寬度(積分)先變成 probability。
Q5. 。用 CDF 表達 ,並計數值。
。Python:stats.binom.cdf(5,10,0.5) - stats.binom.cdf(2,10,0.5)。
Q6. 骰子: 係幾多? 呢?
。(骰子冇 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 = 收入。
- ;所有 bar 面積 = 1。
- Normal:; = location, = scale。
- PMF(discrete,exact prob,sum = 1);CMF(discrete,running total → 1);PDF(continuous,density 唔係 prob,面積 = 1,單點 = 0);CDF(both,,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。